////////////////////////////////////
// Jon Suderman - Feb 12, 2009
///////////////////////////////////
var PageTabs = Class.create({
	initialize: function(container){

		// Ensure container exists
		if (!$(container)) { return false; }

		// Ensure there are tabs in this container
		if ($(container).select('span.tab').length < 1) { return false; }

		// Ensure we're not in surf-to-edit
		if (location.href.match(/nterchange/g)) { return false; }

		// Properties
		this.container = $(container);
		this.sections = new Hash();
		this.default_tab = 'default';
		this.tabs_container = 'tabs';
		this.page_title = this.elementToString($(container).down('h1').remove());

		// Make it so
		this.parseTabs();
		this.buildTabs();
		this.observeTabs();
		
	},
	
	
	// Look for span.tab's inside the container and group them together
	parseTabs: function() {
		
		// Set default name for hash
		this.sections.set(this.default_tab,'');

		// Set the current tab as the default name
		current_tab = this.default_tab;
		
		// Each tab contains everything up to the next tab or end of container
		this.container.childElements().each(function(asset){ 

			// This asset is a tab asset
			if (asset.hasClassName('tab')) {					

				// Start a new section named after this tab asset
				current_tab = asset.innerHTML.strip();
				this.sections.set(current_tab,'');


			// This asset is any other kind
			} else {
				
				// Get the contents of this section and add the new contents to it				
				current_tab_contents = this.sections.get(current_tab);
				this.sections.set(current_tab, current_tab_contents + this.elementToString(asset));
			}
		}.bind(this));	
	},


	// Clear the container, print the tab links, reprint all the content inside wrapping div's id'ed as tabs
	buildTabs: function() {
		
		// Clear out container leaving the page title h1 and the tabs ul
		var tabs_container = '<ul id="'+ this.tabs_container +'"></ul>';
		this.container.update(this.page_title + tabs_container);

		// Loop through each key or tab section
		var keys =
		this.sections.keys().sortBy(function(tab_name){return 1-tab_name;}).each(function(tab_name) {
      
			// Get a half-decent id to use			
			var tab_id = tab_name.replace(/&amp;/g,'and');	// replace & with and		
			tab_id = tab_id.replace(/ /g,'-'); 				// replace space with -
			tab_id = tab_id.replace(/\//g,'-');				// replace / with -
			tab_id = tab_id.replace(/\-\-/g,'-');			// reduce double - to single -
			tab_id = tab_id.replace(/[^A-Za-z0-9\-]/g,'');		// strip all non alpha, - characters

			// Add each tab (except for the default, which is really everything before the first real tab)
			if (tab_name!=this.default_tab) {
				$('tabs').update($('tabs').innerHTML+ 
				//'<li><a href="#'+tab_id+'" rel="'+tab_id+'"><span class="tab-text">'+tab_name+'</span><span class="right-corner"/></a></li>' );
				'<li><a href="#'+tab_id+'" rel="'+tab_id+'"><span>'+tab_name+'</span></a></li>' );
			}

			// Create the new tab section
			var tab_section = new Element('div',{ 'id':'tab_'+tab_id, 'class':'tab_section' });	

			// Add this tab section to the container
			this.container.appendChild(tab_section);
			$('tab_'+tab_id).update(this.sections.get(tab_name));
			
		}.bind(this));
		
		// The "default" tab isn't really a tab, so just remove the classname.
		$('tab_'+this.default_tab).removeClassName('tab_section');
	},
	

	observeTabs: function(){
		
		// Set click events for each tab
		$(this.tabs_container).select('a').each(function(a) {
			a.observe('click', this.activeTab.bind(this,a));
		}.bind(this));
		
		// Activate the tab that's in the hash
		if (location.hash != '') {
			$(this.tabs_container).select('a[href$="'+ location.hash +'"]').each(this.activeTab.bind(this));
		}

		// If no tab is active, select the first one
		if ($(this.tabs_container).select('a.active').length<1) {
		  // Not sure why IE builds these backwards and always selects the last tab...
			if (firstTab = $(this.tabs_container).select('a')[0]) {
				this.activeTab(firstTab);
			}
		}
	},
	
	
	activeTab: function(a,event){

		// Hide all sections and unclass all tabs from being active
		$(this.container).select('.tab_section').invoke('hide');
		$(this.tabs_container).select('a').invoke('removeClassName','active');
		
		// Show the section and set the clicked tab as active
		$('tab_'+a.rel).show();
		$(a).addClassName('active');
		
		// Update the URL for any bookmarking
		location.hash = a.rel;
		// console.log(a.rel);
		// Don't the browser scroll up or down to the id
		if (event) { event.stop() }
	},
	
	// Basically an attempt to copy the behaviour of MS's outerhtml method
	elementToString: function(element) {		
		var html = '';
		html += '<' +element.tagName.toLowerCase();	
			
		if (element.readAttribute('id')) {
			html += ' id="' +element.readAttribute('id')+ '"';
		}
		if (element.readAttribute('class')) {
			html += ' class="' +element.readAttribute('class')+ '"';
		}
		if (element.readAttribute('style')) {
			html += ' style="' +element.readAttribute('style')+ '"';
		}
		
		html += '>' + element.innerHTML + '</' +element.tagName.toLowerCase() + '>';		
		return html;
	}	
});




