Delicious.Fader = new Class({
	Implements: [Events, Options],
	Binds: ['startTransition' , 'endTransition'],
	
	options: {
		element: 'device-preview',
		screenShotClass: 'screenshot',
		deviceClass: 'device',
		lowerzIndex: 85,
		upperzIndex: 86,
		transitionDelay: 3000,
		transitionGap: 1000,
		transitionTypes: ['fade' , 'swap' , 'slide'],
		transitionType: 'fade'
	},
	
	initialize: function(o)
	{
		o = o || {};
		this.setOptions(o);
		this.element = $(this.options.element);
		
		if (!this.element)
		{
			return;
		}
		
		this.screenShots = [];
		this.build();
	},
	
	build: function()
	{
		this.device = this.element.getElement('.' + this.options.deviceClass);
		this.screenShots = this.element.getElements('img.screenshot');
		this.screenShots.hide();
		this.currentScreenShot = this.screenShots[0].show();
		window.setTimeout(this.startTransition , this.options.transitionDelay);
	},
	
	getNextScreenShot: function()
	{
		var index = this.screenShots.indexOf(this.currentScreenShot);
		if (index + 1 == this.screenShots.length)
		{
			return this.screenShots[0];
		}
		else
		{
			return this.screenShots[index + 1];
		}
	},
	
	startTransition: function()
	{
		this.currentScreenShot.setStyle('z-index' , this.options.upperzIndex);
		this.nextScreenShot = this.getNextScreenShot();
		this.nextScreenShot.setStyle('z-index' , this.options.lowerzIndex).setStyle('opacity' , 1).show();
		this.transitionOut();
		window.setTimeout(this.endTransition , this.options.transitionGap);
	},
	
	transitionOut: function()
	{
		switch(this.options.transitionType)
		{
			case 'slide':
				this.remember = this.currentScreenShot.getStyle('left').toInt();
				new Fx.Morph(this.currentScreenShot , {duration: this.options.transitionGap - 100}).start({
					left: (this.remember - this.currentScreenShot.getStyle('width').toInt()) + 'px',
					opacity: '0'
				});;
			break;
			
			default:
			case 'fade':
				this.currentScreenShot.fade('out');
			break;
		}
	},
	
	setClippingMask: function()
	{
		this.currentScreenShot.setStyle('clip' , 'rect(0,' + 0 + 'px,1000px,0px)');
	},
	
	cleanupTransition: function()
	{
		switch(this.options.transitionType)
		{
			case 'slide':
				this.currentScreenShot.setStyles({
					opacity: 1,
					left: this.remember
				});
			break;
			
			case 'swap':
				// this one does nothign.
			break;
			
			case 'clip':
				this.currentScreenShot.setStyle('clip' , 'auto');
			break;
			
			default:
			case 'fade':
				this.currentScreenShot.setStyle('opacity' , 1).setStyle('visibility' , '');
			break;
		}
	},
	
	endTransition: function()
	{
		this.currentScreenShot.hide();
		this.cleanupTransition();
		this.currentScreenShot = this.nextScreenShot;
		this.currentScreenShot.setStyle('z-index' , this.options.lowerzIndex);
		window.setTimeout(this.startTransition , this.options.transitionDelay);
	}
});

window.addEvent('domready', function() {
	window.fader = new Delicious.Fader();
});
