/**
 * @fileoverview 
 * @author florian
 */

/**
 * @class Tabs
 * @lends Tabs
 */
mangrove.TabRotator = Class.create({
	/**
	 * @description rotates through different tabs of content, content is not loaded dynamicaly, but has to be set to display:none; the active item will have the class "active", wich must be set to show the item
	 * @constructs
	 * @param {Element} element or id
	 * @params {Object} options (contentselecotr, tabselector, interval)
	 */
	initialize: function(element, options){
		this.element = $(element);
		this.options = Object.extend({
			contentselector: '.detail',
			tabselector: '.list',
			interval: 10,
			parameterName: 'id',
			activator: 'li a'
		}, options || { });
		
		this.content = this.element.down(this.options.contentselector);
		this.tabs = this.element.down(this.options.tabselector);
		
		Event.observe(this.tabs, 'click', this.clickHandler.bindAsEventListener(this));
		
		if(this.options.interval > 0){
			this.timer = new PeriodicalExecuter(this.timerHandler.bindAsEventListener(this), this.options.interval);
			Event.observe(this.element, 'mouseover', this.overHandler.bindAsEventListener(this));
			Event.observe(this.element, 'mouseout', this.outHandler.bindAsEventListener(this));
		}
	},
	/**
	 * @private
	 * @description handle all clicks inside the tab element
	 * @param {Object} event
	 */
	clickHandler: function(event){
		var link = null;
		if(link = event.findElement('a')){
			this.handleLinkInfo(link);
			link.blur();
			event.stop();
		}
	},
	outHandler: function(){
		this.timer = new PeriodicalExecuter(this.timerHandler.bindAsEventListener(this), this.options.interval);
	},
	overHandler: function(){
		this.timer.stop();
	},
	/**
	 * @private
	 * @description handle the time-out rotation
	 */
	timerHandler: function(){
		var link = null;
		var next = false;
		this.tabs.select(this.options.activator).each(function(element){
			if(next && link == null){
				link = element;
			}
			if(element.hasClassName('active')){
				next = true;
			}
		});
		if(link == null){
			link = this.tabs.down(this.options.activator);
		}
		this.handleLinkInfo(link);
	},
	/**
	 * @description  [options.paramterName] is stripped from the link href, then calls activateItem with this value
	 * @param {Element} link to use,
	 */
	handleLinkInfo: function(link){
		var itemID = $H(link.readAttribute('href').toQueryParams()).get(this.options.parameterName);
		this.activateItem(itemID);
		this.tabs.down('.active').removeClassName('active');
		link.addClassName('active');
	},
	/**
	 * @description activates the items with the selected value
	 * @param {String} value value to compare with the [options.parameterName] from items in content
	 */
	activateItem: function(value){
		this.content.childElements().each(function(item){
			item.removeClassName('active');
			var itemValue = Element.getClassParameter(item, this.options.parameterName);
			if(value == itemValue){
				item.addClassName('active');
			}
		}.bind(this))
	}
});

