var oldOpenTab=''

/**
 * @short Opens the given tab
 *
 * calls the custom function openTab_<tabname>(). For example:
 *   openTab_add_followup().
 */
openTab=function(tab){
	if (oldOpenTab){
		var oldtab=$(oldOpenTab+'tab')
		//insertSiblingNodesAfter($(oldOpenTab),oldtab)
		oldtab.className='hiddentab'
		$(oldOpenTab).className='hiddentablabel'
	}
	var cn=tab.id
	oldOpenTab=cn

	tab.className='currenttablabel'
	tab=$(cn+'tab')
	tab.className='showntab'
	insertSiblingNodesAfter($('brtabs'),BR({'id':'brtabs_replace'}))
	swapDOM($('brtabs_replace'), tab)

	// custom function to be  called when a tab is opened.
	try{
		eval('openTab_'+cn+'()')
	}
	catch(e){
	}
}

/**
 * @short hides tabs, and prepares to unhide them.
 */
doTabs = function(){
	if (print_mode)
		return;
	tabs=getElementsByTagAndClassName('div','tab');
	if (tabs.length==0)
		return;
	forEach(tabs,function(tab){
		tab.className='hiddentab'
		var el=getFirstElementByTagAndClassName('*',null,tab)
		if (el)
			el.style.clear='both'
	})
	insertSiblingNodesAfter(tabs[tabs.length-1],BR({'id':'brtabs'}))
	tabs=getElementsByTagAndClassName('h2','tablabel');
	forEach(tabs,function(tab){
		aa=A({'href':'#'+tab.id},tab.textContent || tab.innerText || "Unknown" )
		replaceChildNodes(tab,aa)
		tab.className='hiddentablabel'
		connect(tab,'onclick',function(e){ openTab(e.src()) })
		connect(aa,'onfocus',function(e){ openTab(e.parentNode.src()) })
	})

	// open a tab.
	try{
		h=window.location.hash
		openTab($(h.substring(1,h.length))) // force at location
	}
	catch(e){
		try{
			openTab($($('opentab').value)) // use a hidden label
		}
		catch(e){
			openTab(tabs[0]) // just open the first
		}
	}
}

addLoadEvent(doTabs)
