/********************************************************************
 *
 * Tools
 * Author: TTI
 * Date:   January 25, 2008
 *
 *******************************************************************/

var ttiTools = new TTITools();

function TTITools()
{
	// ===========================================================
	// Date & Time
	// ===========================================================

	function getFormattedNow() 
	{
		var now = new Date;
		return(getFormattedDateTime(now));
	}
	this.getFormattedNow = getFormattedNow;

	function getFormattedDateTime(date, showSeconds) 
	{
		return(getDayName(date) + ",&nbsp;" + getMonthName(date) + "&nbsp;" + date.getDate() + ",&nbsp;" + getFormattedTime(date, showSeconds));
	}
	this.getFormattedDateTime = getFormattedDateTime;

	function getFormattedDate(date) 
	{
		return(getDayName(date) + ",&nbsp;" + getMonthName(date) + "&nbsp;" + date.getDate());
	}
	this.getFormattedDate = getFormattedDate;

	function getFormattedTime(date, showSeconds, showSuffix) 
	{
		if (showSuffix == undefined)
			showSuffix = true;
		
		var hours = date.getHours();
		if (hours > 12)
			hours -= 12;
		else if (hours == 0)
			hours = 12;
		
		var minutes = date.getMinutes();
		if (minutes < 10)
			minutes = "0" + minutes;

		var returnTime = hours + ":" + minutes
		
		if (showSeconds)
		{
			var seconds = date.getSeconds();
			if (seconds < 10)
				seconds = "0" + seconds;	
			returnTime += ":" + seconds;
		}
		
		if (showSuffix)
		{
			if (date.getHours() > 11) 
				returnTime += "&nbsp;pm"
			else
				returnTime += "&nbsp;am"
		}
		
		return returnTime;
	}
	this.getFormattedTime = getFormattedTime;

	function getDayName(date) 
	{
		var dayName;
		switch(date.getDay()) 
		{
			case 0: dayName = "Sun"; break;
			case 1: dayName = "Mon"; break;
			case 2: dayName = "Tue"; break;
			case 3: dayName = "Wed"; break;
			case 4: dayName = "Thu"; break;
			case 5: dayName = "Fri"; break;
			case 6: dayName = "Sat"; break;
		}
		return(dayName);
	}
	this.getDayName = getDayName;

	function getMonthName(date) 
	{
		var monthName
		switch(date.getMonth())
		{
			case 0: monthName = "Jan"; break;
			case 1: monthName = "Feb"; break;
			case 2: monthName = "Mar"; break;
			case 3: monthName = "Apr"; break;
			case 4: monthName = "May"; break;
			case 5: monthName = "Jun"; break;
			case 6: monthName = "Jul"; break;
			case 7: monthName = "Aug"; break;
			case 8: monthName = "Sep"; break;
			case 9: monthName = "Oct"; break;
			case 10: monthName = "Nov"; break;
			case 11: monthName = "Dec"; break;
		}
		return(monthName);
	}
	this.getMonthName = getMonthName;

	// ===========================================================
	// Cookies
	// ===========================================================

	function setCookie(cookieName, value, expirationDate)  
	{
		if (!expirationDate)
		{
			expirationDate = new Date();
			expirationDate.setYear(3000);
		}
		document.cookie = cookieName + "=" + escape(value) + "; expires=" + expirationDate.toGMTString();
	}
	this.setCookie = setCookie;

	function getCookie(cookieName) 
	{
		var cookie = null;
		cookieName += "=";
		
		if (document.cookie.length > 0) // if there are any cookies
		{ 
			offset = document.cookie.indexOf(cookietName)
			if (offset != -1) // if cookie exists 
			{ 
				offset += cookieName.length
				end = document.cookie.indexOf(";", offset)
				if (end == -1)
					end = document.cookie.length
				cookie = unescape(document.cookie.substring(offset, end))
			}
		}
		return cookie;
	}
	this.getCookie = getCookie;
	
	function deleteCookie(cookieName)
	{
		setCookie(cookieName, "", -1);
	}
	this.deleteCookie = deleteCookie;

	// ===========================================================
	// Miscellaneous
	// ===========================================================

	function getValueFromQueryString(name, defaultValue, targetWindow)
	{
		var queryString
		if (targetWindow)
			queryString =  targetWindow.location.search;
		else
			queryString =  location.search;
		
		if (queryString.charAt(0) == '?')
			queryString = queryString.substring(1);
			
		var keyValuePairs = queryString.split('&');
		for (var i = 0; i < keyValuePairs.length; i++)
		{
			var keyValuePair = keyValuePairs[i].split('=');
			if (keyValuePair.length == 2)
			{
				if (unescape(keyValuePair[0]) == name)
					return unescape(keyValuePair[1]);
			}
		}
		return defaultValue;
	}
	this.getValueFromQueryString = getValueFromQueryString;
	
	function showElement(elementName, theDocument)
	{
		var doc;
		if (theDocument)
			doc = theDocument;
		else
			doc = document;
		doc.getElementById(elementName).style.display = "";
	}
	this.showElement = showElement;
	
	function hideElement(elementName, theDocument)
	{
		var doc;
		if (theDocument)
			doc = theDocument;
		else
			doc = document;
		doc.getElementById(elementName).style.display = "none";
	}
	this.hideElement = hideElement;
	
	function toggleElementVisibility(elementName, theDocument)
	{
		var doc;
		if (theDocument)
			doc = theDocument;
		else
			doc = document;
			
		if (elementIsVisible(elementName, doc))
			hideElement(elementName, doc)
		else
			showElement(elementName, doc);
	}
	this.toggleElementVisibility = toggleElementVisibility;
	
	function elementIsVisible(elementName, theDocument)
	{
		var doc;
		if (theDocument)
			doc = theDocument;
		else
			doc = document;
		return doc.getElementById(elementName).style.display != "none";
	}
	this.elementIsVisible = elementIsVisible;
	
	function setElementVisibility(elementName, visible, theDocument)
	{
		var doc;
		if (theDocument)
			doc = theDocument;
		else
			doc = document;
			
		if (visible)
			showElement(elementName, doc);
		else
			hideElement(elementName, doc);
	}
	this.setElementVisibility = setElementVisibility;
	
	function getFrame(frameName, theWidow)
	{
		var win;
		
		if (theWindow)
			win = theWindow;
		else
			win = window;
		for (var i = 0; i < win.frames.length; i++) 
		{
			if (win.frames[i].name == "guts")
				return win.frames[i];
		}
	}
	this.getFrame = getFrame;
	
	//Return a string suitable for insertion into a cell in a table.  
	function getCellText(originalText)
	{
		var cellText = "";
		if ((originalText != null) && (originalText.length > 0))
			cellText = originalText;
		else
			cellText = "&nbsp;"
		return cellText;
	}
	this.getCellText = getCellText;

	//Replace all but the first row (header row) of a table with the provided rows
	function replaceTableRows(tableHTML, newRowsHtml)
	{
		var trTag = "</TR>";
		if (tableHTML.indexOf(trTag) == -1)
			trTag = trTag.toLowerCase();
			
		var fields = tableHTML.split(trTag);
		var header = fields[0] + trTag;
		var footer = fields[fields.length - 1];
		return header + newRowsHtml + footer;
	}
	this.replaceTableRows = replaceTableRows;

	//Execute the specified function on each item in an associative array
	function forEach(array, fn)
	{
		if (array != null)
		{
			for (var key in array)
			{
//				if (key != "extend") //Needed when using prototype-1.3.1 library
					fn(array[key]);
			}
		}
	}
	this.forEach = forEach;

	//Usefull for associatve arrays for which the length property always returs 0
	function getArrayLength(array)
	{
		var length = 0;
		forEach(array, function () {length++;});
		return length;
	}
	this.getArrayLength = getArrayLength;
	
	var traceWindow;
	showTraceWindow = function()
	{
		if ((this.traceWindow != null) && (!this.traceWindow.closed))
			this.traceWindow.focus();
		else
			this.traceWindow = window.open("/Guts/Trace.htm", 'Trace', "menubar=no, status=no, resizable=yes, scrollbars=yes, width=800, height=400, top=0, left=0");
	}
	this.showTraceWindow = showTraceWindow;
	
	traceWrite = function(text)
	{
		try
		{
			if ((this.traceWindow != null) && (!this.traceWindow.closed))
				this.traceWindow.append(this.getFormattedTime(new Date(), true, false) + " - " + text);
		}
		catch(exception)
		{
		}
	}
	this.traceWrite = traceWrite;

	function beginGetFile(filePath, onSuccessFunction, onFailureFunction)
	{
		var request = GXmlHttp.create();
		var ttiTools = this;
		request.onreadystatechange = function() 
		{
			if (request.readyState == 4) 
			{
				if ((request.status == undefined) || (request.status == 0) || ((request.status >= 200) && (request.status < 300)))
				{
					ttiTools.traceWrite("Received " + filePath);
					if (onSuccessFunction)
						onSuccessFunction(request);
				}
				else
				{
					ttiTools.traceWrite("Unable to download " + filePath + " - " + request.statusText);
					if (onFailureFunction)
						onFailureFunction(request);
				}
			}
		};
		ttiTools.traceWrite("beginGetFile " + filePath);
		request.open('GET', filePath, true);
		request.send(null);
	}
	this.beginGetFile = beginGetFile;	
	
	function getWindowHeight(targetWindow)
	{
		var win;
		if (targetWindow)
			win = targetWindow;
		else
			win = window;

		var winHeight;
		if (win.innerHeight) 
			winHeight = win.innerHeight;
		else if (win.document.documentElement && win.document.documentElement.clientHeight) 
			winHeight = win.document.documentElement.clientHeight;
		else
			winHeight = win.document.body.clientHeight;

		return winHeight;
	}
	this.getWindowHeight = getWindowHeight;
	
	function getWindowWidth(targetWindow)
	{
		var win;
		if (targetWindow)
			win = targetWindow;
		else
			win = window;

		var winWidth;
		if (win.innerWidth) 
			winWidth = win.innerWidth;
		else if (win.document.documentElement && win.document.documentElement.clientWidth) 
			winWidth = win.document.documentElement.clientWidth;
		else
			winWidth = win.document.body.clientWidth;

		return winWidth;
	}
	this.getWindowWidth = getWindowWidth;

	//Returns a shallow clone of the specified object
	function clone(sourceObject)
	{
		var clone = new sourceObject.constructor();
		for (var propertyName in sourceObject)
			clone[propertyName] = sourceObject[propertyName];
		return clone;
	}
	this.clone = clone;
	
	//Insert breaks ("</br>") into a string so that no line exceeds maxLineLength characters	
	//Attempts to break lines on spaces
	function insertLineBreaks(targetString, maxLineLength)
	{
		var brokenString = "";
		var lastCharIndex = 0;

		while(true)
		{
			var charIndex = lastCharIndex + maxLineLength;
			if (charIndex > targetString.length)
			{
				brokenString = append(brokenString, targetString.substring(lastCharIndex, targetString.length));
				break;
			}
			else
			{
				while((targetString.charAt(charIndex) != ' ') && (charIndex > lastCharIndex))
					charIndex--;
				if (charIndex == lastCharIndex)
					charIndex = lastCharIndex + maxLineLength;
				brokenString = append(brokenString, targetString.substring(lastCharIndex, charIndex));
				lastCharIndex = charIndex;
			}
		}
		return brokenString;
		
		function append(brokenString, textToAppend)
		{
			var newString = brokenString;
			if (newString.length > 0)
				newString += "<br/>";
			return newString += textToAppend;
		}
	}	
	this.insertLineBreaks = insertLineBreaks;
	
	//String trimming
	function trimLeft(theString) 
	{
		while (theString.charAt(0) == ' ' || theString.charAt(0) == '\n' || theString.charAt(0) == '\t')
			theString = theString.substring(1, theString.length);
		return theString;
	}
	this.trimLeft = trimLeft;

	function trimRight(theString) 
	{
		while (theString.charAt(theString.length - 1) == ' ' || theString.charAt(theString.length - 1) == '\n' || theString.charAt(theString.length - 1) == '\t')
			theString = theString.substring(0, theString.length - 1);
		return theString;
	}
	this.trimRight = trimRight;

	function trim(theString)
	{
		return trimRight(trimLeft(theString));
	}
	this.trim = trim;
	
	function getSelectedRadioButtonValue(radioButtonArray)
	{
		var value;
		for (var i = 0; i < radioButtonArray.length; i++)
		{
			if (radioButtonArray[i].checked) 
			{
				value = radioButtonArray[i].value;
				break;
			}
		}
		return value;
	}
	this.getSelectedRadioButtonValue = getSelectedRadioButtonValue;
		
	//===================================
	// JSOD
	//===================================
	
	function beginExecuteScript(url, scriptElementId, targetDocument)
	{
		var doc = document;
		if (targetDocument)
			doc = targetDocument;
				
		var requestId = new Date().valueOf();
		url = url.replace("$REQUEST_ID$", requestId);
		
		var elementId = scriptElementId || "JavascriptOnDemand";
		ttiTools.traceWrite("beginExecuteScript " + url + "  elementId=" + elementId);
		var head = doc.getElementsByTagName('head').item(0)
		var scriptElement = doc.getElementById(elementId);
		removeElement(head, scriptElement);
		scriptElement = doc.createElement('script');
		scriptElement.type = "text/javascript";
		scriptElement.id = elementId;
		scriptElement.src = url;
		scriptElement.onreadystatechange = function()
		{
			ttiTools.traceWrite("ReadyStateChanged readyState=" + scriptElement.readyState + "  " + url);
			if (scriptElement.readyState == "loaded")
			{
				removeElement(head, scriptElement);
				ttiTools.traceWrite("Processed " + url);
			}
		}
		scriptElement.onload = function()
		{
			removeElement(head, scriptElement);
			ttiTools.traceWrite("Loaded and processed " + url);
		}
		scriptElement.onerror = function()		
		{
			ttiTools.traceWrite("Error loading " + url);
			removeElement(head, scriptElement);
		}
		head.appendChild(scriptElement);

		function removeElement(head, element)
		{
			try
			{
				if (element)
					head.removeChild(element);
			}
			catch(exception) {/*Do Nothing */}
		}
	}
	this.beginExecuteScript = beginExecuteScript;
}
	
function $(elementId)
{
	return document.getElementById(elementId);
}