/**
 * @author orange
 */
var Tabs = Class.create();

Tabs.prototype={
	autoPage:3,
	initialize: function(element, options){
		this.currentPos=0;
		this.options = this._set_options(options);		
		this.element = element;
		this.headers = element.getElementsByClassName("tab_handle");
		this.bodies = element.getElementsByClassName("tab");
		if(this.buttonNext=element.getElementsByClassName("tabs_next")[0]){
			Event.observe(this.buttonNext,"click",this.next.bindAsEventListener(this));
		}
		if(this.buttonPrev=element.getElementsByClassName("tabs_prev")[0]){
			Event.observe(this.buttonPrev,"click",this.prev.bindAsEventListener(this));
		}
		
		this.content=element.getElementsByClassName("tabs_content")[0];
		this.container=element.getElementsByClassName("tabs_container")[0];
		
		if(this.headers && this.headers.length && this.bodies.length != this.headers.length){
			throw Error('Number of headers/bodies does not match!');
		}
		this.container.style.width=this.posToPx(this.bodies.length)+"px";
		for(var i = 0; i < this.headers.length; i++){		
			Event.observe(this.headers[i], this.options.event_trigger, this.show.bind(this, i));
			this.headers[i].style.cursor = "pointer";
		}
		this.show(this.options.defaultTab);
		
	},
	posToPx:function(pos){
		var sum=0
		for(i=0; i<pos; i++){
			sum+=this.bodies[i].getWidth();
		}
		return sum;
	},
	next:function(){
		index=this.currentPos+1;
		if ((index >= this.bodies.length) || (index < 0)){
			index=0;
		}
		this.show(index);
	},
	prev:function(){
		index=this.currentPos-1;
		if ((index >= this.length) || (index < 0)){
			index=this.length-1;
		}
		this.show(index);
	},
	show: function(index){		
		if ((index >= this.length) || (index < 0)){
			throw Error('Index out of range');
		}
		this.headers[this.currentPos].removeClassName("selected");
		oldPx=this.posToPx(this.currentPos);
		this.currentPos=index;
		this.headers[this.currentPos].addClassName("selected");
		newPx=this.posToPx(this.currentPos);
		var diff=oldPx-newPx;
		
		for(i=0;i<this.bodies.length;i++){
			this.effect=new Effect.Move(this.bodies[i], { x: diff,transition: Effect.Transitions.linear,duration: 0.5, queue: { position: 'end', scope: this.element.id+i }});
		}
		if(this.autoPage){
			if(this.timer){
				clearTimeout(this.timer);
			}
			this.timer=setTimeout(this.next.bind(this), this.autoPage*1000);
		}
	},
	_default_options: 
	{
		defaultTab: 0,
		duration: 0.3,
		event_trigger: 'click'
	},
	
	_set_options: function(options){
		if(typeof options != "undefined"){		
			var result = [];
			for(option in this._default_options){
				if(typeof options[option] == "undefined"){
					result[option] = this._default_options[option];
				}
				else{
					result[option] = options[option];
				}
			}
		
			return result;
		}
		else{
			return this._default_options;
		}
	}
}
document.observe('dom:loaded', function () {
	elements=$$(".tabs");
	elements.each(function (element){
		new Tabs(element);
	});
});
