
/*******************************************************************************
FILE: RegExpValidate.js

AUTHOR:			Karen Gayda
MODIFIED BY:	Adam Tice - atice@aesoponline.com

  VALIDATION FUNCTIONS:

  validateCurrency	- checks for valid currency format
  validateTime		- checks for valid 12 hour time
  validateState		-  checks for valid state abbreviation  
  validateSSN		- checks format of social security number
  validateEmail		- checks format of email address
  validateUSPhone	- checks format of US phone number
  validateNumeric	- checks for valid numeric value
  validateInteger	- checks for valid integer value
  validateNotEmpty	- checks for blank form field
  validateZip		- checks for valid US zip code
  validateDate		- checks for valid date in US format
  validateValue		- checks a string against supplied pattern
  validateRangeInt	- first checks for a valid integer value, then compares against min and max values
  
  FORMAT FUNCTIONS:
  
  rightTrim			- removes trailing spaces from a string
  leftTrim			- removes leading spaces from a string
  trimAll			- removes leading and trailing spaces from a string
  removeCurrency	- removes currency formatting characters (), $ 
  addCurrency		- inserts currency formatting characters
  removeCommas		- removes comma separators from a number
  addCommas			- adds comma separators to a number
  removeCharacters	- removes characters from a string that match passed pattern
*******************************************************************************/


function checkForm(theForm){// return true if all is well
	if (typeof(Date.format) == "undefined")
	{
		Date.format = Date.shortFormat
		if (Date.format.indexOf("MM") < 0) Date.format = Date.format.replace("M", "MM");
		if (Date.format.indexOf("dd") < 0) Date.format = Date.format.replace("d", "dd");
	}
	var elArr = theForm.elements; // get all elements of the form into array
	var patType = 0;
	var valid = true;
	var fields = "";
	//alert(elArr.length)
	for(var i=0; i < elArr.length; i++)
		with(elArr[i]){ // for each element of the form...
		{
//			alert("validating field: " + elArr[i].getAttribute("name"));
			 //don't validate disabled elements
			if (elArr[i].getAttribute("disabled") ||
				elArr[i].disabled ||
				!isVisible(elArr[i])){}
			else{
			
				var valid = true
				var req = elArr[i].getAttribute("required");
				//Causing mac IE to change select boxes by -1
				//elArr[i].value = trimAll( elArr[i].value )			
				if (req && trimAll(value)=='') 
				{
					displayRequiredMessage(elArr[i]);
					setFocus(elArr[i]);
					return false;
				}
				
				if (value!='') {
					if (valid) valid = validateLength(elArr[i]);
					if (valid) valid = validateValue(elArr[i]);
				}
				if(!valid){
					setFocus(elArr[i]);
					return false;
				}
			}			
		}
	}	
		
	if (checkDateRange(null)==false)
	{
		return false;
	}
	
	// At this point all standard validation is OK
	// Attempt user validation.
	// If user function doesn't exist (ie. try/catch block), return TRUE
	// else return resuls from user validation.
	try	{return(CheckForm_userValidation());}
	catch(er) {return true;}
	
	//return true;
	//return false;
}

function validateLength( item) {
	var maxlen	= item.getAttribute("maxlen");
	var minlen	= item.getAttribute("minlen");
	var val		= item.value;
	var valid	= true;

	if ((!maxlen) && (!minlen)) return true;

	if ((valid) && (maxlen)) {
		if (val.length > maxlen)
		{
			valid = false;
			displayLengthMessage(item, "max");
		}
	}

	if ((valid) && (minlen)) {
		if (val.length < minlen)
		{
			valid = false;
			displayLengthMessage(item, "min");
		}
	}

	if (!valid)	{item.focus();}
	return valid;
}

function validateValue( item ) {
	
	var pat = item.getAttribute("mask");
    var locss = item.getAttribute("locss");
	var locid = item.getAttribute("loc_id");
	var id = item.getAttribute("id");

    if(locss == null)
    {
        locss = "en-us"
    }
	if(locid == null)
	{
		locid = 1
	}
        
    var vals = new Array();
    vals = locss.split("-");
    var loc = vals[1];
    var lan = vals[0];

	var val = item.value;
	var format;
	var valid = false;

	if(!pat) return true; // no validator property, skip
	if (val == '') return true;
	//alert(item.name)

	switch (pat)
	{
	case "valTime":
		format = "'hh:mm'. \n - hh = 00-23 \n - mm = 00-59";
		valid = validateTime(val);
		if (!valid) displayValidationMessage(item, format);
		if (valid) valid = checkMinMax(item, "time");
		break;
	case "valTime2DigitHour":
		format = "'hh:mm'. \n - hh = 00-23 \n - mm = 00-59";
		valid = validateTime2DigitHour(val);
		if (!valid) displayValidationMessage(item, format);
		if (valid) valid = checkMinMax(item, "time");
		break;
	case "valTime12Hour":
	    format = "'hh:mm'. \n - hh = 00-12 \n - mm = 00-59";
	    insertColonIntoTime(item);
	    val = item.value;
		valid = validateTime12Hour(val);
		if (!valid) displayValidationMessage(item, format);
		if (valid) valid = checkMinMax(item, "time");
		break;
//	case "valDate":
//	    alert("validatingDate: " + loc);
//	    format = Date.format;
//		valid = validateDate(val,loc);
//		if (!valid) displayValidationMessage(item, format);
//		//if (valid)	{item.value = replaceCharacters(val, "[-,.]", "/")}
//		if (valid) valid = checkMinMax(item, "date");
//		break;
		
	case "valDate":
	
	    // Pivot if the date has a shortDateFormat defined
	    var dtFmt = Date.shortFormat;
	    if (typeof(dtFmt) == "undefined") format = "'mm/dd/yyyy' or 'mm/dd/yy'";
	    else format = "'" + dtFmt + "'";
	    
		valid = validateDate(val);
		if (!valid) displayValidationMessage(item, format);
		//if (valid)	{item.value = replaceCharacters(val, "[-,.]", "/")}
		if (valid) valid = checkMinMax(item, "date");
		break;		
		
		
	case "valSSN" :
		format = "'111111111'";
		valid = validateSSN(val);
		if (valid)	{item.value = removeCharacters(val, "[-]")}
		if (!valid) displayValidationMessage(item, format);
		break;
	case "valInt" :
		format = "an integer";
		valid = validateInteger(val);
		if (!valid) displayValidationMessage(item, format);
		if (valid) valid = checkMinMax(item, "int");
		break;
	case "valPhone" :

		var minDigits,maxDigits;
		minDigits = document.getElementById('h_minPhoneDigits').value;
		maxDigits = document.getElementById('h_maxPhoneDigits').value;

		if(minDigits == maxDigits)
		{
			format="'"+minDigits+" Digits'";		
		}
		else
		{
			format="'"+minDigits+" - "+maxDigits+" Digits'";
		}

//		switch (loc)
//		{		
//			case "us":
//				format = "'1111111111'";
//				break;
//			case "gb" :
//
//				format = "11 digits";
//				break;
//			default :
//				format = "'1111111111'";
//				break;
//		}
		valid = validatePhone(val,loc,minDigits,maxDigits);
		if (valid) item.value = removeCharacters(val, "[-,\(,\),' ',\.]");
		if (!valid) displayValidationMessage(item, format);
		break;
	case "valZip" :

		switch (locid)
		{
			case "1":
				format = "'11111'"
				break;
			case "39":
				format = "A1A 1A1'"
				break;
			case "2" :
				format = "UK Postal Code";
				break;
			default :
				format = "Postal Code";
				break;
		}
		valid = validateZip(val,locid);
		if (valid)	{item.value = removeCharacters(val, "[-]")}
		if (!valid) displayValidationMessage(item, format);
		break;
	case "valPIN" :
		format = "\n- Numeric, \n- 4 or 5 digits, \n- Not a sequence (eg. 1234, 4321), \n- Same digit not consecutive 4 or more times (eg. 9999)"
		valid = validatePIN(val);
		if (!valid) displayValidationMessage(item, format);
		break;
	case "valCur" :
		format = "'Currency'"
		valid = validateCurrency(val);
		if (!valid) displayValidationMessage(item, format);
		break;
	case "valFloat" :
		format = "numeric"
		valid = validateNumeric(val);
		if (!valid) displayValidationMessage(item, format);
		if (valid) valid = checkMinMax(item, "int");
		break;
	case "valEmail" :
		format = "'yourname@yourcompany.com'"
		valid = validateEmail(val);
		if (!valid) displayValidationMessage(item, format);
		break;
	case "valFileNameExt" :
		format = "Filename extension (txt, xls etc).  Enter without the dot."
		valid = validateFileNameExt(val);
		if (!valid) displayValidationMessage(item, format);
		break;
	case "valAlphaUserid" :
		format = "\n- 1st position alpha. \n- Special chars hyphen (-), period (.) and at-sign (@) allowed."
		valid = validateAlphaUserid(val);
		if (!valid) displayValidationMessage(item, format);
		break;
	case "RWFFT":
		var typeid = id + "_op";
		var typeitem = document.getElementById(typeid);
		valid = true;
		if(typeitem != null && val != "")
		{
			format = "";
			if(typeitem.value == "M")
			{
				var firstchar = val.charAt(0);
				var lastchar = val.charAt(val.length-1);
				if( (firstchar == "%") && (lastchar == "%") && (val.length > 1))
				{
					valid = false;
				}
			}
		}
		if (!valid) 
		{
			alert("Error: Filter value cannot begin and end with '%' when type is 'Equals'");
		}
		break;
	default :
		return true;
	}
	if (!valid)
	{
		var existingOldColor = item.getAttribute("oldColor");
		if(existingOldColor == null)
		{			
			var windowStyle = window.getComputedStyle(item,"");
			var oldColor = windowStyle.getPropertyValue("background-color")
			item.setAttribute("oldColor",oldColor)
		}
		item.style.backgroundColor = "Red";
		item.focus();
	}
	else
	{
		//if this item is valid, and it has an old color attribute, then restore the background to that old color
		var restoreColor = item.getAttribute("oldColor");
		if(restoreColor  != "") 
		{
			item.style.backgroundColor = restoreColor;
		}
	}
	return valid;
}

function checkMinMax(item, type)
{	
	var min = item.getAttribute("min");
	var max = item.getAttribute("max");
	if (!item.getAttribute("min") && !item.getAttribute("max")) return true

	switch (type)
	{

	case "time" :
		var valid = true;
		var hour = item.value.substring(0,2);
		var minute = item.value.substring(3,5);
		var curtime = new Date (2001,1,1,hour, minute);
		if (item.getAttribute("min")) 
		{
			var minhour = min.substring(0,2);
			var minminute = min.substring(3,5);
			var mintime = new Date (2001,1,1,minhour, minminute);
			if (mintime > curtime) valid=false
			if (!valid) 
			{	displayMinMaxMessage(item, "min");
				return valid;
			}
		}
		if (item.getAttribute("max")) 
		{
			var maxhour = max.substring(0,2);
			var maxminute = max.substring(3,5);
			var maxtime = new Date (2001,1,1,maxhour, maxminute);
			if (maxtime < curtime) valid=false
			if (!valid) 
			{	displayMinMaxMessage(item, "max");
				return valid;
			}
		}
		break;
	
	case "date" :	
		var valid = true;
        var curdate = Date.fromString(zeroPadDate(item.value));		
		
		if (curdate.getFullYear() < 1990)
		{		    
			curdate.setFullYear(curdate.getFullYear() + 100);				
		}
		if (item.getAttribute("min")) 
		{
			min = zeroPadDate(min);  //Required for javascript to run comparisons properly
			var mindate = Date.fromString(zeroPadDate(min));
			if (mindate > curdate) valid = false;
			if (!valid) 
			{	displayMinMaxMessage(item, "min", "date");
				return valid;
			}
		}
		if (item.getAttribute("max")) 
		{
			max = zeroPadDate(max);  //Required for javascript to run comparisons properly
			var maxdate = Date.fromString(zeroPadDate(max));
			if (maxdate < curdate) valid = false;
			if (!valid) 
			{	displayMinMaxMessage(item, "max", "date");
				return valid;
			}
		}
		break;

	case "int" :
		var valid = true;
		var cur = new Number(item.value);
		if (item.getAttribute("min")) 
		{
			min = new Number(min);
			if (min > cur) valid = false
			if (!valid) 
			{	displayMinMaxMessage(item, "min");
				return valid;
			}
		}
		if (item.getAttribute("max")) 
		{
			max = new Number(max);
			if (max < cur) valid = false
			if (!valid) 
			{	displayMinMaxMessage(item, "max");
				return valid;
			}
		}
		break;

	}//end case
	return valid;
}

function validateCurrency( strValue )  {
	var objRegExp = /^(\d*\.\d{2}$)|(\d*\.\d{1}$)/;
	return objRegExp.test( strValue );
}

function validateTime ( strValue ) {
	//var objRegExp = /^(0[1-9]|2[0-4]|1[0-9]):[0-5][0-9]$/;
	var objRegExp = /^([0-9]|0[0-9]|2[0-3]|1[0-9]):[0-5][0-9]$/;
	return objRegExp.test( strValue );
}

function validateTime2DigitHour ( strValue ) {
	//var objRegExp = /^(0[1-9]|2[0-4]|1[0-9]):[0-5][0-9]$/;
	var objRegExp = /^(0[0-9]|2[0-3]|1[0-9]):[0-5][0-9]$/;
	return objRegExp.test( strValue );
}

function validateTime12Hour ( strValue ) {
	//var objRegExp = /^(0[1-9]|2[0-4]|1[0-9]):[0-5][0-9]$/;
	var objRegExp = /^([0-9]|0[0-9]|1[0-2]):[0-5][0-9]$/;
	return objRegExp.test( strValue );
}

function validateState (strValue ) {
	var objRegExp = /^(AK|AL|AR|AZ|CA|CO|CT|DC|DE|FL|GA|HI|IA|ID|IL|IN|KS|KY|LA|MA|MD|ME|MI|MN|MO|MS|MT|NB|NC|ND|NH|NJ|NM|NV|NY|OH|OK|OR|PA|RI|SC|SD|TN|TX|UT|VA|VT|WA|WI|WV|WY)$/i; 
	return objRegExp.test(strValue);
}

function validateSSN( strValue ) {
	var objRegExp  = /(^\d{3}\-\d{2}\-\d{4}$)|(^\d{9}$)/;
	return objRegExp.test(strValue);
}

function validateEmail(strValue) {
  //NOTE: RFC822 - STANDARD FOR THE FORMAT OF ARPA INTERNET TEXT MESSAGES
  var sQtext = '[^\\x0d\\x22\\x5c\\x80-\\xff]';
  var sDtext = '[^\\x0d\\x5b-\\x5d\\x80-\\xff]';
  var sAtom = '[^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+';
  var sQuotedPair = '\\x5c[\\x00-\\x7f]';
  var sDomainLiteral = '\\x5b(' + sDtext + '|' + sQuotedPair + ')*\\x5d';
  var sQuotedString = '\\x22(' + sQtext + '|' + sQuotedPair + ')*\\x22';
  var sDomain_ref = sAtom;
  var sSubDomain = '(' + sDomain_ref + '|' + sDomainLiteral + ')';
  var sWord = '(' + sAtom + '|' + sQuotedString + ')';
  var sDomain = sSubDomain + '(\\x2e' + sSubDomain + ')*';
  var sLocalPart = sWord + '(\\x2e' + sWord + ')*';
  var sAddrSpec = sLocalPart + '\\x40' + sDomain; // complete RFC822 email address spec
  var sValidEmail = '^' + sAddrSpec + '$'; // as whole string
  var objRegExp = new RegExp(sValidEmail);
  return objRegExp.test(strValue);
}

function validatePhone( strValue,loc,minDigits,maxDigits ) {
	switch (loc)
	{
		case "us":
			return ValidatePhoneUS(strValue,minDigits,maxDigits)
			break;
		case "gb" :
			return ValidatePhoneUK(strValue,minDigits,maxDigits)
			break;
		default :
			return ValidatePhoneUS(strValue,minDigits,maxDigits)
			break;
	}
}


function ValidatePhoneUK(strValue,minDigits,maxDigits)
{
//	return strValue.length <= 15;
    //Modifed 2/6/08 - NRF - To accept 0 as the first digit.  Request by L. Foxx
	if(strValue.length >= minDigits && strValue.length <= maxDigits)
	{
		if(validateNumeric(strValue))
		{
			return true;
		}	
	}
	return false;
//	var objRegExp  =/^\d\d\d\d\d\d\d\d\d\d\d$/;
//	return objRegExp.test(strValue); 
}

function ValidatePhoneUS(strValue,minDigits,maxDigits)
{
    //Modifed 2/6/08 - NRF - To accept 0 as the first digit.  Request by L. Foxx
	var objRegExp  = /(^\([0-9]\d{2}\)\s?\d{3}\-\d{4}$)|(^[0-9]\d{2}[0-9]\d{6}$)|(^[0-9]\d{2}\-[0-9]\d{2}\-\d{4}$)|(^[0-9]\d{2}\.[0-9]\d{2}\.\d{4}$)/;
	return objRegExp.test(strValue); 
}

function  validateNumeric( strValue ) {
	var objRegExp  =  /(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/; 
	return objRegExp.test(strValue);
}

function validateInteger( strValue ) {
	var objRegExp  = /(^-?\d\d*$)/;
	return objRegExp.test(strValue);
}

function validateNotEmpty( strValue ) {
	var strTemp = strValue;
	strTemp = trimAll(strTemp);
	if(strTemp.length > 0){
		return true;
	}  
	return false;
}

//function validateZip( strValue ) {
//	var objRegExp  = /(^\d{5}$)|(^\d{5}-\d{4}$)|(^[A-Za-z][0-9][A-Za-z][' '][0-9][A-Za-z][0-9]$)|(^[A-Za-z][0-9][A-Za-z][0-9][A-Za-z][0-9]$)/;
//	return objRegExp.test(strValue);
//}

function validateZip( strValue,locale) {
	switch (locale)
	{
	case "1" :
		var objRegExp  = /(^\d{5}$)|(^\d{5}-\d{4}$)/;
		break;
	case "39" :
		var objRegExp  = /(^[A-Za-z][0-9][A-Za-z][' '][0-9][A-Za-z][0-9]$)|(^[A-Za-z][0-9][A-Za-z][0-9][A-Za-z][0-9]$)/;
		break;
	case "2" :
		var objRegExp  = /(^[A-Za-z]{1,2}\d[A-Za-z0-9]?[' ']\d{1,2}[A-Za-z]{2}$)/;
		break;
	default :
		var objRegExp  = /(^[A-Za-z]{1,2}\d[A-Za-z0-9]?[' ']\d{1,2}[A-Za-z]{2}$)/;
		break;
	}
	return objRegExp.test(strValue);
}

function validatePIN( strValue ) {
	var objRegExp;
	
	// length must be 4 or 5 digits
	objRegExp  = /^(\d{5})|(\d{4})$/; 
	if (!objRegExp.test(strValue)) return false;

	// any given digit can't be consecutive 4 or more times... eg. 19999, 88887, 6666
	objRegExp  = /(0{4}|1{4}|2{4}|3{4}|4{4}|5{4}|6{4}|7{4}|8{4}|9{4})/;
	if (objRegExp.test(strValue)) return false;

	// number can't be a sequence (ascending or descending... eg. 1234, 23456, 9876, 87654
	objRegExp  = /^(01234?|12345?|23456?|34567?|45678?|56789?|6789|98765?|87654?|76543?|65432?|54321?|43210?|3210)$/;
	if (objRegExp.test(strValue)) return false;

	return true;
}

function validateFileNameExt( strValue ) {
	//var objRegExp = /^(txt|xsl|xml|html|csv|dat|htm|doc|rft|xslt|xls)$/i; 
	var objRegExp = /^[a-z0-9]/;
	return objRegExp.test(strValue);
}

function validateDate( strValue ) {
    // Escape here to the Date format check if a format was specified
    if (typeof(Date.shortFormat) != "undefined") return Date.isDate(strValue);

	//var objRegExp = /^\d{1,2}(\-|\/|\.)\d{1,2}\1(\d{2}|\d{4})$/
	var objRegExp = /^\d{1,2}(\-|\/|\.)\d{1,2}\1(\d{4})$/
	var objRegExp2DigYr = /^\d{1,2}(\-|\/|\.)\d{1,2}\1(\d{2})$/

	if(!objRegExp.test(strValue) && !objRegExp2DigYr.test(strValue))
		return false; //doesn't match pattern, bad date
	else{
		var arrayDate = strValue.split(RegExp.$1); //split date into month, day, year
		var intDay = parseInt(arrayDate[1],10); 
		var intYear = parseInt(arrayDate[2],10);
	    var intMonth = parseInt(arrayDate[0],10);

		//check for valid month
		if(intMonth > 12 || intMonth < 1) {
			return false;
		}

		//create a lookup for months not equal to Feb.
		var arrayLookup = { '1' : 31,'3' : 31, '4' : 30,'5' : 31,'6' : 30,'7' : 31,
	                        '8' : 31,'9' : 30,'10' : 31,'11' : 30,'12' : 31}
	    //check if month value and day value agree
		if(arrayLookup[intMonth] != null) {
			if(intDay <= arrayLookup[parseInt(arrayDate[0])] && intDay != 0)
				return true;	//found in lookup table, good date
				//return true; 
		}
		
	    //check for February
		var booLeapYear = (intYear % 4 == 0 && intYear != 00 && intYear % 100 != 0);
	    if( ((booLeapYear && intDay <= 29) || (!booLeapYear && intDay <=28)) && intDay !=0)
			return true; //Feb. had valid number of days
	  }
	  return false; //any other values, bad date
}


function validateDateOld(strValue, loc)
{    
    if(loc == "gb")
    {
        return validateDateGB(strValue);
    }
    else if(loc == "us")
    {
        return validateDateUS(strValue);       
    }
    else    
    {
        //the default will be as if it were "us"
        return validateDateUS(strValue);               
    }    
    
   
}


function validateDateGB( strValue ) {


    // Escape here to the Date format check if a format was specified
    if (typeof(Date.shortFormat) != "undefined") return Date.isDate(strValue);
	//var objRegExp = /^\d{1,2}(\-|\/|\.)\d{1,2}\1(\d{2}|\d{4})$/
	var objRegExp = /^\d{1,2}(\-|\/|\.)\d{1,2}\1(\d{4})$/
	var objRegExp2DigYr = /^\d{1,2}(\-|\/|\.)\d{1,2}\1(\d{2})$/

	if(!objRegExp.test(strValue) && !objRegExp2DigYr.test(strValue))
	{
		return false; //doesn't match pattern, bad date
	}
	else{
		var arrayDate = strValue.split(RegExp.$1); //split date into month, day, year
		var intDay = parseInt(arrayDate[0],10); 
		var intYear = parseInt(arrayDate[2],10);
	    var intMonth = parseInt(arrayDate[1],10);

		//check for valid month
		if(intMonth > 12 || intMonth < 1) {
			return false;
		}

		//create a lookup for months not equal to Feb.
		var arrayLookup = { '1' : 31,'3' : 31, '4' : 30,'5' : 31,'6' : 30,'7' : 31,
	                        '8' : 31,'9' : 30,'10' : 31,'11' : 30,'12' : 31}
	    //check if month value and day value agree
		if(arrayLookup[intMonth] != null) {		    
			if(intDay <= arrayLookup[parseInt(intMonth)] && intDay != 0)
			{
				return true;	//found in lookup table, good date
			}			
		}
		
		
	    //check for February
		var booLeapYear = (intYear % 4 == 0 && intYear != 00 && intYear % 100 != 0);
	    if( ((booLeapYear && intDay <= 29) || (!booLeapYear && intDay <=28)) && intDay !=0)
			return true; //Feb. had valid number of days
	  }
	  return false; //any other values, bad date
}


function validateDateUS( strValue ) {



    // Escape here to the Date format check if a format was specified
    if (typeof(Date.shortFormat) != "undefined") return Date.isDate(strValue);

	//var objRegExp = /^\d{1,2}(\-|\/|\.)\d{1,2}\1(\d{2}|\d{4})$/
	var objRegExp = /^\d{1,2}(\-|\/|\.)\d{1,2}\1(\d{4})$/
	var objRegExp2DigYr = /^\d{1,2}(\-|\/|\.)\d{1,2}\1(\d{2})$/



	if(!objRegExp.test(strValue) && !objRegExp2DigYr.test(strValue))
		return false; //doesn't match pattern, bad date
	else{
		var arrayDate = strValue.split(RegExp.$1); //split date into month, day, year
		var intDay = parseInt(arrayDate[1],10); 
		var intYear = parseInt(arrayDate[2],10);
	    var intMonth = parseInt(arrayDate[0],10);

		//check for valid month
		if(intMonth > 12 || intMonth < 1) {
			return false;
		}

		//create a lookup for months not equal to Feb.
		var arrayLookup = { '1' : 31,'3' : 31, '4' : 30,'5' : 31,'6' : 30,'7' : 31,
	                        '8' : 31,'9' : 30,'10' : 31,'11' : 30,'12' : 31}
	    //check if month value and day value agree
		if(arrayLookup[intMonth] != null) {
			if(intDay <= arrayLookup[parseInt(intMonth)] && intDay != 0)
				return true;	//found in lookup table, good date
				//return true; 
		}
		
	    //check for February
		var booLeapYear = (intYear % 4 == 0 && intYear != 00 && intYear % 100 != 0);
	    if( ((booLeapYear && intDay <= 29) || (!booLeapYear && intDay <=28)) && intDay !=0)
			return true; //Feb. had valid number of days
	  }
	  return false; //any other values, bad date
}

function validateAlphaUserid( strValue ) {
	var objRegExp = /^[A-Za-z]([A-Za-z0-9_\-\.@]*)$/;
	return objRegExp.test(strValue);
}

function rightTrim( strValue ) {
	var objRegExp = /^([\w\W]*)(\b\s*)$/;
    if(objRegExp.test(strValue)) {
       //remove trailing a whitespace characters
       strValue = strValue.replace(objRegExp, '$1');
    }
	return strValue;
}

function leftTrim( strValue ) {
	var objRegExp = /^(\s*)(\b[\w\W]*)$/;
	if(objRegExp.test(strValue)) {
       //remove leading a whitespace characters
       strValue = strValue.replace(objRegExp, '$2');
    }
	return strValue;
}

function trimAll( strValue ) {
	var objRegExp = /^(\s*)$/;
	//check for all spaces
	if(objRegExp.test(strValue)) {
       strValue = strValue.replace(objRegExp, '');
       if( strValue.length == 0)
          return strValue;
    }
	//check for leading & trailing spaces
	objRegExp = /^(\s*)([\W\w]*)(\b\s*$)/;
    if(objRegExp.test(strValue)) {
       //remove leading and trailing whitespace characters
       strValue = strValue.replace(objRegExp, '$2');
    }
	return strValue;
}

function removeCurrency( strValue ) {
	var objRegExp = /\(/;
	var strMinus = '';
	//check if negative
	if(objRegExp.test(strValue)){
		strMinus = '-';
	}
	objRegExp = /\)|\(|[,]/g;
	strValue = strValue.replace(objRegExp,'');
	if(strValue.indexOf('$') >= 0){
		strValue = strValue.substring(1, strValue.length);
	}
	return strMinus + strValue;
}

function addCurrency( strValue ) {
	var objRegExp = /-?[0-9]+\.[0-9]{2}$/;
   	if( objRegExp.test(strValue)) {
		objRegExp.compile('^-');
		strValue = addCommas(strValue);
		if (objRegExp.test(strValue)){
			strValue = '($' + strValue.replace(objRegExp,'') + ')';
		}
		else {
			strValue = '$' + strValue;
		}
		return  strValue;
    }
    else
		return strValue;
}

function removeCommas( strValue ) {
	var objRegExp = /,/g; //search for commas globally
	//replace all matches with empty strings
	return strValue.replace(objRegExp,'');
}

function addCommas( strValue ) {
	var objRegExp  = new RegExp('(-?[0-9]+)([0-9]{3})'); 
	//check for match to search criteria
    while(objRegExp.test(strValue)) {
       //replace original string with first group match, 
       //a comma, then second group match
       strValue = strValue.replace(objRegExp, '$1,$2');
    }
	return strValue;
}

function removeCharacters( strValue, strMatchPattern ) {
	var objRegExp =  new RegExp( strMatchPattern, 'gi' );
	//replace passed pattern matches with blanks
	return strValue.replace(objRegExp,'');
}

function replaceCharacters( strValue, strMatchPattern, strReplacePattern ) {
	var objRegExp =  new RegExp( strMatchPattern, 'gi' );
	//replace passed pattern matches with blanks
	return strValue.replace(objRegExp, strReplacePattern);
}

function displayValidationMessage(item, format)
{
	var desc = item.getAttribute("desc");
	if(!desc || desc == ''){
		desc = 'this field';
	}
	var alertstring = "Error, Format for " + desc + " is " + format;
	alert(alertstring.replace("<br>", " "))
}

function displayRequiredMessage(item)
{
	var alertstring = "The field '" + item.getAttribute("desc") + "' is required.  Please enter a value for this field."
	alert(alertstring.replace("<br>", " "))
}

function displayMinMaxMessage(item, type, fieldType)
{
	switch (type)
	{
	case "min" :
		var minDate = item.getAttribute("min");
		if(fieldType == "date") minDate = zeroPadDate(minDate);
		var alertstring = "Error, Value of " + item.value + " is less than the Minimum value of " + minDate + " for " + item.getAttribute("desc");
		break;
	case "max" :
		var maxDate = item.getAttribute("max");
		if(fieldType == "date") maxDate = zeroPadDate(maxDate);
		var alertstring = "Error, Value of " + item.value + " exceeds the Maximum value of " + maxDate + " for " + item.getAttribute("desc");                                                                                                		
		break;
	}
	alert(alertstring.replace("<br>", " "));
}

function displayLengthMessage(item, type)
{
	switch (type)
	{
	case "min" :
		var alertstring = "Error, Minimum length for " + item.getAttribute("desc") + " is " + item.getAttribute("minlen");
		break;
	case "max" :
		var alertstring = "Error, Maximum length for " + item.getAttribute("desc") + " is " + item.getAttribute("maxlen");
		break;
	}
	alert(alertstring.replace("<br>", " "));
}


function checkStartDateBeforeEndDate(startDateName,endDateName,errMsg)
{
	var startDate,endDate
	startDate = document.getElementById(startDateName)
	endDate = document.getElementById(endDateName)

	if(startDate == null || endDate == null)
	{
		//if one of them is not there, just return true
		return true;
	}

	startDate = Date.fromString(zeroPadDate(startDate.value));
    endDate = Date.fromString(zeroPadDate(endDate.value));
		
	if(endDate < startDate)
	{
		alert(errMsg);
		return false;
	}
	return true;
}


///////////////////////////////////////
//NEW FUNCTION MPS 07/18/02
//Make sure date range on reports is limited to 365 days
//-------------------------------------
function checkDateRange(curField){
	var startDate, endDate, dateDiff, alertstring;

	try{
		if (curField==null)
		{
			curField = document.getElementById('startDate');
			if(curField == null || curField.value == '')	//curField.value == '' is used for change log
			{
				//put this check here in case the form doesn't atually have a date field with start date on it
				return true;
			}
		}
       
        startDate = Date.fromString(zeroPadDate(document.getElementById('startDate').value));
        endDate = Date.fromString(zeroPadDate(document.getElementById('endDate').value));
		
		//assume anything before 1980 is 20xx
		if(startDate.getFullYear()<1980) startDate.setFullYear(startDate.getFullYear()+100);
		if(endDate.getFullYear()<1980) endDate.setFullYear(endDate.getFullYear()+100);

		dateDiff = endDate-startDate;	//difference in milliseconds
		dateDiff = dateDiff/1000;		//to seconds
		dateDiff = dateDiff/3600;		//to hours
		dateDiff = dateDiff/24;			//to days
		dateDiff = parseInt(dateDiff);	//convert to integer

		if (dateDiff>365)	
		{
			alertstring  = "Sorry, you cannot search on a date range greater than 365 days.";
			alert(alertstring);
			curField.focus();
			return false;
		}else{
			return true;
		}
	}
	catch(er){}

}

///////////////////////////////////////
//NEW FUNCTIONs EGA 09/24/02
//-------------------------------------

// Check the form and then disable buttons on the page so that user can't hit them again.
// strCancel is a comma separated list of button names.  If the button pressed is one of these
// then the check should be ignored.
//
// strCancel is a comma separated list of button names
//	- case sensitive 
//	- must be coded with ID='xxxxx' for netscape.
//
// strButtons is a comma separated list of button names
//	- case sensitive 
//	- must be coded with ID='xxxxx' for netscape.
function checkFormAndDisableButtons(form, strCancel, strButtons) {

	var doCheck		= true;
	
	// See if any CANCEL button was pressed... if so, skip the CHECK
	var arCancel	= strCancel.split(",");
	for (var i=0; i<arCancel.length; i++) {
		if (checkButtonPressed(arCancel[i])) {
			doCheck = false;
			break;
		}
	}
	
	// Call function to validate the page values
	var checkResult;
	if (doCheck)	{ checkResult = checkForm(form); }
	else			{ checkResult = true; }
	
	// Disable the requested buttons so impatient user doesn't hit them again.
	// Only disable if the form validation was OK.
	// The disable button call assumes a hidden form field called 'submitButton'.
	if (checkResult) {
		var arButtons = strButtons.split(",");
		for (var i=0; i<arButtons.length; i++) {
			//showAttributes(arButtons[i]);
			disableButton(arButtons[i], "submitButton");
		}
	}

	// Return true/false to drive the submit of the form
	return checkResult;
}

// Helper function
function showAttributes(elName) {
	var save = document.getElementById(elName)
	var s;
	// dump out all the attributes
	for (i=0; i<=save.attributes.length-1; i++) {
		s += save.attributes[i].name + "=" + save.attributes[i].value + "\t";
		if (i % 2 == 0) s += "\n";
	}
	alert(s);
}

// Disable a button.  But if it was the button pressed, then remember its name.
function disableButton(elName, elSubmit) {
	if (!document.getElementById) return;
	
	// This function:
	//	-	Checks the 'expando' attribute 'buttonPressed'.
	//	-	If true then the name of the button is saved to the elSubmit hidden form field.
	//		This is required because in IE, a disabled button is NOT passed to the server in the
	//		request.form collection.
	// -	Finally, the button itself is disabled

	// elSubmit is a hidden form element to hold the elName
	var el = document.getElementById(elName);
	if (checkButtonPressed(elName)) {
		var submitButton = document.getElementById(elSubmit);
		if (submitButton) submitButton.value = elName;
	}
	disableElement(elName);
}

// Check if a button was pressed.  
// This function requires the 'expando' attribute 'buttonPressed'.
// This attribute is created automatically if the 'buttonPressed' function is linked to the button's onclick event.
function checkButtonPressed(elName) {
	var el = document.getElementById(elName);
	if (!el) return false;

	var btnPressed = el.getAttribute("buttonPressed");
	if (btnPressed) {
		return btnPressed;
	}
	else return false;
}

// Mark a named element disabled
function disableElement(elName) {
	var el = document.getElementById(elName);
	if (el) el.disabled = true;
}

// Create 'buttonPressed' attribute for an element
//MCH changed the name of this function(used to be called buttonPressed(el), because apparently IE doesn't like it when 
//there is a function that has a name, and then an element is assigned an attribute that shares a name with the function
function SetButtonPressedTrue(el) {
	// Create an expando property that indicates whether the button was pressed or not
	// This function is linked to the onclick event for submit buttons
	el.setAttribute("buttonPressed", true);		// IE and Netscape both work here
}

/******************************************
* Generic SQL lookup from the browser
* This routine is passed
*	- lookupType	used in server side case in page BrowserSQLLookup.asp
*	- formName		form on web page that elements are found
*	- p1 thru p6	names of elements on the form
*
*	This routine will add the following to the querystring if the 
*	the corresponding form element is found
*	- GUID
*	- SESSION
*
*	This routine will fail if the following form element is NOT
*	found
*	- URL
*******************************************/
function SQLLookup(lookupType, formName, p1, p2, p3, p4, p5, p6) {
	var httpResponse;

	var form = document.forms(formName);
	if (!form) {
		//alert("Form (" + formName + ") not found in SQLLookup");
		return false;
	}

	var xmlhttp = new ActiveXObject ("Microsoft.XMLHTTP"); 
	
	// realpage=false keeps extraneous stuff from being sent back by the server
	qs = 'realpage=false';
	// Always pass the Lookuptype and the GUID
	qs += '&check=' + lookupType;
	qs += getFormVal(form, "GUID", "GUID");

	// Up to 6 parameters will be passed in
	if (p1 != "" ) qs += getFormVal(form, "p1", p1);
	if (p2 != "" ) qs += getFormVal(form, "p2", p2);
	if (p3 != "" ) qs += getFormVal(form, "p3", p3);
	if (p4 != "" ) qs += getFormVal(form, "p4", p4);
	if (p5 != "" ) qs += getFormVal(form, "p5", p5);
	if (p6 != "" ) qs += getFormVal(form, "p6", p6);
	
	// Add the session ID
	qs += getFormVal(form, "SESSIONID", "SESSIONID");
	var openStr 
	if (form.elements("URL").value.substr(0,4) == 'http'){
		openStr = ''
	}else{
		openStr='https://';
	}

	openStr = openStr + form.elements("URL").value + '/navigator/browserSQLLookup.asp?' + qs
	//alert(openStr);
	xmlhttp.Open('GET', openStr, false);
	xmlhttp.Send();
	
	httpResponse = xmlhttp.ResponseText;
	//alert("." + httpResponse + ".");
	if (httpResponse == "Found")
	{
		//alert("true");
		return true;
	} else {
		//alert("false");
		return false;
	}
}

function getFormVal(form, qsName, elName) {
	if (form.elements(elName)) {
		return "&" + qsName + "=" + form.elements(elName).value;
	}
	else
		return "";
}

// Focus the cursor on a named element within a named form
function focusFormElement(pFormName, pFieldName) {
	try
	{
		var el = document.forms(pFormName).elements(pFieldName);
		setFocus(el);
	}						
	catch (e) {	}			
}

// Focus the cursor on an element
function setFocus(el) {
	try {
		el.focus();
		el.blur();	
		el.select();
	}
	catch (e) {}
}

// This function should work in both Netscape and IE
// Find the requested form in the document.forms collection.
function getFormByName(formName) {
	var docforms = document.forms;
	for (var form=0; form<docforms.length; form++ )	{
		if (docforms[form].name == formName) return(docforms[form]);
	}
	// thru the entire forms collection and no matching name
	return(false);
}

// This function should work in both Netscape and IE
// Find the requested element in the passed in element collection.
function getFormElementByName(elName, elCollection) {
	for (var el=0; el<elCollection.length; el++)	{
		if (elCollection[el].name == elName) return(elCollection[el]);
	}
	// thru the entire form elements collection and no matching name
	return(false);
}

//Functions below are called by abence create and modify
//Purpose is to populate the entitlement list
function buildEnttList(xLocation, instID, wktId,PleaseSelectText,description) 
{
	var curselectEl = document.getElementById(xLocation).childNodes[0];
	var curOption = curselectEl.options[curselectEl.selectedIndex];
	var curValue = null;
	if (curOption)
	{
		curValue = curOption.value;
	}
	var enttList = "";
	var xml = Sarissa.getDomDocument();
	xml.async = false;
	xml = (new DOMParser()).parseFromString(xmlString, "text/xml");
	if (instID == '')
	{
		return;
	}

	enttList += "<option " + (curValue == '' ? ' selected ' : '') + " value=''>"+PleaseSelectText+"</option>";
	var	EnttNodeList			= xml.selectNodes("//ROOT/row[@Entt_ID != '']");
	for( var i = 0; i < EnttNodeList.length; i++ ) 
	{ 
		if (getInstfromEntt(instID, EnttNodeList.item(i).getAttribute( "Inst_ID" )))
		{
			var val = EnttNodeList.item(i).getAttribute( "Entt_ID" );
			enttList += '<option ' + (curValue == val ? ' selected ' : '') + 'value=' + val + '>' + EnttNodeList.item(i).getAttribute( "Entt_Description" ) + "</option>";
		}
	}
	var newHtml;
	newHtml = "<select name='Entitlement' onFocus='populate(event)'onKeyDown='setSelection(event)' onKeyPress='javascript:return false' desc='"+description+"'  id='select2' required='true' >";
	newHtml += enttList;
	newHtml += "</select>";
	document.getElementById(xLocation).innerHTML = newHtml;		
}

//Functions below are called by abence create and modify
//Purpose is to populate the vacancy reason list
function buildVacList(xLocation, instID,IncludeDefaultReason,RequiresVacancyReason,PleaseSelectText,description) 
{
	var curselectEl = document.getElementById(xLocation).childNodes[0];
	var curOption = curselectEl.options[curselectEl.selectedIndex];
	var curValue = null;
	if (curOption)
	{
		curValue = curOption.value;
	}
	var enttList = "";
	var xml = Sarissa.getDomDocument();
	xml.async = false;
	xml = (new DOMParser()).parseFromString(xmlVacReason, "text/xml");
	if (instID == '')
	{
		return;
	}
	if(RequiresVacancyReason)
	{
			enttList += "<option " + (curValue == '' ? ' selected ' : '') + "value=''>"+PleaseSelectText+"</option>";
	}
	var	EnttNodeList			= xml.selectNodes("//ROOT/row[@Entt_ID != '']");
	for( var i = 0; i < EnttNodeList.length; i++ ) 
	{ 
		var val = EnttNodeList.item(i).getAttribute( "Entt_ID" );
		if (getInstfromEntt(instID, EnttNodeList.item(i).getAttribute( "Inst_ID" )) || (IncludeDefaultReason && val == 0) )
		{
			enttList += '<option ' + (curValue == val ? ' selected ' : '') + 'value=' + val + '>' + EnttNodeList.item(i).getAttribute( "Entt_Description" ) + "</option>";
		}
	}
	var newHtml;
	newHtml = "<select name='Entitlement' onFocus='populate(event)'onKeyDown='setSelection(event)' onKeyPress='javascript:return false' desc='"+description+"'  id='select2'  name='Entitlement' required='true' >";
	newHtml += enttList;
	newHtml += "</select>";
	document.getElementById(xLocation).innerHTML = newHtml;		
}



//Functions below are called by abence create and modify
//Purpose is to populate the entitlement list
function buildAccdList(xLocation, instID, pname) 
{
	if (!document.getElementById(xLocation))
	{
		return;
	}
	var accdList = "";
	//var xml = new ActiveXObject("Microsoft.XMLDOM");
	//var xmlString = document.getElementById("data").innerHTML;
	var xml = Sarissa.getDomDocument();
	xml.async = false;
	xml = (new DOMParser()).parseFromString(xmlString, "text/xml");

	if (instID == '')
	{
		return;
	}

	var InstNode				= xml.selectNodes("//ROOT/row[@inst_id = '" + instID + "']")[0];
	var lType = InstNode.getAttribute("acdt_id");


	if((lType == "1") || (lType == "3")){
		var curSelect = document.getElementById(pname);
		var curSelValue = "";
		if (curSelect)
		{
			if(curSelect.options)
			{
				curSelValue = curSelect.options[curSelect.selectedIndex].value;
			}
		}

		var	AccdNodeList			= xml.selectNodes("//ROOT/row[@accd_id != '']");

		accdList += "<select name='" + pname + "' id='"  + pname + "' "
		if(lType == "3"){
			accdList += " onchange=\"document.getElementById('txt' + this.id).disabled = (this.value != '0');if(this.value == '0'){document.getElementById('txt' + this.id).focus();}\""
		}
		accdList += ">"
		accdList += "<option value=''>-- none selected --</option>"
		for( var i = 0; i < AccdNodeList.length; i++ ) 
		{ 
			if (AccdNodeList.item(i).getAttribute( "Inst_ID" ) == null || getInstfromEntt(instID, AccdNodeList.item(i).getAttribute( "Inst_ID" )))
			{
				accdList += '<option value=' + AccdNodeList.item(i).getAttribute( "accd_id" ) 
					+ (curSelValue == AccdNodeList.item(i).getAttribute( "accd_id" ) ? ' selected' : '') + '>' 
					+ AccdNodeList.item(i).getAttribute( "accd_description" ) + '</option>';
			}
			//getInstfromEntt(instID, EnttNodeList.item(i).selectSingleNode( "@Inst_ID" ).text);
		}

		if(lType == "3"){
			accdList +=  "<option value='0'>";
			accdList +=  "Custom";
			accdList +=  "</option>";
		}
		//Set the entitlement list
		//<option value=''>Select an Entitlement</option>
		accdList +=  "</select>"
	}

	if(lType == "2" || lType == "3"){
		var curTb = document.getElementById('txt' + pname);
		var curValue = '';
		if (curTb)
		{
			curValue = curTb.value.replace(/\"/gi, '&quot;');
		}

		if(lType == "2"){ 
			accdList +=  "<input type=hidden value=0 name='" + pname + "'>"
		}
		accdList +=  "<input type=text maxlength=30 size=" + (lType == "2" ? 35 : 20) + " name='txt" + pname + "' id='txt" + pname + "' value=\"" + curValue + "\""
		if(lType != "2"){ 
			accdList += "disabled "
		}
		accdList += ">"
	}

	document.getElementById(xLocation).innerHTML =  accdList ;
	
}

function getInstfromEntt(instID, eInstID)
{
	var instListArray, i, instList, returnVal;
	
	instList		= getInstList(instID);
	
	instListArray	= instList.split(',');
	returnVal		= false;

	for(var i=0; i < instListArray.length; i++)
	{
		if (instListArray[i] == eInstID) 
		{
			returnVal = true;
		}
	}
	
	return returnVal;
}

function getInstList(instID)
{
	var enttXML, EnttXMLObj, EnttNode, EnttNodeList;
	
	//var xml = new ActiveXObject("Microsoft.XMLDOM");
	var enttList;
	//xml.async = false;
	//var xmlString = document.getElementById("data").innerHTML;

	var xml = Sarissa.getDomDocument();
	xml.async = false;
	xml = (new DOMParser()).parseFromString(xmlString, "text/xml");
	//xml.loadXML(document.getElementById("data").xml);
	var	EnttNodeList			= xml.selectSingleNode("ROOT/row[@inst_id ='" + instID + "']");

	return EnttNodeList.getAttribute("inst_parents");
}

function countInsts()
{
	var returnVar;

	returnVar = true;

	//Multiple Insts selected?
	if (countMulti(document.formMain.inst_id) > 1)
	{
		if (document.formMain['worker.WORK_DefStartTime'].value == '' || document.formMain['worker.WORK_HalfDayBreak'].value == '' || document.formMain['worker.WORK_HalfDayBreak2'].value == '' || document.formMain['worker.WORK_DefEndTime'].value == '')
		{
			alert('Intinerant employees are required to have start time, half day break, and end time.');
			returnVar = false;
		}
	}
	
	if (returnVar == true)
	{
		returnVar	= checkForm(formMain);
	}	

	return returnVar;
}

function countMulti(sel) { 
	var i=-1, c=0; 
	while (sel.options[++i]) if (sel.options[i].selected) c++; 
	return c; 
} 

function isVisible(el){
	if (el.parentNode == null)
	{
		return true;
	}
	if(el.style.display == 'none'){
		return false;
	}
	else{
		return isVisible(el.parentNode);
	}
}

function insertColonIntoTime(el){
    if(el.value.indexOf(":") < 0){
        var val = el.value
        var len = val.length;
        el.value = val.substr(0, len-2) + ":" + val.substr(len-2, 2);
    }
}

// helper function to add required zero characters to fixed length fields
function zeroPadDate(pDate) {
		var delimChar = (pDate.indexOf("/") != -1) ? "/" : "-"; 
		var aSplitDate = pDate.split(delimChar);
		return zeroPad(aSplitDate[0])+delimChar+zeroPad(aSplitDate[1])+delimChar+aSplitDate[2]
}

// helper function to add required zero characters to fixed length fields
function zeroPad(num) {
		var s = '0'+num;
		return s.substring(s.length-2)
}



if (!window.getComputedStyle) {
	window.getComputedStyle = function(el, pseudo) {
		this.el = el;
		this.getPropertyValue = function(prop) {
			var re = /(\-([a-z]){1})/g;
			if (prop == 'float') prop = 'styleFloat';
			if (re.test(prop)) {
				prop = prop.replace(re, function () {
					return arguments[2].toUpperCase();
				});
			}
			return el.currentStyle[prop] ? el.currentStyle[prop] : null;
		}
		return this;
	}
}

 
