/*
	Slideshow v1.0 for Backdoor (www.backdoor.co.nz)
	Requires MooTools 1.2.4
	
	Author: Andrew Ferri <andrew@blacksheepcreative.co.nz>
	Date: 4 June 2010
*/

var Slideshow = new Class({
	Implements: [Options, Events],
	
	current: 0,
	next_index: 0,
	ul: null,
	images: null,
	period: null,
	
	options: {
		duration: 300,
		interval: 8000,
		transition: Fx.Transitions.Sine.easeOut,
		direction: 'forward',
		autoplay: true
	},
	
	initialize: function(ul,options)
	{
		this.setOptions(options);
		
		this.ul = ul;
		this.images = this.ul.getElements('li');
		
		this.setup();
	},
	
	setup: function()
	{
		var counter = 0;
		this.images.each(function(el){
			el.store('fx',new Fx.Morph(el,{
				duration: this.options.duration,
				transition: this.options.transition,
				link: 'cancel'
			},this));
			if (counter != this.current)
			{
				el.retrieve('fx').set({'opacity':0});
			}
			el.setStyle('display','block');
			counter++;
		},this);
		
		if (this.options.autoplay == true)
		{
			this.play();
		}
	},
	
	slide: function()
	{
		switch(this.options.direction)
		{
			case 'forward':
				this.next();
			break;
			
			case 'reverse':
			case 'backwards':
				this.previous();
			break;
		}
	},
	
	next: function()
	{
		var next = this.current + 1;
		if (next >= this.images.length)
		{
			next = 0;
		}
		this.toImage(next);
	},
	
	previous: function()
	{
		var prev = this.current - 1;
		if (prev < 0)
		{
			prev = this.images.length;
		}
		this.toImage(prev);
	},
	
	toImage: function(index)
	{
		this.next_index = index;
		this.fireEvent('start');
		
		if (index != this.current)
		{
			var slideshow = this;
			var current = this.images[this.current];
			var next = this.images[index];
			
			next.retrieve('fx').set({'opacity':0});
			next.setStyle('z-index',20);
			next.retrieve('fx').start({opacity:1}).chain(function(){
				current.retrieve('fx').set({'opacity':0});
				next.setStyle('z-index',10);
				slideshow.fireEvent('complete');
			});
			
			this.current = index;
			if (this.current > this.images.length)
			{
				this.current = 0;
			}
			if (this.current < 0)
			{
				this.current = this.images.length;
			}
		} else
		{
			this.fireEvent('complete');
		}
	},
	
	pause: function()
	{
		$clear(this.period);
	},
	
	play: function()
	{
		this.period = this.slide.periodical(this.options.interval,this);
	}
});
