/*
* 
*
* validateField.js
*
* 
*/
var blnValueFailed = false;  // Variable used for handleFailedFlag. This variable is set to true if a field is invalid.

/***************************************************
DESCRIPTION: common function to set focus to a field.
    
PARAMETERS:
   objField - the field object to set focus to.
   valPassed - global
      
RETURNS:
   True if valPassed is true, otherwise false.
*************************************************/
function handleFailedFlag (objField) { 

	if (blnValueFailed == true)
  	{
  		// Flag has been set (an invalid field was detected)
		// Set focus and clear flag.
		if(objField.disabled == false){
	  		objField.focus();
  			//objField.select();
		}
		blnValueFailed = false;
		return false;
   	}  
   	else{
		// Flag has not been set
		return true;
	}
}

function handleFailedFlagForSelectField (objField) { 

	if (blnValueFailed == true)
  	{
  		// Flag has been set (an invalid field was detected)
		// Set focus and clear flag.
		if(objField.disabled == false){
	  		objField.focus();
		}
		blnValueFailed = false;
		return false;
   	}  
   	else{
		// Flag has not been set
		return true;
	}
}
/******************************************************************
DESCRIPTION: common function to check for special characters.
    
PARAMETERS:
   objField - the field object to set focus to.
      
RETURNS:
   None.
******************************************************************/
function checkSpecialChar(objField)
{
	// Set list of special characters.
  	var objRegExp = /\!|\(|\)|\_|\+|=|\[|\]|\{|\}|;|:|\\|'|"|\.|,|<|>|\/|-|\@|\~|\`|\#|\%|\&|\*|\x24|\x5E|\x3F|\x7C|\^/g
  	var strValue = objField.value
 
  	//check to see if special characters exist
	
  	if(objRegExp.test(strValue)){
   		alert("You are not allowed to enter special charaters!"); //doesn't match pattern, bad date
	}
}

function checkRequiredField(objField, strMessage)
/************************************************
DESCRIPTION: common function for required field validation
			 including 1) checking whether the value is filled in
			 2) place the cursor focus on the first missing required field
			 3) display a JavaScript message box
    
PARAMETERS:
   objField - the field object 
   strMessage - text to display in the JavaScript message
      
RETURNS:
   True if validation check passed, otherwise false.
*************************************************/
{
	var strFieldValue = String(objField.value);
	
	if (!checkEmptyValue(strFieldValue)){
		// Field is not blank.
		return true;
	}
	
	// Field is blank, validation failed.		
	objField.focus();
	alert(strMessage);
	// Set flag used to return focus to field.
	blnValueFailed = true;
	return false;
}

function checkEmptyValue(strValue)
/************************************************
DESCRIPTION: Pass in a text field object to verify
			if it is a blank field.  
    
PARAMETERS:
   strValue - value to check whether blank or not
   
RETURNS:
   True if blank(or just spaces), otherwise false.
*************************************************/
{
	var i;
	
	for (i = 0; i < strValue.length; i++)
  	{
    	if (strValue.charAt(i) != " "){
			// Field is not blank.
			return false;
		}
	}
	return true;
}
/*****************************************************************************
BEGIN DATE FUNCTIONS*******************************************************************************/
function checkDate(objDateField) {
	return checkDate2(objDateField, false);
}

function checkDate2(objDateField, bTimeReqired) {
/************************************************
DESCRIPTION: Pass in a date object to verify if it is a 
			valid date.  Separate error messages will be
			displayed depending on the error code.
    
PARAMETERS:
   objDateField - Date Object to be tested for validity
   
RETURNS:
   True if valid, otherwise false.
*************************************************/
     var aryMonth = new Array(12);
	
	 aryMonth[0] = "January";
	 aryMonth[1] = "February";
	 aryMonth[2] = "March";
	 aryMonth[3] = "April";
	 aryMonth[4] = "May";
	 aryMonth[5] = "June";
	 aryMonth[6] = "July";
	 aryMonth[7] = "August";
	 aryMonth[8] = "September";
	 aryMonth[9] = "October";
	 aryMonth[10] = "November";
	 aryMonth[11] = "December";
	 
	 if (objDateField.value == "" || objDateField.value == null)
	 	return true;
	 
	 var intResultValue = validateUSDate(objDateField, bTimeReqired);
	 var strMessage;
	 if (intResultValue != 0) {
		// Validation failed.
		// Determine alert message based on return code.
		switch(intResultValue){
			case -99:
				strMessage = "Year must be greater than 1600"
				break
			case -1:
				if (bTimeReqired) {
					strMessage = "Invalid Date Format. Please enter a date in one of the following formats:\n\n" 
						+ "For a date requiring time use formats:\n"
						+ "     mm/dd/yyyy hh:mm:ss AM/PM or\n"
						+ "     mm-dd-yyyy hh:mm:ss AM/PM or\n"
						+ "     mm.dd.yyyy hh:mm:ss AM/PM\n\n"				
				} else {				
					strMessage = "Invalid Date Format. Please enter a date in one of the following formats:\n\n" 
						+ "For a date that does not require the time use formats:\n"
						+ "     mm/dd/yyyy or mm-dd-yyyy or mm.dd.yyyy.\n\n"
				}
				break
			case 1:
			case 3:
			case 5:
			case 7:
			case 8:
			case 10:
			case 12:
				strMessage = aryMonth[intResultValue-1] + " can only have 31 days"
				break
			case 2:
				strMessage = "February has invalid number of days"
				break
			case 4:
			case 6:
			case 9:
			case 11:
				strMessage = aryMonth[intResultValue-1] + " can only have 30 days"
				break
			case 13:
				strMessage = "Invalid Month"
				break
			case 14:
				strMessage = "Invalid Hour value for the date time \"" + objDateField.value + "\". Value must be between 0 and 12 inclusive."
				break
			case 15:
				strMessage = "Invalid Minute value for the date time \"" + objDateField.value + "\". Value must be between 0 and 59."
				break
			case 16:
				strMessage = "Invalid Seconds value for the date time \"" + objDateField.value + "\". Value must be between 0 and 59."
				break
			
			
		}
		
		alert(strMessage);
		// Set flag used to return focus to field.
		blnValueFailed = true;
		objDateField.value = "";
		objDateField.focus();
		return false;
	}
	else {
		return true;
   }
}

function validateUSDate( objDateField, bTimeReqired ) {
/************************************************
DESCRIPTION: Validates that a string contains only 
    valid dates with 2 digit month, 2 digit day, 
    4 digit year. Date separator can be ., -, or /.
    Uses combination of regular expressions and 
    string parsing to validate date.
    Ex. mm/dd/yyyy or mm-dd-yyyy or mm.dd.yyyy
    
PARAMETERS:
   objDateField - Date Object to be tested for validity
   
RETURNS:
   True if valid, otherwise false.
   
REMARKS:
   Avoids some of the limitations of the Date.parse()
   method such as the date separator character.
*************************************************/
  var objDateRegExp = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/
  var objDateTimeRegExp = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4} \d{1,2}(\:)\d{1,2}\2\d{1,2} (AM|PM)$/

  var dateStr = "";
  var timeStr = null;
  var strValue = objDateField.value
 
  //check to see if in correct format
  if (objDateRegExp.test(strValue)) {
  	dateStr = strValue;
  	if (bTimeReqired)
  		return -1; // Date without time where time IS required.
  	
  } else if (objDateTimeRegExp.test(strValue)) {
  	var aryDT = strValue.split(" ");
  	dateStr = aryDT[0];
  	timeStr = aryDT[1];
  	if (!bTimeReqired)
  		return -1; // Date with time where time is not required.
  } else {
  	return -1;
  }
  
  // Validate the specified date
  var aryDate = dateStr.split(RegExp.$1); //split date into month, day, year
  var intDay = parseInt(aryDate[1],10); 
  var intYear = parseInt(aryDate[2],10);
  var intMonth = parseInt(aryDate[0],10);
	
  // check for year to make sure it is after 1600.
  if (intYear <= 1600) {
	return -99;
  }

  //check for valid month
  if(intMonth > 12 || intMonth < 1) {
	return 13;
  }
	
  //create a lookup for months not equal to Feb.
  var aryLookup = { '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(aryLookup[intMonth] != null) {
  	if(intDay <= aryLookup[intMonth] && intDay != 0) {
  //		objDateField.value = intMonth + "-" + intDay + "-" + intYear 
  //		return 0; //found in lookup table, good date
	} else {
		return intMonth;
	}
   } else {
	
		
   	//check for February
   	var blnLeapYear = (intYear % 4 == 0 && (intYear % 100 != 0 || intYear % 400 == 0));
   	if( ((blnLeapYear && intDay <= 29) || (!blnLeapYear && intDay <=28)) && intDay !=0) {
		  //OLDstrDateField.value = intMonth + "/" + intDay + "/" + intYear
	  //	objDateField.value = intMonth + "/" + intDay + "/" + intYear 
	  //	return 0; //Feb. had valid number of days
	   }
	   else
		return intMonth;
  }
 
  
  if (timeStr != null) {
	  // Validate the specified date
	  var aryTime = timeStr.split(RegExp.$2); //split date into hour, minute, second
	  var intHour = parseInt(aryTime[0],10); 
	  var intMin = parseInt(aryTime[1],10);
	  var intSec = parseInt(aryTime[2],10);
	  
	  if (intHour > 12 || intHour < 0) {
	  	return 14;
	  } else if (intMin > 59 || intMin < 0) {
	  	return 15;
	  } else if (intSec > 59 || intSec < 0) {
	  	return 16;
	  }
  }
  
  return 0;
}

function doDateCheck(objFrom, objTo) {
	if (Date.parse(objFrom.value) <= Date.parse(objTo.value)) {
		alert("The dates are valid.");
	}
	else {
	if (objFrom.value == "" || objTo.value == "") 
		alert("Both dates must be entered.");
	else 
		alert("To date must occur after the from date.");
   }
}

function validateBetweenDates(objDateLow, objDateHigh) {
	if (objDateLow.value != "" && objDateHigh.value != "") {	
	
		if (checkDate(objDateLow)) {// no action
		}
		else {return false}

		if (checkDate(objDateHigh)) {// no action
		}
		else {return false}
	
		// Make sure that high date is beyond the low date
		if (getDateDiff(objDateLow, objDateHigh) < 0) {
			alert("The end date must be greater than or equal to the start date in a date search")
			objDateLow.focus()
			// Set flag used to return focus to field.
			blnValueFailed = true;
			return false
		}
	}
	return true;
}
function validateBetweenDatesWithMsg(objDateLow, objDateHigh, s_Message) {
	if (objDateLow.value != "" && objDateHigh.value != "") {	
	
		if (checkDate(objDateLow)) {// no action
		}
		else {return false}

		if (checkDate(objDateHigh)) {// no action
		}
		else {return false}
	
		// Make sure that high date is beyond the low date
		if (getDateDiff(objDateLow, objDateHigh) < 0) {
			alert(s_Message)
			objDateLow.focus()
			// Set flag used to return focus to field.
			blnValueFailed = true;
			return false
		}
	}
	return true;
}
function getDateDiff(objDtmFirst, objDtmSecond) {
	intTempfirst = Date.parse(objDtmFirst.value)
	intTempsecond = Date.parse(objDtmSecond.value)
	intNumDaysDiff = intTempsecond - intTempfirst
	intNumDaysDiff = Math.round(intNumDaysDiff / (1000 * 60 * 60 * 24));
	return intNumDaysDiff;
}

function calcDateDiff(Date1, Date2 ) {
	while (Date1.match('-'))  Date1 = Date1.replace('-', '/');
	while (Date2.match('-'))  Date2 = Date2.replace('-', '/');
	intTemp1      = Date.parse(Date1);
	intTemp2      = Date.parse(Date2);
	intNumDaysDiff = intTemp2 - intTemp1;
	intNumDaysDiff = Math.round(intNumDaysDiff / (1000 * 60 * 60 * 24));
	
	return intNumDaysDiff;
}



/*****************************************************************************
					END DATE FUNCTIONS
*******************************************************************************/


/********************************************************
* Description: A wrapper function to validate numeric value
*
* PARAMETERS:
* objValue - String to be tested for validity
**********************************************************/
function checkNumber(objValue,strMessage ) {
if (objValue.value == ""){
	// field is blank.  do not validate.
	return true;
}
var intResultValue = validateNumeric( objValue)
if (intResultValue == 0) {
	alert(strMessage);
	// Set flag used to return focus to field.
	blnValueFailed = true;
	return false;
}
else
	return true;
}
/********************************************************
* Description: A wrapper function to validate numeric value
*
* PARAMETERS:
* objValue - String to be tested for validity
**********************************************************/
function checkNumberNoMessage(objValue ) {
if (objValue.value == ""){
	// field is blank.  do not validate.
	return true;
}
var intResultValue = validateNumeric( objValue)
if (intResultValue == 0) {
	// Set flag used to return focus to field.
	blnValueFailed = true;
	return false;
}
else
	return true;
}

function  validateNumeric( objValue ) {
/******************************************************************************
DESCRIPTION: Validates that a string object contains only valid numbers.

PARAMETERS:
   objValue - String to be tested for validity
   
RETURNS:
   True if valid, otherwise false.
******************************************************************************/
 var objRegExp  =  /(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/; 
  
  //check for numeric characters
  return objRegExp.test(objValue.value);
}

/***************************************************************
Description: A wrapper function to validate if number is integer
*
* PARAMETERS:
* objValue - String to be tested for validity
*****************************************************************/
function checkInteger( objValue ) {
if (objValue.value == ""){
	// field is blank.  do not validate.
	return true;
}
else{
	var intResultValue = validateInteger( objValue)
	if (intResultValue == 0) {
		alert("Invalid value.  Value must be an integer.");
		objValue.focus();
		// Set flag used to return focus to field.
		blnValueFailed = true;
		return false;
	}
	else
		return true;
	}
}

function validateInteger( objValue ) {
/************************************************
DESCRIPTION: Validates that a string object contains only 
    valid integer number.
    
PARAMETERS:
   objValue - String to be tested for validity
   
RETURNS:
   True if valid, otherwise false.
******************************************************************************/
  var objRegExp  = /(^-?\d\d*$)/;
 
  //check for integer characters
  return objRegExp.test(objValue.value);
}
/***************************************************************
Description: A function to validate if number is a positive integer
*			 or zero
*
* PARAMETERS:
* objValue - String to be tested for validity
*****************************************************************/
function checkPositiveInteger( objValue ) {
	if (!checkInteger(objValue)) {
		return false;
	}
	else {
		var intValue = objValue.value * 1;
		if (intValue < 0) {
			alert("Value cannot be less than zero");
			objValue.focus();
			// Set flag used to return focus to field.
			blnValueFailed = true;
			return false;
		}
		else {
			return true;
		}
	}
}
			
	
/*****************************************************************************
BEGIN CURRENCY FUNCTIONS*******************************************************************************/
function formatNumericAndCurrency(objInputField, blnInteger, blnIncludeCommas, blnOverrideDecimals, numDigitsAfterDecimal, strCurrencySymbol) {
/***************************************************************
* Description: A function to validate currency and integers.
*				This function also first strips out any currenty
*				symbols and commas.  It then validates that the
*				remaining characters are numeric.  Finally, it
*				it formats the field based on the input arguments
* 				and returns true if number is valid.
*
* PARAMETERS:
* objValue - Form field object to be tested and formatted.
*****************************************************************/

if (blnInteger) {
	if (numDigitsAfterDecimal) {
		alert("Invalid Parameters Passed")
		// Set flag used to return focus to field.
		blnValueFailed = true;
		return false
	}
}
if (objInputField.value != "") {
	if (objInputField.value == 0) {
		//objInputField.value = "";
		objInputField.value = "$0.00";
		return true;
	}
	removeCommas(objInputField);
	removeCurrency(objInputField);

	if (blnInteger) {
		if (validateInteger(objInputField)) {
		// field passed validation okay
		}
		else {
			alert("Number is not an Integer")
			return false
		}
	}
	else {
		if (validateNumeric(objInputField)) {
		// field passed validation okay
		}
		//else {
			//alert("Number is not valid")
			//return false
		//}
	}

	// check for negative value and strip off for future addition.
	if (objInputField.value.substring(0, 1) == '-') {
		// strip off negative sign and set flag
		blnNegativeValue = true
		strTmpValue = objInputField.value
		objInputField.value = strTmpValue.substring(1, strTmpValue.length)
	}
	else {
		blnNegativeValue = false
	}

	// Remove leading zero
 	if (objInputField.value.substring(0,1) == "0"){
		objInputField.value = objInputField.value.substring(1,objInputField.value.length)
	}

	// Check for decimal place existence.
	idxFirstDecimal = objInputField.value.indexOf('.');
	idxLastDecimal  = objInputField.value.lastIndexOf('.');

	if (idxFirstDecimal >= 0) { // At least one decimal point found.
		if (idxLastDecimal != idxFirstDecimal) { // too many decimals error
			alert("Only one decimal point should be entered")
			return false
		}

		aryNum = objInputField.value.split('.')
		numLeftOfDecimal = aryNum[0]
		numRightOfDecimal = aryNum[1]
		if (numLeftOfDecimal == "") {
			numLeftOfDecimal = "0"
		}

	}
	else { // no decimals are present in input number. 
	
		//numLeftOfDecimal = objNumericUnit.InputValue
		numLeftOfDecimal = objInputField.value
		numRightOfDecimal = ""
	}	

	if (blnOverrideDecimals) {
		// Pad right of decimal with trailing zeroes as appropriate
		for (var intDigit = numRightOfDecimal.length; intDigit < numDigitsAfterDecimal; intDigit++) {
			numRightOfDecimal += "0"
		}

		if (numRightOfDecimal.length > 0) { // chop off digits if they entered more than allowed.
			numRightOfDecimal = numRightOfDecimal.substring(0, numDigitsAfterDecimal);
		}
	}	

	if (blnIncludeCommas) {
		switch(numLeftOfDecimal.length) {
			case 0:
				break;
			case 1:
				break;
			case 2:
				break;
			case 3:
				break;
			case 4:
				tmpLeftOfDecimal =	numLeftOfDecimal.substring(0, 1) + 
									"," + 
									numLeftOfDecimal.substring(1,4)
				numLeftOfDecimal =	tmpLeftOfDecimal
				break;
			case 5:
				tmpLeftOfDecimal =	numLeftOfDecimal.substring(0, 2) + 
									"," + 
									numLeftOfDecimal.substring(2,5)
				numLeftOfDecimal =	tmpLeftOfDecimal
				break;
			case 6:
				tmpLeftOfDecimal =	numLeftOfDecimal.substring(0, 3) + 
									"," + 
									numLeftOfDecimal.substring(3,6)
				numLeftOfDecimal =	tmpLeftOfDecimal
				break;
			case 7:
				tmpLeftOfDecimal =	numLeftOfDecimal.substring(0, 1) + 
									"," + 
									numLeftOfDecimal.substring(1,4) + 
									"," + 
									numLeftOfDecimal.substring(4,7)
				numLeftOfDecimal =	tmpLeftOfDecimal
				break;
			case 8:
				tmpLeftOfDecimal =	numLeftOfDecimal.substring(0, 2) + 
									"," + 
									numLeftOfDecimal.substring(2,5) + 
									"," + 
									numLeftOfDecimal.substring(5,8)
				numLeftOfDecimal =	tmpLeftOfDecimal
				break;
			case 9:
				tmpLeftOfDecimal =	numLeftOfDecimal.substring(0, 3) + 
									"," + 
									numLeftOfDecimal.substring(3,6) + 
									"," + 
									numLeftOfDecimal.substring(6,9)
				numLeftOfDecimal =	tmpLeftOfDecimal
				break;
			case 10:
				tmpLeftOfDecimal =	numLeftOfDecimal.substring(0, 1) + 
									"," + 
									numLeftOfDecimal.substring(1,4) + 
									"," + 
									numLeftOfDecimal.substring(4,7) +
									"," +
									numLeftOfDecimal.substring(7,10)
				numLeftOfDecimal =	tmpLeftOfDecimal
				break;
			case 11:
				tmpLeftOfDecimal =	numLeftOfDecimal.substring(0, 2) + 
									"," + 
									numLeftOfDecimal.substring(2,5) + 
									"," + 
									numLeftOfDecimal.substring(5,8) +
									"," +
									numLeftOfDecimal.substring(8,11)
				numLeftOfDecimal =	tmpLeftOfDecimal
				break;
			case 12:
				tmpLeftOfDecimal =	numLeftOfDecimal.substring(0, 3) + 
									"," + 
									numLeftOfDecimal.substring(3,6) + 
									"," + 
									numLeftOfDecimal.substring(6,9) +
									"," +
									numLeftOfDecimal.substring(9,12)
				numLeftOfDecimal =	tmpLeftOfDecimal
				break;
			default:
				alert("A number of length greater than 12 left of the decimal was passed to comma insert routine.  Can only handle up to 12 places")
				return false
				break;
		}
	}

	if (strCurrencySymbol != "") { // create output field with currency symbol on front.
		numLeftOfDecimal = strCurrencySymbol + numLeftOfDecimal
	}

	if (blnNegativeValue) {
		numLeftOfDecimal = "-" + numLeftOfDecimal
	}	
	
	if (numRightOfDecimal.length != 0) {
		objInputField.value = numLeftOfDecimal + "." + numRightOfDecimal
	}
	else { // don't include the decimal point.
		objInputField.value = numLeftOfDecimal
	}
}

	return true;	

}
function checkCurrency(objInputField,intNumDigits,blnFormat){
/***************************************************************
* Description: A wrapper function to check currency and format it
*
* PARAMETERS:
* objInputField - Form field object to be tested and formatted.
*****************************************************************/
	if(objInputField.value == ""){
		// Field is empty - nothing to validate, so field passes check
		return true;
	}
	else{
		// remove formatting.
		removeSpace(objInputField);
		removeCommas(objInputField);
		removeCurrency(objInputField);
		
		if (objInputField.value == 0) {
			//objInputField.value = "$0.00";
			return true;
		}
			
		if(!validateNumeric(objInputField)){
			alert("Invalid currency value!");
			objInputField.value = "";
			objInputField.focus();
			// Set flag used to return focus to field.
			blnValueFailed = true;
			return false;
		}
		else{
			if (objInputField.value < 1) {
				alert("Invalid currency value!");
				objInputField.value = "";
				objInputField.focus();
				// Set flag used to return focus to field.
				blnValueFailed = true;
				return false;
			}
			else {
			// Valid number, so format field.
				if (blnFormat == "true")
					return formatNumericAndCurrency(objInputField,false,true,true,intNumDigits,"$");
				else
					return objInputField.value;
			//return objInputField.value;
			}
		}
	}
}

function checkPercent(objInputField,intNumDigits){
/***************************************************************
* Description: A wrapper function to check percent and format it
*
* PARAMETERS:
* objInputField - Form field object to be tested and formatted.
*****************************************************************/
	if(objInputField.value == ""){
		// Field is empty - nothing to validate, so field passes check
		return true;
	}
	else{
		// remove formatting.
		removeSpace(objInputField);
		removeCommas(objInputField);
		removeCurrency(objInputField);
		
		if (objInputField.value == 0)
			return true;
			
		if(!validateNumeric(objInputField)){
			alert("Invalid Percent value!");
			objInputField.focus();
			// Set flag used to return focus to field.
			blnValueFailed = true;
			return false;
		}
		else{
			if (objInputField.value < 0) {
				alert("Invalid Percent value!");
				objInputField.focus();
				// Set flag used to return focus to field.
				blnValueFailed = true;
				return false;
			}
			else {
			// Valid number, so format field.
			return formatNumericAndCurrency(objInputField,false,true,true,intNumDigits,"");
			}
		}
	}
}
function getCurrencyValue(objInputField){
/***************************************************************
* Description: A function to get the numeric value of a currency
*				field (for use in calculations)
*
* PARAMETERS:
* objInputField - Form field object to be tested and formatted.
*
* RETURNS: integer value of the passed in field.
*****************************************************************/
		// Create object so that original field is not affected
		var objNumericUnit = new Object();
		var intValue;
		objNumericUnit.value = objInputField.value;

		// Remove commas and currency
		intValue=removeSpace(objNumericUnit);
		intValue=removeCommas(objNumericUnit);
		intValue=removeCurrency(objNumericUnit);
	
		// Force js to see value as a number.  If empty, calculate as zero.
		intValue = parseFloat((intValue == "")? 0 : intValue);
		
	return intValue;		
}


/*****************************************************************************
					END CURRENCY FUNCTIONS
*******************************************************************************/


/*****************************************************************************
BEGIN REMOVE FUNCTIONS*******************************************************************************/

function removeCurrency(objValue) {
/************************************************
DESCRIPTION: Removes currency formatting from 
  source string.
  
PARAMETERS: 
  objValue - Source string from which currency formatting
     will be removed;

RETURNS: Source string with commas removed.
*************************************************/
  var objRegExp = /\-/;
  var strMinus = '';
 
  //check if negative
  if(objRegExp.test(objValue.value)){
    strMinus = '-';
  }
  
  objRegExp = /\-|[,]/g;
  objValue.value = objValue.value.replace(objRegExp,'');
  if(objValue.value.indexOf('$') >= 0){
    objValue.value = objValue.value.substring(1, objValue.value.length);
  }
  
  objValue.value = strMinus + objValue.value
  return objValue.value;
}

function removeCommas( objValue ) {
/************************************************
DESCRIPTION: Removes commas from source string.

PARAMETERS: 
  objValue - Source string from which commas will 
    be removed;

RETURNS: Source string with commas removed.
*************************************************/
  var objRegExp = /,/g; //search for commas globally
 
  //replace all matches with empty strings
  var strString = objValue.value.replace(objRegExp,'');
  objValue.value = objValue.value.replace(objRegExp,'');
  return objValue.value;
}

function removeDash( objValue ) {
/************************************************
DESCRIPTION: Removes dashes from source string.

PARAMETERS: 
  objValue - Source string from which dash will 
    be removed;

RETURNS: Source string with dashes removed.
*************************************************/
  var objRegExp = /\-/g; //search for dash globally
 
  //replace all matches with empty strings
  var strString = objValue.value.replace(objRegExp,'');

  objValue.value = objValue.value.replace(objRegExp,'');
}

function removeParenthesis( objValue ) {
/************************************************
DESCRIPTION: Removes Parenthesis from source string.

PARAMETERS: 
  objValue - Source string from which Parenthesis will 
    be removed;

RETURNS: Source string with Parenthesis removed.
*************************************************/
  var objRegExp = /\(|\)/g; //search for Parenthesis globally
 
  //replace all matches with empty strings
  var strString = objValue.value.replace(objRegExp,'');

  objValue.value = objValue.value.replace(objRegExp,'');
}

function removePercent(objValue) {
/************************************************
DESCRIPTION: Removes Percent sign from source string.

PARAMETERS: 
  objValue - Source string from which Percent will 
    be removed;

RETURNS: Source string with Percent removed.
*************************************************/
  var objRegExp = /\%/g; //search for Percent globally
 
  //replace all matches with empty strings
  var strString = objValue.value.replace(objRegExp,'');

  objValue.value = objValue.value.replace(objRegExp,'');
}

function removeSpace(objValue) {
/************************************************
DESCRIPTION: Removes spaces from source string.

PARAMETERS: 
  objValue - Source string from which Space will 
    be removed;

RETURNS: Source string with Space removed.
*************************************************/
  //var objRegExp = /\s/g; //search for Space globally
  
  // The regular expression escape character \s will not match a space character on IE.
  // The expression used here is the long equivalent of escape character \s, with one exception.
  // The space character is specified as Unicode \u00A0 AND a "regular" space ( ) character. 
  // This modified version now works in both IE and Firefox. To summarize:
  //
  //  Expression below works in Firefox, not IE.
  //		var objRegExp = /\s/g; 
  //
  //  Expression below (long form of escape character \s) works in IE, not Firefox
  //		var objRegExp = /[\f\n\r\t\v\u00A0\u2028\u2029]/g;
   
  
  var objRegExp = /[ \f\n\r\t\v\u00A0\u2028\u2029]/g;
 
  //replace all matches with empty strings
  var strString = objValue.value.replace(objRegExp,'');

  objValue.value = objValue.value.replace(objRegExp,'');
}
/*****************************************************************************
					END REMOVE FUNCTIONS
*******************************************************************************/


/**************************************************
DESCRIPTION: A wrapper to check and format SSN

PARAMERTERS:
	 objValue - Source string to be checked

**************************************************/
function checkSSN (objValue) {

	if (objValue.value == "" || objValue.value == null)
		return true;
		
	if (validateSSN (objValue)) {
		formatSSN (objValue);
		return true;
	}
	else {
		alert("Social Security Number is not Valid");
		// Set flag used to return focus to field.
		blnValueFailed = true;
		return false
	}
}
function validateSSN( objValue ) {
/************************************************
DESCRIPTION: Validates that a string contains a 
  valid social security number. 
  
 PARAMETERS:
   objValue - String to be tested for validity
   
RETURNS:
   True if valid, otherwise false.
*************************************************/
var objRegExp = /^\d{3}((\s|\-)?)\d{2}\1\d{4}$/
 
  //check for valid SSN
  return objRegExp.test(objValue.value);

}

function formatSSN ( objValue ) {
/***********************************************
 DESCRIPTION: Format any valid SSN into the following
 	format: ddd-dd-dddd
	
 PARAMETERS:
 	objValue - String to be formatted
	
 RETURNS:
 	the formatted string.
*************************************************/

var objRegExp = /(\s|\-)/g; //search for commas globally
var objRegExp2 = /(\d{3})(\d{2})(\d{4})/;

objValue.value = objValue.value.replace(objRegExp,'').replace(objRegExp2,'$1-$2-$3');
return objValue.value;


}
/**************************************************
DESCRIPTION: A wrapper to check and format Phone Number
*
PARAMERTERS:
	 objValue - Source string to be checked
*
**************************************************/
function checkPhoneNumber (objValue, strMessage) {

	if (objValue.value == "" || objValue.value == null)
		return true;
		
	if (validatePhoneNumber (objValue)) {
		formatPhoneNumber (objValue);
		return true;
	}
	else {
		alert(strMessage);
		//sobjValue.value = "";
		objValue.focus();
		// Set flag used to return focus to field.
		blnValueFailed = true;
		return false
	}
}
function validatePhoneNumber( objValue ) {
/************************************************
DESCRIPTION: Validates that a string contains a 
  valid Phone number. 
  
 PARAMETERS:
   objValue - String to be tested for validity
   format allowed: nnn-nnn-nnnn
   or			   nnnnnnnnnn
   or			   nnn-nnnnnnn
   or			   nnnnnn-nnnn
   or			  (nnn)nnn-nnnn
   or			  (nnn) nnn-nnnn
   or			  (nnn)nnnnnnn
   or			  (nnn) nnnnnnn
			--------------------- new
			or      nnn-nnn-nnnn
			or      nnn nnn nnnn
			or     (nnn) nnn nnnn
			or     (nnn)-nnn-nnnn
      
RETURNS:
   True if valid, otherwise false.
*************************************************/
var objRegExp = /((^\d{3})|(^(\()\d{3}(\))))(((-)|(\s))?)\d{3}(((-)|(\s))?)\d{4}$/

  //check for valid phone number
  return objRegExp.test(objValue.value);

}

function formatPhoneNumber ( objValue ) {
/***********************************************
 DESCRIPTION: Format any valid SSN into the following
 	format: (nnn) nnn-nnnn
	
 PARAMETERS:
 	objValue - String to be formatted
	
 RETURNS:
 	the formatted string.
*************************************************/

var objRegExp = /(\-|\(|\)|\s)/g; 
var objRegExp2 = /(\d{3})(\d{3})(\d{4})/;

objValue.value = objValue.value.replace(objRegExp,'').replace(objRegExp2,'($1) $2-$3');
return objValue.value;


}
 	
/**************************************************
DESCRIPTION: A wrapper to check and format Zip Code
*
PARAMERTERS:
	 objValue - Source string to be checked
*
**************************************************/
function checkZipCode (objValue) {
	
	if (objValue.value == "" || objValue.value == null)
		return true;
		
	if (validateZipCode(objValue)) {
		return true;
	}
	else {
		alert("Zip Code is not Valid");
		objValue.value="";
		objValue.focus();
		// Set flag used to return focus to field.
		blnValueFailed = true;
		return false
	}
}
function validateZipCode( objValue ) {
/************************************************
DESCRIPTION: Validates that a string contains a 
  valid Zip Code. 
  
 PARAMETERS:
   objValue - String to be tested for validity
   format allowed: 12345
   				   12345-6789
   
RETURNS:
   True if valid, otherwise false.
*************************************************/

var objRegExp = /(^\d{5}$)|(^\d{5}-\d{4}$)/

  //check for valid Zip Code
  return objRegExp.test(objValue.value);

}
/**************************************************
DESCRIPTION: A wrapper to check and format email address

PARAMERTERS:
	 objValue - Source string to be checked

**************************************************/
function checkEmail (objValue) {

	if (objValue.value == "" || objValue.value == null)
		return true;
		
	if (validateEmail (objValue)) {
		return true;
	}
	else {
		alert("Email Address is not Valid");
		// Set flag used to return focus to field.
		objValue.value = "";
		objValue.focus();
		blnValueFailed = true;
		return false
	}
}
/**************************************************
DESCRIPTION: A wrapper to check and format email address
This version will not erase the existing data

PARAMERTERS:
	 objValue - Source string to be checked

**************************************************/
function checkEmailNoErase (objValue) {

	if (objValue.value == "" || objValue.value == null)
		return true;
		
	if (validateEmail (objValue)) {
		return true;
	}
	else {
		alert("Email Address is not Valid");
		// Set flag used to return focus to field.
		objValue.focus();
		blnValueFailed = true;
		return false
	}
}
function validateEmail( objValue ) {
/************************************************
DESCRIPTION: Validates that a string contains a 
  valid email address. 
  
 PARAMETERS:
   objValue - String to be tested for validity
   
RETURNS:
   True if valid, otherwise false.
*************************************************/

//var objRegExp = /^\w+(\.{1})\w+(\@{1})\w+(\.{1})(com|org|edu|gov)$/
//var objRegExp = /^(.(\W*\w*(\.?)\W*\w*(\.?))+)(\@{1})(.(\W*\w*(\.?)\W*\w*(\.?))+)(com|org|edu|gov|mil)$/
//var objRegExp = /^\w+(\.{1})\w+\W*\w+(\@{1})\w(+)(\.{1})(com|org|edu|gov|mil)$/
//var objRegExp = /^[\w\.-]+(\@{1})[\w\.-]+(com|org|edu|gov|mil|net|biz|au|ca|de|jp|mx|nz|uk|us){1}$/
var objRegExp = /^[\w\.-]+(\@{1})[\w\.-]+$/

 
  //check for valid Email
  return objRegExp.test(objValue.value);

}
/************************************************
DESCRIPTION: function to automatically populate the Country
			 drop down when a certain state is selected
			 
PARAMETERS: o_State - object of the state form field
			s_FormName - String of the form name of the calling program
			s_Cntry - string that contains the name of the form field name of the country drop down box
			
*************************************************/
function processState(o_State,s_FormName,s_Cntry) {
	var s_Value = o_State.options[o_State.selectedIndex].value;
	var a_Array = s_Value.split("-");  // break the value attribute of state form field control into 2 parts:
									   // ste_prov_cd-cntry_cd, a_Array[0] is ste_prov_cd, and a_Array[1] is cntry_cd
	var o_FormName = eval("document." + s_FormName);
	var o_Cntry = eval("document." + s_FormName + "." + s_Cntry);
	if (s_Value == "0") {
		o_Cntry.selectedIndex = 0;
	}
	else {
		for (var i=0; i<o_Cntry.length; i++) {
			if (o_Cntry.options[i].value == a_Array[1]) {
					o_Cntry.selectedIndex = i;
					break;
			}
		}
	}
}
/************************************************
DESCRIPTION: function to automatically check if the country currently
			selected correspond to the state being selected
			
PARAMETER: o_Country - object of the country form field
		   s_FormName - String of the form name of the calling program
		   s_State - string that contains the name of the form field name of the state drop down box
		   b_display - boolean to determine whether to display the alert box or not
*************************************************/
function processCountry(o_Country,s_FormName,s_State,b_display) {
	var s_CntryText = o_Country.options[o_Country.selectedIndex].text;
	var s_CntryValue = o_Country.options[o_Country.selectedIndex].value;
	var o_FormName = eval("document." + s_FormName);
	var o_State = eval("document." + s_FormName + "." + s_State);
	var s_StateCntryText = o_State.options[o_State.selectedIndex].text;
	if (s_CntryValue == "0"){ // if country is not selected, make sure state is not selected
		o_State.selectedIndex = 0;
	}
	else { // otherwise, if the country does not correspond to the state, default both state and country
			// back to the default values when the form is loaded
		if (s_StateCntryText != s_CntryText) {
			if (b_display) {
				alert("Country selected did not match state selected from State drop down box");
			}
			for (var i=0; i <o_Country.length; i++) {      
				if (o_Country.options[i].defaultSelected == true) {         
					o_Country.options[i].selected=true;
				}   
			}
			for (var i=0; i<o_State.length; i++) {
				if (o_State.options[i].defaultSelected == true) {
					o_State.options[i].selected=true;
				}
			}
			return false;
		}
		else { return true; }
	}
}
/************************************************
DESCRIPTION: function to automatically populate the status code
			 drop down when a certain reason code is selected
			 
PARAMETERS: o_RChgStatus - object of the state form field
			s_FormName - String of the form name of the calling program
			s_statcd - string that contains the name of the form field name of the Rstatus drop down box
			
*************************************************/
function ProcessStatusChange(o_RChgStatus,s_FormName,s_statcd) {
	var s_Value = o_RChgStatus.options[o_RChgStatus.selectedIndex].value;
	var a_Array = s_Value.split("-");  // break the value attribute of RChgStatus form field control into 2 parts:
									   // sts_chng_rsn_cd-rvwr_sts_cd, a_Array[0] is sts_chng_rsn_cd, and a_Array[1] is rvwr_sts_cd
	var o_FormName = eval("document." + s_FormName);
	var o_statcd = eval("document." + s_FormName + "." + s_statcd);
	if (s_Value == "0") {
		o_statcd.selectedIndex = 0;
	}
	else {
		for (var i=0; i<o_statcd.length; i++) {
			if (o_statcd.options[i].value == a_Array[1]) {
					o_statcd.selectedIndex = i;
					break;
			}
		}
	}
}
/************************************************
DESCRIPTION: function to automatically check if the status currently
			selected correspond to the reason code being selected
			
PARAMETER: o_Rstatus - object of the Rstatus form field
		   s_FormName - String of the form name of the calling program
		   s_RChgStatus - string that contains the name of the form field name of the state drop down box
		   b_display - boolean to determine whether to display the alert box or not
*************************************************/
function ProcessStatus(o_Rstatus,s_FormName,s_RChgStatus,b_display) {
	var s_statcdText = o_Rstatus.options[o_Rstatus.selectedIndex].text;
	var s_statcdValue = o_Rstatus.options[o_Rstatus.selectedIndex].value;
	var o_FormName = eval("document." + s_FormName);
	var o_RChgStatus = eval("document." + s_FormName + "." + s_RChgStatus);
	var s_statChgstatcdText = o_RChgStatus.options[o_RChgStatus.selectedIndex].text;
	if (s_statcdValue == "0"){ // if Rstatus is not selected, make sure RChgStatus is not selected
		o_RChgStatus.selectedIndex = 0;
	}
	else { // otherwise, if the Rstatus does not correspond to the state, default both state and Rstatus
			// back to the default values when the form is loaded
		if (s_statChgstatcdText != s_statcdText) {
			if (b_display) {
				alert("Status selected did not match reason selected from reason status drop down box");
			}
			for (var i=0; i <o_Rstatus.length; i++) {      
				if (o_Rstatus.options[i].defaultSelected == true) {         
					o_Rstatus.options[i].selected=true;
				}   
			}
			for (var i=0; i<o_RChgStatus.length; i++) {
				if (o_RChgStatus.options[i].defaultSelected == true) {
					o_RChgStatus.options[i].selected=true;
				}
			}
			return false;
		}
		else { return true; }
	}
}



function normalizeProjectNumber(objValue) {

  if (objValue.length == 4) {
		  objValue= '00-00-' + objValue;
	 }
		return objValue;
 }

function formatCurrency(num) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num)) num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if (cents < 10) cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	num = num.substring(0,num.length-(4*i+3))+','+
	num.substring(num.length-(4*i+3));
	//alert('formatCurrency will return: '+((sign)?'':'-') + '$' + num + '.' + cents+'!');
	return (((sign)?'':'(') + '$' + num + '.' + cents +((sign)?'':')'));
}
// function to cotnrol the timer shown of the page

var milisec = 0;
var seconds = 0;
var minutes = 0;
var hours = 0;
function displayClock(s_Form){
var o_Form;
	o_Form = eval("document." + s_Form);
	if (milisec>=9){
		 milisec=0;
		 seconds+=1;
		 if (seconds>=60) {
			seconds = 0;
			minutes+=1;
		}
		if (hours>=60) {
			minutes = 0;
			hours+=1;
		}
	}
	else {
		 milisec+=1;
		 
	}
	if (hours == 2) {
		location.href = "<cfoutput>#application.s_RootPath#</cfoutput>/logout.cfm?timeOut=yes";
	}
	else {
		o_Form.t_timeElapsedDisplay.value = hours + " hours " + minutes + " minutes " + seconds + " seconds";
		setTimeout("displayClock('"+ s_Form +"')",100);
	}
}




function checkGMISProjectNumber (objValue) {
	
	if (objValue.value == "" || objValue.value == null)
		return true;
		
	if (validateGMISProjectNumber(objValue)) {
		return true;
	}
	else {
		alert("GMIS project number is not a valid format. The valid format is:" +
			"\n\n\t70NANBxHxxxx\n\n" +
			"where each lower case \"x\" in the format string must be a digit (0-9). \n\n\tExample: 70NANB3H3001");
		objValue.value="";
		objValue.focus();
		return false
	}
	
	return true;
}

function validateGMISProjectNumber( objValue ) {
/************************************************
DESCRIPTION: Validates that a string contains a 
    valid GMIS project number
    Ex. 70NANBnHnnnn
    
PARAMETERS:
   objValue - GMIS project number field to be tested for validity
   
RETURNS:
   True if valid, otherwise false.
   
REMARKS:
   Avoids some of the limitations of the Date.parse()
   method such as the date separator character.
*************************************************/
  var objRegExp = /^70NANB\d{1}H\d{4}$/
  
  return objRegExp.test(objValue.value);  
}


/*
 * textCounter.js
 */

/***************************************************
DESCRIPTION: Tracks number of characters typed into textarea 
	and displays counter for remaining characters 
    
PARAMETERS:
   objField - the name of textarea to check length
   counterField - readonly display for number of characters
   	remaining
   maxlength - maximum number of characters allowed
      
RETURNS:
   None
   
USAGE:
<textarea name="textarea1" 
	onKeyDown="textCounter(document.formName.textarea1,document.formName.counterField1,2000)"
	onKeyUp="textCounter(document.formName.textarea1,document.formName.counterField1,2000)">
</textarea>

<input readonly type="text" name="counterField1" size="4" maxlength="4" value="2000"> remaining characters

***************************************************/

function textCounter(objField, counterField, maxLength) {
	if (objField.value.length > maxLength) {
		//alert("Maximum number of characters reached!");
		objField.value = objField.value.substring(0, maxLength);
	}
	else {
		counterField.value = maxLength - objField.value.length;
	}
}
