// Chad, why do we need this line? It stops all $ from working
// jQuery.noConflict();

jQuery('html').addClass('js'); // Prevent the flashy effect on onload 

// $(function()
jQuery(document).ready(function($) {
	// Add tabindex to all elements that could have tabindex on the page
	// following their html markup order
	var  i = 1;
	defaultTab = (typeof(defaultTab) != "undefined")?defaultTab:0;
	$('*').each(function(){
		if (this.tagName == 'A' || this.tagName == 'AREA' || this.tagName == 'BUTTON' || 
			 this.tagName == 'INPUT' || this.tagName == 'OBJECT' || this.tagName == 'SELECT' ||
this.tagName == 'TEXTAREA') {
			this.tabIndex = i++;
		}
	});
			  
	// Show content of this tab
	var switchTab = function(e) {
		var $this = $(this);
		var $container = $this.parent().parent();
		
		e.preventDefault();
		$('> div', $container).hide().filter('.' + this.hash.substr(1)).show();
		$('> h2 a.tabup, > h3 a.tabup', $container).removeClass('tabup');
		$this.addClass('tabup');
	};	
	
	$.fn.addTabs = function() {
		var $container = $(this);
		
		// Recursive for all other sub-container inside this container
		$('> div', $container).each(function(i) {
			$(this).addClass('tab' + i);
			$(this).addTabs();
		});
		
		// Add event to tab links
		$('> h2 a, > h3 a', $container).each(function(i) {
			var $this = $(this);
			$this.attr('href', '#tab' + i);	
			$this.bind("click", switchTab);
			$this.bind("focus", switchTab);
		});		
	
		// Show the default tab
	 	if (arguments.length == 0) {
			$('> h2:eq(0) a, > h3:eq(0) a', $container).click();
		}
		else {
			$thisContainer = $container;
			for (var i = 0; i < arguments.length; i++) {
				$('> h2:eq(' + arguments[i] + ') a, > h3:eq(' + arguments[i] + ') a', $thisContainer).click();
				$thisContainer = $('> .tab' + arguments[i], $thisContainer);
			}
		};	
	};
	
	$.fn.moveTabs = function(parentIndex) {
		var $container = $(this);
		
		// Recursion
		$('> div', $container).each(function(i) {
			$(this).moveTabs();	
		});
		
		// Get the first and last link inside the container
		firstIndx = $('a').index($('a:first', $container));
		lastIndx = $('a').index($('a:last', $container));
	
		// Move all the heading to the top
		$container.prepend('<div class="tempholder"></div>');
				
		$allTabs = $('> h2, > h3', $container);
		
		$allTabs.each(function(i) {
			// Move the tab to the top
			$(this).clone(true).insertBefore($('.tempholder'));
			$(this).remove();
		});
		$('.tempholder').remove();
	};
	
	$('#tabber').addTabs(defaultTab);
	$('#tabber').moveTabs();
	
	$('#tabber-nested').addTabs();
	$('#tabber-nested').moveTabs();
	
});