// (C) 2009 Sven Latham <sven@svenlatham.com>
// Yep, I know it's not perfect "but it works"
// Unless it hasn't worked for you, in which case, please let me know ;)

var tabControl = null;
var tabContentContainer = null;

function rearrangeDom() {
	// Get all dynamicTab content boxes
	var allDivs = tabControl.getElementsByTagName("div");
	var movestack = new Array();
	for (var i=0;i<allDivs.length; i++) {
		if (allDivs[i].className.indexOf('tabcontent') > -1) {
			// Move this to the tab container
			movestack[movestack.length] = allDivs[i];
		}
	}
	
	for (var i=0;i<movestack.length;i++) {	
			tabContentContainer.appendChild(movestack[i].cloneNode(true));	
			movestack[i].parentNode.removeChild(movestack[i]);
	}
	

}


function attachEventsToTabs() {
	// Get all the tabs in this tab control
	var allTabs = tabControl.getElementsByTagName("h2");
	for (var i=0;i<allTabs.length; i++) {
		if (allTabs[i].firstChild.tagName=='A') {
			allTabs[i].firstChild.onclick=function() { activateTab(this.name); return false; }
		}		
	}
}

function activateTab(item) {
	// Make sure all the other tabs go away
	var allContent = tabContentContainer.getElementsByTagName("div");
	var showItem = "content-"+item;
	var foundIt = false;
	for (var i=0;i<allContent.length; i++) {
		if (allContent[i].className == "tabcontent") {
			allContent[i].style.display = (allContent[i].id == showItem ? "block":"none");
			if (allContent[i].id == showItem) { foundIt = true; }
		}
	}
	
	var allTabs = tabControl.getElementsByTagName("div");
	for (var i=0;i<allTabs.length; i++) {
		if (allTabs[i].className.indexOf("outer") > -1) {
			allTabs[i].className = (allTabs[i].firstChild.firstChild.name == item?"outer active":"outer");
		}
	}
	return foundIt;
}


function initialiseDynamicTabs() {
	tabControl = document.getElementById("dynamicTabControl");
	tabContentContainer = document.getElementById("dynamicTabContent");
	if (!tabControl) {
		alert("Could not initialise tab control");
		return false;
	}
	rearrangeDom();
	attachEventsToTabs();
	
	// If there is a hashtag, use this to determine the first node
	if (document.location.href) {
		defaultTag = document.location.href.replace(/[^#]+#/,'');
	} else {
		defaultTag = ''; // We'll find the first one!
	}
	
	var foundTag = activateTab(defaultTag);
	if (!foundTag) {
		// Go highlight the default tag!
		var allTabs = tabControl.getElementsByTagName("h2");
		if (allTabs && allTabs.length > 0) {
			var firstTab = allTabs[0].firstChild.name;
			activateTab(firstTab);
		}
	}
	
		
}









