/*
**	Simple (image)rotator Javascript class
**
**	(c) 2010 Mikoon Webservices
*/

/*
**	Usage:
**
**	myrotator = new rotator('container-element-id', 'items-subselector', {options});
*/

var rotator = new Class({
	
	Implements: Options,
	
	options: {
		duration: 500,		//	duration of rotation animation
		width: 984,			//	width of rotator element
		period: 0			//	auto loop period
    },
	
	initialize: function(in_element, in_items, options){
		//	assign local variables
		this.id = in_element;
		this.el = $(in_element);
		this.items = $$('#'+in_element+' '+in_items);
		this.current = 0;
		//	set options
		this.setOptions(options);
		//	set container & element styles
		this.el.setStyle('width', this.items.length * this.options.width * 2 + 'px');
		this.items.setStyles({'float': 'left', 'display': 'block'});
		//	hide prev/next if less than 2 images
		if(this.items.length < 2) $$('#'+this.id+'_prev, #'+this.id+'_next').setStyle('display', 'none');
		//	if periodical set -> start auto loop
		if(this.options.period > 0) this.next.periodical(this.options.period, this);
		//	run setup
		this.setup();
	},
	
	setup: function(){
		//	setup prev & next button click-events
		if($defined($(this.id+'_prev'))){
			var prev_function = this.prev.bind(this);
			$(this.id+'_prev').addEvent('click', prev_function);
		}
		if($defined($(this.id+'_next'))){
			var next_function = this.next.bind(this);
			$(this.id+'_next').addEvent('click', next_function);
		}
	},
	
	to: function(in_item_nr){
		var options = this.options;
		var complete_to = this.complete_to.bind(this);
		this.current = in_item_nr;
		new Fx.Tween(this.el, {duration: options.duration, onComplete: complete_to}).start('margin-left', this.el.getStyle('margin-left').toInt(), -1 * this.current * options.width);
	},
	
	prev: function(){
		var options = this.options;
		if(--this.current < 0){
			this.current = (this.items.length-1);
			this.el.setStyle('margin-left', -1 * this.current * options.width);	
			this.current--;
		} 
		this.to(this.current);
	},
	
	next: function(){
		this.current++;
		this.to(this.current);	
	},
	
	complete_to: function(){
		if(this.current >= this.items.length-1){
			this.current = 0;
			this.el.setStyle('margin-left', '0px');	
		} 
		window.fireEvent('rotator_slide'); 
	}
	
});
