/*  Prototabs
 *  (c) 2007 James Starmer
 *
 *  Prototabs is freely distributable under the terms of an MIT-style license.
 *  For details, see the web site: http://www.jamesstarmer.com/prototabs
 *  
 *  Added History module support by Burak Yigit Kaya <byk@groups-inc.com> 2009
 *
/*--------------------------------------------------------------------------*/

var ProtoTabs = Class.create();
ProtoTabs.prototype = {
	
	initialize: function(element, options) {
		this.options = Object.extend({
			defaultPanel: '',
			ajaxUrls: 			{},
			ajaxLoadingText: 	'Loading...',
			contentIdFormat: '%s-content',
			historyKey: 'tab-' + (element.id || element)
		}, options || {});
		
		this.currentTab = '';
		
		this.element = $(element);
		this.listElements = $A(this.element.getElementsByTagName('LI'));

		//loop over each list element
		for(i = 0; i < this.listElements.length; i++) {	
			
			//get the tabs
			tabLI = this.listElements[i];
			tabLI.itemId = this.options.contentIdFormat.format(tabLI.id);
			tabLI.linkedPanel = $(tabLI.itemId);
			tabLI.linkedPanel.style.clear = "both";		//firefox hack

			//check for the intially active tab
			if((this.options.defaultPanel != '') && (this.options.defaultPanel == tabLI.itemId) || (i == 0) && (this.options.defaultPanel == '')){
				this.openPanel(tabLI);
			}else{
				$($(tabLI).linkedPanel).hide();
			}
			
			// watch for clicked
			$(tabLI).observe('click', function(event){
					element = Event.findElement(event, "LI");
					this.openPanel(element);					
					Event.stop(event); // like return false;
			}.bind(this));
		}
		var self = this;
		this.history = HistoryManager.register(
			this.options.historyKey,
			[this.currentTab.id],
			function(values){self.openPanel(values[0]);},
			function(values){return self.options.historyKey + '=' + values[0];},
			this.options.historyKey + '=(\\w+)'
		);
		HistoryManager.start();
	},
	
	openPanel: function(tab){
		tab = $(tab);
		
		if(this.currentTab != ''){
			this.currentTab.linkedPanel.hide();
			this.currentTab.removeClassName('selected');
			this.currentTab.firstDescendant().removeClassName('special_bg_reverse');
			this.currentTab.firstDescendant().removeClassName('special_border');
		}
		
		//set the currently open panel to the new panel
		this.currentTab = tab;
		
		tab.linkedPanel.show();
		tab.addClassName('selected');
		tab.firstDescendant().addClassName('special_bg_reverse');
		tab.firstDescendant().addClassName('special_border');
		var url = this.options.ajaxUrls[tab.itemId];
		
		// if there is an ajax url defined update the panel with ajax
		if(url != undefined){
			tab.linkedPanel.update(this.options.ajaxLoadingText);
			new Ajax.Request(url,{
				onComplete: function(transport) {
					tab.linkedPanel.update(transport.responseText);
				}
			});
		}
		if (this.history)
			this.history.setValue(0, tab.id);
	}
};