// 記錄各自的 tab 區塊
var tabAreas = new Array();

function initTabs(areas)
{
	for(var a = 0; a < areas; a++)
	{
		var tabLinks = new Array();
		var contentDivs = new Array();

		// Grab the tab links and content divs from the page
		var tabListItems = document.getElementById('tabs' + a).childNodes;
		
		for ( var i = 0; i < tabListItems.length; i++)
		{
			if (tabListItems[i].nodeName == "LI")
			{
				var tabLink = getFirstChildWithTagName(tabListItems[i], 'A');
				var id = getHash(tabLink.getAttribute('href'));
				tabLinks[id] = tabLink;
				contentDivs[id] = document.getElementById(id);
			}
		}
	
		var area = new Array();
		area[0] = tabLinks;
		area[1] = contentDivs;

		tabAreas[a] = area;
		
		// Assign onclick events to the tab links, and
		// highlight the first tab
		var i = 0;
	
		for ( var id in tabLinks)
		{
			tabLinks[id].onclick = showTab;
			tabLinks[id].onfocus = function()
			{
				this.blur()
			};
			if (i == 0)
				tabLinks[id].className = 'selected';
			i++;
		}
	
		// show the first div
		var i = 0;
		for(var id in contentDivs)
		{
			if(i == 0)
				contentDivs[id].className = 'tabContent show';
			i++;
		}
	} // for(var a = 0; a < areas; a++)
}

function showTab()
{
	var selectedId = getHash(this.getAttribute('href'));
	
	if(selectedId.indexOf("http") >= 0)
	{
		window.open(selectedId);
		return false;
	}

	// 找出此 id 放在哪一組 tab area 中
	for(var area in tabAreas)
	{
		var x = tabAreas[area];

		var tabLinks = x[0];
		var contentDivs = x[1];

		var inThisArea = false;
		// Highlight the selected tab, and dim all others.
		// Also show the selected content div, and hide all others.
		for ( var id in contentDivs)
		{
			if (id == selectedId)
			{
				inThisArea = true;
				break;
			}
		}
		
		// 有找到在此 tab 區
		if(inThisArea)
		{
			for(var id in contentDivs)
			{
				if(contentDivs[id] != null && tabLinks[id] != null)
				{ // 因為 tabs 上可能直接擺另開新視窗的連結而不會有 tab
					if(id == selectedId)
					{
					tabLinks[id].className = 'selected';
					contentDivs[id].className = 'tabContent show';
					}
					else
					{
						tabLinks[id].className = '';
						contentDivs[id].className = 'tabContent hide';
					}
				}
			}
		}
	} 
	// Stop the browser following the link
	return false;
}

function getFirstChildWithTagName(element, tagName)
{
	for ( var i = 0; i < element.childNodes.length; i++)
	{
		if (element.childNodes[i].nodeName == tagName)
			return element.childNodes[i];
	}
}

function getHash(url)
{
	var hashPos = url.lastIndexOf('#');
	return url.substring(hashPos + 1);
}

