/**
 * @author Dale Morrell <dalemorrell@irisassociates.com>
 * @copyright 2009 Dale Morrell
 * @package Fan-tab-stic
 * @version 1.0
 */
 
var tabs = Class.create({

    // Initialize Tabs
    initialize: function(list, activeState, openTab)
	{
		// Check that the tabs exist
		if (!$(list))
		{
            throw (list + " doesn't exist!");
            return false;
        }
		
		// The initial set-up
		theURL = window.location.href.replace(window.location.href.split('#')[0],'').split('/').last().replace(/#/,'');
		
		// Check for URL or use the user-supplied active tab
		if (theURL != null)
		{
			if ($(theURL))
			{
				openTab = theURL;
			}
		}
		
		var tabList = Element.descendants(list);
		tabList.each(function(tab)
		{
			// Cycle through each tab
			var toggler = Element.descendants(tab);
			toggler.each(function(theLink)
			{
				// Get the tab ID from the href
				tabID = theLink.getAttribute('href').replace(window.location.href.split('#')[0],'').split('/').last().replace(/#/,'');
						
				if (tabID == openTab)
				{
					// Show the open tab's content
					Element.addClassName(theLink, 'active');
					Element.writeAttribute($(tabID), 'style', 'display: block;');
				} else {
					// Hide the other tab's content
					Element.removeClassName(theLink, 'active');
					Element.writeAttribute($(tabID), 'style', 'display: none;');
				}
				
				// Activate the toggle
				theLink.onclick = function(){
							
					// Reset all tabs and content
					var resetter = Element.descendants(tab);
					resetter.each(function(rLinkCont)
					{
						// Get the tab ID from the href
						rID = rLinkCont.getAttribute('href').replace(window.location.href.split('#')[0],'').split('/').last().replace(/#/,'');
						
						// Deselect all the tabs
						var tabbies = $$('.tab');
						tabbies.each(function(tabbie)
						{
							Element.firstDescendant(tabbie).removeClassName('active');
						});
						
						// Hide all the content
						var contents = $$('.tabcontent');
						contents.each(function(cont)
						{
							Element.writeAttribute($(cont.id), 'style', 'display: none;');
						});
					});
							
					// Set the active tab and content
					var setNew = function() {
						Element.addClassName(theLink, 'active');
						Element.writeAttribute($(rID), 'style', 'display: block;');
					}.defer();
				}
				
			});
		});
	}
});
