




var zipCodeLookup;

function hideShowStateDropDown(){
    zipCodeLookup = createXmlHttpObject();
  
    var zipCode  = document.form1.PROP_ZIP.value;
    var url = "/common/zipLookup.asp?zipCode=" + (zipCode);

    zipCodeLookup.open("GET", url, true);

    zipCodeLookup.onreadystatechange = returnState;
    zipCodeLookup.send(null);
}

function returnState() {
  if (zipCodeLookup.readyState == 4) {
    var response = zipCodeLookup.responseText;
    var stateDropDown = document.form1.PROP_STATE_CONST;
    var stateValue = "00";
    
    if (response > 0){
            stateValue = response;
    }
	else
	{
	        stateValue = "00";
	}
	
	if (stateDropDown)
	{
	    stateDropDown.value = stateValue;
	    stateDropDown.onchange();
        
        hideShowHETenneseeMsg();
	}
  }
}

function setBypass()
{
  document.form1.VIEW_LENDERS_PATH.value = "0";
  document.form1.GS_INCENTIVE.value = "1";
  setVerb('continue');document.forms['form1'].submit();
}

function setValidate()
{
  document.form1.VIEW_LENDERS_PATH.value = "1";
  setVerb('continue');document.forms['form1'].submit();
}

function setCreditPull()
{
  if(document.form1.OPTIN_CONST[0].checked == true) {
    document.form1.VIEW_LENDERS_PATH.value = "1";
    document.form1.CREDITPULL_OPTIN.value = "1";
  }
  else {
    document.form1.VIEW_LENDERS_PATH.value = "0";
    document.form1.CREDITPULL_OPTIN.value = "0";
  }
  setVerb('continue');document.forms['form1'].submit();
}

function RedirectToRefi()
{
	window.location = '/refi/qform.asp?page=loan_selection&verb=continue&O_loan_type=LOAN_TYPE_REFINANCE&siteid=&bp=ltespanol&esourceid=529420&source=529420&init=1'
}
function RedirectUser()
{
	
  try{	
	var sRedirectURL;
	var sRedirectQS;
	var sCurrentQS;
	var foundMatchTypeConst = false;
	var exceptionValueArray = ["TYPE_CONST"];
	var sScrubbedIncomingQS = '';
	var sUseBP;
	
	if(document.forms.form1.BP && document.forms.form1.BP.value != ''){
		sUseBP = document.forms.form1.BP.value;
	}
	else{
		sUseBP = "gsnew";
	}
	
	
	if (document.forms.form1.TYPE_CONST.value != document.forms.form1.ORIG_TYPE_CONST.value) {
	
	
	
		
		if ((document.forms.form1.TYPE_CONST) && (document.forms.form1.TYPE_CONST.value == "1"))
		{	
			sRedirectURL = "/gs_purchase/ctl_Borrower.asp";
			sRedirectQS = "page=loan_selection&amp;verb=continue&amp;O_loan_type=LOAN_TYPE_PURCHASE&amp;source=" + document.forms.form1.s.value + "&amp;esourceid=" + document.forms.form1.es.value + "&amp;siteid=" + document.forms.form1.site.value + "&amp;bp=" + sUseBP + "&amp;init=1" + createRedirectVersion();
			foundMatchTypeConst = true;
		} 
		else if ((document.forms.form1.TYPE_CONST) && (document.forms.form1.TYPE_CONST.value == "2"))
		{	
			sRedirectURL = "/gs_refinance/ctl_Borrower.asp";
			sRedirectQS = "page=loan_selection&amp;verb=continue&amp;O_loan_type=LOAN_TYPE_REFINANCE&amp;source=" + document.forms.form1.s.value + "&amp;esourceid=" + document.forms.form1.es.value + "&amp;siteid=" + document.forms.form1.site.value + "&amp;bp=" + sUseBP + "&amp;init=1" + createRedirectVersion();
			foundMatchTypeConst = true;
		}
		else if ((document.forms.form1.TYPE_CONST) && (document.forms.form1.TYPE_CONST.value == "3"))
		{	
			sRedirectURL = "/gs_home_equity/ctl_Borrower.asp";
			sRedirectQS = "page=loan_selection&amp;verb=continue&amp;O_loan_type=LOAN_TYPE_HOME_EQUITY&amp;source=" + document.forms.form1.s.value + "&amp;esourceid=" + document.forms.form1.es.value + "&amp;siteid=" + document.forms.form1.site.value + "&amp;bp=" + sUseBP + "&amp;init=1" + createRedirectVersion();
			foundMatchTypeConst = true;
		} 
		else if ((document.forms.form1.TYPE_CONST) && (document.forms.form1.TYPE_CONST.value == "4"))
		{
			sRedirectURL = "/gs_debt_consolidation/ctl_Borrower.asp";
			sRedirectQS = "page=loan_selection&amp;verb=continue&amp;O_loan_type=LOAN_TYPE_DEBT_CONSOLIDATION&amp;source=" + document.forms.form1.s.value + "&amp;esourceid=" + document.forms.form1.es.value + "&amp;siteid=" + document.forms.form1.site.value + "&amp;bp=" + sUseBP + "&amp;init=1" + createRedirectVersion(); 
			foundMatchTypeConst = true;	
		} 
	}
	
	
	
	if (foundMatchTypeConst == true){
		sScrubbedIncomingQS = removeExceptionValues(getQueryString(location.search), exceptionValueArray);
		sCombinedRedirectQS = mergeQSValues(sRedirectQS, sScrubbedIncomingQS);
		// need to add the combined QS onto the redirectURL
		sRedirectURL = sRedirectURL + "?" + sCombinedRedirectQS;
		document.forms['form1'].elements['validNavigation'].value = '1';
		window.location = sRedirectURL;
	}
  
  } catch(exception){
  	// do nothing
  } 
}				

function STMRCWindow(page, sHeight, swidth) {
	if (swidth && sHeight) {
			window.open(page, "CtrlWindow", ",toolbar=no,menubar=no,location=no,scrollbars=no,resizable=no,dependent=no,directories=no,width="+swidth+",height="+sHeight+",x=50,y=50");
		}
		else { 
			window.open(page, "CtrlWindow", "toolbar=no,menubar=no,location=no,scrollbars=yes,resizable=no,dependent=no,directories=no,width=455,height=540,x=50,y=50");
		}
}

function createRedirectVersion(){
	sRedirectVersion = '';
	
	try{
		// LTQuickMatch is coded to handle version 23 for HE & Refi and Version 28 for Purchase
		if(document.forms.form1.BP && document.forms.form1.BP.value.toLowerCase() == "ltquickmatch"){
			// Purchase
		        if ((document.forms.form1.TYPE_CONST) && (document.forms.form1.TYPE_CONST.value == "1")) {	
	                	sRedirectVersion = "&version=28";
			} 
			 
			else {	
	                	sRedirectVersion = "&version=23";
			}
		} 
		else{
		
	        // find the QF version if it's available on the page
	        if ((document.forms.form1.version) && (document.forms.form1.version.value != "")){
        	    
	            //===[ v.sodha -    v500 HACK Redirect to current champion versions since they don't exsist
	            //===				for other products beside purchase
        	
	            if(document.forms.form1.version.value == "500") {
        	    
	                // Refi
	                if ((document.forms.form1.TYPE_CONST) && (document.forms.form1.TYPE_CONST.value == "2")) {	
                        sRedirectVersion = "&version=30";
		            } 
		            // HE
		            else if ((document.forms.form1.TYPE_CONST) && (document.forms.form1.TYPE_CONST.value == "3")) {	
                        sRedirectVersion = "&version=30";
		            }
		            // DC
		            else if ((document.forms.form1.TYPE_CONST) && (document.forms.form1.TYPE_CONST.value == "4")) {
                        sRedirectVersion = "&version=30";
		            }
	            }
        	    
	            else {
		            sRedirectVersion = "&version=" + document.forms.form1.version.value;
	            }
	        }
		}
	}catch(exception){
		// do nothing
	}
	
	return sRedirectVersion;
}

function getQueryString(sURL){
	var sQueryString = sURL;
	var iQuestionMarkIndex = sURL.indexOf("?")
	
	// get the query string, ignore the ? at the front.
	if (iQuestionMarkIndex > -1){
		sQueryString = sURL.substring(iQuestionMarkIndex + 1,sURL.length);
	}
	return sQueryString;
}

function mergeQSValues(sValuesQS, sBaseQS){	
	// We're going to add the values from sValuesQS into the sBaseQS.
	// If the name exists on the sBaseQS already, we're going to replace the value
	// with that from sValuesQS.  If the name doesn't exist at all, we're 
	// going to add it to the end of sBaseQS.
	
	var sReturnQS = sBaseQS;
	
	// if the query string passed in is blank, there's no processing to do.
	if (sValuesQS.length > 0){
	
		// if the query strings were passed in with escaped '&' signs, unescape them
		var re = new RegExp("&AMP;",  "gi"); 
		sValuesQS = sValuesQS.replace(re, "&");
		sReturnQS = sReturnQS.replace(re, "&");
		
		// first, we split the URL that was passed in into name=value segments.
		var sValue_array = sValuesQS.split("&");

		// next, we loop through the array of name=value segments and look to see
		// if the value is on the baseQS already
		for (i=0; i < sValue_array.length; i++){
			// get a single name=value pair from the array
			var sCombinedNameValuePair = sValue_array[i];
			sReturnQS = replaceValuePairOnString(sCombinedNameValuePair, sReturnQS);
		}
	}
	return sReturnQS;
}


function replaceValuePairOnString(sCombinedNameValuePair, sBaseQS){
	// seperate the name from the value
	var sNameValue_array = sCombinedNameValuePair.split("=");
	var sName = sNameValue_array[0];
	var sReturnQS = sBaseQS;
	
	// if the name is found on the baseQS, we replace the current value with the
	// value that is on the valuesQS
	if (sReturnQS.toLowerCase().indexOf(sName.toLowerCase()) > -1){
		
		// get the first character's index for the new parameter match
		var beginOfMatchIndex = sReturnQS.toLowerCase().indexOf(sName.toLowerCase());
		
		// Must ensure that this is an exact match.
		// This must be the first character of the baseQS or the first character preceeding the name must an &
		if ((beginOfMatchIndex == 0) || 
			(sReturnQS.substring(beginOfMatchIndex - 1, beginOfMatchIndex) == "&")){
		
			// take a substring from the new parameter match to the end of the current QS
			var matchSubString = sReturnQS.substring(beginOfMatchIndex, sReturnQS.length);
			
			// find the first instance of an & after the new parameter match
			var ampIndex = matchSubString.indexOf("&");
			
			// if the '&' match not found, this must be the last parameter - take length of matchSubString
			if (ampIndex < 0){
				ampIndex = matchSubString.length;
			}	
			var replaceSubString = matchSubString.substring(matchSubString, ampIndex);
			
			//now, replace the replaceSubString with the array's name=value pair 
			sReturnQS = sReturnQS.replace(replaceSubString, sCombinedNameValuePair);
		}
	}
	else{	
		// if the name is not found, we add the name=value to the 
		sReturnQS = sReturnQS + "&" + sCombinedNameValuePair;
	}
	
	return sReturnQS;
}



function removeExceptionValues(sQS, sExceptionValueArray){
	
	var sName;
	var sReturnQS = sQS;
	
	// going to iterate over the exception array.
	// if a match is found, going to remove that segment from the query string (sQS)
	for (i = 0; i <  sExceptionValueArray.length ; i++){
		
		sName = sExceptionValueArray[i];
		
		if (sQS.indexOf(sName) > -1){
			var beginOfMatchIndex = sReturnQS.indexOf(sName);
			
			// Must ensure that this is an exact match.
			// This must be the first character of the baseQS or the first character preceeding the name must an &
			if ((beginOfMatchIndex == 0) || (sReturnQS.substring(beginOfMatchIndex - 1, beginOfMatchIndex) == "&")){
				
				// take a substring from the new parameter match to the end of the current QS
				// see if the & must be removed too
				var matchSubString = sReturnQS.substring(beginOfMatchIndex, sReturnQS.length);
				var includeLeadingAmp = false;
				
				if (sReturnQS.substring(beginOfMatchIndex - 1, beginOfMatchIndex) == "&"){
					includeLeadingAmp = true;
				}
				
				// find the first instance of an & after the new parameter match
				var ampIndex = matchSubString.indexOf("&");
				
				// if the '&' match not found, this must be the last parameter - take length of matchSubString
				if (ampIndex < 0){
					ampIndex = matchSubString.length;
				}	
				var replaceSubString = matchSubString.substring(matchSubString, ampIndex);
				
				if (includeLeadingAmp = true){
					replaceSubString = "&" + replaceSubString;
				}
				
				//now, replace the replaceSubString with an empty string
				sReturnQS = sReturnQS.replace(replaceSubString, '');
			}
		}
	}
	
	return sReturnQS;
}

function setHelConst()
{
  // radio button logic
  if( document.form1.HEL_CONST[0].tagName.toLowerCase() == 'input'){
    if( (document.form1.HEL_PAYMENT.value.length==0 || document.form1.HEL_PAYMENT.value==null ||
      document.form1.HEL_PAYMENT.value==0) &&
	    document.form1.HEL_BALANCE.value.length==0 || document.form1.HEL_BALANCE.value==null ||
	    document.form1.HEL_BALANCE.value==0) {
	    document.form1.HEL_CONST[1].checked = true;  
	  }
	  else {
	    document.form1.HEL_CONST[0].checked = true;
	  }
  }
  
  // select box logic
  else if (document.form1.HEL_CONST[0].tagName.toLowerCase() == 'option'){
	  if( (document.form1.HEL_PAYMENT.value.length==0 || document.form1.HEL_PAYMENT.value==null ||
	      document.form1.HEL_PAYMENT.value==0) &&
	      document.form1.HEL_BALANCE.value.length==0 || document.form1.HEL_BALANCE.value==null ||
	      document.form1.HEL_BALANCE.value==0) {

		  document.form1.HEL_CONST.value = 2;
	  }
	  else {
	    
		  document.form1.HEL_CONST.value = 1;
	  }
  }
}

function zeroSecondMortgageValues()
{
	var iSel;
	var selectVal;
	
	try{	
		// this logic is for radio buttons	
		if( document.form1.HEL_CONST[0].tagName.toLowerCase() == 'input'){
			if (document.form1.HEL_CONST[1].checked == true){
				document.form1.HEL_BALANCE.value = 0;
				document.form1.HEL_PAYMENT.value = 0;
			}
		}
		// this logic is for select boxes
		else if (document.form1.HEL_CONST[0].tagName.toLowerCase() == 'option'){
			iSel = document.form1.HEL_CONST.selectedIndex;
			selectVal = document.form1.HEL_CONST.options[iSel].value;
			if (selectVal == '2'){
				document.form1.HEL_BALANCE.value = 0;
				document.form1.HEL_PAYMENT.value = 0;
			}
		}
	}catch(exception){
		//nothing to recover from - just don't error out the page
	}
}	


// provided by Brad Gebert
function addCommasNoSpecialCharacters(oObj){
	//alert("keycode = " + window.event.keyCode);
	if (window.event){
		if((window.event.keyCode==9)||(window.event.keyCode==16)){return (oObj.value);}
	}else if (key.which){
		if((key.which.keyCode==9)||(key.which==16)){return (oObj.value);}
	}
	
	try{
		var sValue = oObj.value;
		 
		var sNewVal = '';
				
		//===[ m.squires - GS-6907 Checking for a decimal point and displaying alert to
		//===				interrupt user input to prevent them from type the rest of the decimal value
		//===				This interruption prevent a the user from type the value 1.11, which would 
		//===				show up as 111, without the interruption
//		if (oObj.value.indexOf(".") >= 0)
//		{
//			alert("Please only use whole numbers when completing the form.  No need to use a decimal point.");
//		}
        //sValue = sValue.replace(/\$|\,/g,'')
        //alert("PRE-sValue = " + sValue);
		sValue = sValue.replace(/[^0-9,.]/g,"");	//remove non numeric values - a two digit decimal value is allowed
		//alert("POST-sValue = " + sValue);
		
		//Remove Leading Zeros, If more than 1
		if (oObj.value.length > 1) {
			while (oObj.value.indexOf("0") == 0){
				sValue = sValue.replace('0',"")
				break;
			}
		}
		if (oObj.value.length > 1) {
			for (idx=1; idx < oObj.maxLength; idx++){
				if(oObj.value.charAt(idx) == "0" && oObj.value.charAt(0) == "0"){
					sValue = sValue.replace(oObj.value.charAt(idx),"")
				}
				else break;
			}

			if(oObj.value.charAt(0) == "0" && oObj.value.charAt(1) != "0") {
				sValue = sValue.replace(oObj.value.charAt(0),"")
			}           
		}
		
		// attempting to remove extra characters that may have slipped in.
		if (oObj.maxLength){
			if (sValue.length > parseInt(oObj.maxLength)){ 
				sValue = sValue.substr(0,oObj.maxLength-(parseInt(oObj.maxLength/3))) //MaxLength must = 4, 7 or 10 
			}
		}
		
		index = 0
		// compVal = the numeric string without added commas used in UI formatting
		compVal = ""
		// decVal = the string of "." + the two decimal values to concatentate onto the post-formatted string value.
		decVal = ""
		
		// Set the value for compVal		
		while ((index < sValue.length) && (oObj.value.charAt(index) != ".")){
				
				if (oObj.value.charAt(index) != ","){
				    compVal = compVal + sValue.substr(index,1);
				}
				index = index + 1;
			
		}
		
		// Set the value for decVal
		if (oObj.value.charAt(index) == "."){
		    
		        decVal = oObj.value.charAt(index) + oObj.value.charAt(index+1) + oObj.value.charAt(index+2);
		      
		}
				      
			//alert("compVal = " + compVal + " compVal.length = " + compVal.length + " sValue = " + sValue);
			//compVal = sValue.replace(/[^0-9]+/g,"");
			//alert("compVal = " + compVal + " sValue = " + sValue);
			
		if(compVal > 99){
		    
			var nCommas = parseInt((compVal.length / 3))
			
			if ((compVal.length % 3) == 0){
				//subtract extra comma that can occur if modulus = 0 
				--nCommas
			}	
			//alert("ncommas = " + nCommas);
			
			if (nCommas > 0){

					for (n = nCommas; n > 0; n--){		//add comma(s)
						sNewVal =  sNewVal + ',' + compVal.substr((compVal.length-(n*3)),3);
					}//add remaining
				    //alert(" STR = " + sValue.substr(0,((sValue.length-(nCommas*3)) / 1)));
					sNewVal =  compVal.substr(0,((compVal.length-(nCommas*3)) / 1)) + sNewVal;
					//alert("sNewVal3 = " + sNewVal)
					sNewVal = sNewVal + decVal;
					oObj.value = sNewVal;
				}
			else{
					oObj.value = compVal + decVal;
			}		
				
		}
		else{
			oObj.value = sValue;
		}   
			return (oObj.value);
	}catch(exception){
		//do nothing
	}
}	


function formatCurrency(num) {
				num = num.toString().replace(/\$|\,/g,'');
				if(isNaN(num))
				num = "0";
				sign = (num == (num = Math.abs(num)));
				num = Math.floor(num*100+0.50000000001);
				cents = num%100;
				num = Math.floor(num/100).toString();
				if(cents<10)
				cents = "0" + cents;
				for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
				num = num.substring(0,num.length-(4*i+3))+','+
				num.substring(num.length-(4*i+3));
				return ('$' + ((sign)?'':'-') + num + '.' + cents);
                
//                if (num == ""){
//                    num = "0.00";
//                }
//                alert(num.toString());
//                if (num.toString().charAt(0) != "$"){
//                    return ('$' + num);
//                }
//                else{
//                    return (num);
//                }
}



function hideShowSecondMortgageFields(){

	try{
		if (document.form1.HEL_CONST){
	
			// this logic is for radio buttons	
			if( document.form1.HEL_CONST[0].tagName.toLowerCase() == 'input'){
				
				// if answer is "No", we'll hide the fields
				if (document.form1.HEL_CONST[1].checked == true){
					//document.getElementById('SMART_REFINANCE_METHOD_CONST_HIDE_ELEMENT').style.display='none';
					document.getElementById('HEL_BALANCE_HIDE_ELEMENT').style.display='none';
					document.getElementById('HEL_PAYMENT_HIDE_ELEMENT').style.display='none';
					document.getElementById('HEL_BALANCE_HIDE_TEMPLATE_SPACE').style.display='none';
					document.getElementById('HEL_PAYMENT_HIDE_TEMPLATE_SPACE').style.display='none';
					document.getElementById('HEL_BALANCE_HIDE_ELEMENT_SPACER_ROW').style.display='none';
					document.getElementById('HEL_PAYMENT_HIDE_ELEMENT_SPACER_ROW').style.display='none';
				}
				// if the answer is anything other then "No", we show the fields
				else {
					//document.getElementById('SMART_REFINANCE_METHOD_CONST_HIDE_ELEMENT').style.display='';
					document.getElementById('HEL_BALANCE_HIDE_ELEMENT').style.display='';
					document.getElementById('HEL_PAYMENT_HIDE_ELEMENT').style.display='';
					document.getElementById('HEL_BALANCE_HIDE_TEMPLATE_SPACE').style.display='';
					document.getElementById('HEL_PAYMENT_HIDE_TEMPLATE_SPACE').style.display='';
					document.getElementById('HEL_BALANCE_HIDE_ELEMENT_SPACER_ROW').style.display='';
					document.getElementById('HEL_PAYMENT_HIDE_ELEMENT_SPACER_ROW').style.display='';
				}
			}
			// this logic is for select boxes
			else if (document.form1.HEL_CONST[0].tagName.toLowerCase() == 'option'){
				var iSel = 0;
				var selectVal = 0;
				
				iSel = document.form1.HEL_CONST.selectedIndex;
				selectVal = document.form1.HEL_CONST.options[iSel].value;
				// if answer is "No", we'll hide the fields
				if (selectVal == '2'){
					document.getElementById('HEL_BALANCE_HIDE_ELEMENT').style.display='none';
					document.getElementById('HEL_PAYMENT_HIDE_ELEMENT').style.display='none';
					document.getElementById('HEL_BALANCE_HIDE_TEMPLATE_SPACE').style.display='none';
					document.getElementById('HEL_PAYMENT_HIDE_TEMPLATE_SPACE').style.display='none';
					document.getElementById('HEL_BALANCE_HIDE_ELEMENT_SPACER_ROW').style.display='none';
					document.getElementById('HEL_PAYMENT_HIDE_ELEMENT_SPACER_ROW').style.display='none';
					//document.getElementById('SMART_REFINANCE_METHOD_CONST_HIDE_ELEMENT').style.display='none';
				}
				// if the answer is anything other then "No", we show the fields
				else {
					document.getElementById('HEL_BALANCE_HIDE_ELEMENT').style.display='';
					document.getElementById('HEL_PAYMENT_HIDE_ELEMENT').style.display='';
					document.getElementById('HEL_BALANCE_HIDE_TEMPLATE_SPACE').style.display='';
					document.getElementById('HEL_PAYMENT_HIDE_TEMPLATE_SPACE').style.display='';
					document.getElementById('HEL_BALANCE_HIDE_ELEMENT_SPACER_ROW').style.display='';
					document.getElementById('HEL_PAYMENT_HIDE_ELEMENT_SPACER_ROW').style.display='';
					//document.getElementById('SMART_REFINANCE_METHOD_CONST_HIDE_ELEMENT').style.display='none';
				}
			}
		}
	}catch(exception){
		//nothing to recover from - just don't error out the page
	}
}

function addCommasNoSpecialCharactersES(oObj){
	if (window.event){
		if((window.event.keyCode==9)||(window.event.keyCode==16)){return}
	}else if (key.which){
		if((key.which.keyCode==9)||(key.which==16)){return}
	}
	
	try{
		var sValue = oObj.value;
		var sNewVal = '';
		
		//===[ m.squires - GS-6907 Checking for a decimal point and displaying alert to
		//===				interrupt user input to prevent them from type the rest of the decimal value
		//===				This interruption prevent a the user from type the value 1.11, which would 
		//===				show up as 111, without the interruption
		if (oObj.value.indexOf(".") >= 0)
		{
			alert("Por favor utiliza números enteros al llenar el formulario. No es necesario usar puntos decimales.");
		}
		sValue = sValue.replace(/[^0-9]/ig,"")	//remove non numeric values
		
		//Remove Leading Zeros, If more than 1
		if (oObj.value.length > 1) {
			while (oObj.value.indexOf("0") == 0){
				sValue = sValue.replace('0',"")
				break;
			}
		}
		if (oObj.value.length > 1) {
			for (idx=1; idx < oObj.maxLength; idx++){
				if(oObj.value.charAt(idx) == "0" && oObj.value.charAt(0) == "0"){
					sValue = sValue.replace(oObj.value.charAt(idx),"")
				}
				else break;
			}

			if(oObj.value.charAt(0) == "0" && oObj.value.charAt(1) != "0") {
				sValue = sValue.replace(oObj.value.charAt(0),"")
			}           
		}
		
		// attempting to remove extra characters that may have slipped in.
		if (oObj.maxLength){
			if (sValue.length > parseInt(oObj.maxLength)){ 
				sValue = sValue.substr(0,oObj.maxLength-(parseInt(oObj.maxLength/3))) //MaxLength must = 4, 7 or 10 
			}
		}
		
		
		if(sValue > 99){
			var nCommas = parseInt((sValue.length / 3))
			if ((sValue.length % 3) == 0){
				//subtract extra comma that can occur if modulus = 0 
				--nCommas
			}	
			
			if (nCommas > 0){

					for (n = nCommas; n > 0; n--){		//add comma(s)
						sNewVal =  sNewVal + ',' + sValue.substr((sValue.length-(n*3)),3);
					}//add remaining
				
					sNewVal =  sValue.substr(0,((sValue.length-(nCommas*3)) / 1)) + sNewVal;
					oObj.value = sNewVal;
				}
			else{
					oObj.value = sValue;
			}		
				
		}
		else{
			oObj.value = sValue;
		}
				
	}catch(exception){
		//do nothing
	}
}	
function hideShowBankruptcyField(){
	
	
	try{
		if (document.form1.BANKRUPTCY_PAST){

			// this logic is for radio buttons	
			if( document.form1.BANKRUPTCY_PAST[0].tagName.toLowerCase() == 'input'){
				
				// if answer is "No", we'll hide the fields
				if (document.form1.BANKRUPTCY_PAST[1].checked == true){
					document.getElementById('BANKRUPTCY_BO_CONST_HIDE_ELEMENT').style.display='none';
					document.getElementById('BANKRUPTCY_BO_CONST_HIDE_TEMPLATE_SPACE').style.display='none';
					document.getElementById('BANKRUPTCY_BO_CONST_HIDE_ELEMENT_SPACER_ROW').style.display='none';
				}
				// if the answer is anything other then "No", we show the fields
				else {
					document.getElementById('BANKRUPTCY_BO_CONST_HIDE_ELEMENT').style.display='';	
					document.getElementById('BANKRUPTCY_BO_CONST_HIDE_TEMPLATE_SPACE').style.display='';
					document.getElementById('BANKRUPTCY_BO_CONST_HIDE_ELEMENT_SPACER_ROW').style.display='';	
				}
			}
			// this logic is for select boxes
			else if (document.form1.BANKRUPTCY_PAST[0].tagName.toLowerCase() == 'option'){
				var iSel = 0;
				var selectVal = 0;
				
				iSel = document.form1.BANKRUPTCY_PAST.selectedIndex;
				selectVal = document.form1.BANKRUPTCY_PAST.options[iSel].value;
				// if answer is "No", we'll hide the fields
				if (selectVal == '2'){
					document.getElementById('BANKRUPTCY_BO_CONST_HIDE_ELEMENT').style.display='none';
					document.getElementById('BANKRUPTCY_BO_CONST_HIDE_TEMPLATE_SPACE').style.display='none';
					document.getElementById('BANKRUPTCY_BO_CONST_HIDE_ELEMENT_SPACER_ROW').style.display='none';
				}
				// if the answer is anything other then "No", we show the fields
				else {
					document.getElementById('BANKRUPTCY_BO_CONST_HIDE_ELEMENT').style.display='';	
					document.getElementById('BANKRUPTCY_BO_CONST_HIDE_TEMPLATE_SPACE').style.display='';
					document.getElementById('BANKRUPTCY_BO_CONST_HIDE_ELEMENT_SPACER_ROW').style.display='';
				}
			}
		}
	}catch(exception){
		//nothing to recover from - just don't error out the page
	}
}


function hideShowHETenneseeMsg(){
	
	var iSel = 0;
	var selectVal = 0;
	
	
	try{
		// check to make sure the field exists on the page before getting the value
		if (document.forms.form1.PROP_STATE_CONST){
			iSel = document.form1.PROP_STATE_CONST.selectedIndex;
			selectVal = document.form1.PROP_STATE_CONST.options[iSel].value;
		}
		
		// if answer is "43" (Tennesee), we'll show the message
		if (selectVal == '43'){
			document.getElementById('HE_TENNESEE_MSG_HIDE_ELEMENT').style.display='';
			document.getElementById('HE_TENNESEE_MSG_HIDE_TEMPLATE_SPACE').style.display='';
			document.getElementById('HE_TENNESEE_MSG_HIDE_ELEMENT_SPACER_ROW').style.display='';
		}
		// if the answer is anything other then "No", we show the fields
		else {
			document.getElementById('HE_TENNESEE_MSG_HIDE_ELEMENT').style.display='none';
			document.getElementById('HE_TENNESEE_MSG_HIDE_TEMPLATE_SPACE').style.display='none';
			document.getElementById('HE_TENNESEE_MSG_HIDE_ELEMENT_SPACER_ROW').style.display='none';
			
		}
		
	}catch(exception){
		//nothing to recover from - just don't error out the page
	}
}

function state_onchange()
{
	var i;
	var opt;
	var iSel;
	var state;
	
	for (i=document.all.PROP_CBSA_CONST.options.length-1;i>0;i--)
		document.all.PROP_CBSA_CONST.options.remove(i);
	
	opt = document.createElement("OPTION")
	opt.value="0";
	opt.text="Not Certain";
	document.all.PROP_CBSA_CONST.options.add(opt);
	
	iSel = document.all.PROP_STATE_CONST.selectedIndex;
	state=document.all.PROP_STATE_CONST.options(iSel).text;
	
	if (state!='') 
	{
		for (i=0;i<document.all.selCBSA.options.length;i++) 
		{
			if (document.all.selCBSA.options(i).value.substring(0,2)==state) 
			{
				opt=document.createElement("OPTION");
				opt.value=document.all.selCBSA.options(i).value.substring(2);
				opt.text=document.all.selCBSA.options(i).text;	
				document.all.PROP_CBSA_CONST.options.add(opt,document.all.PROP_CBSA_CONST.options.length);
			}
		}
		document.all.PROP_CBSA_CONST.selectedIndex=0;
	}
	opt=null;
	
	if (arguments.length>0) {
		var cbsa=arguments[0];
		for (i=2;i<document.all.PROP_CBSA_CONST.options.length;i++) {
			if (document.all.PROP_CBSA_CONST.options[i].value==cbsa) {
				document.all.PROP_CBSA_CONST.selectedIndex=i;
				break;
			}
		}
	}
	opt=null;
	
}	
function hideShowDCHomeOwnerMsg(){
      if(document.forms.form1.HOME_OWNER_CONST[1].checked == true) {
        document.getElementById('DC_HOME_OWNER_MSG_HIDE_ELEMENT').style.display='';
			  document.getElementById('DC_HOME_OWNER_MSG_HIDE_TEMPLATE_SPACE').style.display='';
			  document.getElementById('DC_HOME_OWNER_MSG_HIDE_ELEMENT_SPACER_ROW').style.display='';
      }
      else {
			  document.getElementById('DC_HOME_OWNER_MSG_HIDE_ELEMENT').style.display='none';
			  document.getElementById('DC_HOME_OWNER_MSG_HIDE_TEMPLATE_SPACE').style.display='none';
			  document.getElementById('DC_HOME_OWNER_MSG_HIDE_ELEMENT_SPACER_ROW').style.display='none';
      }
}

function hideShowFields(pCallingFormField, pSFieldToHide ){
	
	var iSel = 0;
	var selectVal = 0;
	
	var objControlField = eval("document.forms.form1." + pCallingFormField);
	var objFieldToHide  = eval("document.forms.form1." + pSFieldToHide);
	
	var x = pSFieldToHide + "_HIDE_ELEMENT";
	var y = pSFieldToHide + "_HIDE_TEMPLATE_SPACE";
	var z = pSFieldToHide + "_ELEMENT_SPACER_ROW";
	
	var objFieldToHide1  = document.getElementById(x);
	var objFieldToHide2  = document.getElementById(y);
	var objFieldToHide3  = document.getElementById(z);
	

	try{
		if (objControlField){
		
			// this logic is for radio buttons	
			if( objControlField[0].tagName.toLowerCase() == 'input'){
				
				// if answer is "No", we'll hide the fields
				if (objControlField[1].checked == true){
					objFieldToHide1.style.display='none';
					objFieldToHide2.style.display='none';
					objFieldToHide3.style.display='none';
				}
				// if the answer is anything other then "No", we show the fields
				else {
					objFieldToHide1.style.display='';	
					objFieldToHide2.style.display='';
					objFieldToHide3.style.display='';	
				}
			}
			
			// this logic is for select boxes
			else if (objControlField[0].tagName.toLowerCase() == 'option'){
				var iSel = 0;
				var selectVal = 0;
				
				iSel = objControlField.selectedIndex;
				selectVal = objControlField.options[iSel].value;
				
				// if answer is "No", we'll hide the fields
				if (selectVal == '2'){
					objFieldToHide1.style.display='none';
					objFieldToHide2.style.display='none';
					objFieldToHide3.style.display='none';
				}
				// if the answer is anything other then "No", we show the fields
				else {
					objFieldToHide1.style.display='';	
					objFieldToHide2.style.display='';
					objFieldToHide3.style.display='';
				}
			}
		}
	}catch(exception){
		//nothing to recover from - just don't error out the page
	}	
	
}



function disableFormFields(objFrm, frmFieldName){
	
	if(objFrm){
		for(var i = 0; i < objFrm.elements.length; i++){
		
			var e = objFrm.elements[i];
				e.disabled = true;	
		}
	}
	
	var objFrmField  = eval("document.forms.form1." + frmFieldName)
	
	if(objFrmField){
		
		objFrmField.disabled = false;	
		document.forms.form1.TYPE_CONST.disabled = false;
	}
}


function enableFormFields(objFrm, frmFieldName){
	
	if(objFrm){
		for(var i = 0; i < objFrm.elements.length; i++){
		
			var e = objFrm.elements[i];
				e.disabled = false;	
		}
	}
	
	
	
	


}

function heCalc() {
	var firstMort;
	var hel;
	var borrow;
	var total = 0;
	
	if(document.form1.FIRST_MORT_BALANCE) {
	  firstMort = removeStr(document.form1.FIRST_MORT_BALANCE.value);
	}
	
	if(document.form1.HEL_BALANCE) {
	  hel = removeStr(document.form1.HEL_BALANCE.value);
	}
	
	if(document.form1.CASH_OUT_AMOUNT) {
	  borrow = removeStr(document.form1.CASH_OUT_AMOUNT.value);
	}
	
	if(isNaN(eval(borrow))) {
		borrow = 0;
	}
	
	if(isNaN(eval(firstMort))) {
		firstMort = 0;
	}

	if(isNaN(eval(hel))) {
		hel = 0;
	}

	total = eval(firstMort) + eval(hel) + eval(borrow);
	document.form1.TOTAL_AMOUNT.value = format(total, '', ',');
}

function mortCalc() {
	var mortType;
	var firstMort;
	var hel;
	var borrow;
	var total = 0;
	
	mortType = document.forms.form1.SMART_REFINANCE_METHOD_CONST.value;
	
	if(document.form1.FIRST_MORT_BALANCE) {
	  firstMort = removeStr(document.form1.FIRST_MORT_BALANCE.value);
	}
	
	if(document.form1.HEL_BALANCE) {
	  hel = removeStr(document.form1.HEL_BALANCE.value);
	}
	
	if(document.form1.CASH_OUT_AMOUNT) {
	  borrow = removeStr(document.form1.CASH_OUT_AMOUNT.value);
	}
	
	if(isNaN(eval(borrow))) {
		borrow = 0;
	}
	
	if(isNaN(eval(firstMort))) {
		firstMort = 0;
	}

	if(isNaN(eval(hel))) {
		hel = 0;
	}
	
	// First mortgage
	if(mortType == 1) {
		total = eval(firstMort) + eval(borrow);
		document.form1.TOTAL_AMOUNT.value = format(total, '', ',');
	}
	
	// Additional mortgage	
	if(mortType == 2) {
		total = eval(hel) + eval(borrow);
		document.form1.TOTAL_AMOUNT.value = format(total, '', ',');
	}
	
	// Both
	if(mortType == 3) {
		total = eval(firstMort) + eval(hel) + eval(borrow);
		document.form1.TOTAL_AMOUNT.value = format(total, '', ',');
	}
	
	// Just CASH_OUT_AMOUNT
	if(mortType == 4) {
		total = eval(borrow);
		document.form1.TOTAL_AMOUNT.value = format(total, '', ',');
	}
}


function calculateReqAmount(){
	try{
		if (document.forms.form1.TYPE_CONST){
			
			var sTypeConst = document.forms.form1.TYPE_CONST.value;
			
			switch (sTypeConst){
				case '1':{
					// purchase is always treated as a purchase
					calculatePurchaseReqAmount();
					break;
				}
				case '2':{
					var iSmartRefiMethodConstSel = 0;
					var selectValSmartRefiMethodConst = 0;
					
					// check to make sure the field exists on the page before getting the value
					if (document.forms.form1.SMART_REFINANCE_METHOD_CONST){
						iSmartRefiMethodConstSel = document.form1.SMART_REFINANCE_METHOD_CONST.selectedIndex;
						selectValSmartRefiMethodConst = document.form1.SMART_REFINANCE_METHOD_CONST.options[iSmartRefiMethodConstSel].value;
					}
					calculateRefiReqAmount(selectValSmartRefiMethodConst);
					break;
				}
				case '3':{
					calculateHEReqAmount();
					break;
				}
				case '4':{
					//SMART_DEBT_CONSOLIDATION_METHOD_CONST
					//1:Refinance existing first mortgage
					//2:Refinance additional mortgages only
					//3:Refinance all existing mortgages
					//4:New first mortgage (no current mortgages)
					//5:New second mortgage
					
					var iSmartDCMethodConstSel = 0;
					var selectValSmartDCMethodConst = 0;
					
					// check to make sure the field exists on the page before getting the value
					if (document.forms.form1.SMART_DEBT_CONSOLIDATION_METHOD_CONST){
						iSmartDCMethodConstSel = document.form1.SMART_DEBT_CONSOLIDATION_METHOD_CONST.selectedIndex;
						selectValSmartDCMethodConst = document.form1.SMART_DEBT_CONSOLIDATION_METHOD_CONST.options[iSmartDCMethodConstSel].value;
					}
					
					switch (selectValSmartDCMethodConst){
						case '1':{
							calculateRefiReqAmount(selectValSmartDCMethodConst);
							break;
						}
						case '2':{
							calculateHEReqAmount();
							break;
						}
						case '3':{
							calculateRefiReqAmount(selectValSmartDCMethodConst);
							break;
						}
						case '4':{
							// both 4 & 5 call the same function.
						}
						case '5':{
							calculateHEReqAmount();
							break;
						}
					}
					break;
				}
			}
		}
	}catch(exception){
		//nothing to recover from - just don't error out the page
	}
}

function calculateRefiReqAmount(sConstVal)
{
	try{
		var firstMortBalance = 0;
		var helBalance = 0;
		var cashOutAmount = 0;
		var bAmtReq = 0;
		
		// check to make sure the field exists on the page before getting the value
		if (document.forms.form1.FIRST_MORT_BALANCE){
			firstMortBalance = removeStr(document.form1.FIRST_MORT_BALANCE.value);
		}
		if (document.forms.form1.HEL_BALANCE){
			helBalance = removeStr(document.form1.HEL_BALANCE.value);
		}
		if (document.forms.form1.CASH_OUT_AMOUNT){
			cashOutAmount = removeStr(document.form1.CASH_OUT_AMOUNT.value);
		}
		
		// if the value doesn't evaluate to a number, set it to zero
		if (isNaN(eval(firstMortBalance))){
			firstMortBalance = 0;
		}
		if (isNaN(eval(helBalance))){
			helBalance = 0;
		}		
		if (isNaN(eval(cashOutAmount))){
			cashOutAmount = 0;
		}
		
		// if Existing first mortgage only or All existing mortgages
		if ((sConstVal == '1') || (sConstVal == '3')){
			bAmtReq = eval(firstMortBalance);
		}
		
		if ((sConstVal == '2') || (sConstVal == '3')){
			bAmtReq = bAmtReq + eval(helBalance);
		}

		// always add in the additional cash out amount
		bAmtReq = bAmtReq + eval(cashOutAmount);

		document.form1.AMT_REQ_DISPLAY.value = format(bAmtReq, '', ',');
	
	}catch(exception){
		//nothing to recover from - just don't error out the page
	}
}

function calculateHEReqAmount()
{
	try{
		var bAmtReq = 0;
		var helBalance = 0;
		var cashOutAmount = 0;
		
		// check to make sure the field exists on the page before getting the value
		if (document.forms.form1.HEL_BALANCE){
			helBalance = removeStr(document.form1.HEL_BALANCE.value);
		}
		if (document.forms.form1.CASH_OUT_AMOUNT){
			cashOutAmount = removeStr(document.form1.CASH_OUT_AMOUNT.value);
		}
		
		// if the value doesn't evaluate to a number, set it to zero
		if (isNaN(eval(cashOutAmount))){
			cashOutAmount = 0;
		}
		if (isNaN(eval(helBalance))){
			helBalance = 0;
		}
		
		bAmtReq = eval(cashOutAmount);
		// if there's a 2nd mortgage, that gets added in
		if (document.form1.HEL_CONST[0].checked == true){
			bAmtReq = bAmtReq + eval(helBalance);
		}
		
		document.form1.AMT_REQ_DISPLAY.value = format(bAmtReq, '', ',');
		
	}catch(exception){
		//nothing to recover from - just don't error out the page
	}
}


function calculatePurchaseReqAmount()
{
	try{
		var purchaseAmount = 0;
		var downPaymentAmount = 0;
		var bAmtReq = 0;
		
		// check to make sure the field exists on the page before getting the value
		if (document.forms.form1.EST_VALUE){
			purchaseAmount = removeStr(document.form1.EST_VALUE.value);
		}
		if (document.forms.form1.DOWN_PAYMENT){
			downPaymentAmount = removeStr(document.form1.DOWN_PAYMENT.value);
		}
		
		// if the value doesn't evaluate to a number, set it to zero
		if (isNaN(eval(purchaseAmount))){
			purchaseAmount = 0;
		}
		if (isNaN(eval(downPaymentAmount))){
			downPaymentAmount = 0;
		}
		
		// amount required is purchase price - down payment
		bAmtReq = eval(purchaseAmount) - eval(downPaymentAmount);
		
		document.form1.AMT_REQ_DISPLAY.value = format(bAmtReq, '', ',');
	}catch(exception){
		//nothing to recover from - just don't error out the page
	}
}

function showElectronicDiscMsg(sTip) {
	
	if(document.forms.form1.ELEC_DISCLOSURE_CONST[0].checked!= true	)
		{
		if (arguments.length > 1 ) {
			var sHeight=arguments[1];
			//OpenWin = this.open('/common/smarttip.asp?' + 'bp=<%=m_objAxxSession.getvalue(kSessionKeyBrandingPartner)%>&tip=' + sTip + '&height='+ sHeight, "CtrlWindow", "toolbar=no,menubar=no,location=no,scrollbars=no,resizable=no,dependent=no,directories=no,width=300,height="+sHeight+",x=50,y=50");
			confirm(sTip);
		}
		else { 
			//OpenWin = this.open('/common/smarttip.asp?' + 'bp=<%=m_objAxxSession.getvalue(kSessionKeyBrandingPartner)%>&tip=' + sTip, "CtrlWindow", "toolbar=no,menubar=no,location=no,scrollbars=no,resizable=no,dependent=no,directories=no,width=300,height=300,x=50,y=50");
			confirm(sTip);
		}
	}	
	
	
}

		/*
			eventToHandle is the event you want to add an event handler to
			     example: window.onload
			newHandler is the name of the function you want to add as an event handler for eventToHandle						
				 example: myEventHandler
		*/
        function addEventHandler(eventToHandle, newHandler)
        {

                    var oldHandlingCode;

                    if (eventToHandle)
                    {
                                oldHandlingCode = eventToHandle;
                    }

                    else
                    {
                                oldHandlingCode = function () {};
                    }

                    eventToHandle = function () {
						try
						{
							oldHandlingCode();
						} 
						catch(ex)
						{}
													
						try
						{
							newHandler();
						}
						catch(ex)
						{}
					};
												
					return eventToHandle;

        }	

function GetQuestionLine(questionID)
{
    return document.getElementById("QUESTION_LINE-" + questionID);
}

function hideShowQuestion(showQuestion, questionID){

	try{
	    var QuestionLine;
	    
	    //retrieve reference to question line
	    QuestionLine = GetQuestionLine(questionID);
	    
	    // is questionline defined?
	    if (QuestionLine)
	    {
	        // show question line?
		    if (showQuestion)
		    {
		        QuestionLine.style.display="block";
            }
            else
            {
                QuestionLine.style.display="none";
            }
        }
	}catch(exception){
		//nothing to recover from - just don't error out the page
	}
}

// ===[ Sets a hidden/text field with the state name
// ===[ that is selected in the dropdown which has been
// ===[ passed in
function setStateNameField(objDropDown, objTextField)
{
	if (objTextField && objDropDown)
	{
		if (objDropDown.selectedIndex > -1)
		{
			objTextField.value = objDropDown.options[objDropDown.selectedIndex].innerText;
		}
	}
}

function setPropertyNameField(objDropDown, objTextField)
{
	if (objTextField && objDropDown)
	{
		if (objDropDown.selectedIndex > -1)
		{
			objTextField.value = objDropDown.options[objDropDown.selectedIndex].innerText;
		}
	}
}

<!-- gs.com javascript template -->


