function formatDate(oTextBox)
{
	// Dates entered with periods as the delimiter (mm.dd.yy) pass the .Net date validator but aren't valid in the JScript Date object
	var dateEntered = oTextBox.value.replace(/\./g, "-"); 
	dateEntered = dateEntered.replace(/\-/g, "/"); // Convert dashes to slashes
	var yearEntered = dateEntered.split("/")[2];
	dateEntered = new Date(dateEntered)
	if (dateEntered.toDateString() != "NaN")
	{
		// If the year is entered as two digits and the calculated date is more than 80 years old, add 100 years to it
		 var calculatedDate = new Date((dateEntered.getMonth() + 1) + "/" + dateEntered.getDate() + "/" + dateEntered.getFullYear());
		 if (yearEntered.length == 2 && (new Date().getFullYear() - calculatedDate.getFullYear()) > 80)
			calculatedDate = new Date((dateEntered.getMonth() + 1) + "/" + dateEntered.getDate() + "/" + (dateEntered.getFullYear() + 100));
		 oTextBox.value = (calculatedDate.getMonth() + 1) + "/" + calculatedDate.getDate() + "/" + calculatedDate.getFullYear();
	}
}

function formatTime(sender, args)
{
	// Called from the ivDataEntryTimeTextBox custom validator; hence the (sender, args) parameters.
	// Most of this code is copied from iVantage TimeInput.htc, so the behavior should be much the same...
	var ctrlName = sender.id.replace("CustomValidator1","TextBox1");
	var text = document.all(ctrlName).value;
	if (text == null)
		text = "";
	else
		text = text.trim() + "X"; // X is an end of input marker for the loop.

	// Parse the time.
	var c = "", lastc, i;
	var h = null, m = null, s = null, ms = null, num = null;
	var hack = false;
	
	if (text.substr(0, 1) == "0")
	{
		// We need a hack for 3 or 4 digit times that begin with 0 (i.e. 12 am).
		// Given the input 013 or 0013, our algorithm will interpret
		// it as 13--that is, 1 pm.  What we do is change the 0
		// to a 1 (giving 113 or 1013) and then change it back.
		if (isDigit(text.substr(1, 1)) && isDigit(text.substr(2, 1)))
		{
			hack = true;
			text = "1" + text.substr(1);
		}
	}
	
	for (i = 0; i < text.length; i++)
	{
		lastc = c;
		c = text.substr(i, 1);
		if (isDigit(c))
		{
			// Digit.
			if (num == null)
				num = parseInt(c);
			else if (num < 10000)
				num = num * 10 + parseInt(c);
			else
				break;
		}
		else
		{
			// Move num into h/m/s/ms.
			if (h == null)
			{
				if (num == null) break;
				if (num < 100)
					h = num;
				else
				{
					h = Math.floor(num / 100);
					m = num % 100;
				}
				num = null;
				if (h > 23 || m > 59) break;
			}
			else if (m == null)
			{
				if (num == null) break;
				if (num < 60) m = num;
				else break;
				num = null;
			}
			else if (s == null)
			{
				if (num == null) break;
				if (num < 60) s = num;
				else break;
				num = null;
			}
			else if (ms == null)
			{
				if (num == null) break;
				if (num < 1000) ms = num;
				else break;
				num = null;
			}
			else if (num != null) 
				break;
			
			if (c == ":")
			{
				// Preceding character must be digit and s must not be populated.
				if (!isDigit(lastc) || s != null) break;
			}	
			else if (c == ".")
			{
				// ms separator.  Preceding character must be a digit.
				if (!isDigit(lastc) || s == null || ms != null) break;
			}
			else if (c == " ")
			{
				// AM/PM separator.  Preceding character must be a digit or space.
				if ((lastc != " " && !isDigit(lastc)) || h == null) break;
				if (m == null) m = 0;
				if (s == null) s = 0;
				if (ms == null) ms = 0;
			}
			else if (c == "a" || c == "A")
			{
				// Preceding character must be digit or space or period.
				if ((lastc != " " && lastc != "." && !isDigit(lastc)) || h == null || h > 12) break;
				if (h == 12) h = 0;
				if (m == null) m = 0;
				if (s == null) s = 0;
				if (ms == null) ms = 0;
			}
			else if (c == "p" || c == "P")
			{
				// Preceding character must be digit or space or period.
				if ((lastc != " " && lastc != "." && !isDigit(lastc)) || h == null || h == 0 || h > 12) break;
				if (h < 12) h += 12; // Convert to 24-hour format.
				if (m == null) m = 0;
				if (s == null) s = 0;
				if (ms == null) ms = 0;
			}
			else if (c == "m" || c == "M")
			{
				// Preceding character must be "a" or "p".
				if (lastc != "a" && lastc != "A" && lastc != "p" && lastc != "P") break;
			}
			else if (c == "X" && i == text.length - 1) { } // End of input.
			else break;
		}
	}
	
	if (i < text.length)
	{
		args.IsValid = false;
	}
	else
	{
		args.IsValid = true;
		if (hack && h == 1) h = 0;
		else if (hack && h == 10) h = 0;
		var time = new Date(1900, 0, 1, h, m, 0, 0); // drop secs and millisecs
		document.all(ctrlName).value = time.toLocaleTimeString().replace(":00 "," "); //drop secs.
	}
}

function isDigit(c)
{
	return (c >= "0" && c <= "9");
}

function formatNumber(oTextBox, DecimalPlaces)
{
	DecimalPlaces = parseInt(DecimalPlaces);
	var amount = oTextBox.value;
	if (amount != "")
	{
		amount -= 0;
		var scale= Math.pow(10,DecimalPlaces);
		if (! isNaN(amount))
		{
			amount = (Math.round(amount*scale))/scale + (1/scale/100) ;
			var sAmount = amount.toString();
			if (DecimalPlaces == 0)
				oTextBox.value = sAmount.substr(0,sAmount.indexOf('.') + DecimalPlaces);
			else
				oTextBox.value = sAmount.substr(0,sAmount.indexOf('.') + DecimalPlaces + 1);
		}
	}
}
function toggleNextRowDisplay(oImage,CourseCode)
{
	if (event.srcElement.tagName.toLowerCase() == 'td')
		oImage = event.srcElement.firstChild;
	var sContractImageName = "contract.gif";
	var sExpandImageName = "expand.gif";
	var sImagePath = oImage.src.substring(0, oImage.src.lastIndexOf("/"));
	var sImageName = oImage.src.substr(oImage.src.lastIndexOf("/")+1);
	if (oImage.parentElement.parentElement.parentElement.parentElement.nextSibling.nextSibling.style.display=="none")
	{
		oImage.parentElement.parentElement.parentElement.parentElement.nextSibling.nextSibling.style.display = "";
		oImage.src = sImagePath + "/contract.gif";
		oImage.title = "Hide Details";
		oImage.parentElement.parentElement.parentElement.parentElement.nextSibling.firstChild.style.display = "none";
	}
	else
	{
		oImage.parentElement.parentElement.parentElement.parentElement.nextSibling.nextSibling.style.display = "none";
		oImage.src = sImagePath + "/expand.gif";
		oImage.title = "Show Details";
		oImage.parentElement.parentElement.parentElement.parentElement.nextSibling.firstChild.style.display = "";
	
	}
}

function getCookieData(name) 
{
	name = name.replace(/\=/g, "_");
//		alert("Getting cookie: " + name);
	var start = document.cookie.indexOf(name+"=");
	var len = start+name.length+1;
	if ((!start) && (name != document.cookie.substring(0,name.length))) return null;
	if (start == -1) return null;
	var end = document.cookie.indexOf(";",len);
	if (end == -1) end = document.cookie.length;
//		alert("Cookie: " + unescape(document.cookie.substring(len,end)));
	return unescape(document.cookie.substring(len,end));
}

function setCookieData(name, value, expires, path, domain, secure) 
{
	name = name.replace(/\=/g, "_");
//		alert("Setting cookie " + name + " to " + value);
	document.cookie = name + "=" +escape(value) +
		( (expires) ? ";expires=" + expires.toGMTString() : "") +
		( (path) ? ";path=" + path : "") + 
		( (domain) ? ";domain=" + domain : "") +
		( (secure) ? ";secure" : "");
}

String.prototype.trim = function () { 
	return this.replace(/\s*/, '').replace(/\s*$/, '');
}

String.prototype.escape = function () { return window.escape(this); }

String.prototype.unescape = function() { return window.unescape(this); }

function ShowHelp(appRoot, helpFileName)
{
	window.open(appRoot + "/Help/" + helpFileName, 'Connect', 'menubar=no, toolbar=no, scrollbars=yes, resizable=yes');
}

function DisplayCalendar(controlName)
{
	var arSpans = document.getElementsByTagName("span");

	for (i=0;i<arSpans.length;i++)
	{	// Find any validators associated with controlName and hide them
		if (arSpans[i].controltovalidate == controlName && arSpans[i].id.match(/.*Validator/gi))
		{
			arSpans[i].style.display="none";
		}
	}

	var windowOptions = 'height=180,width=235,left=200,top=150'
	var textBox = document.forms[0].elements[controlName]

	var controlDate = new Date(textBox.value).toDateString();
	var TestControlDate = new Date(controlDate)
	if (TestControlDate.toDateString() == "NaN" || controlDate == ""  || controlDate == "Invalid Date") {
		controlDate = "";
		textBox.value = "";
	} 

	var url = getPathRoot() + '/Common/ivDataEntryCalendar.aspx?ControlDate=' + controlDate + '&FormName=' + document.forms[0].name + '&ControlName=' + controlName;
	var DateWindow=window.open(url,'ivDataEntryDate',windowOptions);
	DateWindow.focus();
}

function getPathRoot()
{
	var s = location.pathname;
	if (s.substr(0, 1) != "/") s = "/" + s;
	var nPos = s.indexOf("/", 1);
	return (s.substr(0, nPos));
}

function displayMessage(header,msg,code)
{
	var windowOptions = 'height=450,width=450,left=200,top=150,resizable=yes,scrollbars=yes'
	var url = getPathRoot() + '/Common/ivDataEntryMessage.aspx?Header=' + header + '&Message=' + msg + '&Code=' + code;
	var MessageWindow=window.open(url,'Message',windowOptions);
	MessageWindow.focus();
}

function formatAjaxDate(oTextBox)
{
	// Calls AJAX process to format date
	var dDateVal
	var arSpans = document.getElementsByTagName("span");

	for (i=0;i<arSpans.length;i++)
	{	// Find the DateExpressionValidator associated with oTextBox so we can shut off its display
		if (arSpans[i].controltovalidate == oTextBox.id && arSpans[i].id.match(/DateExpressionValidator/gi))
		{
			var oValidator = arSpans[i];
			i = arSpans.length;
		}
	}
	dDateVal = runAJAXProcess("/Common/AjaxFunctions.aspx?Func=FormatDate&sDate=" + oTextBox.value)
	if (dDateVal != "INVALID")
	{
		oTextBox.value = dDateVal;
		oValidator.style.display = "none";  // Hide regular expression validator error message
	}
	else
	{
		oValidator.innerHTML = "Invalid date format";
		oValidator.style.display = "";
	}
}

function runAJAXProcess(url)
{
	g_req = createXMLHTTPConduit();
	var url = getPathRoot() + url;
	if(g_req != null)
	{
		g_req.open("GET", url, false); // 'false' means call it synchronously -- wait for the ASP page to finish
		g_req.send(null);
		if (g_req.status == 200)
		{
			return g_req.responseText;
		}
		else if (g_req.status == 500)
		{
			// Internal Server Error -- show entire contents of error in a pop-up
			var errorText = "<span style='font-family: arial; font-size: x-small; font-weight: bold;'>Error encountered by runAJAXProcess<br><span style='font-size: small'>" + url + "</span></span><br><br>"
			errorText += g_req.responseText;
			var errorWin;
			// Create a new window and display the error
			errorWin = window.open('', 'errorWin');
			errorWin.document.body.innerHTML = errorText;
			errorWin.focus();
		}
	}
}

function createXMLHTTPConduit()
{
	//This function creates an XMLHTTP object to be used in AJAX-type operations
	var oXMLHTTP;
	try
	{
		oXMLHTTP = new ActiveXObject("Msxml2.XMLHTTP");
	}
	catch(e)
	{
		try
		{
			oXMLHTTP = new ActiveXObject("Microsoft.XMLHTTP");
		}
		catch(oc)
		{
			oXMLHTTP = null;
		}
	}

	if(!oXMLHTTP && typeof XMLHttpRequest != "undefined")
	{
		oXMLHTTP = new XMLHttpRequest();
	}
	return oXMLHTTP;
}