// Modified from http://www.bobbyvandersluis.com/articles/unobtrusiveshowhide.php
// Cookie functions, modified from http://www.quirksmode.org/js/cookies.html

if (document.getElementById && document.getElementsByTagName && document.createElement) {
	document.write('<style type="text/css" media="all">@import "tabs.css" ; </style>');
	window.onload = initShowHide;
}

function initShowHide() {
	if (document.getElementById && document.getElementsByTagName && document.createTextNode) {
		var myTabs = new Array() ;
		var myCookie = read_cookie_tab('tab') ;
		var toggle = document.getElementById('tabSelector');
		var as = toggle.getElementsByTagName('a');
		hide();
		for( var i = 0; i < as.length; i++ ) {
			myTabs.push( as[i].href.match(/#(\w.+)/)[1] ) ;
			as[i].onclick = function() {
				show(this);
				return false;
			}
		}
	}
	// Check to see if a cookie is set, or else activate first tab by default
	for( var j = 0; j < myTabs.length; j++ ) {
		if( myCookie == myTabs[j] ) {
			show( as[j] ) ;
			return ;
		}
	}
	show( as[0] ) ;
}

function show(s) {
	hide();

	// Erase the current cookie
	erase_cookie_tab('tab');

	var id = s.href.match(/#(\w.+)/)[1];

	// Set a cookie to ensure reload keeps tab focus
	set_cookie_tab('tab',id,1) ;

	document.getElementById(id).style.display = 'block';

	// Try to get a reference to an element with the id 'current' (a previously active tab header)
 	var oldCurrent = document.getElementById('current');

	// If this element exists, remove its ID attribute
	if (oldCurrent) oldCurrent.removeAttribute('id');

	// Add the ID attribute with value 'current' to the newly active tab header (LI element)
	s.parentNode.setAttribute('id', 'current');
}

function hide() {
	var toggleable = document.getElementById('tabbedContent').getElementsByTagName('div');
	for (var i = 0; i < toggleable.length; i++) {
		toggleable[i].style.display = 'none';
	}
}

function set_cookie_tab(name,value,days) {
	if( days ) {
		var date = new Date() ;
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = " ; expires="+date.toGMTString();
	}

	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/" ;
}

function read_cookie_tab( name ) {
	var cookieName = name + "=" ;
	var ca = document.cookie.split( ';' ) ;
	for( var i=0; i<ca.length; i++ ) {
		var c = ca[i];
		while( c.charAt(0)==' ' ) c = c.substring( 1,c.length ) ;
		if( c.indexOf( cookieName ) == 0 ) return c.substring( cookieName.length,c.length ) ;
	}
}

function erase_cookie_tab(name) {
	set_cookie_tab(name,"",-1);
}
