/* file: tabs.js
 * JavaScript Tabs
 * by Zuriel Barron
 */
 
var Tab = Class.create();
Tab.prototype = {
	
	initialize: function( tabLinkId, tabDivId ) {
		this.name = tabLinkId;
		this.linkObject = $( tabLinkId );
		this.divObject = $( tabDivId );
		this.linkObject.tabObject = this;
		this.tabSet = null;
		this.selectFunction = null;
		this.initFunction = null;
		this.init = false;
		this.selected = false;
		
		this.linkObject.onclick = function() {
			this.tabObject.doIt();
			return false;
		}
	},
	
	doIt: function() {
		this.tabSet.select( this );
	},
	
	reset: function() {
		Element.removeClassName( this.linkObject, "activeTab" );
		Element.hide( this.divObject );
		this.selected = false;
	},
	
	select: function() {
		Element.addClassName( this.linkObject, "activeTab" );
	    this.linkObject.blur();
	    Element.show( this.divObject );
	    this.selected = true;
	    
	    // run the init function if provided
	    // it only runs once.
	    if( this.initFunction != null && !this.init ) {
	    	this.initFunction();
	    	this.init = true;
	    }
	
		// run the select function
		// it runs everytime a tab is selected.
		if( this.selectFunction != null )
			this.selectFunction();
	} 
};

var TabSet = Class.create();
TabSet.prototype = {

	initialize: function( name, persistent ) {
		this.name = name;
		this.tabs = new Array();
		this.persistent = persistent == null ? false : persistent;
	},
	
	add: function ( tab ) {
		tab.tabSet = this;
		this.tabs[ tab.name ] = tab;
		this.tabs[ this.tabs.length ] = tab;
	},
	
	select: function( tab ) {
		var selectedTab = tab;
		
		if ( selectedTab == null ) {
			if ( this.persistent ) {
				if ( Cookie.read( this.name ) != null ) {
					var persistentTabName = Cookie.read( this.name );
					selectedTab = this.get( persistentTabName );
				} else {
					selectedTab = this.tabs[0];
				}
			} else {
				selectedTab = this.tabs[0];
			}
		}
		
		this.tabs.each( function( element, index ) {
			element.reset();
		});
		
		if( this.persistent )
			Cookie.create(this.name, selectedTab.name, 0);
		selectedTab.select();
	},

	get: function( name ) {
		return this.tabs[ name ];
	},
	
	getSelected: function() {
		this.tabs.find( function(tab){
			return (tab.selected == true);
		});
	}
};