var Tabs = Class.create();
Object.extend(Tabs.prototype, {
	
	initialize: function(element)
	{
		this.element = $(element);
		this.childClass = 'tab';
		this.childTitleContainer = 'h3';
		this.childTitleClass = 'tab-title';
		this.childContentClass = 'tab-content';
		
		this.tabs = [];
		this.handles = [];
		this.build();
	},
	
	build: function()
	{
		var title, li, a, ul = new Element('ul').addClassName('tab-handles');
		this.element.insert({top: ul});
		
		$$('#' + this.element.id + ' .' + this.childClass).each(function(tab, i) {
		
			this.tabs.push(tab);
			
			title = tab.down('.' + this.childTitleClass)
			title.hide();
			
			//handle
			a = new Element('a')
				.update(title.down(this.childTitleContainer).innerHTML)
				.observe('click', this.onClick.bindAsEventListener(this, i));
			a.href = "#";
			this.handles.push(a);
			
			//new li
			li = new Element('li').insert(a);
			ul.appendChild(li);
			
		}, this);
		
		//add class name "last" on last created tab
		li.addClassName('last');
		
		this.showTab(0);
	},
	
	
	onClick: function(e, tabIndex)
	{
		e.stop();
		this.showTab(tabIndex);	
	},
	
	showTab: function(tabIndex)
	{
		var handle, content;
		$A(this.tabs).each(function(tab, i) {
			
			handle = this.handles[i];
			content = tab.down('.' + this.childContentClass);
		
			if(i == tabIndex) {
				handle.addClassName('active');
				content.show();
			} else {
				handle.removeClassName('active');
				content.hide();
			}
			
		}, this);
		
	}

});