//---------------------------------------------------------
// global data
//---------------------------------------------------------
var sCurPage;
var sNewMenu;
var sPageName;
var sPageData;
var bPrintPreviewOn = 1;
var sCurPageRefID;


//---------------------------------------------------------
// functions for connecting header/menubar/footer and main body
//---------------------------------------------------------
function body_onload( sPage, sMenu, sPageRefID, bAutoPrint )
{
	var sTemp;
	
	sCurPage = sPage;
	sNewMenu = sMenu;
	sCurPageRefID = sPageRefID;
	
	// alert("body_onload( ) " + sPage + ": " + sMenu + ": " + bAutoPrint);
	if ( bAutoPrint == 1 ) {
		self.print();
	}

	switch( sPage ) {
	case "Header":
	case "Footer":
	case "Menubar":
		return true;
	}

	switch( sPage ) {
	case "Admin":
	case "About":
	case "LoginDefault":
	case "LostPassword":
	case "Contacts":
	case "SecurityRegisterAttack":
	case "PageExpired":
	case "Header":
	case "Footer":
	case "Menubar":
	case "TermsConditions":
	case "ForceChangePassword":
	case "AdminHome":
		break;
	default:
		check_for_cookie( );
		break;
	}
	
	if ( body_onloadex != null ) {
		body_onloadex( );
	}
	
	if ( sPage == "ChooseLanguage" ) {
		check_lang_onload( );
	}
	
	switch( sPage ) {
	case "Header":
	case "Footer":
	case "Menubar":
	case "PageExpired":
	case "SecurityRegisterAttack":
	case "":
		break;
	case "LoginDefault":
	case "LostPassword":
	case "TermsConditions":
	case "Contacts":
	default:
		if ( parent.frames && parent.frames.tmenubar) {
			//if ( parent.frames.tmenubar.checkupdate ) {
			//	parent.frames.tmenubar.checkupdate( sPage, sMenu );
			//} else {
				setTimeout( 'do_menuupdate( )', 250);
			//}
		} else {
			setTimeout( 'do_menuupdate( )', 250);
		}
		fnUpdateToolbar( sPage, sMenu, sPageRefID );
		window.focus( );
		break;
	}		

	if ( window.sys_error_message && window.sys_error_message.value != "" )
	{
		// alert( "FormErrorAlert" );
		error_popup( window.sys_error_message.value );
		bReturn = true
	}

	// See if a form requires that focus be set to a particular control.
	if ( parent && parent.main && parent.main.set_form_focus )
	{
		set_form_focus();
	}	
	return true;
}

function do_menuupdate ( )
{
	if ( parent.frames && parent.frames.tmenubar) {
		if ( parent.frames.tmenubar.checkupdate ) {
			parent.frames.tmenubar.checkupdate( sCurPage, sNewMenu, sCurPageRefID );
		} else {
			setTimeout( 'do_menuupdate( )', 250);
		}
	} else {
		// alert( "setTimeout-do_menuupdate" );
		setTimeout( 'do_menuupdate( )', 250);
	}
}

//---------------------------------------------------------
// Toolbar and Header communtication - moved from TUtils.asp
//---------------------------------------------------------
function fnUpdateToolbar ( sPage, sMenu, sPageRefID )
{
	var	sTarget;
	
	sTarget = "../forms/header.asp?page=" + sPage + "&menu=" + sMenu + "&pageref=" + sPageRefID;
	// Added a communication mechanism to allow for the toolbar and menubar needing to know
	// if the print link should be available or not.
	if ( parent && parent.main && parent.main.fnIsPrintPreviewOn )
	{
		if ( parent.main.fnIsPrintPreviewOn() == true )
			sTarget = sTarget + "&print=on";
	}		

	// alert("fnUpdateToolbar( ) " + sTarget );
	if ( parent.frames.t_toolbar != null ) {
		parent.frames.t_toolbar.document.location.replace( sTarget );
	}
}

function fnHideToolbar ( bool )
{
	// alert("fnHideToolbar( ) " + bool );
	if ( parent.frames.t_toolbar && parent.frames.t_toolbar.hide_toolbar ) {
		parent.frames.t_toolbar.hide_toolbar( bool );
	}
}

function body_onloadex ( )
{
	// alert( "body_onloadex - base" );
}

//---------------------------------------------------------
// window handling
//---------------------------------------------------------
function new_window ( sTargetUrl, sFolder )
{
	var newWindow; 

	// alert("new_window() " + sTargetUrl + "," + sFolder);
	newWindow = window.open(sFolder+sTargetUrl, null, "status=yes,toolbar=no,menubar=no,location=no");
	return true;
}

function page_window ( sTargetUrl, sFolder, sPager )
{
	var t, newWindow; 
	t =  sTargetUrl.split(".");
	// alert("page_window() " + sTargetUrl + "," + sFolder + "," + sPager + "=" + t[1]);
	
	switch( t[1] ) {
	case "pdf":
		newWindow = window.open(sFolder+sTargetUrl, null, "status=yes,toolbar=no,menubar=no,location=no");
		break;
	case "htm":
	default:
		parent.main.location.href = sPager + sTargetUrl;
		break;
	}
	return true;
}


function frame_redirect ( sTargetUrl )
{
	// alert("frame_redirect: " + sTargetUrl);
	top.location.href = sTargetUrl;
	return true;
}

// ------------------------------------------------------
// helper function to replace the current page
// ------------------------------------------------------
function page_replace ( sTargetUrl )
{
	if ( sTargetUrl == "goback" ) {
		window.history.go(-1);
	} else {
			
		// Need to make sure parent & parent.main exist.
		if ( parent && parent.main ) {
			parent.main.location.replace( sTargetUrl );
		}
		else {
			// Here if in a popup window.
			document.location.replace(sTargetUrl);
		}
	}
	return true;
}

// ------------------------------------------------------
// helper function to go back one page
// ------------------------------------------------------
function page_back ( )
{
	// alert("page_back()");
	// parent.main.history.back(-1); 
	// parent.frames[0].history.back(-1); 
	// window.history.back(-1); 
	//	history.go(-1); 
	
	if ( parent && parent.main ) {
		parent.main.history.go(-1);
	} else {
		history.go(-1);
	}
	return true;
}

// ------------------------------------------------------
// helper function to skip back and replace the original page after a post/commit
// ------------------------------------------------------
function backup_replace ( sTarget )
{
	// alert("backup_replace() " + sTarget);
	if ( parent && parent.frames.tmenubar  ) {
		parent.frames.tmenubar.mb_backup_replace( sTarget );
	} else {
		if ( parent && parent.main ) {
			parent.main.history.go(-1);
			parent.main.location.replace( sTarget );
		} else {
			history.go(-1);
			location.replace( sTarget );
		}
	}
}

// ------------------------------------------------------
// helper function to skip back twice after a post/commit
// ------------------------------------------------------
function double_back ( )
{
	// alert("double_back()");
	if ( parent && parent.frames.tmenubar  ) {
		parent.frames.tmenubar.mb_doubleback( );
	} else {
		if ( parent && parent.main ) {
			parent.main.history.go(-2);
		} else {
			history.go(-2);
		}
	}
}

// window.onfocus=wonfocus; 
function wonfocus( )
{
	sPage = fnGetThisPage( );
	alert("wonfocus() " + sPage);
}

//---------------------------------------------------------
// debugging
//---------------------------------------------------------
function dbtrace ( sLabel, sValue )
{
	if( parent && parent.dbtrace )
		parent.dbtrace( sLabel, sValue );
	else
		alert( sLabel + sValue );
	
}

//---------------------------------------------------------
// image handling utility functions
//---------------------------------------------------------
var iCnt = 0

function window_onload ( )
{
    // alert("window_onload ()")
	if (iCnt < imgArray.length) {
		var loadImage = new Image
		iCnt++  
		// loadImage.onerror = loadImage.onload = DoLoad
		loadImage.src = imgArray[iCnt-1]
	} else
		alert("DoLoad error!")
}

function swapImage(sName,sImage) {
  document.images[sName].src = sImage
}

//---------------------------------------------------------
//
//---------------------------------------------------------
function localSubmit ( f )
{
	//alert("localSubmit()" + f.form.name );
	//alert("localSubmit()" + document.forms[0].name );
	document.forms[f.form.name].submitstring.value=f.value;
	document.forms[f.form.name].printpreview.value = "false";
	f.form.submit();
	return true;
}

//---------------------------------------------------------
// debug function only!
//
//---------------------------------------------------------
function doClick() {
   // Build a string of all the offsets, starting from the
   // clicked element.
   var el = event.srcElement;
   var offset = "Offsets\n";
   while (el != null) {
      offset += "\n" + el.tagName + ":  (" + el.offsetTop +
         ", " + el.offsetLeft + ")";
      el = el.offsetParent;
   }
   offset += "\ntagName: " + document.elementFromPoint(event.x, event.y).tagName;
   offset += "\nid: " + document.elementFromPoint(event.x, event.y).id;
   offset += "\nclassName: " + document.elementFromPoint(event.x, event.y).className;
   offset += "\nname: " + document.elementFromPoint(event.x, event.y).name;
  alert(offset);
}

// document.onclick = doClick;

//---------------------------------------------------------
// print handlers
//---------------------------------------------------------
window.document.onbeforeprint=beforeprint;
window.document.onafterprint=afterprint;
window.onbeforeprint=beforeprint;
window.onafterprint=afterprint;

var	strBackgroundUrl

function beforeprint( )
{
	// alert( "beforeprint:" + document.body.background);
	
	if (document.all.main)	
		main.style.width = "100%";
	if (document.body.background){	
	    strBackgroundUrl = document.body.background;
	    document.body.background = "";
	}
}

function afterprint()
{
	if (document.all.main)	
		main.style.width = "100%";
	if (strBackgroundUrl){	
	    document.body.background = strBackgroundUrl;
	}
}

//---------------------------------------------------------------------
// cookie utilities
//---------------------------------------------------------------------

// Code for these cookie functions from http://www.netkontoret.dk/jscookies.htm
function setCookie(NameOfCookie, value, expiredays) 
{
	// Three variables are used to set the new cookie. 
	// The name of the cookie, the value to be stored,
	// and finaly the number of days till the cookie expires.
	// The first lines in the function converts 
	// the number of days to a valid date.

	  var ExpireDate = new Date ();
	  ExpireDate.setTime(ExpireDate.getTime() + (expiredays * 24 * 3600 * 1000));

	// The next line stores the cookie, simply by assigning 
	// the values to the "document.cookie"-object.
	// Note the date is converted to Greenwich Meantime using
	// the "toGMTstring()"-function.

	  document.cookie = NameOfCookie + "=" + escape(value) + 
	  ((expiredays == null) ? "" : "; expires=" + ExpireDate.toGMTString());
}

function getCookie(NameOfCookie)
{
	// First we check if there is a cookie stored at all.
	// Otherwise the length of document.cookie would be zero.

	  if (document.cookie.length > 0) 
	{ 

	// Second we check if the cookies name is stored in the
	// "document.cookie"-object for the page.

	// Since more than just one cookie can be set on a
	// single page it is possible that our cookie
	// is not present, even though the "document.cookie"-object
	// is not just an empty text.
	// If our cookiename is not present the value -1 is stored
	// in the variable called "begin".

	    begin = document.cookie.indexOf(NameOfCookie+"="); 
	    if (begin != -1)   // Note: != means "is not equal to"
	   { 

	// Our cookie was set. 
	// The value stored in the cookie is returned from the function.

	     begin += NameOfCookie.length+1; 
	      end = document.cookie.indexOf(";", begin);
	      if (end == -1) end = document.cookie.length;
	      return unescape(document.cookie.substring(begin, end));       } 
	  }
	return null;  

	// Our cookie was not set. 
	// The value "null" is returned from the function.
}
 
function check_for_cookie ( )
{
	if (getCookie("hidLogId") == "1")
	{	
		// alert("Logged in");
		return true;
	}
	else
	{
		// alert("Not logged in. sCurPage=" + sCurPage);
		document.location = "../forms/PageExpired.asp?page_name=" + sCurPage;
		
		// -- friendlier error handling, this should take the user back a "re-login" the session.
		// document.location.replace = "../default.asp"
	}		
}

//---------------------------------------------------------
// hideLevel & showLevel AutoMagic!!!
//---------------------------------------------------------
function hideLevel( _levelId)
{
	var thisLevel = document.getElementById( _levelId );
	thisLevel.style.display = "none";
}

function showLevel( _levelId)
{
	var thisLevel = document.getElementById( _levelId );
	// alert("showLevel= " + _levelId + ": " + thisLevel.value);
	if ( thisLevel.style.display == "none")
	{
		thisLevel.style.display = "block";
	}
	else
	{
		hideLevel( _levelId);
	}
}

//---------------------------------------------------------
// miscellany
//---------------------------------------------------------

function doprintpreview ()
{
	if ( parent.frames.tmenubar.clearmenu ) {
		parent.frames.tmenubar.clearmenu( );
	}
	
	//alert("doprintpreview()");
	if ( parent.main.document.forms["documentfrm"].printpreview ) {
		parent.main.document.forms["documentfrm"].printpreview.value = "true";
		parent.main.document.forms["documentfrm"].submitstring.value="";
		parent.main.document.forms["documentfrm"].submit( );
	}
}

function go_back ( )
{
	// alert("go_back()");
	parent.main.history.back(-1); 
	return true;
}

//---------------------------------------------------------
// Forms validation helpers 
//		validateRequiredField(objFormControl, strMessage)
//		validateSelect(objFormControl, strMessage )
//		validateString(objFormControl, strMessage )
//		validateStringAndLength(objFormControl, iMaxLength, strMessage )
//		validateDatePicker(objFormControl, strMessage )
//		validateNumber(objFormControl, strMessage)
//		validateWholeNumber(objFormControl, strMessage)
//		validateFloat (objFormControl, strMessage )
//		validateDecimalField (objFormControl, strMessage)
//---------------------------------------------------------

// Returns true if the field is not blank string
// else prompts user to input non-blank string
// Pass in the form object.
// Indicate whether using AM/PM or military time
function validateTime(timeStr, bIncludeAMPM, bMilitaryTimeOK) 
{
	// Checks if time is in HH:MM:SS AM/PM format.
	// The seconds and AM/PM are optional.
	
	var timePat = /^(\d{1,2}):(\d{2})(:(\d{2}))?(\s?(AM|am|PM|pm))?$/;
	
	var matchArray = timeStr.match(timePat);
	if (matchArray == null) 
	{
	 	alert("Time is not in a valid format.");
		return false;
	}
	
	hour = matchArray[1];
	minute = matchArray[2];
	second = matchArray[4];
	ampm = matchArray[6];
	
	if (second=="") { second = null; }
	if (ampm=="") { ampm = null }
	
	if(bMilitaryTimeOK == false)
	{
		if(hour < 1 || hour > 12)
		{
			alert("Please enter an hour between 1 and 12.");
			return false;
		}
	}
	else if (hour < 0  || hour > 23) 
	{
		alert("Hour must be between 1 and 12. (or 0 and 23 for military time)");
		return false;
	}
	if (hour <= 12 && ampm == null && bIncludeAMPM) 
	{
		if(bMilitaryTimeOK)
		{
			if (confirm("Please indicate which time format you are using.  OK = Standard Time, CANCEL = Military Time")) 
			{
				alert("You must specify AM or PM.");
				return false;
			}
		}
		else
		{
			alert("You must specify AM or PM.");
			return false;
		}
	}
	if  (hour > 12 && ampm != null && bMilitaryTimeOK) 
	{
		alert("You can't specify AM or PM for military time.");
		return false;
	}
	if (minute < 0 || minute > 59) 
	{
		alert ("Minute must be between 0 and 59.");
		return false;
	}
	if (second != null && (second < 0 || second > 59)) 
	{
		alert ("Second must be between 0 and 59.");
		return false;
	}

	return true;
}

function validateRequiredField(objFormControl, strMessage )
{
	var strText = strMessage;
	
	if ( strText == "" ) {
		strText = "Please enter a non-blank value in the required field: " + objFormControl.name;
	}

	if ( isblank(objFormControl.value) ) {
		alert( strText );
		objFormControl.focus();
		return false;
	}
	return true;
}

// Returns true if string contains legal chars.
function validateString(objFormControl, strMessage )
{
	var strText = strMessage;
	var strValue = objFormControl.value;
	
	if ( strText == "" )
	{
		strText = "Illegal character(s) were detected in the input field.";
	}

	if ( isblank(strValue) )
	{
		return true;
	}
	
	// disallow scriptable tags
	if (/(<|%60|&lt;)\s*(script|object|applet|embed|form|img)(\s[^>]*)?(>|%62|&gt;)/i.test(strValue))
	{
		alert( strText );
		objFormControl.focus();
		return false;
	}
		
	// disallow sql injectable commands as well as injection of scripts with =', =", or =; patterns
	if (/(having\s*1\s*=\s*1)|(=\s*')|(=\s*\\')|(=\s*\")|(=\s*\\\")|(=\s*;)/i.test(strValue))
	{
		alert( strText );
		objFormControl.focus();
		return false;
	}
		
	// disallow &xxxx;, javascript, and other encoded characters.
	if (/(&.{1,5};)|javascript|%2e%2e|%2e%2e%2e|%2e%2f|%5c|%7c|%3c|%3e|%21|%22|%7b|%7d|%5e|%5b/i.test(strValue))
	{
		alert( strText );
		objFormControl.focus();
		return false;
	}
	
	// disallow invalid unicode chars.
	//if (/([^\x20-\xD7FF\xE000-\xFFFD\x9\xA\xD])/.test(strValue))
	//{
	//	alert( strText + ": Invalid Unicode" );
	//	objFormControl.focus();
	//	return false;
	//}
	
	return true;
}

// Returns true if string is within expected length and contains legal chars.
function validateStringAndLength(objFormControl, iMaxLength, strMessage )
{
	if ( isblank(objFormControl.value) )
	{
		return true;
	}
	
	//Check length of the string to make sure that it's within specified maximum
	var strValue = new String(objFormControl.value);
	if (strValue.length > iMaxLength)
	{
		if ( strMessage == "" )
		{
			alert("Input field is too long.  It must not be more than " + iMaxLength + " characters long.");
		}
		else
		{
			alert(strMessage);
		}
		objFormControl.focus();
		return false;
	}
	
	return validateString(objFormControl, strMessage);
	
}

// Returns True if drop down has a non-empty selection
// Else displays an Alert message prompting user to make a selection
// Pass in the form object.
function validateSelect(objFormControl, strMessage )
{
	var strText = strMessage;
	
	if ( strText == "" ) {
		strText = "Please select from the drop-down list: " + objFormControl.name;
	}

	if ( objFormControl.options[0].selected && (objFormControl.value == 0) ) {
		alert( strText );
		objFormControl.focus();
		return false;
	}
	return true;
}

// Returns True if the field is a valid positive integer number ( > 0).
// Else displays an Alert message prompting user to enter valid number
// Pass in the form object.
function validateNumber(objFormControl, strMessage )
{
	var strText = strMessage;
	
	if ( strText == "" ) {
		strText = "Please enter a positive number in the field: " + objFormControl.name;
	}
	
	if ( IsWholeNumber(objFormControl.value, 1) != true ) {
		alert( strText );
		objFormControl.focus();
		return false;
	}
	return true;
}

// Returns True if the field is a valid whole number (>= 0).
// Otherwise displays an Alert message prompting user to enter valid number.
function validateWholeNumber(objFormControl, strMessage )
{
	var strText = strMessage;
	
	if ( strText == "" ) {
		strText = "Please enter a positive number in the field: " + objFormControl.name;
	}
	
	if ( IsWholeNumber(objFormControl.value, 0) != true ) {
		alert( strText );
		objFormControl.focus();
		return false;
	}
	return true;
}

// IsWholeNumber
// returns true, if the string represents a whole number >= specified minimum.
//         false otherwise
function IsWholeNumber(strNumber, iMinNumber)
{
	var inputValue;
	var valid = 0;
	var str = strNumber;
	
	if ( str == "" )
	{
		return false;	
	}

	str = cleanUpNumber(str);
	inputValue = parseInt(str);
	if ( inputValue == str )
	{
		if (isNaN(inputValue) == false )
		{
			if ( inputValue >= iMinNumber ) 
			{
				valid = 1;
			} 
		}
	}
	
	if (!valid)
	{
		return false;
	}
	
	return true;
}

// getInteger
// returns integer value, if the string represents a positive integer
//         false otherwise
//
// This function was named "IsNumberValid"
//
function getInteger(strNumber)
{
	var inputValue;
	var valid = 0;
	var str = strNumber;
	
	if ( str == "" )
	{
		return false;	
	}

	str = cleanUpNumber(str);
	inputValue = parseInt(str);
	if ( inputValue == str )
	{
		if (isNaN(inputValue) == false )
		{
			if ( inputValue > 0 ) 
			{
					valid = 1;
			} 
		}
	}
	
	if (!valid)
	{
		return false;
	}
	
	return inputValue;
}

// Right trim the string...
function RTrim(strTrim)
{
	var str = new String(strTrim);
	var i = 0;
	var c = "";
	var endpos = 0
	var whitespace = new String(" \t\n\r");
	
	for (i = str.length; i >= 0 && endpos == 0; i = i - 1) {
		c = str.charAt(i);
		if (whitespace.indexOf(c) == -1)
			endpos = i;
	}

	return str.substring(0,endpos+1);
}

// Left trim the string...
function LTrim(strTrim)
{
	var str = new String(strTrim);
	var i = 0;
	var c = "";
	var iFirstNonWSChar = -1;
	var whitespace = new String(" \t\n\r");
	
	for (i = 0; i < str.length && iFirstNonWSChar == -1; i = i + 1) {
		c = str.charAt(i);
		if (whitespace.indexOf(c) == -1)
			iFirstNonWSChar = i;
	}
	
	// The string is nothing but whitespace characters.
	if ( iFirstNonWSChar == -1 )
		return "";
		
	return str.substr(iFirstNonWSChar,str.length-iFirstNonWSChar);
		
}

function Trim(strTrim)
{
	var str = strTrim;
	str = LTrim(str);
	str = RTrim(str);
	return str;
}

function TrimLeadingZeros(strTrim)
{
	var str = new String(strTrim);
	var i = 0;
	var iFirstNonZeroChar = -1;
	
	for (i = 0; i < str.length && iFirstNonZeroChar == -1; i = i + 1) {
		if ( str.substr(i,1) != "0" )
			iFirstNonZeroChar = i;
	}
	
	// The string is nothing but zeros
	if ( iFirstNonZeroChar == -1 )
		return strTrim;
		
	return str.substr(iFirstNonZeroChar,str.length-iFirstNonZeroChar);
}

function cleanUpNumber(strNumber)
{
	var str = Trim(strNumber);
	str = TrimLeadingZeros(str);
	return str;
}

// Returns false if the field is not valid floating number
// Pass in the form object.
function validateFloat (objFormControl, strMessage )
{
	var strNum = objFormControl.value;
	var strText = strMessage;
	
	if ( strText == "" ) {
		strText = "Please enter a valid number in the field: " + objFormControl.name;
	}

	// Trim whitespace calls go here.
	strNum=Trim(strNum);
	objFormControl.value=strNum;
	
	// alert("validateFloat" + strNum);
	if ( IsNumeric(strNum) )
	{
		// alert("Valid value entered.");
		return true;
	}
	else
	{
		alert( strText );
		objFormControl.focus();
		return false;
	}
}

function validateMoney ( objFormControl, strMessage  )
{
	var	iSigDigits = 13;
	var	iDecimalsAllowed = 2;
	var bValue;

	bValue = validateMoneyEx( objFormControl, iSigDigits, iDecimalsAllowed, strMessage  );
	return bValue;
}

function validateMoneyEx ( objFormControl, iSigDigits, iDecimalsAllowed, strMessage  )
{
	// max vbscript (and ADO) value allowed is parseFloat( "922,337,203,685,477" );
	// we will limit to the user-specificed number of significant digits
	var lTmp;
	var	lMax;
	
	// note: recommended limit is 13.2 or the number will lose precision in the jscript parseFloat( )
	if ( iSigDigits > 13 )
		iSigDigits = 13;
		
	lMax = Math.pow( 10, iSigDigits ) - .01;
	// lMax = parseFloat( "922337203685477.58" ); // or Math.pow( 2, 63 );
	// lTmp = Math.pow( 10, 7 ) - .01;	//lMax / 1000000;
	// alert( "lTmp = " + formatNumber(lMax,"1,234.00") );
	
	if ( validateDecimalField( objFormControl, iDecimalsAllowed, strMessage ) == false )
	{
		return false;
	} else {
		var monAmt = parseFloat( objFormControl.value);
		// alert( "monAmt = " + monAmt );
		if ( monAmt > lMax ) {
			alert( "Value entered: " + formatNumber(monAmt,"1,234.00") + " has exceeded the maximum allowed: " + formatNumber(lMax,"1,234.00") + "\n\n" + strMessage );
			objFormControl.focus();
			return false;
		}
	}
	return true;
}

// ----------------------------
// TODO: the following function is based on validateDecimalField, but will allow up to 4 decimal places
//		but Lauren says we should stick to just 2 for now.
function validateDecimalField (objFormControl, iDecimalsAllowed, strMessage )
{
	var strNum = objFormControl.value;
	var bValid = false;
	var strText = strMessage;
	
	if ( strText == "" ) {
		strText = "Please enter a number, with up to " + iDecimalsAllowed + " decimal places, in the field: " + objFormControl.name;
	}

	// Trim whitespace calls go here.
	strNum=Trim(strNum);
	objFormControl.value=strNum;
	
	// alert("validateDecimalField" + strNum);
	if ( IsNumeric(strNum) )
	{
		// Here if the value is a valid number of some sort.
		// Now see if there is a decimal followed by two numbers.
		var iDecimalIndex = strNum.indexOf(".");
		if ( iDecimalIndex != -1 )
		{
			// Here if a decimal is found in the string.
			// Adding 2 should take us to the end of the string.
			// We know that the entire string is a valid number.
			// Examples:
			//	3.45 - string length is 4, decimal is at 1.
			//	123.75 - string length is 6, decimal is at 3.
			// alert("iDecimalIndex=" + iDecimalIndex + "  strNum.length=" + strNum.length );
			if ( iDecimalIndex + iDecimalsAllowed >= strNum.length - 1 )
			{
				bValid = true;
			}
			else
			{
				bValid = false;
			}
		} else {
			// Here if no decimal so true can be returned.
			bValid = true;
		}
	}

	if ( bValid == true )
	{
		return true;
	}
	else
	{
		alert( strText );
		objFormControl.focus();
		return false;
	}
}

// Utility function returns true if a string containing only whitespace characters
function isblank(s) {
	for (var i = 0; i < s.length; i++) {
		var c = s.charAt(i);
		if ((c != ' ') && (c != '\n') && (c != '\t')) return false
	}
	return true
}

 // Original JavaScript code by Duncan Crombie: dcrombie@chirp.com.au
   // Please acknowledge use of this code by including this header.

   // CONSTANTS
  var separator = ",";  // use comma as 000's separator
  var decpoint = ".";  // use period as decimal point
  var percent = "%";
  var currency = "$";  // use dollar sign for currency

  function formatNumber(number, format) {  // use: formatNumber(number, "format")

    if (number - 0 != number) return null;  // if number is NaN return null
    var useSeparator = format.indexOf(separator) != -1;  // use separators in number
    var usePercent = format.indexOf(percent) != -1;  // convert output to percentage
    var useCurrency = format.indexOf(currency) != -1;  // use currency format
    var isNegative = (number < 0);
    number = Math.abs (number);
    if (usePercent) number *= 100;
    format = strip(format, separator + percent + currency);  // remove key characters
    number = "" + number;  // convert number input to string

     // split input value into LHS and RHS using decpoint as divider
    var dec = number.indexOf(decpoint) != -1;
    var nleftEnd = (dec) ? number.substring(0, number.indexOf(".")) : number;
    var nrightEnd = (dec) ? number.substring(number.indexOf(".") + 1) : "";

     // split format string into LHS and RHS using decpoint as divider
    dec = format.indexOf(decpoint) != -1;
    var sleftEnd = (dec) ? format.substring(0, format.indexOf(".")) : format;
    var srightEnd = (dec) ? format.substring(format.indexOf(".") + 1) : "";

     // adjust decimal places by cropping or adding zeros to LHS of number
    if (srightEnd.length < nrightEnd.length) {
      var nextChar = nrightEnd.charAt(srightEnd.length) - 0;
      nrightEnd = nrightEnd.substring(0, srightEnd.length);
      if (nextChar >= 5) nrightEnd = "" + ((nrightEnd - 0) + 1);  // round up

	// patch provided by Patti Marcoux 1999/08/06
      while (srightEnd.length > nrightEnd.length) {
        nrightEnd = "0" + nrightEnd;
      }

      if (srightEnd.length < nrightEnd.length) {
        nrightEnd = nrightEnd.substring(1);
        nleftEnd = (nleftEnd - 0) + 1;
      }
    } else {
      for (var i=nrightEnd.length; srightEnd.length > nrightEnd.length; i++) {
        if (srightEnd.charAt(i) == "0") nrightEnd += "0";  // append zero to RHS of number
        else break;
      }
    }

     // adjust leading zeros
    sleftEnd = strip(sleftEnd, "#");  // remove hashes from LHS of format
    while (sleftEnd.length > nleftEnd.length) {
      nleftEnd = "0" + nleftEnd;  // prepend zero to LHS of number
    }

    if (useSeparator) nleftEnd = separate(nleftEnd, separator);  // add separator
    var output = nleftEnd + ((nrightEnd != "") ? "." + nrightEnd : "");  // combine parts
    output = ((useCurrency) ? currency : "") + output + ((usePercent) ? percent : "");
    if (isNegative) {
      // patch suggested by Tom Denn 25/4/2001
      output = (useCurrency) ? "(" + output + ")" : "-" + output;
    }
    return output;
  }

  function strip(input, chars) {  // strip all characters in 'chars' from input
    var output = "";  // initialise output string
    for (var i=0; i < input.length; i++)
      if (chars.indexOf(input.charAt(i)) == -1)
        output += input.charAt(i);
    return output;
  }

  function separate(input, separator) {  // format input using 'separator' to mark 000's
    input = "" + input;
    var output = "";  // initialise output string
    for (var i=0; i < input.length; i++) {
      if (i != 0 && (input.length - i) % 3 == 0) output += separator;
      output += input.charAt(i);
    }
    return output;
  }


//---------------------------------------------------------
// helper functions for locating popup windows
//---------------------------------------------------------
function GetHorizontalCenterForWindow(iWindowWidth) {
    if (document.all)
        var xMax = screen.width;
    else
        if (document.layers)
            var xMax = window.outerWidth;
        else
            var xMax = 800;

    var xOffset = (xMax - iWindowWidth)/2;
	return xOffset;
}

function GetVerticalCenterForWindow(iWindowHeight) {
    if (document.all)
        var yMax = screen.height;
    else
        if (document.layers)
            var yMax = window.outerHeight;
        else
            var yMax = 600;

    var yOffset = (yMax - iWindowHeight)/2;
	return yOffset;
}

//---------------------------------------------------------
// helper functions for decoding URLEncoded strings
//---------------------------------------------------------
function URLDecode( strEncoded )
{
  // Replace + with ' '
  // Replace %xx with equivalent character
  var plaintext = "";
  var strResult;
  
  // alert( strEncoded );
  var i = 0;
  while (i < (strEncoded.length)) {
      var ch = strEncoded.charAt(i);
       if (ch == "+") {
           plaintext += " ";
            i++;
       } else if (ch == "%" && strEncoded.charAt(i+1) != "%") {
           plaintext += unescape( strEncoded.substr(i,3) );
            i += 3;
         } else {
            plaintext += ch;
            i++;
         }
    } // while
    
    // if (i < strEncoded.length) {
    //     plaintext += strEncoded.substr(i,strEncoded.length-i);
    // }
    
  strResult = unescape(plaintext);
  return strResult;
};

function DirtyAlert( strMsg )
{
	// alert( strMsg );
}

//---------------------------------------------------------
//	IsFormDirty( oForm ) 
//	- checks to see if any of the form elements are modified from default values
//---------------------------------------------------------
function IsFormDirty (eForm)
{
  // alert("IsFormDirty( )...    ");
  
  var iNumElems = eForm.elements.length;
  for (var i=0; i<iNumElems; i++)
  {
    var eElem = eForm.elements[i];
    if ("text" == eElem.type || "TEXTAREA" == eElem.tagName)
    {
      if (eElem.value != eElem.defaultValue) {
		DirtyAlert(eElem.name + ":" + eElem.value + ":" + eElem.defaultValue );
		return true;
	  }
    }
    else if ("checkbox" == eElem.type || "radio" == eElem.type)
    {
      if (eElem.checked != eElem.defaultChecked)  { 
		DirtyAlert(eElem.name + ":" + eElem.checked + ":" + eElem.defaultChecked );
		return true;
		}
    }
    else if ("SELECT" == eElem.tagName)
    {
      var cOpts = eElem.options;
      var iNumOpts = cOpts.length;
      var index;
      
	  index = eElem.selectedIndex		// index of currently selected item
	  var eOpt = cOpts[index];
	  if (eOpt.selected != eOpt.defaultSelected) { 
		DirtyAlert(eElem.name + ":" + eOpt.selected + ":" + eOpt.defaultSelected ); 
		return true; 
	  }
    }
  }
  return false;
}

//---------------------------------------------------------
//	Menu rollovers for "TabMenu control"
//---------------------------------------------------------
function mtab_over( x ) 
{
	if (x == null)
  		x= window;
	x.event.srcElement.style.cursor = "hand";
	// x.event.srcElement.style.color = "#ff0000";
}

function mtab_out( x ) 
{
	if (x == null)
  		x= window;
	x.event.srcElement.style.cursor = "default";
	// x.event.srcElement.style.color = "#ffffff";
}

// Called when each form's Help button is clicked.
// strTopicDirectory is the relative directory path for the specific help .htm file to display
// strHelpFileName is the .htm file to display.
// Examples:
//	"Billing", "AttendanceNotes.htm"
//	"Matters", "MatterSummary.htm"
//	"", "RootLevelHelpFile.htm"
//
function help_popup( strTopicDirectory, strHelpFilename )
{
	var winPopup;
	var xPos,yPos;
	var strWindowProperties;
	var strURL = "";
	
	// Set these to the width and height for the popup.
	var iWidth=800;		// 680
	var iHeight=600;	// 420

	xPos = GetHorizontalCenterForWindow(iWidth)
	yPos = GetVerticalCenterForWindow(iHeight) - 20;

	strWindowProperties = "screenX=" + xPos + ",left=" + xPos + ",screenY=" + yPos + ",top=" + yPos + ",height=" + iHeight + ",width=" + iWidth + ",toolbar=0,menubar=0,status=0,location=0,scrollbars=1,resizable=1,fullscreen=0";
	
	// Set the URL.
	strURL = "../WebHelp/Jewel.htm#";
	if ( strTopicDirectory != "" )
	{
		strURL=strURL + strTopicDirectory + "/";
	}
	
	strURL=strURL + strHelpFilename;

	// alert ( strURL );
	winPopup = window.open( strURL, "", strWindowProperties);

}

function error_popup( strText )
{
	var winPopup;
	var xPos,yPos;
	var strWindowProperties;
	var strURL = "";
	var strHtml = "<font color='red'>xyzzy.com</font>";

	// Set these to the width and height for the popup.
	var iWidth=600;		// 680
	var iHeight=300;	// 420

	xPos = GetHorizontalCenterForWindow(iWidth)
	yPos = GetVerticalCenterForWindow(iHeight) - 20;

	strWindowProperties = "dialogLeft=" + xPos + ",left=" + xPos + ",screenY=" + yPos + ",top=" + yPos + ",height=" + iHeight + ",width=" + iWidth + ",toolbar=0,menubar=0,status=0,location=0,scrollbars=1,resizable=1,fullscreen=0";

	// Set the URL.
	strURL = "../forms/ErrorForm.asp";

	// alert( strText );
	showModalDialog( strURL, strText, "dialogWidth:15cm; dialogHeight:10cm; dialogTop:5cm; dialogLeft:5cm" );
}

dblclick_counter = 0;
 
function dblclick_filter () { 
	// alert("dblclick_filter=" + dblclick_counter);
	dblclick_counter++; 
	if(dblclick_counter > 1) { 
		// if(dblclick_counter > 2) { return false; } 
		alert('One click is sufficient.\n\n' +
			'The server should respond in a few seconds.\n\n' +
			'Thank you for your co-operation.' );
		dblclick_counter = 0;		// clear counter after warning
		return false; 
	} 
	return true; 
}

//	helper function to check the max number of characters allowed in a <textarea> field
function LimitTextArea (fieldObj, maxChars)
{
	var result = true;
	var nExceeds;
	
	nExceeds = maxChars - fieldObj.value.length;
	if ( nExceeds < 0 ) {
		alert("The text input in field '" + fieldObj.name + "' has exceeded the maximum length of " + maxChars + " characters, by " + (-nExceeds) + " characters.");
		// Truncate content to maxChars
		// fieldObj.value = fieldObj.value.substring(0,maxChars);		
		result = false;
    }
    return result;
}

function round(number,X)
{
	X = (!X ? 2 : X);
	return Math.round(number*Math.pow(10,X))/Math.pow(10,X);
}

function MM_swapImgRestore() 
{ //v3.0
  	var i,x,a=document.MM_sr; 
	for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) 
		x.src=x.oSrc;
}

function MM_preloadImages()
{ //v3.0
  	var d=document; if(d.images)
	{ 
		if(!d.MM_p) d.MM_p=new Array();
    	var i,j=d.MM_p.length,a=MM_preloadImages.arguments; 
		for(i=0; i<a.length; i++)
    		if (a[i].indexOf("#")!=0)
			{ 
				d.MM_p[j]=new Image; 
				d.MM_p[j++].src=a[i];
			}
	}
}
function MM_swapImgRestore() 
{ //v3.0
  	var i,x,a=document.MM_sr; 
	for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) 
		x.src=x.oSrc;
}

function MM_preloadImages() 
{ //v3.0
  	var d=document; 
	if(d.images)
	{ 
		if(!d.MM_p) 
			d.MM_p=new Array();
    	var i,j=d.MM_p.length,a=MM_preloadImages.arguments; 
		for(i=0; i<a.length; i++)
    		if (a[i].indexOf("#")!=0)
			{ 
				d.MM_p[j]=new Image; 
				d.MM_p[j++].src=a[i];
			}
	}
}
function MM_findObj(n, d) 
{ //v4.01
  	var p,i,x;  
  	if(!d) 
		d=document; 
  	if((p=n.indexOf("?"))>0&&parent.frames.length) 
  	{
   	 	d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);
	}
  	if(!(x=d[n])&&d.all) x=d.all[n]; 
		for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  			for(i=0;!x&&d.layers&&i<d.layers.length;i++) 
				x=MM_findObj(n,d.layers[i].document);
  	if(!x && d.getElementById) 
		x=d.getElementById(n); 
	return x;
}
function MM_swapImage() 
{ //v3.0
  	var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; 
	for(i=0;i<(a.length-2);i+=3)
		if ((x=MM_findObj(a[i]))!=null)
		{
			document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];
		}
}

function MM_goToURL() 
{ //v3.0
  var i, args=MM_goToURL.arguments; 
  document.MM_returnValue = false;
  for (i=0; i<(args.length-1); i+=2) eval(args[i]+".location='"+args[i+1]+"'");
}

function page_redirect ( sTargetUrl )
{
	// alert("page_redirect() " + sTargetUrl);
	if ( sTargetUrl == "goback" ) {
		parent.history.go(-1);			//window.history.back(1);
	} else {
		parent.location.href = sTargetUrl;
	}
	return true;
}

function compareDates(from, to) 
{
	if (Date.parse(from.value) <= Date.parse(to.value)) 
	{
		return true;
	}
	else 
	{
		return false;
	}
}

function compareDateStrings(from, to) 
{
	if (Date.parse(from) <= Date.parse(to)) 
	{
		return true;
	}
	else 
	{
		return false;
	}
}

// Compares times for the same day only
function compareTimes(startTime, endTime, bIncludeAMPM, bMilitaryTimeOK) 
{
	// Checks if time is in HH:MM:SS AM/PM format.
	// The seconds and AM/PM are optional.
	var starthour;
	var startminute;
	var startsecond;
	var startampm;
	var endhour;
	var endminute;
	var endsecond;
	var endampm;
	var timePat = /^(\d{1,2}):(\d{2})(:(\d{2}))?(\s?(AM|am|PM|pm))?$/;
	var matchStartArray = startTime.match(timePat);
	var matchEndArray = endTime.match(timePat);
	
	if (matchStartArray == null)
	{
	 	alert("Start time is not in a valid format (HH:MM).");
		return false;
	}
	
	if(matchEndArray == null) 
	{
	 	alert("End time is not in a valid format (HH:MM).");
		return false;
	}
	
	starthour = matchStartArray[1];
	startminute = matchStartArray[2];
	startsecond = matchStartArray[4];
	startampm = matchStartArray[6];
	
	endhour = matchEndArray[1];
	endminute = matchEndArray[2];
	endsecond = matchEndArray[4];
	endampm = matchEndArray[6];
	
	if (startsecond=="") { startsecond = null; }
	if (startampm=="") { startampm = null }
	if (endsecond=="") { endsecond = null; }
	if (endampm=="") { endampm = null }
	
	if(bIncludeAMPM == true)
	{
		if(parseInt(endampm) < parseInt(startampm))
		{
			return false;
		}
	}
	else if(bMilitaryTimeOK == true)
	{
		if(parseInt(endhour) < parseInt(starthour))
		{
			return false;
		}
		else if(parseInt(endhour) == parseInt(starthour))
		{
			if(parseInt(endminute) < parseInt(startminute))
			{
				return false;
			}
			else if(parseInt(startminute)==parseInt(endminute))
			{
				if(parseInt(endsecond) < parseInt(startsecond))
				{
					return false;
				}
			}
		}
	}
	else
	{
		if(parseInt(endhour) < parseInt(starthour))
		{
			return false;
		}
		else if(parseInt(endhour) == parseInt(starthour))
		{
			if(parseInt(endminute) < parseInt(startminute))
			{
				return false;
			}
			else if(parseInt(endminute) == parseInt(startminute))
			{
				if(parseInt(endsecond) < parseInt(startsecond))
				{
					return false;
				}
			}
		}
	}
	

	return true;
}

// Compares two times in 12 hour format that reside on the same day only
function compareTimes12HourSameDay(startTime, iStartTimeAMPM, endTime, iEndTimeAMPM) 
{
	// Checks if time is in HH:MM:SS AM/PM format.
	// The seconds and AM/PM are optional.
	var starthour;
	var startminute;
	var startsecond;
	var startampm;
	var endhour;
	var endminute;
	var endsecond;
	var endampm;
	var timePat = /^(\d{1,2}):(\d{2})(:(\d{2}))?(\s?(AM|am|PM|pm))?$/;
	var matchStartArray = startTime.match(timePat);
	var matchEndArray = endTime.match(timePat);

	if (matchStartArray == null)
	{
	 	alert("Start time is not in a valid format (HH:MM).");
		return false;
	}
	
	if(matchEndArray == null) 
	{
	 	alert("End time is not in a valid format (HH:MM).");
		return false;
	}
	
	starthour = matchStartArray[1];
	startminute = matchStartArray[2];
	startsecond = matchStartArray[4];
	
	endhour = matchEndArray[1];
	endminute = matchEndArray[2];
	endsecond = matchEndArray[4];
	
	if (startsecond=="") { startsecond = null; }
	if (endsecond=="") { endsecond = null; }
	
	
	var nStartHour = parseInt(starthour);
	var nStartMinute = parseInt(startminute);
	var nStartSecond = parseInt(startsecond);
	var nEndHour = parseInt(endhour);
	var nEndMinute = parseInt(endminute);
	var nEndSecond = parseInt(endsecond);
	var nStartTimeAMPM = parseInt(iStartTimeAMPM);
	var nEndTimeAMPM = parseInt(iEndTimeAMPM);
	
	/*
	alert("Start Hour: " + nStartHour + 
		"\nEnd Hour: " + nEndHour +
		"\nStart minute: " + nStartMinute +
		"\nEnd Minute: " + nEndMinute +
		"\nStart Second: " + nStartSecond +
		"\nEnd Second: " + nEndSecond +
		"\nStart AM/PM: " + nStartTimeAMPM +
		"\nEnd AM/PM: " + nEndTimeAMPM);
	*/
	
	if(nEndTimeAMPM == nStartTimeAMPM)
	{
		if(nEndHour < nStartHour)
		{
			if(nStartHour = 12)
			{
				return true;
			}
			else
			{
				return false;
			}
		}
		else if(nEndHour == nStartHour)
		{
			if(nEndMinute < nStartMinute)
			{
				return false;
			}
			else if(nEndMinute == nStartMinute)
			{
				if(nEndSecond < nStartSecond)
				{
					return false;
				}
			}
		}
	}
	else if(nEndTimeAMPM < nStartTimeAMPM)
	{
		return false;
	}
	
	return true;
}
function validateEmail(str) {

		var at="@"
		var dot="."
		var lat=str.indexOf(at)
		var lstr=str.length
		var ldot=str.indexOf(dot)
		if (str.indexOf(at)==-1)
		{
		   alert("Please enter a valid email address (e.g. yourname@yourhost.com).")
		   return false
		}

		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		   alert("Please enter a valid email address (e.g. yourname@yourhost.com).")
		   return false
		}

		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		    alert("Please enter a valid email address (e.g. yourname@yourhost.com).")
		    return false
		}

		 if (str.indexOf(at,(lat+1))!=-1){
		    alert("Please enter a valid email address (e.g. yourname@yourhost.com).")
		    return false
		 }

		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		    alert("Please enter a valid email address (e.g. yourname@yourhost.com).")
		    return false
		 }

		 if (str.indexOf(dot,(lat+2))==-1){
		    alert("Please enter a valid email address (e.g. yourname@yourhost.com).")
		    return false
		 }
		
		 if (str.indexOf(" ")!=-1){
		    alert("Please enter a valid email address (e.g. yourname@yourhost.com).")
		    return false
		 }

 		 return true					
	}
function validatePassword(password, passwordConfirm) 
{
	var invalid = " "; // Invalid character is a space
	var minLength = 8; // Minimum length
	var maxLength = 12; // Maximum length
	var pw1 = password.value;
	var pw2 = passwordConfirm.value;
	// check for a value in both fields.
	if (pw1 == '') 
	{
		alert('Please enter the password.');
		password.focus();
		return false;
	}
	if (pw2 == '') 
	{
		alert('Please confirm the password.');
		passwordConfirm.focus();
		return false;
	}
	// check for minimum length
	if (password.value.length < minLength) 
	{
		alert('Your password must be at least ' + minLength + ' characters long.\n\nPlease re-enter the password.');
		password.focus();
		return false;
	}
	// check for maximum length
	if (password.value.length . maxLength) 
	{
		alert('Your password must be less than ' + maxLength + ' characters long.\n\nPlease re-enter the password.');
		password.focus();
		return false;
	}
	// check for spaces
	if (password.value.indexOf(invalid) > -1) 
	{
		alert("Sorry, spaces are not allowed in the password.");
		password.focus();
		return false;
	}
	else 
	{
		if (pw1 != pw2) 
		{
			alert ("You did not enter the same password in each field.\n\nPlease re-enter the password.");
			password.focus();
			return false;
		}
		else 
		{
			return true;
	  	}
   }
   return false;
}

function validateDecimal ( objFormControl, lMinAmount, lMaxAmount)
{
	// max vbscript (and ADO) value allowed is parseFloat( "922,337,203,685,477" );
	// we will limit to the user-specificed number of significant digits
	var lTmp;
	var	lMax;
	var lMin
	
	if(IsNumeric(objFormControl.value) == false)
	{
		return false;
	}
	
	var number = parseFloat( objFormControl.value);
	var lMin = parseFloat(lMinAmount);
	var lMax = parseFloat(lMaxAmount);
	
	if(number > lMax)
	{
		alert( "Please enter a value less than or equal to " + formatNumber(lMax,"1.00"));
		objFormControl.focus();
		return false;
	}
	else if(number < lMin)
	{
		alert( "Please enter a value greater than equal to or " + formatNumber(lMin,"1.00"));
		objFormControl.focus();
		return false;
	}
	return true;
}
function validateDecimal ( objFormControl, lMinAmount, lMaxAmount, strMessage)
{
	// max vbscript (and ADO) value allowed is parseFloat( "922,337,203,685,477" );
	// we will limit to the user-specificed number of significant digits
	var lTmp;
	var	lMax;
	var lMin
	
	if(IsNumeric(objFormControl.value) == false)
	{
		return false;
	}
	
	var number = parseFloat( objFormControl.value);
	var lMin = parseFloat(lMinAmount);
	var lMax = parseFloat(lMaxAmount);

	if(number > lMax)
	{
		alert( strMessage);
		objFormControl.focus();
		return false;
	}
	else if(number < lMin)
	{
		alert( strMessage);
		objFormControl.focus();
		return false;
	}
	return true;
}
// Makes sure the number is a valid integer or decimal number.
// Only 0-9 and one decimal followed by 0-9 characters are allowed.
function IsNumeric(strNum)
{
	var len= strNum.length;
	var i = 0;
	var ok=true;
	var bDecimalFound = false;
	var bNegativeFound = false;

	if (len==0)
		return false;

	while ( i < len && ok == true )
	{
		ch= strNum.charAt(i);
		// Make sure of the placement of only one negative sign
		if(i==0)
		{
			if ( ch == '-' && bNegativeFound == true)
			{
				return false;
			}
			if ( ch == '-' )
			{
				bNegativeFound = true;
				i++;
				continue;
			}
		}

		// Make sure there's only once decimal point.
		if ( ch == '.' && bDecimalFound == true )
		{
			return false;
		}
		if ( ch == '.' )
		{
			bDecimalFound = true;
			i++;
		}
		else if ('0'<=ch && ch<='9')
		{
			i++;
		}
		else
		{
			ok= false;
		}
	}
	return ok;
}

function validateUSPhoneNumber(objControl) 
{ 
 	var cleanedPhoneNumber = ""; 
 	var phoneNumber;
	var	strError = "Please enter a valid, 10 digit phone number, with area code first. [Example: (123)456-7890]";
	var index = 0;
	var length = objControl.value.length;
 
 	phoneNumber = objControl.value;
	//strip out acceptable non-numeric characters
	 //Walk through the inputted string and collect only number characters, appending them to CleanedString
	 while (index != length) 
	 { 
	  	if (isNaN(parseInt(phoneNumber.charAt(index)))) 
		{ 
		} 
	  	else 
	  	{ 
	  		cleanedPhoneNumber = cleanedPhoneNumber + phoneNumber.charAt(index);
	  	} 
	  	index = index + 1; 
	 }
	 
	 //If CleanedString is exactly 10 digits long, then format it and allow form submission
	 if (cleanedPhoneNumber.length == 10) 
	 { 
	 	cleanedPhoneNumber = 
			"(" + cleanedPhoneNumber.substring(0,3) + ") " + cleanedPhoneNumber.substring(3,6) + 
			"-" + cleanedPhoneNumber.substring(6,10); 
	  	objControl.value = cleanedPhoneNumber;
		return true;
	 }
	 else 
	 { 
	 	//If CleanedString is not 10 digits longs, show an alert and cancel form submission
	  	alert(strError);
	 	return false;
	 } 
	
	return false;
} 

function win_popup( strURL )
{
	var winPopup;
	var xPos,yPos;
	var strWindowProperties;
	
	// Set these to the width and height for the popup.
	var iWidth=800;		// 680
	var iHeight=600;	// 420

	xPos = GetHorizontalCenterForWindow(iWidth)
	yPos = GetVerticalCenterForWindow(iHeight) - 20;

	strWindowProperties = "screenX=" + xPos + ",left=" + xPos + ",screenY=" + yPos + ",top=" + yPos + ",height=" + iHeight + ",width=" + iWidth + ",toolbar=1,menubar=1,status=0,location=0,scrollbars=1,resizable=1,fullscreen=0";
	
	// Set the URL.
	winPopup = window.open( strURL, "", strWindowProperties);
	return winPopup;
}

/**
 * DHTML date validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */
// Declaring valid date character, minimum year and maximum year
var dtCh= "/";
var minYear=2004;
var maxYear=2100;

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

function isDate(dtStr){
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strMonth=dtStr.substring(0,pos1)
	var strDay=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		alert("The date format should be : mm/dd/yyyy")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		alert("Please enter a valid month")
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		alert("Please enter a valid day")
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		alert("Please enter a valid date")
		return false
	}
return true
}

function validateDate(iYear, iMonth, iDay)
{
	var dateStr;
	dateStr = iMonth + "/" + iDay + "/" + iYear;
	if(isDate(dateStr) == false)
	{
		return false;
	}
	else
	{
		return true;
	}
	
	return true;
}
