var Slideshow = Class.create();

Slideshow.prototype = {
	
	initialize: function(selector , options) {
		
		this.items = $$(selector);
		this.next_item = 0;
		this.current_item = null;
		this.started = false;
		
		this.fadeLock = false;
		
		this.options = {
			duration: 8,
			fadeDuration:2,
			startOnInit:true
		}
		
		Object.extend(this.options,options || {});
		
		this.items.invoke('setStyle' , 'visibility: visible');
		
		// on init hide all slideshow items.
		this.items.invoke('hide');
		
		// do the first slide right away
		this.slide();
		// the update will exucute every .. seconds
		if(this.options.startOnInit == true)
			this.start();	
		
	},
	start: function() {
		this.executer = new PeriodicalExecuter(this.slide.bind(this), this.options.duration);
		this.started = true;
	},
	stop: function() {
		if(this.started) {
			this.executer.stop();
			this.started = false;
		}
	},
	toggle: function() {
		if(this.started)
			this.stop();
		else
			this.start();	
	
	},
	slide: function() {
		this.fadeTo(this.next_item);
	},
	fadeTo: function(i) {
		
		var item = this.items[i];
			
			
		if(this.current_item !== null && this.current_item !== item) {
			
			this.next_item = i;
			
			this.fadeLock = true;
			
			
			// fade out
			new Effect.Fade(this.current_item, {
				duration: this.options.fadeDuration,
				fps: 50,
				from:1.0,
				to:0
			});
			
			// set the current item
			this.current_item = item;
			
			// fade in
			new Effect.Appear(item, {
				duration: this.options.fadeDuration + 0.5,
				fps: 50,
				from:0,
				to:1.0,
				afterFinish: function() { 
					this.fadeLock = false;
				}.bind(this)
			});	
			
			
			// set the next item
			if(this.next_item < this.items.length -1 ) {
				this.next_item++;
			} else {
				this.next_item=0;
			}
			
		} else {
			
			new Effect.Appear(item, {
				duration: 1,
				fps: 50
			});	
			this.current_item = item;
			
			if(this.next_item < this.items.length-1 ) {
				this.next_item++;
			} else {
				this.next_item=0;
			}
		}
		
		
	}	
	
	
}