/* 
 * Hangar Bicocca
 *
 * @package		HB
 * @author		Oskar Krawczyk (o.krawczyk@keepthinking.it)
 * @version		1.2
 * @dependecies	MooTools 1.2+
 * @copyright	Copyright (c) 2009-2010, Oskar Krawczyk (Keepthinking Ltd.)		
 * @link		http://keepthinking.it
 * 
 ======================================================================= */

var RotatorAdv = new Class({
	Implements: [Events, Options],
	
	options: {
		// delay: 1000
		longPause: 30000,
		elements: {
			rotorCont: 'rotator-adv-cont',
			rotorNav: 'rotator-adv-nav',
			rotorItems: '.rotatorAdvItem'
		}
	},
	
	counter: 0,
	
	initialize: function(options) {
		this.setOptions(options);
		
		if(!($$(this.options.elements.rotorItems).length > 1)){
			return false;
		};
		
		this.rotatorCont = $(this.options.elements.rotorCont);
		this.triggerCont = $(this.options.elements.rotorNav);
		this.rotatorItems = $$(this.options.elements.rotorItems);
		this.triggers = this.triggerCont.getElements('a');
		this.maxIndex = this.rotatorItems.length-1;
		this.timer = $empty;
		this.timerStopper = false;
		
		this.triggers.each(function(trigger, index){
			trigger.addEvents({
				click: function(e){
					if (e) e.stop();
					
					// hide all slide
					this.rotatorItems.fade('out');
					
					// show the current slide
					this.rotatorItems[index].fade('in');

					// unhighlight all triggers
					this.triggerCont.getChildren().getChildren().each(function(el) {
						el[0].removeClass('active');
					});
					// highlight current trigger
					this.triggers[index].addClass('active');
					
					// check if the trigger was actually triggered manually (click)
					if (e && $(e.target)){
						
						// clear the timer
						this.timer = $clear(this.timer);
						this.timerStopper = true;
						
						// wait a few seconds and re-launch the timer
						(function(){
							this.timer = this.increment.periodical(this.options.delay, this);
						}).delay(this.options.longPause, this);
					}
					
					// update the counter
					this.counter = index;
				}.bind(this)
			});
		}, this);
		
		this.timer = this.increment.periodical(this.options.delay, this);

		this.manage();
	},
	
	manage: function(){
		this.rotatorCont.addEvents({
			mouseenter: function(){
				
				// clear the timer
				this.timer = $clear(this.timer);
			}.bind(this),
			
			mouseleave: function(){
				
				// don't re-launch the timer if user switched the slide manually (click)
				if (!this.timerStopper){
					this.timer = this.increment.periodical(this.options.delay, this);
				}
			}.bind(this)
		});
	},
	
	increment: function(){
		this.triggers[this.counter].fireEvent('click');

		if (this.counter === this.maxIndex){
			this.counter = -1;
		}

		this.counter = ++this.counter;
	}
});

window.addEvents({
	domready: function(){
		new RotatorAdv();
	}
});
