﻿var activeTab = null; // Holds the active tab
// Set up the tab event listeners/handlers
function initTabTable() {
	// This is the row the tabs are on
	var row = byId('tabbedTable').rows[1];
	// Loop over the tabs
	for(var i = 0; i < 4; i ++) {
		// Add listeners to the tabs
		addListener(row.cells[i], 'click', switchTab);
		
		// Set the active tab, and remove its listener
		if(row.cells[i].id == 'activeTab') {
			activeTab = row.cells[i];
			removeListener(activeTab, 'click', switchTab);
		}
	}
	row = null;
}
// Event handler for the tabs click, to switch to another tab
function switchTab(evt) {
	// IE does not pass in the event object, but others do
	evt = (typeof evt == 'undefined') ? window.event : evt;
	// Clear the active id from the current tab
	activeTab.id = '';
	// Add the listener back to this tab
	addListener(activeTab, 'click', switchTab);
	// Change the active tab to the new tab
	activeTab = (document.all) ? evt.srcElement : evt.target;
	activeTab.id = 'activeTab';
	// Remove the listener from the new active tab
	removeListener(activeTab, 'click', switchTab);
	// Display the content for the new active tab
	showContent();
}
// Switch the active content based on the active tab index
function showContent() {
	var index = getCellIndex(activeTab);
	var parent = byId('displayContent');
	var children = parent.getElementsByTagName('div');
	// Remove the current active contents id, making it inactive
	byId('activeContent').id = '';
	// Set the content block identified by the tab index as active
	children[index].id = 'activeContent';
}
// Returns the index of the newly active tab
function getCellIndex(cell) {
	// Loops over the tabs to find the index
	for(var i = 0; i < cell.parentNode.cells.length; i ++) {
		if(cell.parentNode.cells[i] == cell) {
			return i;
		}
	}
	// If the tabs stop working, check here first
	return false;
}
// Shorten function, makes for less typing
function byId(id) {
	return document.getElementById(id);
}
// Simple cross-browser adding of event listener
function addListener(obj, type, func) {
	if(document.all) {
		type = 'on' + type;
		obj.attachEvent(type, func);
	} else {
		obj.addEventListener(type, func, false);
	}
}
// Simple cross-browser removing of event listener
function removeListener(obj, type, func) {
	if(document.all) {
		type = 'on' + type;
		obj.detachEvent(type, func);
	} else {
		obj.removeEventListener(type, func, false);
	}
}
