var Slide = Class.create();
Slide.prototype = {
	initialize: function(sSource, options) {
		this.src = sSource;
		this.options = options;
	}  
};

var SlideShowController = {
	get : function(sName) {
		if(!this.controllers) return null;
		return this.controllers[sName];
	}
	, put : function(oController) {
		if(!this.controllers) {
			this.controllers = {};
		}        
		this.controllers[oController.id] = oController;	
	}	
}

var SlideShow = Class.create();
SlideShow.prototype = {
	initialize : function(eSlideContainer, arrSlides, options) {
		this.slideContainer = eSlideContainer;
		this.id = ""+new Date().getTime();
		this.slides = arrSlides || new Array();
		this.options = Object.extend({delay: 5000, transitionOpacity: 0.5, transitionDuration: 1.8},options);
		this.animationId = 0;
		SlideShowController.put(this);
		this._initCurrentSlide();
	}
	, _initCurrentSlide : function() {
		this.currentSlideIndex = 0;
		this.slides.unshift(new Slide(this.slideContainer.innerHTML));
	}
	, displaySlide : function(oSlide) {
		new Effect.Opacity(this.slideContainer,{
			duration: this.options.transitionDuration/2, to: this.options.transitionOpacity
			, afterFinish : function(obj) {
				this._loadSlide(oSlide);
				new Effect.Opacity(this.slideContainer,{duration: this.options.transitionDuration/2, to: 1.0});
			}.bind(this)
		});
	}
	, _loadSlide : function(oSlide) {
    this.slideContainer.innerHTML = oSlide.src;
	}
	, play : function() {
		if(this.state == "playing") return;
		this._waitForNextSlide();
		this._setState("playing");
	}
	, pause : function() {
		if(this.state == "paused") return;
		this._setState("paused");
	}
	, _setState : function(sState) {
		this.state = sState;
	}
	, _nextAnimationId : function() {
		this.animationId++;
		return this.animationId;
	}
	, _getSlide : function(idx) {
		return this.slides[idx];
	}
	, nextSlide : function(iAnimationId) {
		if(this.animationId != iAnimationId || this.state != "playing") {
			return;
		}
		this.currentSlideIndex = (this.currentSlideIndex+1)%this.slides.length;
		this.displaySlide(this.slides[this.currentSlideIndex]);
		this._waitForNextSlide();
	}
	, _waitForNextSlide : function() {
		setTimeout("SlideShowController.get("+this.id+").nextSlide("+this._nextAnimationId()+")",this.options.delay);            
	}
};

