/*
	Tabs Javascript
*/

/* ! TabManager Class */
var TabManager = Class.create({

	initialize: function() {
		/* ! Member Variable Setup */
		this.panels = new Array();
		var i = 0;
		
		// Loop through grabbing all the tab panel elements:
		$$('.tab_panel').each(function(element, index) {
			// Create a new Tab object:
			this.panels[i] = new TabPanel(element);
			i ++;
		}, this);
		
	}

});


var TabPanel = Class.create({
	
	initialize: function(element) {
		this.element = element;
		this.tabs = new Array();
		this.bodies = new Array();
		this.selectedIndex = 0;
		
		var i = 0;
		
		// Ok, now go through and grab the tabs objects
		element.getElementsBySelector('.tabs li').each(function(li, index) {
		
			// If it has a classname of 'linktab' leave it alone since this
			// doesn't want to be included in the execution of the tabs:
			if(!li.hasClassName('linktab')) {
				this.tabs[i] = li;
				if(li.hasClassName('on')) {
					this.selectedIndex = i;
				}
				
				i ++;
			}
			
		}, this);
		
		// And all the body objects:
		element.getElementsBySelector('.tab_body').each(function(body, index) {
			this.bodies[index] = body;
		}, this);
		
		// Ok, now if there's more than 1 tab, go and do the events.
		// If not, we leave it alone for performance.
		if(this.tabs.length > 1) {
			
			// Ok, now loop through and attach the event listeners:
			this.tabs.each(function(tab, idx) 
			{
				tab.observe('click', (function(event) 
				{
					event.stop();
					this.tabClicked(idx);
				}).bind(this));
				
			}, this);
			
			// And as a final piece of candy, if there's a #tab-xxxx specified in the
			// url, we can open it by default. Clever no?!
			if(document.location.hash != '') {
				//alert('There is a hash');
				var hash = document.location.hash;
				if(hash.indexOf('tab-') == 1) {
					var tabId = hash.replace(/#tab-/i, '');
					// Loop through the tabs and look for one which has the 
					this.tabs.each(function(tab, idx) {
						if(tab.id == tabId) {
							this.tabClicked(idx);
							throw $break;
						}
					}, this);
				}
			}
			
		}
		
	},
	
	tabClicked: function(clickedIdx) {
		// Hide the current tab:
		this.tabs[this.selectedIndex].removeClassName('on');
		this.bodies[this.selectedIndex].style.display = 'none';
		
		// And show the new one:
		this.tabs[clickedIdx].addClassName('on');
		var a = this.tabs[clickedIdx].select('a');
		if(a.length != 0){ a[0].blur(); }
		this.bodies[clickedIdx].style.display = 'block';
		
		// Update the selected tab:
		this.selectedIndex = clickedIdx;
	}
	
});

var TabManager = new TabManager();
