/*
**	Simple crossfader Javascript class
**
**	(c) 2010 Mikoon Webservices
*/

/*
**	Usage:
**
**	myfader = new xFader('container-element-id', 'items-subselector', {options});
*/

var xFader = new Class({
	
	Implements: Options,
	
	options: {
		duration: 1000,				//	duration of fade animation
		period: 4000,				//	auto fade period
		onComplete: (function(){ })	//	onComplete function, fired after fade completes	
    },
	
	initialize: function(in_element, in_items, options){
		
		//	set options
		this.setOptions(options);
		
		//	assign local variables
		this.el = $(in_element);
		this.items = $$('#'+in_element+' '+in_items);
		this.current = 0;
		this.length = this.items.length;
		
		//	set container & element styles
		this.items.setStyles({'position': 'absolute', 'opacity': 0, 'display': 'block'});
		
		//	if periodical set -> start auto loop
		if(this.options.period) this.next.periodical(this.options.period, this);
		
		//	display 1st image
		this.items[0].setStyle('opacity', 1);
	},
	
	to: function(in_item_nr){
		var options = this.options;
		this.current = in_item_nr;
		if(this.infx) this.infx.cancel();
		this.infx = new Fx.Tween(this.items[this.current], {duration: options.duration, onComplete: options.onComplete.bind(this)}).start('opacity', 0, 1);
	},
	
	set: function(in_item_nr){
		var options = this.options;
		if(this.outfx) this.outfx.cancel(); 
		this.outfx = new Fx.Tween(this.items[this.current], {duration: options.duration}).start('opacity', 1, 0);
		this.to(in_item_nr);
	},
	
	prev: function(){
		if(this.items.length > 1){
			var options = this.options;
			if(this.outfx) this.outfx.cancel();
			this.outfx = new Fx.Tween(this.items[this.current], {duration: options.duration}).start('opacity', 1, 0);
			if(--this.current < 0) this.current = this.length-1;
			this.to(this.current);
		}
	},
	
	next: function(){
		if(this.items.length > 1){
			var options = this.options;
			if(this.outfx) this.outfx.cancel();
			this.outfx = new Fx.Tween(this.items[this.current], {duration: options.duration}).start('opacity', 1, 0);
			if(++this.current >= this.length) this.current = 0;
			this.to(this.current);
		}
	}
	
});
