// ===================== Functions for Online Field Validations -- (Begin) ==================================


/**
 * <p>Title: field_validation.js</p>
 * <p>Description: </p>
 * <p>Copyright: </p>
 * <p>Company: filogix</p>
 * @author henryk
 * @version -1.0
 */

// =======================================================================================
// Function to left trim a String
// =======================================================================================
function ltrim(argvalue) {

  while (1) {
    if (argvalue.substring(0, 1) != " ") break;
    argvalue = argvalue.substring(1, argvalue.length);
  }

  return argvalue;
}

// =======================================================================================
// Function to right trim a String
// =======================================================================================
function rtrim(argvalue) {

  while (1) {
    if (argvalue.substring(argvalue.length - 1, argvalue.length) != " ")
      break;
    argvalue = argvalue.substring(0, argvalue.length - 1);
  }

  return argvalue;
}

//****************************************************************************
//****************************************************************************
function hilight(field) {
	field.focus();
	field.select();
}

//****************************************************************************
//****************************************************************************
function clr(txfield) {
	txfield.value="";
}

//****************************************************************************
//****************************************************************************
function clrCB(cbField) {
	cbField.selectedIndex = 0;
}


//****************************************************************************
//****************************************************************************
function isDigit(inp){
	if(inp == '0' || inp == '1' || inp == '2'  || inp == '3' || inp == '4' ||
	   inp == '5' || inp == '6' || inp == '7'  || inp == '8' || inp == '9'){
		return true;
	}

	return false;
}


//****************************************************************************
//****************************************************************************
// Function to check if the input value is an Alpha char only
function isAlpha(inValue){
	for(var i=0;i<inValue.length;i++){
		if(  isDigit(inValue.charAt(i)) == true ){
			alert(NUMERALS_NOT_ALLOWED);
			return false;
		}
	}
	return true;
}

//****************************************************************************
//****************************************************************************
function isAlphaCharacter(s){
	if(s == null) return false;
	if(s.length == 0) return false;

	for(var i=0; i<s.length; ++i) {
		if("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".indexOf(s.charAt(i)) < 0) {
			return false;
		}
	}
	return true;
}


//****************************************************************************
//****************************************************************************
// Function to check if the input value includes a special characters
// Function to check if the input value is an Integer
function isInteger(inValue){
	for(var i=0;i<inValue.length;i++){
		if(  isDigit(inValue.charAt(i)) == false ){
			return false;
		}
	}
	return true;
}

//****************************************************************************
//****************************************************************************
// Function to check if the input value includes a special characters
// that causes troubles for the BXP document processing.
function isSpecialCharacter(inValue){
	for(var i=0;i<inValue.length;i++){
		if(  inValue.charAt(i) == '>' || inValue.charAt(i) == '<' ||
		     inValue.charAt(i) == '\"' || inValue.charAt(i) == '\&'){
			return false;
		}
	}
	return true;
}

//****************************************************************************
//****************************************************************************
// Function to check if the input value is a Decimal
//function isDecimal(inValue){
//	decimalFound = false;
//
//	for(var i=0;i<inValue.length;i++){
//		if( isDigit(inValue.charAt(i)) == false ){
//			if( inValue.charAt(i) == '.' && decimalFound == false ){
//				decimalFound = true;
//			}
//			else{
//				return false;
//			}
//		}
//	}
//	return true;
//}
//
function isDecimal(inValue){
	decimalFound = true;
    dotFound = false;

	for(var i=0;i<inValue.length;i++){
		if (i==0 && inValue.charAt(i)=='-' && inValue.length>1) {
			continue;
		} else if( isDigit(inValue.charAt(i)) == false ){
			if(  inValue.charAt(i) != '.' ){
				decimalFound = false;
                break;
			} else if ( dotFound ) {
				decimalFound = false;
                break;
			} else {
              	dotFound = true;
            }
		}
	} if (  dotFound   && inValue.length < 2 ) {
      	decimalFound = false;
	}
	return decimalFound;
}

//****************************************************************************
//****************************************************************************
// Function to check if the input value includes a special characters
// Function to round a Value to a Specified Number of Decimals and pad Zero(s)
function round_decimals(original_number, decimals){
	var result1 = original_number * Math.pow(10, decimals);
	var result2 = Math.round(result1);
	var result3 = result2 / Math.pow(10, decimals);
	return pad_with_zeros(result3, decimals);
}

//****************************************************************************
//****************************************************************************
// Function to check if the input value includes a special characters
function pad_with_zeros(rounded_value, decimal_places){
	// Convert the number to a string
	var value_string = rounded_value.toString();

	// Locate the decimal point
	var decimal_location = value_string.indexOf(".");
	// Is there a decimal point?
	if (decimal_location == -1){
		// If no, then all decimal places will be padded with 0s
		decimal_part_length = 0;
		// If decimal_places is greater than zero, tack on a decimal point
		value_string += decimal_places > 0 ? "." : "";
	}
	else{
		// If yes, then only the extra decimal places will be padded with 0s
		decimal_part_length = value_string.length - decimal_location - 1;
	}

	// Calculate the number of decimal places that need to be padded with 0s
	var pad_total = decimal_places - decimal_part_length;

	if (pad_total > 0){
		// Pad the string with 0s
		for (var counter = 1; counter <= pad_total; counter++){
			value_string += "0";
		}
	}
	return value_string;
}


//****************************************************************************
//****************************************************************************
// Function to check if the input value includes a special characters
// Function to check if the year is a leap year
function isLeapYear(intYear) {
	if (intYear % 100 == 0){
		if (intYear % 400 == 0) {
			return true;
		}
	}
	else{
		if ((intYear % 4) == 0) {
			return true;
		}
	}
	return false;
}

//****************************************************************************
//****************************************************************************
// Function to check if the input value includes a special characters
function getMonthVal(str){
	if(str == "" || str == "0.0"){
		return 0;
	}
	if(str == "Jan" || str == "January"  || str == "1.0" ){
		return 1;
	}
	if(str == "Feb" || str == "February"  || str == "2.0"){
		return 2;
	}
	if(str == "Mar" || str == "March"  || str == "3.0"){
		return 3;
	}
	if(str == "Apr" || str == "April"  || str == "4.0"){
		return 4;
	}
	if(str == "May"  || str == "5.0"){
		return 5;
	}
	if(str == "Jun" || str == "June"  || str == "6.0"){
		return 6;
	}
	if(str == "Jul" || str == "July"  || str == "7.0"){
		return 7;
	}
	if(str == "Aug" || str == "August"  || str == "8.0"){
		return 8;
	}
	if(str == "Sep" || str == "September"  || str == "9.0"){
		return 9;
	}
	if(str == "Oct" || str == "October"  || str == "10.0"){
		return 10;
	}
	if(str == "Nov" || str == "November"  || str == "11.0"){
		return 11;
	}
	if(str == "Dec" || str == "December"  || str == "12.0"){
		return 12;
	}
	// else return 0
	return 0;
}


//****************************************************************************
//****************************************************************************
// Function to check if the attached field value is an Integer with requestLength
//		Note : if requestLength = 0 means any length
function isFieldInteger(requestLength, field,vfieldName){
	var theField = field;
	var theFieldValue = theField.value;
	var theFieldName = theField.name;

	if(theFieldValue == ""){
		currFieldToValidate = "";
		return true;
	}

	if( !isInteger(theFieldValue) ){
  		alert(NUMERIC_ONLY);
		var tmp = theField.value;
		theField.focus();
		theField.select();
		return false;
	}
	else{
		// Check Length
		if( requestLength > 0 ){
			if( theFieldValue.length != requestLength ){
				alert(printf(INPUT_NUM_DIGITS, requestLength));
				theField.focus();
				theField.select();
				return false;
			}
		}
	}
	currFieldToValidate = "";
	return true;
}

//****************************************************************************
//****************************************************************************
// Function to check if the attached field value is within the range (integer)
function isFieldInIntRange(min, max, field){
	var theField = field;
	var theFieldValue = theField.value;
	var theFieldName = theField.name;


	if(theFieldValue == ""){
		currFieldToValidate = "";
		return true;
	}

	if( !isInteger(theFieldValue) ){
		//--> Ticket#4191: Warning message is against special coding instruction in BRD
    //--> By BingLi 28Apr2005
    //alert(NUMERIC_ONLY);
    alert(printf(INPUT_INTVALUE_RANGE, min, max));
    //-->============================End of changes for Ticket#4191=====================================
		var tmp = theField.value;
		theField.focus();
		theField.select();
		return false;
	}
	else{
		// Check Length
               //being: SCR 3097, Wei Li, Jan 25, 2005
		if( theFieldValue < parseInt(min) || theFieldValue > parseInt(max) ){
			alert(printf(INPUT_INTVALUE_RANGE, min, max));
			theField.focus();
			theField.select();
			return false;
		}
                //end: SCR 3097, Wei Li, Jan 25, 2005
	}
	currFieldToValidate = "";
	return true;
}


//****************************************************************************
//****************************************************************************
// Function to check if the attached field value is within the range (decimal)
function isFieldInDecRange(min, max, field){
	var theField = field;
	var theFieldValue = theField.value;
	var theFieldName = theField.name;

	if(theFieldValue == ""){
		currFieldToValidate = "";
		return true;
	}

	if( !isDecimal(theFieldValue) ){
		alert(INVALID_DECIMAL);
		var tmp = theField.value;
		theField.focus();
		theField.select();
		return false;
	}
	else{
            	// Check Length
		if( theFieldValue < min || theFieldValue > max ){
                    	// force 3 decimal if the max is 3 decimal
                        var  maxField=field;
        		 maxField.value=max;
                        var theSplitedValues = maxField.value.split(".");
			if(theSplitedValues.length > 1){
				if(theSplitedValues[1].length == 3){
                        		alert(printf(INPUT_VALUE_RANGE_3DECIMAL, min, max));
                                      	theField.focus();
					theField.select();
					return false;
				}
                        }
                        // end of SCR 2717
                        alert(INPUT_VALUE_RANGE_PERCENTAGES);
			theField.focus();
			theField.select();
			return false;
		}
	}
	currFieldToValidate = "";
	return true;
}


//****************************************************************************
//****************************************************************************
// Function to check if the attached field value is an Alpha string with any length
function isFieldAlpha(field){
	var theField = field;
	var theFieldValue = theField.value;
	var theFieldName = theField.name;

	if(theFieldValue == ""){
		currFieldToValidate = "";
		return true;
	}

	if( !isAlpha(theFieldValue) ){
		theField.focus();
		theField.select();
		return false;
	}
	currFieldToValidate = "";
	return true;
}

//****************************************************************************
//****************************************************************************
// Function to check if the attached field value is an Alpha string with any length
function isFieldHasSpecialChar(field){
	var theField = field;
	var theFieldValue = theField.value;
	var theFieldName = theField.name;

	if(theFieldValue == ""){
		currFieldToValidate = "";
		return true;
	}

	if( !isSpecialCharacter(theFieldValue) ){
		alert(DO_NOT_USE_SPECIAL_CHARACTERS);
		theField.focus();
		theField.select();
		return false;
	}
	currFieldToValidate = "";
	return true;
}

//****************************************************************************
//****************************************************************************
// Function to check and convert the attached fieldvalue to a Decimal number with # of decimal place = numDecPlace
function isFieldDecimal(numDecPlace, field){
	var theField = field;
	var theFieldValue = theField.value;
	var theFieldName = theField.name;

	if(theFieldValue == ""){
		currFieldToValidate = "";
		return true;
	}

	if( !isDecimal(theFieldValue) ){
		alert(INVALID_DECIMAL);
		theField.focus();
		theField.select();
		return false;
	}

	// Check for precision
	var theSplitedValues = theFieldValue.split(".");
	if(theSplitedValues.length > 1){
		if(theSplitedValues[1].length > numDecPlace){
			alert(printf(MAX_PRECISION, numDecPlace));
			theField.focus();
			theField.select();
			return false;
		}
		// Fix#2487 Modified by Michael Lee
		if(theSplitedValues[1].length == numDecPlace){
			currFieldToValidate = "";
			return true;
		}
	}

	// Convert field to correct format
	// Fix#2487 Modified by Michael Lee
	theField.value = pad_with_zeros(theField.value, numDecPlace);
	currFieldToValidate = "";
	return true;
}

//****************************************************************************
//****************************************************************************
// Function to Check Postal Code : FSA
function isFieldFSA(field){
	var theField = field;
	var theFieldValue = theField.value;
	var theFieldName = theField.name;

	if(theFieldValue == ""){
		currFieldToValidate = "";
		return true;
	}

	if(theFieldValue.length != 3){
		alert(INVALID_POSTAL_CODE);
		theField.focus();
		theField.select();
		return false;
	}

	if(theFieldValue.length == 3){
		var fletter = theFieldValue.charAt(0);
		var sdigit = theFieldValue.charAt(1);
		var tletter = theFieldValue.charAt(2);

		if(!isAlphaCharacter(fletter) || !isDigit(sdigit) || !isAlphaCharacter(tletter)){
			alert(INVALID_POSTAL_CODE);
			theField.focus();
			theField.select();
			return false;
		}

	}
	theField.value = theFieldValue.toUpperCase();
	currFieldToValidate = "";
	return true;
}

//****************************************************************************
//****************************************************************************
// Function to Check Postal Code : LDU
function isFieldLDU(field){
	var theField = field;
	var theFieldValue = theField.value;
	var theFieldName = theField.name;

	if(theFieldValue == ""){
		currFieldToValidate = "";
		return true;
	}

	if(theFieldValue.length != 3){
		alert(INVALID_POSTAL_CODE);
		theField.focus();
		theField.select();
		return false;
	}

	if(theFieldValue.length == 3){
		var lletter = theFieldValue.charAt(0);
		var ddigit = theFieldValue.charAt(1);
		var uletter = theFieldValue.charAt(2);

		if(!isDigit(lletter) || !isAlphaCharacter(ddigit) || !isDigit(uletter)){
			alert(INVALID_POSTAL_CODE);
			theField.focus();
			theField.select();
			return false;
		}

	}
	theField.value = theFieldValue.toUpperCase();
	currFieldToValidate = "";
	return true;
}


//****************************************************************************
//****************************************************************************
//New Function based on get1stPartName. The old get1stPartName is now not used.

function extract1stPartName(control_Full_Name)
{
	//alert(control_Full_Name.name);
	var pos1 = control_Full_Name.indexOf("_");
	var pos2 = control_Full_Name.lastIndexOf("_");
	//Check if not Repeated ; if not repeat format just returns
	if(pos1 < 0 || pos2 < 0 || pos1 >= pos2) return "";

  var name1stPart = control_Full_Name.substring(0, pos1 + 3);
	return name1stPart;
}
//****************************************************************************
//****************************************************************************
//New Function to get first part of Ccontrol name in JATO repeated format
// Input -- control full name e.g. "pgPageName_RepeatName[2]_controlName"
// Output -- the first part of name e.g. "pgPageName_RepeatName["
//  -- By Billy 08July2002
function get1stPartName(control_Full_Name)
{
	//alert(control_Full_Name.name);
	var pos1 = control_Full_Name.lastIndexOf("[");
	var pos2 = control_Full_Name.lastIndexOf("]");
	//alert("get1stPartName::pos1::" + pos1 + "  pos2::" + pos2);

	//Check if not Repeated (Note: if not repeat format just return the fullname)
	 if(pos1 < 0 || pos2 < 0 || pos1 >= pos2) return control_Full_Name;

	var name1stPart = control_Full_Name.substring(0, pos1 + 1);
	//alert("get1stPartName::name1stPart::" + name1stPart);
	return name1stPart;
}

//****************************************************************************
//****************************************************************************
//New Function to get second part of Ccontrol name in JATO repeated format
// Input -- control full name e.g. "pgPageName_RepeatName[2]_controlName"
// Output -- the first part of name e.g. "pgPageName_RepeatName["
//  -- By Billy 08July2002
function get2ndPartName(control_Full_Name)
{
	var pos1 = control_Full_Name.lastIndexOf("[");
	var pos2 = control_Full_Name.lastIndexOf("]");
	//alert("get2ndPartName::pos1::" + pos1 + "  pos2::" + pos2);

	//Check if not Repeated (Note: if not repeat format just return "")
	 if(pos1 < 0 || pos2 < 0 || pos1 >= pos2) return "";

	var name2ndPart = control_Full_Name.substring(pos2, control_Full_Name.length);
	return name2ndPart;
}

//****************************************************************************
//****************************************************************************
function getRepeatRowId(myCtl){
	//alert("getRepeatRowId::start");

	var tmpCtlName = myCtl.name;
	//alert("getRepeatRowId::tmpCtlName::" + tmpCtlName);
	if(tmpCtlName.indexOf("checkbox") != -1){
		tmpCtlName = tmpCtlName.substring(9, tmpCtlName.length);
	}

	var pos1 = tmpCtlName.indexOf("_");
	//alert('111');
	var pos2 = tmpCtlName.lastIndexOf("_");
	//alert('222');
	//alert("getRepeatRowId::pos1::" + pos1 + "  pos2::" + pos2);

	//Check if not Repeated
	if(pos1 < 0 || pos2 < 0 || pos1 >= pos2) return -1;
	//alert('didnt return -1');

	var tmpRowNum = -1;
	tmpRowNum = tmpCtlName.substring(pos1+1, pos2) * 1;
	//alert("getRepeatRowId::the substring = " + tmpCtlName.substring(pos1+1, pos2));
	//alert("getRepeatRowId::CurRowNum::" + tmpRowNum);

	return tmpRowNum;
}
//****************************************************************************
//****************************************************************************
// This function is more generic than isFieldValidDuration(theYear, theMonth, field)
// It takes only two parameters : durYpes = amort or term, field = current field.
// It can be used anywhere where we have the list of editable  mortgages.

function isTermOrAmortValidDuration(durType,field){

name1stPart = extract1stPartName(field.name);
var theMonth =  name1stPart + durType + "Months" ;
var theYear =  name1stPart + durType + "Years" ;

return isFieldValidDuration(theYear, theMonth, field);
}
//****************************************************************************
//****************************************************************************
// Function to check for the Duration (# of Year and # of Month)
//		Month should be 0 to 11 if Year input. Otherwise Month can be 0 to 99.
function isFieldValidDuration(theYear, theMonth, field){
	var theField = field;
	var theFieldValue = "";
	var theFieldName = "";
	var rowId = -1;
	var name1stPart = "";
//alert(theYear + theMonth + theField.name);
	if ( theField != null ) {
		theFieldValue = theField.value;
		theFieldName = theField.name;
		rowId = getRepeatRowId(theField);
		name1stPart = get1stPartName(theFieldName);
	}
	var inputRowNdx = "";
	if (rowId != -1) inputRowNdx = rowId+"]_";
    
	var theYearCtl = eval("document.forms[0]." + theYear);
	var theMonthCtl = eval("document.forms[0]." + theMonth);

	var theYearCtl, theMonthCtl;
	//alert("document.forms[0]." + theYear);
	if (rowId != -1) {
		theYearCtl = eval("document.forms[0]."+ theYear);
		theMonthCtl = eval("document.forms[0]." + theMonth);
	} else {
		theYearCtl = eval("document.forms[0]." + theYear);
		theMonthCtl = eval("document.forms[0]." + theMonth);
	}

	//alert(theYearCtl);
	//alert(theYearCtl.value);
	var theYearValue = theYearCtl.value;
	var theMonthValue = theMonthCtl.value;
	//alert('isFieldValidDuration ---444');


	// Check if Year input > 0
	if(theYearValue > 0){
	// Check # of years 0-80
	if(theYearValue > 80){
			alert(NUM_YEARS);
			theYearCtl.focus();
			theYearCtl.select();
			currFieldToValidate = theYear;
			return false;
	}
	//maximum is 80. if year is 80, month must be 0.
      else if (theYearValue == 80 && theMonthValue >0)
      {
	      alert(MAX_YEAR);
	      theMonthCtl.focus();
			  theMonthCtl.select();
			  currFieldToValidate = theMonth;
			  return false;
     }
	// Check # of Month 0-11
		else if(theMonthValue > 11){
			alert(NUM_MONTHS);
			theMonthCtl.focus();
			theMonthCtl.select();
			currFieldToValidate = theMonth;
			return false;
		}
	}
	currFieldToValidate = "";
	return true;
}

function isFieldValidAmortTermDuration(theYear, theMonth, field){
	var theField = field;
	var prefix = "m_" + theField.name.substring(theField.name.indexOf("_") + 1,theField.name.lastIndexOf("_") + 1);
	var theFieldValue = "";
	var theFieldName = "";
	var rowId = -1;
	var name1stPart = "";
//alert(theYear + theMonth + theField.name);
	if ( theField != null ) {
		theFieldValue = theField.value;
		theFieldName = theField.name;
		rowId = getRepeatRowId(theField);
		name1stPart = get1stPartName(theFieldName);
	}
	var inputRowNdx = "";
	if (rowId != -1) inputRowNdx = rowId+"]_";
    
	var theYearCtl = eval("document.forms[0]." + prefix + theYear);
	var theMonthCtl = eval("document.forms[0]." + prefix + theMonth);

	var theYearCtl, theMonthCtl;
	//alert("document.forms[0]." + theYear);
	if (rowId != -1) {
		theYearCtl = eval("document.forms[0]."+ prefix + theYear);
		theMonthCtl = eval("document.forms[0]." + prefix + theMonth);
	} else {
		theYearCtl = eval("document.forms[0]." + prefix + theYear);
		theMonthCtl = eval("document.forms[0]." + prefix + theMonth);
	}

	//alert(theYearCtl);
	//alert(theYearCtl.value);
	var theYearValue = theYearCtl.value;
	var theMonthValue = theMonthCtl.value;
	//alert('isFieldValidDuration ---444');


	// Check if Year input > 0
	if(theYearValue > 0){
	// Check # of years 0-80
	if(theYearValue > 80){
			alert(NUM_YEARS);
			theYearCtl.focus();
			theYearCtl.select();
			currFieldToValidate = theYear;
			return false;
	}
	//maximum is 80. if year is 80, month must be 0.
      else if (theYearValue == 80 && theMonthValue >0)
      {
	      alert(MAX_YEAR);
	      theMonthCtl.focus();
			  theMonthCtl.select();
			  currFieldToValidate = theMonth;
			  return false;
     }
	// Check # of Month 0-11
		else if(theMonthValue > 11){
			alert(NUM_MONTHS);
			theMonthCtl.focus();
			theMonthCtl.select();
			currFieldToValidate = theMonth;
			return false;
		}
	}
	currFieldToValidate = "";
	return true;
}

//****************************************************************************
//****************************************************************************
// Function to check if the max length of the field
function isFieldMaxLength(maxLength,field){
	var theField =field;
	var theFieldValue = theField.value;
	var theFieldName = theField.name;

	// Check if this is the current field to validate
	//		-- In order to prevent dead lock
//	if( currFieldToValidate == "" || currFieldToValidate == theFieldName ){
//		currFieldToValidate = theFieldName;
//	}
//	else{
//		//alert("Locked by = " + currFieldToValidate);
//		return true;
//	}

	if(theFieldValue == ""){
		currFieldToValidate = "";
		return true;
	}

	if( theFieldValue.length > maxLength ){
		alert(printf(MAX_CHARS, maxLength));
		theField.focus();
		theField.select();
		return false;
	}
	currFieldToValidate = "";
	return true;
}

//This was imported from GenericCommonFunctions.js as I.E wasnt able to call it wihout it being explicitely stated in this file.
function printf(arg)
{
  var i, c, c2, c3, ww, pointer = 1, w = 0, d = 0, left, period
  var format = printf.arguments[0]
  var line = ""

  for (i = 0; i < format.length; i++) 
  {
    c = format.charAt(i)
   
    if (c == "\n") 
    {
      if (line == "") line = " "
      line += newline
    }
    else if (c == "%") 
    {
      left = 0
      i++
      c2 = format.charAt(i)
   
      if (c2 == "%") 
      {
        line += c2
        continue
      }
      else if (c2 == "-") 
      {
        left = 1
        c2 = format.charAt(++i)
      }
      
      if (isDigit(c2)) 
      {
        period = 0
        w = 0
        d = 0
      
        while ((c3 = format.charAt(i)) != "s" && c3 != "f" && c3 != "g" && c3 != "i" && c3 != "d") 
        {
          if (c3 == ".") 
          {
            period = 1
          }
          else if (isDigit(c3) == 0) 
          {
            err100("non digit after % ("+c3+")")
          }
          else if (period == 0) 
          {
            w = w*10+eval(c3)
          }
          else if (period == 1) 
          {
            d = d*10+eval(c3)
          }
          i++
        }
      
        if (c3 == "s") 
        {
          line += print_string(left, w, printf.arguments[pointer++])
        }
        else if (c3 == "g" || c3 == "f") 
        {
          line += print_number(c3, w, d, printf.arguments[pointer++])
        }
        else if (c3 == "i" || c3 == "d") 
        {
          line += print_number(c3, w, 0, printf.arguments[pointer++])
        }
      }
      else if (c2 == "s") 
      {
        line += print_string(left, 0, printf.arguments[pointer++])
      }
      else if (c2 == "f") 
      {
        line += print_number(c2, 0, 3, printf.arguments[pointer++])
      }
      else if (c2 == "g") 
      {
        line += print_number(c2, 0, 6, printf.arguments[pointer++])
      }
      else if (c2 == "i" || c2 == "d") 
      {
        line += print_number(c2, 0, 0, printf.arguments[pointer++])
      }
    }
    else 
    {
      line += c
    }
  }
  return line
}

// This function checks and limits the length of any text input element. It will
// truncate the field and optionally warn if more than maxLength characters are
// entered.
//
// @param obj the input element instance to check
// @param maxLength the maximum length allowed
// @param shouldWarn boolean if the user should be notified.
// @return true if okay, false if the value was truncated.
function limitFieldLength(obj, maxLength, shouldWarn){
  var result = true;
  
  //18296 increase the size of the string to reflect that the server interpretes newlines as 2 chars.
  var numNewLines = countNewLines(obj);
    
  if (obj.value.length + numNewLines > maxLength){
    
    var stripped = obj.value.substring(0, maxLength - numNewLines);
    obj.value = stripped;
    result = false;

    if (shouldWarn) {
      alert(printf(MAX_CHARS, maxLength));
    }
  }
}

function countNewLines(obj){
  var count = 0;
  for(var i=0; i< obj.value.length; i++){
     if(obj.value.charAt(i) == '\n'){
      count++;
    }
  }
  return count;
}



//****************************************************************************
//****************************************************************************
function Email_Check(element, warn) {
	var emailStr = element.value;
	if (emailStr == "none" || emailStr == "")
		return true;
	var emailPat=/^(.+)@(.+)$/
	var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
	var validChars="\[^\\s" + specialChars + "\]"
	var quotedUser="(\"[^\"]*\")"
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
	var atom=validChars + '+'
	var word="(" + atom + "|" + quotedUser + ")"
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")


	var matchArray=emailStr.match(emailPat)
	if (matchArray==null) {
		if (warn)
			alert(INVALID_EMAIL)
		return false
	}
	var user=matchArray[1]
	var domain=matchArray[2]

	if (user.match(userPat)==null) {
		if (warn)
			//alert(i18nK("BadEmailAddressEntered"))
			alert(INVALID_EMAIL);
		return false
	}

	var IPArray=domain.match(ipDomainPat)
	if (IPArray!=null) {
		  for (var i=1;i<=4;i++) {
		    if (IPArray[i]>255) {
			if (warn)
				alert(INVALID_EMAIL)
			return false
		    }
		   }
		   return true
	}

	var domainArray=domain.match(domainPat)
	if (domainArray==null) {
		if (warn)
			alert(INVALID_EMAIL)
	    return false
	}

	var atomPat=new RegExp(atom,"g")
	var domArr=domain.match(atomPat)
	var len=domArr.length
	if (domArr[domArr.length-1].length<2 ||
	    domArr[domArr.length-1].length>3) {
		if (warn)
			alert(INVALID_EMAIL_DOMAIN)
		   return false
	}

	if (len<2) {
		if (warn)
			alert(INVALID_EMAIL_HOSTNAME);
		return false
	}
	return true;
}
///////////////////////////////////////////////////////////////////////////////
// EXPERT TAGLIB SUPPORT
//////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------
// Supports expert PHONE tag
//
// assembles the 3 phone components into the full phone
//	fullPhone - hidden field, will be the parameter parsed in the request
//      area_fullPhone, phone1_fullPhone, phone2_fullPhone  -- input fields to build fullPhone
//
//------------------------------------------------------------------------------

//****************************************************************************
//****************************************************************************
function expPhoneCheck(currentObj,digits,fullPhoneObj) {
	if ( !isFieldInteger(digits, currentObj)) {
		clr(currentObj);
		hilight(currentObj);
	}
        if (digits > 0) { // not extension
		expAssemblePhone(fullPhoneObj);
	}

}

function expAssemblePhone(fullPhoneObj) {
	var formname = fullPhoneObj.form.name;
	var temp;
	var p1 = document.forms[formname].elements["area_" + fullPhoneObj.name].value;
	var p2 = document.forms[formname].elements["phone1_" + fullPhoneObj.name].value;
	var p3 = document.forms[formname].elements["phone2_" + fullPhoneObj.name].value;

	if (p1 == '') {temp ='000'; document.forms[formname].elements["area_" + fullPhoneObj.name].value = '000'} else {temp = p1};
	if (p2 == '') {temp+='000'; document.forms[formname].elements["phone1_" + fullPhoneObj.name].value = '000'}else {temp+=p2};
	if (p3 == '') {temp+='0000'; document.forms[formname].elements["phone2_" + fullPhoneObj.name].value = '0000'}else {temp+=p3};


	if (temp !='0000000000')
        {
             fullPhoneObj.value=temp
        }
        else
        {
             fullPhoneObj.value='';
             document.forms[formname].elements["area_" + fullPhoneObj.name].value = '';
             document.forms[formname].elements["phone1_" + fullPhoneObj.name].value = '';
             document.forms[formname].elements["phone2_" + fullPhoneObj.name].value = ''
        };
}

//****************************************************************************
// EXPERT DATE TAG support
//****************************************************************************
// clear a date group using direct object ref
function expClearMDY(monthObj, dayObj, yearObj) {
	yearObj.value="";
	monthObj.selectedIndex = 0;
	dayObj.value = "";
}

function expHandleDate(fullDateObj, currentObj, time, fromDateStr, toDateStr) {
	var formname = fullDateObj.form.name;

	var monthObj = document.forms[formname].elements["month_" + fullDateObj.name];
	var dayObj = document.forms[formname].elements["day_" + fullDateObj.name];
	var yearObj = document.forms[formname].elements["year_" + fullDateObj.name];
  var hourObj = document.forms[formname].elements["hour_" + fullDateObj.name];
  var minObj = document.forms[formname].elements["min_" + fullDateObj.name];
  var meridiemObj = document.forms[formname].elements["meridiem_" + fullDateObj.name];

    if(time == "true") {
    		expCheckDate(monthObj, dayObj, yearObj, currentObj, fromDateStr, toDateStr);
    		expAssembleDateTime(fullDateObj, monthObj, dayObj, yearObj, hourObj, minObj, meridiemObj);
  		if(formname == "manualLenderResponseForm" && fullDateObj.name == "decisionDate" && document.forms[formname].elements["descDateChange"] != null){
      		document.forms[formname].elements["descDateChange"].value = "true";
    		}
  	}else {
    		expCheckDate(monthObj, dayObj, yearObj, currentObj, fromDateStr, toDateStr);
    		expAssembleDate(fullDateObj, monthObj, dayObj, yearObj);
  }

}

function expCheckDate(monthObj, dayObj, yearObj, currentObj, fromDateStr, toDateStr) {
	var valid = true;
	if (currentObj.name == monthObj.name) {
		if (fromDateStr == "" && toDateStr == "" ) {
			if(!isExpFieldValidDate(yearObj, monthObj, dayObj ,currentObj)) {
				valid = false;
			}
		}
		else {
			if (!isExpFieldValidDateInRange(yearObj, monthObj, dayObj, fromDateStr, toDateStr, currentObj)) {
				valid = false;
			}
		}
	}
	else if (currentObj.name == dayObj.name) {
		if (fromDateStr == "" && toDateStr == "" ) {
			if(!(isFieldInIntRange(1, 31,currentObj) && isExpFieldValidDate(yearObj, monthObj, dayObj ,currentObj))){
				valid = false;
			}
		}
		else {
			if (!(isFieldInIntRange(1, 31,currentObj) && isExpFieldValidDateInRange(yearObj, monthObj, dayObj, fromDateStr, toDateStr, currentObj))) {
				valid = false;
			}
		}

	}

	// change 1800, 2100 to grab from start/end
	else if (currentObj.name == yearObj.name) {
		if (fromDateStr == "" && toDateStr == "" ) {
			if(!(isFieldInIntRange(1800, 2100,currentObj) && isExpFieldValidDate(yearObj, monthObj, dayObj ,currentObj))){
				valid = false;
			}
		}
		else {
			var fromYear = 1800;
			var toYear = 2100;
			if (fromDateStr.length == 11) {
				fromYear = fromDateStr.substring(7,11);
			}
			if (toDateStr.length == 11) {
				toYear = toDateStr.substring(7,11);
			}
			if (!(isFieldInIntRange(fromYear, toYear,currentObj) && isExpFieldValidDateInRange(yearObj, monthObj, dayObj, fromDateStr, toDateStr, currentObj))) {
				valid = false;
			}
		}
	}

	if (valid == false) {
		expClearMDY(monthObj, dayObj, yearObj);
	}

}

//****************************************************************************
//****************************************************************************
function expAssembleDateTime(fullDateObject, monthObj, dayObj, yearObj, hourObj, minObj, meridiemObj)  {
  var formname = fullDateObject.form.name;

	var month = monthObj.value;
	var day = dayObj.value;
	var year = yearObj.value;
  var hour = hourObj.value;
  var min = minObj.value;
  var meridiem = meridiemObj.value;

  var hour = hour-0;

  if(meridiem == 2 && hour < 12)  {
    hour += 12;
  }else if(meridiem == 1 && hour == 12)  {
    hour = 0;
  }else if(meridiem == 2 && hour == 12)  {
    hour = 12;
  }

	if (month > 0 && day > 0 && year > 0) {
	    //#5160 , use UTC zone to save Date, refer to comments in  convert() of JspRuntimeLibraryFilogix.java
		var dt = new Date(Date.UTC(year,month-1,day,hour,min,0,0));

		// #4754, it seems a big bug of Javascript??, now use local timezone.   When introspected into bean, it will use server's local timezone
		//       accordingly, taglibs/Date.java  will use server's default timezone to retrieve date from database.
		//dt.setUTCFullYear(year);
		//dt.setUTCMonth(month - 1);  // Month number is zero based 0-11
		//dt.setUTCDate(day);
		fullDateObject.value=dt.getTime();
	}
	else {
		fullDateObject.value='';
	}
}

function expAssembleDate(fullDateObject, monthObj, dayObj, yearObj) {
	var formname = fullDateObject.form.name;

	//var month = document.forms[formname].elements["month_" + fullDateObject.name].value;
	//var day = document.forms[formname].elements["day_" + fullDateObject.name].value;
	//var year = document.forms[formname].elements["year_" + fullDateObject.name].value;
	var month = monthObj.value;
	var day = dayObj.value;
	var year = yearObj.value;

	if (month > 0 && day > 0 && year > 0) {
	    //#5160 , use UTC zone to save Date, refer to comments in  convert() of JspRuntimeLibraryFilogix.java
		var dt = new Date(Date.UTC(year,month-1,day,0,0,0,0));
		// #4754, it seems a big bug of Javascript??, now use local timezone.   When introspected into bean, it will use server's local timezone
		//       accordingly, taglibs/Date.java  will use server's default timezone to retrieve date from database.
		//dt.setUTCFullYear(year);
		//dt.setUTCMonth(month - 1);  // Month number is zero based 0-11
		//dt.setUTCDate(day);
		fullDateObject.value=dt.getTime();
	}
	else {
		fullDateObject.value='';
	}
}

//****************************************************************************
//****************************************************************************
function isExpFieldValidDate(yearObj, monthObj, dayObj, currentObj){
	if(currentObj.value == ""){
		return true;
	}

	var theYearValue = yearObj.value;
	var theMonthValue = monthObj.value;
	var theDayValue = dayObj.value;

	// Check valid day except Feb
	if((theMonthValue == 4 || theMonthValue == 6 || theMonthValue == 9 || theMonthValue == 11) && theDayValue > 30 || (theDayValue < 1 && theDayValue!="")){
		alert(INVALID_NUM_DAYS_31);
		currentObj.focus();
		return false;
	}

	// Check day for Feb
	if( theMonthValue == 2){
		if (isLeapYear(theYearValue ) == true){
			if (theDayValue > 29){
				alert(INVALID_NUM_DAYS_29);
				currentObj.focus();
				return false;
			}
		}
		else{
			if (theDayValue > 28){
				alert(INVALID_NUM_DAYS_28);
				currentObj.focus();
				return false;
			}
		}
	}

	return true;
}


//****************************************************************************
//****************************************************************************
function isExpFieldValidDateInRange(yearObj, monthObj, dayObj, fromDateStr, toDateStr, currentObj){
	// Valid if the date if valid first and out if invalid date input
	if(!isExpFieldValidDate(yearObj, monthObj, dayObj, currentObj)){
		return false;
	}

	if(currentObj.value == ""){
		return true;
	}

	var theYearValue = yearObj.value;
	var theMonthValue = monthObj.value;
	var theDayValue = dayObj.value;

	if(toDateStr != ""){
		// Compare the date and report error if the input date > theToDateToCompare
		var theDateInput = new Date(theMonthValue + "/" + theDayValue + "/" + theYearValue);
		var theDateCompare = new Date(toDateStr );
		//alert('The theDateInput = ' + theDateInput.toLocaleString() + 'The theToDateToCompare = ' + theToDateToCompare.toLocaleString());
		if(theDateInput >= theDateCompare){
			if(!confirm(CONFIRM_OVERRIDE_INVALID_DATE_BEFORE_PREFIX  + toDateStr + CONFIRM_OVERRIDE_INVALID_DATE_BEFORE_SUFFIX)){
				currentObj.focus();
				return false;
			}
		}
	}

	if(fromDateStr != ""){
		// Compare the date and report error if the input date > theToDateToCompare
		var theDateInput = new Date(theMonthValue + "/" + theDayValue + "/" + theYearValue);
		var theDateCompare = new Date(fromDateStr);
		//alert('The theDateInput = ' + theDateInput.toLocaleString() + 'The theFromDateToCompare= ' + theFromDateToCompare.toLocaleString());
		if(theDateInput <= theDateCompare){
			if(!confirm(CONFIRM_OVERRIDE_INVALID_DATE_AFTER_PREFIX + fromDateStr + CONFIRM_OVERRIDE_INVALID_DATE_AFTER_SUFFIX)){
				currentObj.focus();
				return false;
			}

		}
	}
	return true;
}

//****************************************************************************
// EXPERT NUMBER TAG support
//****************************************************************************

function expCheckCurrency(field){
	if (isNaN(field.value)) {
		alert(INVALID_DECIMAL);
		clr(field);
		return false;
	}

	if (isFieldInDecRange(0, 9999999999.99, field) && isFieldDecimal(2,field)) {
		return true;
	} else {
		clr(field);
		return false;
	}
}

//****************************************************************************
//****************************************************************************
function expCheckRate (field) {
	if (isNaN(field.value)) {
		alert(INVALID_DECIMAL);
		clr(field);
		return false;
	}

	if (isFieldInDecRange(0, 99.999, field) && isFieldDecimal(3,field)) {
		return true;
	} else {
		clr(field);
		return false;
	}
}
//****************************************************************************
// EXPERT CHECKBOX TAG support
//****************************************************************************
function expCheckBox(checkBoxObj, saveFieldObj, checkedValue) {
  try {
    disablePriorEncumberances();
  } catch (e) {}
	var unCheckedValue = "0";
	if (checkedValue == "Y") {
		unCheckedValue = "N";
	}

	if (checkBoxObj.checked == true) {
		saveFieldObj.value = checkedValue;
	}
	else {
		saveFieldObj.value = unCheckedValue;
	}
}
// Function to check if the input value is a Decimal, can be below zero
function isAbsDecimal(inValue){
	decimalFound = true;
        dotFound = false;
        var k = 0;
        if (inValue.charAt(0) == '-' )
{
           var k = 1;
}
	for(var i=k;i<inValue.length;i++){
		if( isDigit(inValue.charAt(i)) == false ){
			if(  inValue.charAt(i) != '.' ){
				decimalFound = false;
                                break;
			}
                        else
                                if ( dotFound )
{
                                   decimalFound = false;
                                   break;
}
                                else
                                   dotFound = true;


		}
	}
        if ( ( dotFound || k == 1 ) && inValue.length < 2 )
{
             decimalFound = false;
}
	return decimalFound;
}
//****************************************************************************
//****************************************************************************
// Function to check if the attached field value is within the range (decimal negative values accepted)

function isFieldInAbsDecRange(min, max, field){

	var theField = field;
	var theFieldValue = theField.value;
	var theFieldName = theField.name;

        if(theFieldValue == ""){
		currFieldToValidate = "";
		return true;
	}

	if( !isAbsDecimal(theFieldValue) ){
		alert(INVALID_DECIMAL);
		var tmp = theField.value;
		theField.focus();
		theField.select();
		return false;
	}
	else{
		// Check Length
		if( theFieldValue < min || theFieldValue > max ){
			alert(printf(INPUT_DECVALUE_RANGE, min, max));
			theField.focus();
			theField.select();
			return false;
		}
	}
	currFieldToValidate = "";

	return true;
}
//****************************************************************************
//****************************************************************************
// Function to check and convert the attached fieldvalue to a Decimal number with # of decimal place = numDecPlace
// can be < 0
function isFieldAbsDecimal(numDecPlace, field){
	var theField = field;
	var theFieldValue = theField.value;
	var theFieldName = theField.name;

	if(theFieldValue == ""){
		currFieldToValidate = "";
		return true;
	}

	if( !isAbsDecimal(theFieldValue) ){
		alert(INVALID_DECIMAL);
		theField.focus();
		theField.select();
		return false;
	}

	// Check for precision
	var theSplitedValues = theFieldValue.split(".");
	if(theSplitedValues.length > 1){
		if(theSplitedValues[1].length > numDecPlace){
			alert(printf(MAX_PRECISION, numDecPlace));
			theField.focus();
			theField.select();
			return false;
		}
	}

	// Convert field to correct format
	theField.value = round_decimals(theField.value, numDecPlace);
	currFieldToValidate = "";
	return true;
}



//****************************************************************************
//   Additional Formatting Functions
//	containsNonUTF8(String), leftTrim(String), isNotAlphaNumberic(String)
//   	-ezacarias
//****************************************************************************
//function to check if non-UTF-8 characters are entered in text modules
function containsNonUTF8(sInputText) {
            if (leftTrim(sInputText)==null) return true;
            var sText = new String(sInputText);
            var iStrLength = sText.length;
            var iCharCode=0;
            for (x=0; x<iStrLength; x++) {
                iCharCode = sText.charCodeAt(x);
            	if (iCharCode > 255) {
        		return true;
	        }
            }
            return false;
}

//   function to trim all non printable characters at left side of string
function leftTrim(argvalue) {
    if (argvalue==null) return null;
    var x=0;
    for (x=0; x<argvalue.length; x++) {
        // trim all non prinable characters in front
        if (argvalue.charCodeAt(x) > 33) {
		break;
        }
    }
    if (x==argvalue.length) {
        return null;
    }
    argvalue = argvalue.substring(x, argvalue.length);
    return argvalue;
}


//   function to check if non-alphanumeric characters are entered in text modules
//   allows .+- and space
function isNotAlphaNumeric(s){
	if(s == null) return false;
	if(s.length == 0) return false;

	for(var i=0; i<s.length; ++i) {
		if("+- .0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".indexOf(s.charAt(i)) < 0) {
			return true;
		}
	}
	return false;
}

// Function to check if the attached field value is an Alpha Numeric string with any length
function isFieldAlphaNumeric(field){
	var theField = field;
	var theFieldValue = theField.value;
	var theFieldName = theField.name;

	if(theFieldValue == ""){
		currFieldToValidate = "";
		return true;
	}

	if(isNotAlphaNumeric(theFieldValue) ){
		alert(ALPHA_NUMERIC_ONLY);
		theField.focus();
		theField.select();
		return false;
	}
	currFieldToValidate = "";
	return true;
}


//Function to format numeric values inserts comma to numbers
function formatNumericValues(number, separator) {
    var strNumber=new String(number);
    var decimals;
    var dotLocation=strNumber.indexOf(".");
    var wholeNumbers;
    var formattedString;
    if ( (number==null) || (number=="") ) {
       	return "";
    }
    if (dotLocation >= 0) {
		decimals=strNumber.substring(dotLocation+1, strNumber.length);
    } else {
		decimals="";
    }
    if (dotLocation < 0) {
		wholeNumbers=strNumber;
    } else if (dotLocation==0) {
		wholeNumbers="0";
    } else {
		wholeNumbers=strNumber.substring(0,dotLocation);
    }

    if (parseInt(wholeNumbers)==0) {
		wholeNumbers="0";
    }

    formattedString="";
    for (i=wholeNumbers.length;i>=0;i--) {
		formattedString = wholeNumbers.charAt(i) + formattedString;
		if ( (((wholeNumbers.length-i) % 3)==0 ) && (i != wholeNumbers.length) && (i>0) ) {
			formattedString = separator + formattedString;
		}
    }
    formattedString = formattedString + "." + decimals;
    return formattedString;
}


//function to validate the length of text areas
function limitTextAreaLength(sField, sLen ) {
    var sValue=sField.value;
    if (sValue==null) {
        return;
    }
    if (sValue.length <= sLen) {
        return;
    }
    sField.value=sValue.substr(0,sLen);
}


//function to clear radio buttons
function clearRadioField(fieldName) {
    var f=document.forms[0];
    var field=eval('document.forms[0].elements[fieldName]');
    for (var i=0; i<field.length; i++) {
        field[i].checked=false;
    }
}

//function to set a radio button
function setRadioField(fieldName, idx) {
    var f=document.forms[0];
    var field=eval('document.forms[0].elements[fieldName]');
    field[idx].checked=true;
}
// Function to check if the field is empty
function isFieldEmpty(value){
	if(value == ""){
		return true;
	}else{
    // Check Length
	  if( ltrim(value).length == 0 ){
	  	  return true;
		  }
  }
	return false;
}
//****************************************************************************
//****************************************************************************

	function isValueValidNumber(field){
		var theValue = field.value;
        if ("" == theValue){
			return true;
        }
		
		if (!isNumericFormat(theValue)){
			return false;
		}			
		
		for (var i = 0; i < theValue.length; i++){
			if ("012345.6789".indexOf (theValue.charAt(i)) == -1){
				return false;
			}
		}
		return true;
	}

	function isNumericFormat(theValue){
		var count = 0;
		for (var i = 0; i < theValue.length; i++){
			if (theValue.charAt(i) == '.'){
					count++;
			}
		}
		if (count > 1){
			return false;
		}
		return true;
	}

function isFieldInRateRange(min, max, field){
		var theField = field;
		var theFieldValue = theField.value;
		var theFieldName = theField.name;
	
		if(theFieldValue == ""){
			currFieldToValidate = "";
			return true;
		}
	
		if( !isDecimal(theFieldValue) ){
			alert(INVALID_DECIMAL);
			var tmp = theField.value;
			theField.focus();
			theField.select();
			return false;
		}
		else{
			if( theFieldValue < min || theFieldValue > max ){
				alert(printf(INPUT_VALUE_RANGE_2X3DECIMAL, min, max));
				theField.focus();
				theField.select();
				return false;
			}
		}
		currFieldToValidate = "";
		return true;
	}


