// starts slideshows
Event.observe(window, 'load', function(e){
	$$('div.slideshow').each(function(elm){
		new Slideshow({
			target : elm
		});
	});
});

/**
 * Slideshow
 *
 * @requires prototype
 * @requires scriptaculous
 * @author Jost Neumann <neumann@die-ordnung.de>
 */
Slideshow = Class.create();
Object.extend(Slideshow.prototype, {

	/**
	 * frame identifiers (start, end, current)
	 */
	frame : {},

	/**
	 * Initializes this class
	 *
	 * @param array options options
	 */
	initialize: function(options){
		// target container
		this.target = $(options.target);
		// delay btw slide
		this.delay = options.delay || 8;
		this.duration = options.duration || 2;
		
		// try to get delay from target class
		var delay = this.target.className.match(/slideshow-delay-\d/g);
		if( delay.length >= 1 ){
			delay = delay[0].substring(16);
			this.delay = delay;
		}
		
		// all images
		this.images = this.target.getElementsBySelector('img.slideshow');
		// first image to start with
		this.first = this.target.getElementsBySelector('img.first');
		
		// hide all images except the last one and get the max height and width
		var h = 0, w = 0;
		this.images.each(function(img){
			if( !img.hasClassName('first') ){
				img.hide();
				img.style.visibility = 'visible';
			}
			h = img.getHeight() > h ? img.getHeight() : h;
			w = img.getWidth() > w ? img.getWidth() : w;
		});
		// set height and width of target container
		this.target.style.height = h + 'px';
		this.target.style.width = w + 'px';
				
		// initialize frame counters
		this.frame.current = 0;
		this.frame.start = 0;
		this.frame.end = this.images.length-1;
		
		// start the show
		new PeriodicalExecuter(this.showFrame.bind(this), this.delay);
	},

	/**
	 * Gets the next frame
	 */
	nextFrame: function(){
		frame = this.frame.current;
		if( frame == this.frame.end ){ 
			frame = this.frame.start; 
		} else { 
			frame++; 
		}
		return frame;
	},
    
    /**
     * Shows the next frame and hides the current one
     */
    showFrame: function(){
    	// get the current/next frame
    	frame = this.nextFrame();
    	
		// animate
		var options = {
			'fps' : 30,
			'duration' : this.duration,
			'transition' : Effect.Transitions.linear
		};
		Effect.Appear(this.images[frame], options);
		Effect.Fade(this.images[this.frame.current], options);
		
		this.frame.current = frame;
    }
});