var Crossfader = Class.create();
Object.extend(Crossfader.prototype, {
	initialize : function( container, options ) {
		this.options = Object.extend({
			wait: 3,
			time: 2,
			repeat: true,
			reverse: false,
			pause: false
        },options || {});

		this.animating = 0;
		this.mousein = false;
		this.container = $(container);
		
		if(this.options.reverse)
		{
			this.divs = $(container).immediateDescendants().reverse();
		}
		else
		{
			this.divs = $(container).immediateDescendants();
		}
		
		$(container).observe('mouseover', this.mouseon.bindAsEventListener(this), false );
		$(container).observe('mouseout', this.mouseoff.bindAsEventListener(this), false );
		
		this.current = 0;
		this.timeout = new PeriodicalExecuter( this.crossfade.bind(this), this.options.wait );

		for(i=1; i<this.divs.length;i++)
		{
			this.divs[i].hide();
		}
	},
	mouseon : function()
	{
		this.mousein = true;
	},
	mouseoff : function()
	{
		this.mousein = false;
	},
	setAnimating : function( arg )
	{
		this.animating += arg
		document.fire('crossfader:animating', { value: this.animating } );
	},
	animating : function()
	{
		return this.animating;
	},
	crossfade : function( pe )
	{
		if(this.options.pause && this.mousein) { return; }
		
		if((this.current == (this.divs.length - 1)) && !this.options.repeat)
		{
			pe.stop();
			return;
		}
		
		if(this.animating)
		{
			return;
		}
		else
		{
			this.setAnimating( 2 );
		}
		
		Effect.Fade(this.divs[this.current], { duration:this.options.time, from:1.0, to:0.0, afterFinish: this.setAnimating.bind(this, -1) } );
		this.current++;
		this.current = this.current % this.divs.length;
		Effect.Appear(this.divs[this.current], { duration:this.options.time, from:0.0, to:1.0, afterFinish: this.setAnimating.bind(this, -1) });
	}
} );
