var Fader = Class.create({
	initialize : function(list, wait, animSpeed)
	{
		this.list        = list;
		this.timer       = null;
		this.animTimer   = null;
		this.wait        = wait ? wait : 3;
		this.currentPage = 0;
		this.animSpeed   = animSpeed ? animSpeed : 1;
		this.current     = null;
		this.next        = null;
		
		var maxHeight = 0;
		this.list.descendants().each(function(obj)
		{
			if(obj.getHeight() > maxHeight)
			{
				maxHeight = obj.getHeight();
			}
		});
		this.list.setStyle({ 'height' : (maxHeight + 30) + 'px' });
		
		return this;
	},
	
	start : function()
	{
		if(this.timer)
		{
			return false;
		}
		
		var page = this.list.down('li', this.currentPage);
		if(!page)
		{
			throw 'Missing page ' + this.currentPage;
			return false;
		}
		
		this.timer = this.fadeTo.bind(this).delay(this.wait, this.list.down('li', this.currentPage + 1) ? this.currentPage + 1 : 0);
		return this;
	},
	
	fadeTo : function(itemId)
	{
		this.timer   = null;
		this.current = this.list.down('li', this.currentPage);
		this.next    = this.list.down('li', itemId);
		
		if(!this.current)
		{
			throw 'Missing item ' + this.currentPage;
			return false;
		}
		if(!this.next)
		{
			throw 'Missing item ' + itemId;
			return false;
		}
		
		this.next.setStyle({ 'z-index'    : (this.current.getStyle('z-index')
		                                  ? parseInt(this.current.getStyle('z-index')) + 1
		                                  : 2),
		                     'opacity'    : 0,
		                     'visibility' : 'visible' });

		var fadeOut = new Animator({ duration   : this.animSpeed * 1000,
		                             onComplete : function() { this.current.setStyle({ 'visibility' : 'hidden' }); this.start(); }.bind(this) })
		            .addSubject(new NumericalStyleSubject(this.current, 'opacity', 1, 0));
		var fadeIn  = new Animator({ duration   : this.animSpeed * 1000 })
		            .addSubject(new NumericalStyleSubject(this.next, 'opacity', 0, 1));

		fadeOut.seekTo(1);
		fadeIn.seekTo(1);
		this.currentPage = itemId;
		this.animTimer = setTimeout(function() { this.animTimer = null; }.bind(this), this.animSpeed * 1000);
	},
	
	stop : function()
	{
		if(!this.timer)
		{
			return false;
		}
		
		clearTimeout(this.timer);
		this.timer = null;
		return true;
	}
});

document.observe('dom:loaded', function()
{
	$$('ul.fader').each(function(obj)
	{
		obj.fader = new Fader(obj, 4, 2).start();
	});
});