﻿// JScript File
var whitespace = " \t\n\r";

var criteriaFail = 0;
var criteriaPass = 1;
var criteriaIgnore = 2;

function stripChars(sString, sStrip)
{
	var sReturnString = "";

	// Search through string's characters one by one.
	// If character is not to be stripped, append to returnString.

	for (var i = 0; i < sString.length; i++)
	{
		var sChar = sString.charAt(i);
		if (sStrip.indexOf(sChar) == -1) 
			sReturnString += sChar;
	}

	return sReturnString;
}

function setDropDownText(objName,strText)
{
	for (var i=0; i < objName.options.length; i++)
   {
      //if option value = to cookie value set the selected index equal to i
      if (objName.options[i].text == strText) 
        objName.options[i].selected = true;
   }
}
function setDropDownValue(objName,strVal)
{
	if (objName.options.length > 50)
	{	//In case a state code comes with a comma attached
		if ((objName.options[1].value=="AL") && (strVal.length == 3))
			strVal = strVal.substr(0,2);
	}
	for (var i=0; i < objName.options.length; i++)
	{	//if option value = to cookie value set the selected index equal to i
		if (objName.options[i].value == strVal)
			objName.options[i].selected = true;
	}
}

function timeout_alert() {
	alert("Your ELS Session has expired, you will be redirected back to the logon page.");
	
	try
	{
	    window.document.location.href="/Welcome.asp"
	}
	catch (e)
    {
        // Page has already been redirected to welcome page
    }
}

function setPaddingWidth() {
	var expire = new Date();
	var width = 780;
	if (document.body) {
		if (document.all) {
			width = document.body.clientWidth;
		} else {
			width = document.body.offsetWidth;
		}
	}
	else 
		width = screen.availWidth;

	if (width > 770) 
		var padwidth = (width - 770)/2;
	else
		var padwidth = 0;
		    
	expire.setTime(expire.getTime() + ( 7*24*60*60*1000 ) ); // expire in 1 week
	document.cookie = "padWidth=" + escape(padwidth) + "; expires=" + expire.toGMTString() + "; path=/";
	
	//TODO Comment on this to team: iPad in most of the user interface pages, and is defaulted to the padding width that is
	//     calculated on the server side.  If the client calculation is different, and the variable has been defined, update
	//     iPad to the new padding width.
    if (typeof(iPad) != "undefined")
	    iPad = padwidth;
	    
}

//Function added to check password change
function PasswordChangeAlert(strIndicator)
{
	if (strIndicator == 'Y')
	{
		alert('Your Password has been changed.');
	}
}

function cancelEdit(f1, loanCaseId) {
	if (window.confirm("Selecting Cancel will abandon all of your changes.  Are you sure you want to continue?"))
	{
		if (window.opener) {
			window.close();
		} 
		else 
		{
			//window.document.location.href="/common/searchqueue.aspx"
			window.document.location.href="/common/cancelprocessor.aspx?LC=" + loanCaseId;
		}
	}
}

function checkOneOfMany(f1,sGroup)
{
	var oCurrElement;
	var bSuccess=false;
	var iCount;
	var sMsg=new String();

	for( iCount=0;iCount<f1.elements.length-1;iCount++)
	{
		oCurrElement = f1.elements[iCount];
		if (oCurrElement.required == "oneofmany"  && oCurrElement.group==sGroup && oCurrElement.checked == true && oCurrElement.type != "text")
			bSuccess=true;
		else if (oCurrElement.required == "oneofmany" && oCurrElement.group==sGroup && !isBlank(oCurrElement.value))
			bSuccess=true;
	}
	if (bSuccess==false){
			for( iCount=0;iCount<f1.elements.length-1;iCount++){
				oCurrElement = f1.elements[iCount];	
				if  (oCurrElement.required == "oneofmany" && oCurrElement.group==sGroup ){
					if (sMsg.length==0)
						sMsg="One of the following fields must be specified :<BR>" +"<li><em>"+oCurrElement.uniqueId+"<em></li>";
					else
						sMsg=sMsg+"<li><em>"+oCurrElement.uniqueId+"<em></li>";
				}
			}
	}
	return(sMsg);
}
function getElementInstanceCount(oCurrElement) {
	var iElCount =0;
	for (var jj = 0; jj < oCurrElement.form.elements.length; jj++) {
	if (oCurrElement.form.elements[jj].name == oCurrElement.name)
	   iElCount++;
	}
	return iElCount;
}

function validateForm(f1) 
{
	var objErrors = new ErrorCollection(f1);
	
	var oCurrElement;	
	// Check for fields that have the required property.
	// If validation fails, alert user and put focus on the required element.

	for (var i = 0; i < f1.elements.length; i++)
	{
		oCurrElement = f1.elements[i];
		
		// set images back to non-error 
		if (oCurrElement.type!="radio")
		{
		    // For LP - Non-Fixed Payment, there are 8 hidden fields that explicitly set the fieldtofocus
		    // to a visible field on the form.  To prevent the second field validation from overriding the first, only
		    // reset the error image if the error is not already present within the error collection
		    if (oCurrElement.fieldtofocus && !objErrors.errors.Contains(oCurrElement.fieldtofocus))
		    {
		        switchImage(oCurrElement.fieldtofocus + "Img", "/images/spacer.gif");
		    }
		    else
		    {
		        // Standard non-radio button form field, reset error on every call to validateForm
		        switchImage(oCurrElement.name + "Img", "/images/spacer.gif");
		    }
		}
		else
	    {
	        // For Radio buttons, only the first radio instance has the fieldtofocus attribute defined.  Only switch the 
	        // error image for the first radio button.  The image name matches the radio button name, suffixed with Img.  The image
	        // name does not contain [0].
	        if (oCurrElement.fieldtofocus)
	            switchImage(oCurrElement.name + "Img", "/images/spacer.gif");    
	    }
	   
		// end image set	
		
		//Check for Maximum Length for TextArea ss 01/14/2003
		if (oCurrElement.ManualMaxlength=="Y" && checkMaxLength(oCurrElement) == false )
		{
			objErrors.AddError("<em>" + oCurrElement.uniqueId + "</em> " + oCurrElement.message, oCurrElement.name);
		}
		
		if (!FieldEntered(oCurrElement))
		{
			if (oCurrElement.required == "y")
			{
				if (oCurrElement.fieldtofocus)
					objErrors.AddError("<em>" + oCurrElement.uniqueId + "</em> " + oCurrElement.message, oCurrElement.fieldtofocus);
				else
					objErrors.AddError("<em>" + oCurrElement.uniqueId + "</em> " + oCurrElement.message, oCurrElement.name);
			}
			else if (oCurrElement.required == "conditional" && checkConditional(oCurrElement) == false)
			{
				if (oCurrElement.fieldtofocus)
					objErrors.AddError("<em>" + oCurrElement.uniqueId + "</em> " + oCurrElement.message,  oCurrElement.fieldtofocus);
				else
					objErrors.AddError("<em>" + oCurrElement.uniqueId + "</em> " + oCurrElement.message, oCurrElement.name);
			}
			else if (oCurrElement.required == "other" && checkOther(oCurrElement) == false)
			{
				objErrors.AddError("<em>" + oCurrElement.uniqueId + "</em> " + oCurrElement.message, oCurrElement.name);
			}
			else if (oCurrElement.required == "either") { 
				if (FieldEntered(oCurrElement.otherField) == false) {
					if(getElementInstanceCount(oCurrElement) > 1) {
		         		objErrors.AddError("<em>" + oCurrElement.uniqueId + "</em> " + oCurrElement.message, oCurrElement.name + "[0]");
			        }
			        else
			        {
					   objErrors.AddError("<em>" + oCurrElement.uniqueId + "</em> " + oCurrElement.message, oCurrElement.name);
					}
				}	
			}
			else if (oCurrElement.required == "value" && checkValueBased(oCurrElement) == false)
			{
				objErrors.AddError("<em>" + oCurrElement.uniqueId + "</em> " + oCurrElement.message, oCurrElement.name);
			}
			else if (oCurrElement.type == "select-multiple")
			{
				if ( isListEmpty(oCurrElement) && (oCurrElement.ValidateList) )
				
				objErrors.AddError("<em>" + oCurrElement.uniqueId + "</em> " + oCurrElement.validationMessage, oCurrElement.name);
			}
			
		}
		else
		{
			if (oCurrElement.fpValidation)
			{
				if (!oCurrElement.fpValidation(oCurrElement))
				{
				    if (oCurrElement.fieldtofocus)
				        objErrors.AddError("<em>" + oCurrElement.uniqueId + "</em> " + oCurrElement.validationMessage,  oCurrElement.fieldtofocus);
				    else
					    objErrors.AddError("<em>" + oCurrElement.uniqueId + "</em> " + oCurrElement.validationMessage, oCurrElement.name);
				}
			}
		}
	}
	
	//SS 11/27/02 One Of Many Check
	if (f1.OneOfmanyCondition=="y")
	{
		var sMsg;
		var sCheck=new String();
		for(i=0;i<f1.elements.length-1;i++)
		{		oCurrElement=f1.elements[i];
				if (oCurrElement.required == "oneofmany" && sCheck.indexOf(oCurrElement.group,0)<0)
				{	
					sCheck=sCheck+oCurrElement.group;
					sMsg=checkOneOfMany(f1,oCurrElement.group,sMsg);
					if(sMsg.length!=0)
					{	objErrors.AddError (sMsg,oCurrElement.name);
						sMsg="";
					}
				}	
		}
	}
		
	if (f1.serviceValidation)
	{
	    f1.serviceValidation(f1, objErrors);
	}
   	
	return objErrors;

}

function oneAddressMatchesSubject(oForm) {
	var oCurrElement;
	var sInstance;
	var oState;
	for (var i = 0; i < oForm.elements.length; i++)
	{
		oCurrElement = oForm.elements[i];
		if (oCurrElement.name.substr(0,5)=='REZip') {
			if (oCurrElement.value==oForm.SubjectPropertyZip.value) {
				sInstance = getInstance(oCurrElement);
				oState = oForm.elements["REState" + sInstance];
				if (oState.options[oState.selectedIndex].value == oForm.SubjectPropertyState.value) {
					if (oForm.elements["REStreet" + sInstance].value.toUpperCase() == oForm.SubjectPropertyStreet.value.toUpperCase()) {
						if (oForm.elements["RECity" + sInstance].value.toUpperCase() == oForm.SubjectPropertyCity.value.toUpperCase()) {
							return true;
						}
					}
				}
			}
		}
	}

	return false;
}

function Contains(fieldName)
{
    for (var i=0;i<this.length;i++)
    {
        if (this[i].focusfield==fieldName) 
        {
            return true;
        }
    }
    
    return false;
}

//  Constructor for an object to collect and display errors for a given form
function ErrorCollection(objForm)
{
	// array of error objects and method to display the errors
	this.form = objForm;
	Array.prototype.Contains = Contains; 
	this.errors = new Array();
	this.AddError = AddError;
	this.IsEmpty = IsErrorCollectionEmpty;
	this.DisplayErrors = DisplayErrors;
}

//  Constructor for an object to contain a single error
//  Arguments:
//      strDescription = the text that is used to describe the error
//      strFocusField = the name of the field that should receive focus when
//                      the user clicks on the string
function ErrorObject(strDescription, strFocusField)
{
	// properties to contain error information
	this.description = strDescription;
	this.focusfield = strFocusField;
}

//  Adds an error to the "errors" array of the ErrorCollection object
//  Arguments:
//      strDescription = the text that is used to describe the error
//      strFocusField = the name of the field that should receive focus when
//                      the user clicks on the string
function AddError(strDescription, strFocusField)
{
	// add a new error object to the collection
	this.errors[this.errors.length] = new ErrorObject(strDescription, strFocusField);
	
	// Verify if the field name is suffixed with "[0]".  If so, remove the suffix and attempt to switch the
	// image placeholder.
	var regex = /^.*\[0\]$/;
	
	if (regex.test(strFocusField))
	{
  	    switchImage(strFocusField.substr(0, strFocusField.length-3) + "Img", "/images/i_error.gif");
    }
    else
    {
        switchImage(strFocusField + "Img", "/images/i_error.gif");
    }
}

function switchImage(strImageID, strImageSource) 
{
   if (document.images[strImageID]) 
   {
       document.images[strImageID].src = strImageSource;
   }
}

//
//  Returns true if the ErrorCollection object is empty, false otherwise
//
function IsErrorCollectionEmpty()
{
	return (this.errors.length == 0);
}

//
//  Displays a list of errors in the ErrorCollection object
//
function DisplayErrors()
{
    // Build display HTML.
    var sErrors = ""
    var strFormName = this.form.name
    for ( var i=0; i < this.errors.length; i++ )
    {
	var objError = this.errors[i];
	sErrors += "<tr><td bgcolor='#ffffff'><A HREF='javascript:opener.document." + strFormName + "." +
		   objError.focusfield + ".focus(); " + "window.close();'>" + objError.description + "</A></td></tr>";
    }
    var sHTML = "<HEAD><style> em { font-weight: bold; } </style><TITLE>Invalid Entries</TITLE></HEAD>" +
		"<BODY BGCOLOR='#FFFFFF' LINK='#003399' ALINK='#003399' " +
		"VLINK='#003399'><table border='0' cellpadding='7' cellspacing='1' bgcolor='#cccccc'>" +
		"<tr><td bgcolor='#003399'>" +
		"<font color='#FFFFFF'><B>The following data entry corrections must be made:</B></font></td></tr>" +
		" " + sErrors + "</TABLE></BODY>";

    // Display error list.
    var wErr = window.open("","ErrWin","width=400,height=300,scrollbars=1,screenX=1,screenY=1");
    wErr.document.open();
    wErr.document.write(sHTML);
    wErr.document.close();
    wErr.focus();
}

// Check whether string s is empty.
function isEmpty(sText)
{
	return ((sText == null) || (sText.length == 0))
}

// Returns true if string s is empty or whitespace characters only
function isBlank (sText)
{   
	if (isEmpty(sText))
		return true;

	for (var i = 0; i < sText.length; i++)
	{
		// Check that current character isn't whitespace
		var sChar = sText.charAt(i);

		if (whitespace.indexOf(sChar) == -1)
			return false;
	}

	// All characters are whitespace
	return true;
}

//  Check for entered field
function FieldEntered(oElement)
{	
	if (!oElement)  return false;
	
	var sValue="";
	switch (oElement.type.substr(0,3))
        {
		case "sel":
			if (!oElement.options.selectedIndex)
				return false;
			if (oElement.options.selectedIndex == -1)
				return false;
			sValue = oElement.options[oElement.options.selectedIndex].value;
			if (sValue.length == 0)
				sValue = oElement.options[oElement.options.selectedIndex].text;
      			if (sValue == "Select One")
				sValue = "";
			break;
		case "rad":
			var sName = oElement.name;
			var sItem = "";
			var oForm = oElement.form;
			for (var i=0; i < oForm.elements[sName].length; i++) {
				sItem = sName + "[" + i + "]";
				if (oForm.elements[sName][i].checked)
					return true;
			}
			break;		
		case "hid":
			sValue = oElement.value;
			if (sValue=="n")
				sValue = "";
			break;		
		case "che":
			if (oElement.checked)
				return true;
			break;		
		default:
			sValue = oElement.value;
	}

	if (!sValue || isBlank(sValue))
		return false;

	return true;
}

function setRequired(oElement, sElementName, bSelectList) {
				
	oElement.required = "y";
	oElement.uniqueId = sElementName;
	
	if (oElement.type.substr(0,3) == "rad")
		oElement.fieldtofocus = oElement.name + "[0]";

	oElement.message = " is a required field.";
}

function setConditional(oElement, sElementName, oCondElement, sMessage) {
	oElement.required = "conditional";
	oElement.uniqueId = sElementName;
	oElement.conditionalfield = oCondElement;
	if (oElement.type.substr(0,3) == "rad")
		oElement.fieldtofocus = oElement.name + "[0]";
	oElement.message = sMessage;
}

function setEither(oElement, sElementName, oCondElement, sMessage) {
	oElement.required = "either";
	oElement.uniqueId = sElementName;
	oElement.otherField = oCondElement;
	oElement.message = sMessage;
}
function unsetEither(oElement, sElementName, oCondElement, sMessage) {
	oElement.required = "";
	oElement.uniqueId = sElementName;
	oElement.otherField = "";
	oElement.message = sMessage;
}
function setOneOfMany(f1,oElement,sElementName,sGroup)
{
		oElement.required = "oneofmany";
		oElement.uniqueId = sElementName;
		oElement.group = sGroup;
		f1.OneOfmanyCondition="y";
}


function setOther(oElement, sElementName, oCondElement, sMessage) {
	oElement.required = "other";
	oElement.uniqueId = sElementName;
	oElement.conditionalfield = oCondElement;
	oElement.message = sMessage;
}

function setHiddenCheck(oElement, sElementName, oFocusElement, sMessage) {
	oElement.required = "y";
	oElement.value = "n";
	oElement.uniqueId = sElementName;
	oElement.fieldtofocus = oFocusElement;
	oElement.message = sMessage;
}

function setHiddenConditional(oElement, sElementName, sFocusElement, oCondElement, sMessage) {
	oElement.required = "conditional";
	oElement.value = "n";
	oElement.uniqueId = sElementName;
	oElement.conditionalfield = oCondElement;
	oElement.fieldtofocus = sFocusElement;
	oElement.message = sMessage;
}

function setValueCheck(oElement, sElementName, oCondElement, sValue, sMessage, sComparisonOperator, sComparisonType) {
	oElement.required = "value";
	oElement.checkValue = sValue;
	oElement.uniqueId = sElementName;
	oElement.conditionalfield = oCondElement;
	oElement.message = sMessage;

	if  ((sComparisonOperator == null) || (sComparisonOperator.length == 0))
	{
		sComparisonOperator = "In";
	}
	
	if  ((sComparisonType == null) || (sComparisonType.length == 0))
	{
		sComparisonType = "Alpha";
	}

	oElement.comparisonType = sComparisonType;
	oElement.comparisonOperator = sComparisonOperator;
}

function setFieldValidation(oElement, sElementName, oValidationFunction, sMessage, sValidChars) {
	oElement.fpValidation = oValidationFunction;
	oElement.uniqueId = sElementName;
	oElement.validChars = sValidChars;
	oElement.validationMessage = sMessage;
}

function setPwdConfValidation(f1,sErrorMessage)
{
	f1.ConfirmPasswords="y"
	for(var i=0;i<f1.elements.length-1;i++)
	{
		if (f1.elements[i].type=="password" )
		{
			f1.elements[i].validationMessage=sErrorMessage;
		}
	}
}

function checkValueBased(field)
{
	var comparisonValues;
	var comparisonValue;
	var comparisonType;
	var comparisonOperator;
	var valueCriteriaMet = false;

	if (field.conditionalfield.type == "select-one")
	{
		var fieldValue = field.conditionalfield.options[field.conditionalfield.selectedIndex].value;
	}
	else
	{
		var fieldValue = field.conditionalfield.value;
	}

	comparisonValue = field.checkValue;
	comparisonType = field.comparisonType;
	comparisonOperator = field.comparisonOperator;

	if ((comparisonType=="Alpha") && (comparisonOperator=="In" || comparisonOperator=="EqualTo"))
	{
		if (comparisonOperator=="EqualTo")
		comparisonOperator = "In";

		comparisonValue = prefixAndSuffixWithPipe(comparisonValue);
		fieldValue = prefixAndSuffixWithPipe(fieldValue);

		valueCriteriaMet = isValueCriteriaMet(comparisonValue,fieldValue,comparisonOperator,comparisonType);
	}
	else
	{
		comparisonValues = comparisonValue.split("|");

		for (var valueIndex = 0; valueIndex < comparisonValues.length; valueIndex++)
		{
			valueCriteriaMet = isValueCriteriaMet(comparisonValues[valueIndex],fieldValue,comparisonOperator,comparisonType);

			if (valueCriteriaMet==criteriaPass || valueCriteriaMet==criteriaIgnore)
				break;
		}
	}
	
	if (valueCriteriaMet==criteriaPass)
	{
		if (!FieldEntered(field))
			return false;
	}

	return true;
}

function prefixAndSuffixWithPipe(stringValue)
{
	if (stringValue.length==0)
	{
		stringValue = "||";
	}
	else
	{	
		if (stringValue.substr(0,1)!="|")
			stringValue = "|" + stringValue;

		if (stringValue.lastIndexOf("|")!=(stringValue.length-1))
			stringValue = stringValue + "|";
	}
	return stringValue;
}

function isValueCriteriaMet(comparisonValue, otherFieldValue, comparisonOperator, comparisonType)
{
	var otherFieldValues;
	var returnValue = criteriaFail;

	if (comparisonType=="Numeric")
	{
		if (!formatCheck_isValidFloat(comparisonValue) || !formatCheck_isValidFloat(otherFieldValue))
		{
			return criteriaIgnore;
		}

		comparisonValue = parseFloat(comparisonValue);
		otherFieldValue = parseFloat(otherFieldValue);

		if (comparisonOperator=="In")
			comparisonOperator = "EqualTo";
	}

	switch (comparisonOperator)
	{
		case "In":
		{
			if (comparisonValue.indexOf(otherFieldValue)>=0)
				returnValue = criteriaPass;

			break;
		}
		case "EqualTo":
		{
			if (comparisonValue==otherFieldValue)
				returnValue = criteriaPass;

			break;
		}
		case "LessThan":
		{
			if (otherFieldValue<comparisonValue)
				returnValue = criteriaPass;
			
			break;
		}
		case "GreaterThan":
		{
			if (otherFieldValue>comparisonValue)
				returnValue = criteriaPass;

			break;
		}
		case "LessThanOrEqualTo":
		{
			if (otherFieldValue<=comparisonValue)
				returnValue = criteriaPass;
				
			break;
		}
		case "GreaterThanOrEqualTo":
		{
			if (otherFieldValue>=comparisonValue)
				returnValue = criteriaPass;

			break;
		}
		case "NotEqualTo":
		{
			if (comparisonValue!=otherFieldValue)
				returnValue = criteriaPass;
				
			break;
		}
		default:
			returnValue = criteriaFail;
			
			break;
	}

	return returnValue;
}

function checkEither(field) {
   if (field.type == "checkbox")
   {
      if (field.checked == false && isBlank(field.conditionalfield.value)) 
         return false;

      if (field.checked == true && !isBlank(field.conditionalfield.value)) 
         return false;
   } 
   else if (field.type == "select-one")
   {
      if (field.options[field.options.selectedIndex].value == "Select One" && isBlank(field.conditionalfield.value)) 
         return false;

      if (field.options[field.options.selectedIndex].value == "Other" && isBlank(field.conditionalfield.value)) 
         return false;
   }
             
   return true
}

function checkOneOfManyChecks(f1,field) {
var sFieldName ;

	if (field.checked==true)
	{
		sFieldName=new String(field.name);
		sFieldName=sFieldName.substr(0,sFieldName.indexOf("_"));
		
		for( var iCount=0;iCount<f1.elements.length-1;iCount++)
		{	
				if (f1.elements[iCount].name.substr(0,f1.elements[iCount].name.indexOf("_"))==sFieldName && field.name !=f1.elements[iCount].name )
				{	f1.elements[iCount].checked=false;
				}
		}
	} 
}


function checkConditional(field) {

	if (FieldEntered(field.conditionalfield))
	{
		if (!FieldEntered(field))
			return false;
	}

	return true
}

function checkOther(field) {

	if (field.conditionalfield.value == "Other")
	{
		if (!FieldEntered(field))
			return false;
	}

   	return true
}


function showDocTypeHelp()
{
    var helpText = "";

    helpText += "Full/Alternative: Verified Income, Assets, and Employment\n\n";
    helpText += "SIVA or VISA: SIVA - Stated Income/Verified Assets and Employment; VISA - Verified Income and Employment/Stated Assets\n\n";
    helpText += "No Ratio (NIVA) or VINA: No Ratio (NIVA) - No Income Stated or Verified/Verified Assets and Employment; VINA - Verified Income and Employment/No Assets Stated or Verified\n\n";
    helpText += "SISA: Stated Income and Stated Assets/Verified Employment\n\n";
    helpText += "NINA: No Income or Assets Stated or Verified/Verified Employment\n\n";
    helpText += "No Doc: No Income or Assets Stated or Verified/No Employment Verified\n\n";
    helpText += "For more information refer to RMIC's Reduced Documentation and underwriting guidelines at www.rmic.com.";
    
    alert(helpText);
}

function sumFields(f1, totalField, sumFieldAttr, bCurrency) 
{
 
   var oCurrElement;
   var totAmt = 0;
   var sValue="";
   
   for (var i = 0; i < f1.elements.length; i++)
   {
       oCurrElement = f1.elements[i];

      if (oCurrElement.sumField==sumFieldAttr) 
      {
          
	      if((formatCheck_isValidCurrency(oCurrElement.value)) && (oCurrElement.value.length>0))
	      {
		    sValue=stripChars(oCurrElement.value,",");
		    if(oCurrElement.oper=="neg")
			    totAmt -= parseFloat(sValue);
		    else
	 		    totAmt += parseFloat(sValue);
	      }
      }
   }
   
   if (bCurrency)
	   f1.elements[totalField].value = formatCurrency(totAmt);
   else
	   f1.elements[totalField].value = totAmt;
}

function formatCurrency(nNumber) {
	var nFormatedNumber = nNumber * 100;
	nFormatedNumber = (Math.round(nFormatedNumber) / 100);
	var sFormatedNumber = nFormatedNumber.toString();
	var decimalPos = sFormatedNumber.indexOf(".");
	if (decimalPos <= 0) {
		sFormatedNumber = sFormatedNumber + ".00";
	} else {
		if ((sFormatedNumber.length - decimalPos) <= 2)
			sFormatedNumber = sFormatedNumber + "0";
	}
	return sFormatedNumber;
}

function calculateLTV(loanAmountField, salesPriceField, appraisedValueField, ltvField) 
{
	var salesPrice = parseFloat(stripChars(salesPriceField.value,","));
	var appraisedValue = parseFloat(stripChars(appraisedValueField.value,","));
	
	if (isNaN(salesPrice))
	{
		salesPrice = appraisedValue;
	}
	
	if (isNaN(appraisedValue))
	{
		appraisedValue = salesPrice;
	}
    
    if (appraisedValue==0)
    {
        ltvField.value = "";
        return;
    }
    
	if (salesPrice >= appraisedValue) 
	{
		var baseValue = appraisedValue;
	} 
	else 
	{
		var baseValue = salesPrice;
	}
	
	if (salesPrice == 0)
		var baseValue = appraisedValue;

	
	var ltvPercent = (parseFloat(stripChars(loanAmountField.value,",")) / baseValue) * 10000;

	ltvPercent = (Math.round(ltvPercent) / 100);

	if (isNaN(ltvPercent)||!isFinite(ltvPercent)) 
	{
		var ltvDisplay = "";
	} 
	else 
	{
		var ltvString = String(ltvPercent);
		var decimal = ltvString.indexOf(".");
		
		if ((decimal > 0) && (decimal + 2 < ltvString.length))
			var ltvDisplay = ltvString.substring(0,decimal + 3);
		else
			var ltvDisplay = ltvString;
	}
	
	ltvField.value = ltvDisplay;
}

function setALPSRefundType(planField, refundField, paymentOptionField, occupancyStatusField, refundExtendedField) 
{
    var REFUND_TYPE_REFUND = "R";
    var REFUND_TYPE_01_NOREFUND = "N";
    var REFUND_TYPE_05_NOREFUND = "M";
    var REFUND_TYPE_LIMITED = "L";
    var REFUND_TYPE_MICHIGAN_REFUND = "C";
    var REFUND_TYPE_SINGLEMAX = "S";

    var Refund = refundField.options[refundField.selectedIndex].value;

    var lfRefund;

    var Plan = planField.options[planField.selectedIndex].value;
  
    switch (paymentOptionField.options[paymentOptionField.selectedIndex].value) 
    {
        case "A":
        {
            if (Refund == "R") 
                lfRefund = REFUND_TYPE_REFUND
            else 
            {
                if (Plan == "STD")
                    lfRefund = REFUND_TYPE_05_NOREFUND;
                else
                    lfRefund = REFUND_TYPE_01_NOREFUND;
            }
	        break;
        }
        case "M":
        {
            if (Refund == "R")
                lfRefund = REFUND_TYPE_REFUND;
            else
                lfRefund = REFUND_TYPE_01_NOREFUND;
         
            break;
        }
        case "S":
        {
            switch (true) 
            {
                case (Plan == "SIN"):
                {
                    if (occupancyStatusField.value == "3") 
                    {
                        if (Refund == "R")
                            lfRefund = REFUND_TYPE_REFUND;
                        else
                            lfRefund = REFUND_TYPE_SINGLEMAX;
                    } 
                    else 
                    {	
                        if (Refund == "R")
                            lfRefund = REFUND_TYPE_REFUND;
                        else
                            lfRefund = REFUND_TYPE_LIMITED;
                    }
                    break;
  	            }
                case (Plan == "P11" || Plan == "P16"):
                {
                    if (Refund != "R")
                        lfRefund = REFUND_TYPE_LIMITED;
                        
                    break;
                }
	        }
	        break;
        }
        case "Z":
        {
            if (Refund == "R")
                lfRefund = REFUND_TYPE_REFUND;
            else
                lfRefund = REFUND_TYPE_01_NOREFUND;
            
            break;
        }
        default:
        {
            lfRefund = "";
            break;
        }
    }
    
    refundExtendedField.value=lfRefund;
}

function onPlanTypeChange(planField, paymentOptionField, refundOptionField, renewalOptionField)
{
	var selectedOption = planField.options[planField.selectedIndex].value;
	
	if (selectedOption != "Select One")
	{
		var origPayment = paymentOptionField.options[paymentOptionField.selectedIndex].value;
		
		setRefundOption(refundOptionField, planField);
		setRenewalOption(planField, paymentOptionField, renewalOptionField);
					
		clearList(paymentOptionField);
		
		switch (true) 
		{
				case (selectedOption == "SIN"):
				{
					var optionName = new Option("Single","S");
					paymentOptionField.options[1] = optionName;
					break;
				}	
				case (selectedOption == "STD"):
				{
					var optionName = new Option("Annual","A");
					paymentOptionField.options[1] = optionName;
					
					break;
				}
				case (selectedOption == "P11" || selectedOption == "P16"):
				{
					var optionName = new Option("Annual","A");
					paymentOptionField.options[1] = optionName;
					
					optionName = new Option("Monthly","M");
					paymentOptionField.options[2] = optionName;
					
					optionName = new Option("Zip Monthly","Z");
					paymentOptionField.options[3] = optionName;
					
					optionName = new Option("Single","S");
					paymentOptionField.options[4] = optionName;
					
					break;
                }
				default:
				{
					var optionName = new Option("Annual","A");
					paymentOptionField.options[1] = optionName;
					
					optionName = new Option("Monthly","M");
					paymentOptionField.options[2] = optionName;
					
					optionName = new Option("Zip Monthly","Z");
					paymentOptionField.options[3] = optionName;
					
					break;
				}
		}
		
		setDropDownValue(paymentOptionField,origPayment);
	}
}

function setRenewalOption(planField, paymentOptionField, renewalOptionField)
{
	var optionName;
	var planOption = planField.options[planField.selectedIndex].value;
	var origPayment = paymentOptionField.options[paymentOptionField.selectedIndex].value;
	var origRenewal = renewalOptionField.options[renewalOptionField.selectedIndex].value;
	
	clearList(renewalOptionField);
	
	if ((((planOption == "P11") || (planOption == "P16")) && (origPayment == "S")) || (planOption == "SIN"))
	{
		optionName = new Option("Single or One Time","N");
		renewalOptionField.options[1] = optionName;
	}
	else if ((planOption == "P11") || (planOption == "P16"))
	{
		optionName = new Option("Outstanding Balance","D");
		renewalOptionField.options[1] = optionName;
	}
	else
	{
		optionName = new Option("Level","L");
		renewalOptionField.options[1] = optionName;
		
		optionName = new Option("Outstanding Balance","D");
		renewalOptionField.options[2] = optionName;
	}
	
	setDropDownValue(renewalOptionField, origRenewal);
}

function setRefundOption(refundField, planField)
{
	var optionName;
	var origRefund = refundField.options[refundField.selectedIndex].value;
	var planOption = planField.options[planField.selectedIndex].value;
	
	clearList(refundField);
	
	if ((planOption == "P11") || (planOption == "P16"))
	{
		optionName = new Option("No Refund","N");
		refundField.options[1] = optionName;
	}
	else
	{
		optionName = new Option("Refund","R");
		refundField.options[1] = optionName;
		
		optionName = new Option("No Refund","N");
		refundField.options[2] = optionName;
	}
	setDropDownValue(refundField, origRefund);
}

function setRefundDisplay(refundField, refundExtendedField, planTypeField, occupancyStatusField) 
{
	var lcPremiumRefund = refundExtendedField.value;
	
	if ((planTypeField.options[planTypeField.selectedIndex].value=="SIN") && (occupancyStatusField.value=="3") && (lcPremiumRefund.length==0))
    {
        lcPremiumRefund = "R";
    }
    else
    {
	    if((lcPremiumRefund == "M") || (lcPremiumRefund == "N") || (lcPremiumRefund == "L") || (lcPremiumRefund == "S"))
		    lcPremiumRefund="N";
	    else
	    {
		    if(lcPremiumRefund.length > 0)
			    lcPremiumRefund = "R";
		    else
			    lcPremiumRefund = "Select One";
	    }
	}
	
	setDropDownValue(refundField, lcPremiumRefund);
}

function clearList(l1)
{
	var length = l1.options.length;
	for(var i=length-1;i>0;i--)
	{
		l1.options[i] = null;
	}
}

function clearAllListItems(l1)
{
	var length = l1.options.length;
	for(var i=length-1;i>=0;i--)
	{
		l1.options[i] = null;
	}
}

function validateFinancedPremiumAmount(paymentOptionField)
{
	if ((paymentOptionField.value != "S" ))
	{	
		return false;
	}
	
	return true;
}


function validateAuFinancedPremiumAmount(planTypeField, paymentOptionField, errors)
{
	if ((planTypeField.value != "SIN") && 
	    (paymentOptionField.value != "S" ))
	{
		strErrorText = " is only allowed with the &quot;Singlemax&quot; Plan Type and the &quot;Single&quot; Payment Option.";
		errors.AddError("<em>Financed Premium Amount</em> " + strErrorText, "FinancedPMI");		
	}	
	return true;
}


function ELSForm_onsubmit(f1) {

   setPaddingWidth();

   var objErrors = validateForm(f1);

   if (!objErrors.IsEmpty()) {
       objErrors.DisplayErrors();
   } else {

	if (f1.confirm) {
		if (window.confirm("Are you sure you want to submit this form?"))
			f1.submit();
	} else {
		f1.submit();
	}
   }
}

function estimateInsurance(hazardField, totalLoanField, recalculate) 
{
	if ((hazardField.value.length == 0) || (recalculate)) 
	{
		var loanAmt = parseFloat(totalLoanField.value);
		
		if (isNaN(loanAmt))
			loanAmt = 0;
			
		var insAmt = loanAmt * (0.0025/12);
		
		if (insAmt>0)
	    {
		    hazardField.value = formatCurrency(insAmt);
		}
	}
}

function estimateTaxes(realEstateTaxesField, totalLoanField, recalculate) 
{
	if ((realEstateTaxesField.value.length == 0) || (recalculate)) 
	{
		var loanAmt = parseFloat(totalLoanField.value);
		
		if (isNaN(loanAmt))
			loanAmt = 0;
			
		var taxAmt = loanAmt * (0.01125/12);
		
		if (taxAmt>0)
		{
		    realEstateTaxesField.value = formatCurrency(taxAmt);
		}
	}
}

function isListEmpty(oElement)
{
	var count = oElement.options.length;
	if ( count <= 0)
		return (true);
	else
		return (false);
}

function setIsEqualTo(oElement, sElementName, oOtherElement, sMessage) 
{
    oElement.fpValidation=isEqualToOtherField;
    oElement.uniqueId = sElementName;
    oElement.otherfield = oOtherElement;
    oElement.validationMessage = sMessage;
}

function isEqualToOtherField(oElement)
{
    if (oElement.value == oElement.otherfield.value)
       return true;
    else
        return false;
}

function isLetter (c)
{
	return ( ((c >= "a") && (c <= "z")) || ((c >= "A") && (c <= "Z")) )
}

// Returns true if character c is a digit (0 .. 9).
function isDigit (c)
{
	return ((c >= "0") && (c <= "9"))
}

// Returns true if Password is at least MinPasswordLength characters
function isValidPassword(oElement)
{
    var MinPasswordLength = 8;
	var sValue = oElement.value;

	if (isEmpty(oElement.value))
		return false;

	if (oElement.validationMessage.length == 0)
	{
		oElement.validationMessage = "is an invalid password. Your new Password should be 8 to 40 characters long and must contain at least one alpha and one numeric character.";
	}
	if ((sValue.length < MinPasswordLength))
		return false;
	
	var bIsDigitPresent=false;
	var bIsCharacterPresent=false;
	sString = oElement.value;
	for(var i = 0;i<oElement.value.length;i++)
	{
		var sChar = sString.charAt(i);
		if(isLetter(sChar))
			bIsCharacterPresent = true;
		if(isDigit(sChar))
			bIsDigitPresent = true;	
	}
	if(bIsCharacterPresent && bIsDigitPresent )
		return true;
	else
		return false;
}

function isEditAllowed(oInput, oEvent) 
{
	if (oInput.editAllowed)
		return true;
	else {
		if (oEvent.which == 0)
			return true;
		return false;
	}
}

function ELSForm_onclear(f1) 
{
	if (window.confirm("Selecting Clear will abandon all of your changes.  Are you sure you want to continue?"))
		window.location.reload();
}

function getInstance(oElement) {
	var sElementName = oElement.name;
	var iInstanceSplit = sElementName.indexOf("_");
	if (iInstanceSplit > 0) {
		var sInstance = sElementName.substring(iInstanceSplit, sElementName.length);
	} else {
		var sInstance = "";
	}
	return sInstance;
}

function getElementInstances(oForm, oElement)
{
	var sElementName;
	var iInstanceSplit;
	var sInstance;
	
	var oElements = new Array();
	var oFormElements = oForm.elements;

	if (typeof(oElement)=="object")
	{
		sElementName = oElement.name
	}
	else
	{
		sElementName = oElement;
	}
	
	iInstanceSplit = sElementName.indexOf("_");
	
	if (iInstanceSplit > 0) 
	{
		sElementName = sElementName.substring(0, iInstanceSplit);
	}
	
	for (var i = 0;i < oFormElements.length;i++)
	{
		sInstance = getInstance(oFormElements[i]);
		
		if (sInstance.length>0)
		{
			if (oFormElements[i].name == (sElementName + sInstance))
			{
				oElements[oElements.length] = oFormElements[i];
			}
		}
	}
	
	return oElements;
}

function initializeBorrowerGovernmentMonitoring(f1)
{
	var initialValue = "Y";
	
	if (!f1.BorrowerDoesNotWishtoFurnish.checked || ((f1.ApplicationTakenBy) && (f1.ApplicationTakenBy.value=="F")))
	{
	    initialValue = "N";
	}
	
	f1.BorrowerDoesNotWishtoFurnishHidden.value = initialValue;
	
	initializeBorrowerRace(f1);
}

function initializeBorrowerRace(f1)
{
    var initialValue = "Y";
	
	if(f1.BorrowerDoesNotWishtoFurnishHidden.value == 'N')
	{

		if (f1.BorrowerAmericanIndianorAlaskaNative.checked || 
		    f1.BorrowerAsian.checked || 
		    f1.BorrowerNativeHawaiianorOtherPacificIslander.checked || 
		    f1.BorrowerBlackorAfricanAmerican.checked || 
		    f1.BorrowerWhite.checked || 
		    f1.BorrowerNotApplicable.checked)
        {
            initialValue = "N";
        }
	}
	else
	{
	    initialValue = "N";
	}
	
	f1.BorrowerRaceRequiredHidden.value = initialValue;
}

function initializeCoBorrowerGovernmentMonitoring(f1)
{
	var initialValue = "Y";
	
	if (isCoBorrowerPresent(f1))
	{
	    if (!f1.CoBorrowerDoesNotWishtoFurnish.checked || ((f1.ApplicationTakenBy) && (f1.ApplicationTakenBy.value=="F")))
	    {
	        initialValue = "N";
	    }
    	
	    f1.CoBorrowerDoesNotWishtoFurnishHidden.value = initialValue;
    	
	    initializeCoBorrowerRace(f1);
	}
	else
	{
	    f1.CoBorrowerDoesNotWishtoFurnishHidden.value = initialValue;
	    initializeCoBorrowerRace(f1);
	}
}

function initializeCoBorrowerRace(f1)
{
    var initialValue = "Y";
	
	if (isCoBorrowerPresent(f1))
	{
	    if(f1.CoBorrowerDoesNotWishtoFurnishHidden.value == 'N')
	    {

		    if (f1.CoBorrowerAmericanIndianorAlaskaNative.checked || 
		        f1.CoBorrowerAsian.checked || 
		        f1.CoBorrowerNativeHawaiianorOtherPacificIslander.checked || 
		        f1.CoBorrowerBlackorAfricanAmerican.checked || 
		        f1.CoBorrowerWhite.checked || 
		        f1.CoBorrowerNotApplicable.checked)
            {
                initialValue = "N";
            }
	    }
	    else
	    {
	        initialValue = "N";
	    }
    	
	    f1.CoBorrowerRaceRequiredHidden.value = initialValue;
    }
    else
    {
        f1.CoBorrowerRaceRequiredHidden.value = "N";
    }
}

function clearOtherRaces(f1, borrower)
{
    if (borrower)
    {
        f1.BorrowerAmericanIndianorAlaskaNative.checked = false; 
	    f1.BorrowerAsian.checked = false; 
	    f1.BorrowerNativeHawaiianorOtherPacificIslander.checked = false; 
	    f1.BorrowerBlackorAfricanAmerican.checked = false; 
	    f1.BorrowerWhite.checked = false; 
        
        initializeBorrowerRace(f1);
    }
    else
    {
		f1.CoBorrowerAmericanIndianorAlaskaNative.checked = false; 
		f1.CoBorrowerAsian.checked = false; 
		f1.CoBorrowerNativeHawaiianorOtherPacificIslander.checked = false; 
		f1.CoBorrowerBlackorAfricanAmerican.checked = false; 
		f1.CoBorrowerWhite.checked = false; 
		
		initializeCoBorrowerRace(f1);
    }
}

function clearNotApplicable(f1, borrower)
{
    if (borrower)
    {
        f1.BorrowerNotApplicable.checked = false; 
        
        initializeBorrowerRace(f1);
    }
    else
    {
        f1.CoBorrowerNotApplicable.checked = false;
        
        initializeCoBorrowerRace(f1);
    }
}

function isCoBorrowerPresent(f1)
{
    //return FieldEntered(f1.CoBorrowerFirstName);
    return FieldEntered(f1.CoBorrowerDisplayedName);
}

function processCheckBoxes(f1) 
{
	var oCurrElement;
	
	for (var i = 0; i < f1.elements.length; i++) 
	{
		oCurrElement = f1.elements[i];
		if (oCurrElement.type=="checkbox") 
		{
			if (!oCurrElement.checked && oCurrElement.value!="") 
			{
                oCurrElement.value = oCurrElement.uncheckedValue;
                oCurrElement.checked = true;
			}   
		}
	}
}

function roundAlways(strValue, intPrecision)
{
	var dblResult = 0;
	var intDecimalPos = 0;
	var bolIncrementLastDigit = false;
	var strTemp;
	
	if (intPrecision < 0)
	{
		intPrecision = 0;
	}
	
	if (typeof(strValue)!="string")
	{
		strValue = new String(strValue);
	}
	
	intDecimalPos = strValue.indexOf(".");

	if (intDecimalPos > -1 && intPrecision > 0)
	{
		strTemp = strValue.substr(intDecimalPos + 1);

		if (strTemp.length>intPrecision && strTemp.substr(intPrecision,1) < 5 && strTemp > 0)
		{
			bolIncrementLastDigit = true;
		}
	}

	dblResult = Math.round(strValue * Math.pow(10,intPrecision));

	if (bolIncrementLastDigit)
	{
		dblResult += 1;
	}

	dblResult = (dblResult / Math.pow(10,intPrecision));

	return dblResult;
}

function Trim(s) 
{
  // Remove leading spaces and carriage returns
  
  while ((s.substring(0,1) == ' ') || (s.substring(0,1) == '\n') || (s.substring(0,1) == '\r'))
  {
    s = s.substring(1,s.length);
  }

  // Remove trailing spaces and carriage returns

  while ((s.substring(s.length-1,s.length) == ' ') || (s.substring(s.length-1,s.length) == '\n') || (s.substring(s.length-1,s.length) == '\r'))
  {
    s = s.substring(0,s.length-1);
  }
  return s;
}

function IsGroupEmpty(instance, key, form)
{
    var elements = form.elements;
    var element = null;
    var instance = "_" + instance.toString();
    
    for (var index=0;index<elements.length;index++)
    {
        element = elements[index];
        
        if ((getInstance(element)==instance) && (element.clearInstance) && (element.clearInstance==key))
        {
            if (FieldEntered(element))
            {
                return false;
            }
        }
    }
    
    return true;
}