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)
{
	var ctrlName;
	if (sender.id.indexOf("MyValidator1") == -1)
	{
		ctrlName = sender.id.replace("MyValidator2","TextBox1");
	}
	else
	{
		ctrlName = sender.id.replace("MyValidator1","TextBox1");
	}
	var ctrl = document.getElementById(ctrlName)

	var arSpans = document.getElementsByTagName("span");

	for (i=0;i<arSpans.length;i++)
	{	// Find the MyValidator1 associated with oTextBox so we can shut off its display
		if (arSpans[i].controltovalidate == ctrl.id && arSpans[i].id.match(/MyValidator/gi))
		{
			var oValidator = arSpans[i];
			i = arSpans.length;
		}
	}
	var oValidator = sender
	
	// Most of this code is copied from iVantage TimeInput.htc, so the behavior should be much the same...
	var text = ctrl.value;
	if (text == null || text == "")
		text = "";
	else
		{
		if (oValidator.attributes['pm_override'].value == "True")
			{
				text = text.trim()
				/*
				if the last character is a number then we add the 'pm', otherwise we do nothing
				becasue the user has given us the 'am' or 'pm'

				if the entire text is numeric the we check for hours > 12
				if it is not then there is a ':' and we need to see if the characters to the left
				are > 12
				if either condition then we do NOT add PM
				
				Also, if the time starts with 0 (05 for 24 hour time for example) then we add nothing to it
				*/
				if (isDigit(text.substr(text.length - 1 ,1)))
				{	
					if (isNaN(text))
					{
						pos = text.search(/:/i)
						if (text.substr(0,pos) <= 12 && text.substr(0,1) != 0)
							text += "pm"
					}
					else
					{
						if (parseInt(text) <= 12)
							text += "pm"
					}
				}
				text = text.trim() + "X"; // X is an end of input marker for the loop.
			}
		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)
	{
		if (oValidator.attributes['display'].value  == 'None')	
		{
		ctrl.style.color= "red"
		ctrl.style.fontWeight="bold";
		ctrl.title = "Invalid time";
		}
		return false;	
	}
	else
	{
		if (oValidator.attributes['display'].value  == 'None')	
		{
			ctrl.style.color= ""
			ctrl.style.fontWeight="";
			ctrl.title = "";
		}
			
		if (text.length > 0)
		{
			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
			ctrl.value = time.toLocaleTimeString().replace(":00 "," "); //drop secs.
		}
		return true;	
	}
}

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(sender)
{
	// Calls AJAX process to format date
	var dDateVal;
	var ctrlName;
	if (sender.id.indexOf("MyValidator1") == -1)
	{
		ctrlName = sender.id.replace("MyValidator2","TextBox1");
	}
	else
	{
		ctrlName = sender.id.replace("MyValidator1","TextBox1");
	}
	var ctrl = document.getElementById(ctrlName)
	if (ctrl.value == "")
	{
		return true
	}
	
	var arSpans = document.getElementsByTagName("span");
	for (i=0;i<arSpans.length;i++)
	{	// Find the DateExpressionValidator associated with TextBox so we can shut off its display if necessary
		if (arSpans[i].controltovalidate == ctrl.id && arSpans[i].id.match(/MyValidator/gi))
		{
			var oValidator = arSpans[i];
			i = arSpans.length;
		}
	}
	var oValidator = sender
	dDateVal = runAJAXProcess("/Common/AjaxFunctions.aspx?Func=FormatDate&sDate=" + ctrl.value)
	if (dDateVal != "INVALID")
	{
		ctrl.value = dDateVal;

		if (oValidator.attributes['display'].value == 'None')	
		{
			ctrl.style.color = ""
			ctrl.style.fontWeight = "";
			ctrl.title = "";
		}
		return true;
	}
	else
	{
		if (oValidator.attributes['display'].value  == 'None')	
		{
			ctrl.style.color = "red"
			ctrl.style.fontWeight = "bold";
			ctrl.title = "Invalid date";
		}
		return false;
	}
}

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;
}