/*
Copyright 2006-2007 Wellspring Technologies, LLC
All Rights Reserved
Unauthorized Use Prohibited
*/
if(Array.push) {
	//Not in IE5
	Array.prototype.push = function(obj) {
		this[this.length] = obj;
	}
}

//Register object...holds static functions & events as well as a register of active tab controls.
var wsTabControls = new Object();
wsTabControls.addEventTo = function(node, type, fn) {
	if(node.addEventListener) node.addEventListener(type, fn, false);
	else if(node.attachEvent) node.attachEvent('on' + type, fn);
}

//Serves as the event handler for all tabs in the collection
wsTabControls.swapTab = function(event) {
	var node;
	//Grab the node from whatever source the browser allows
	if(!event || !event.nodeName) {
		if(!event) event = window.event;
		node = (event.target)?event.target:event.srcElement;
	} else if(event.nodeName) {
		node = event;
	}
	if(node) {
		//Get the tab itself
		while(node.parentNode && !(node.className.indexOf('tab') == 0 || node.className.indexOf('activeTab') == 0)) {
			node = node.parentNode;
		}
		if(node.className.indexOf('tab') == 0 || node.className.indexOf('activeTab') == 0) {
			if(!node.ddmlButton) ddmlButtonFixHTMLButton(node);
			if(node.ddmlButton && node.ddmlButton.target) {
				if(node.ddmlButton.target.indexOf('http') == 0) {
					//static link
					window.open(node.ddmlButton.target);
				} else {
					//Set a cookie pointing at the current tab
					wsTabControls.createCookie('tabControl:' + node.ddmlButton.containerId + 'Tabs:last', node.ddmlButton.target.replace('Container', ''), 7);
					//Record that something in this tab control has been clicked
					wsTabControls[node.ddmlButton.containerId].clicked = true;
					//Go through all the other tabs in the container and make sure they and their targets are set properly
					var divs = document.getElementById(node.ddmlButton.containerId + 'Tabs').getElementsByTagName('div');
					for(var i = 0; i < divs.length; i ++) {
						if(divs[i].ddmlButton) {
							if(divs[i].className.indexOf('tab') == 0 || divs[i].className.indexOf('activeTab') == 0) {
								divs[i].ddmlButton.className = 'tab';
								divs[i].className = 'tab';
							}
							if(document.getElementById(divs[i].ddmlButton.target)) 
								document.getElementById(divs[i].ddmlButton.target).style.display = (divs[i] == node)?'block':'none';
						}
					}
					node.ddmlButton.className = 'activeTab';
					node.className = 'activeTab';
				}
			}
		}
	}
}

wsTabControls.createCookie = function(name,value,days) {
	var currDomain = window.location.toString();
	currDomain = currDomain.replace(/https?\:\/\//i, '');
	if(currDomain.indexOf('/') > 0) currDomain = currDomain.substr(0, currDomain.indexOf('/'));
	//Strip of the subdomain unless we're on an IP
	var isIP = currDomain.search(/\d+.\d+.\d+\d+/) >= 0;
	if(currDomain.indexOf('.') >= 0 && currDomain.indexOf('.') != currDomain.lastIndexOf('.') && !isIP) 
		currDomain = currDomain.substring(currDomain.indexOf('.') + 1, currDomain.length);
	if(!isIP) currDomain = '.' + currDomain;
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	var newCookie = name + "=" + value + expires + "; path=/;domain=" + currDomain;
	document.cookie = newCookie;
}

wsTabControls.readCookie = function(name) {
	var nameEQ = 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(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

//Actual tab control object.  Replaces divs marked "for=$id" with buttons linked to the target.
//Maintains onclick functions, but cannot move events....than means <div onclick="fn()"> works, but node.addEventListener() doesn't.
function wsTabControl(containerId) {
	if(!wsTabControls[containerId]) {
		wsTabControls[containerId] = this;
		this.container =  document.getElementById(containerId + 'Tabs');
		this.tabs = new Array();
		this.clicked = false;
		var nodes = this.container.getElementsByTagName('div');
		var button;
		var tabCount = 0;
		var contents;
		var buttonElement;
		var currTabName = '';
		var isDefault = false;
		//Figure out our values for determining starting position
		var lastTarget = wsTabControls.readCookie('tabControl:' + containerId + 'Tabs:last');
		var qsRegEx = new RegExp('.*?[?&]' + containerId + '=([^&]*)');
		var location = window.location.toString();
		var querystringValue = (location.search(qsRegEx) >= 0)?location.replace(qsRegEx, '$1'):'';

		//Swap seeded divs for ddmlButtons.  Move any inner text into the new div.
		//Queue up a switch to the current tab(note that it has to be queued because the targets might not exist yet)
		for(var i = nodes.length - 1; i >= 0; i --) {
			if(nodes[i].getAttribute('for') && nodes[i].getAttribute('for') != '' && nodes[i].className != 'clear') {
				//Figure out if the tab is going to be active or not.
				//Use the last-clicked from the cookie, whichever is marked as the default, or what's in the querystring
				//Querystring > cookie > default
				currTabName = nodes[i].getAttribute('for').replace('Container', '');
				isDefault = nodes[i].getAttribute('defaultTab').toLowerCase() == 'true';
				//alert('Name=' + currTabName + '\n\nQSValue=' + querystringValue + '\n\nlastTarget=' + lastTarget + '\n\nisDefault=' + isDefault);
				if(
					querystringValue == currTabName
					|| (querystringValue == '' && lastTarget == currTabName)
					|| (querystringValue == '' && lastTarget == null && isDefault)
				) {
					className = 'activeTab';
					this.queueSwap(nodes[i].getAttribute('for'));
				} else className = 'tab';
				
				//Build the tab
				if(nodes[i].innerText) contents = nodes[i].innerText;
				else if(nodes[i].textContent) contents = nodes[i].textContent;
				else contents = nodes[i].innerHTML;
				button = new ddmlButton(contents, wsTabControls.swapTab, className);
				button.target = nodes[i].getAttribute('for');
				button.containerId = containerId;
				buttonElement = button.getObject();
				if(nodes[i].onclick) wsTabControls.addEventTo(buttonElement, 'click', nodes[i].onclick);
				this.tabs.push(buttonElement);
				tabCount ++;
				nodes[i].parentNode.removeChild(nodes[i]);
			}
		}
		for(var i = this.tabs.length - 1; i >= 0; i --) {
			this.container.appendChild(this.tabs[i]);
			if(this.tabs[i].className == 'activeTab') wsTabControls.swapTab({target:this.tabs[i]});
		}
	}
	this.currNode = null;
}
wsTabControl.prototype.queueSwap = function(id) {
	var controlName = 'wsTabControls.' + this.container.id.replace(/Tabs$/, '');
	var func = 'if (!' + controlName + '.clicked) { window.status = ' + controlName + '.clicked; ' + controlName + '.swapContents(\'' + id + '\'); }';
	
	if(window.attachEvent) window.attachEvent('onload', new Function(func));
	else if(window.addEventListener) window.addEventListener('load', new Function(func), false);
}
wsTabControl.prototype.swapContents = function(id) {
	var node;
	for(var i = 0; i < this.tabs.length; i ++) {
		node = document.getElementById(this.tabs[i].ddmlButton.target);
		if(node) node.style.display = (this.tabs[i].ddmlButton.target == id)?'block':'none';
	}
}

