function baseLoanAmtDefinition()
{
	var strMessage;
	strMessage = "Base Loan Amount does not include Financed Premium Amount."
	alert(strMessage);
}

function showInitialPremiumAmmountHelp()
{
    alert("Estimated Rate/Premium Amount does not include any applicable state, county, or municipal premium taxes or assessments.");
}

function showProgramDescriptionHelp()
{
    alert("Reflects the base rates (as shown in RMIC's marketing materials) used for this loan, as well as all applicable adjustments that were applied.");
}

function showFICOHelp()
{
	var strMessage;
	strMessage = "To determine the Loan Representative FICO score, first determine each Borrower's Representative Score by using:\n\n";
	strMessage += "Middle of three scores, Lower of two scores, or, if only one score is available for the borrower, use that score.\n\n";
	strMessage += "The Loan Representative Score is the lowest of all Borrower Representative Scores."
	alert(strMessage);
}

function showSpecialPremiumRateHelp()
{
    var strMessage;
    
    strMessage = "The 'Special Premium Rate' field describes available non-standard MI rate programs.\n\n";
    strMessage += "For standard MI requests this field should be left blank.";

    alert(strMessage); 
}

function showTotalIncomeHelp()
{
    alert("'Total Income' is a monthly sum including all borrowers and all sources.");
}

function showDebtToIncomeHelp()
{
    var strMessage;
    
    strMessage = "The 'Debt-to-Income %' is the borrowers Total Monthly Debt including Proposed Housing PITI divided by Total Monthly Income.\n\n";
    strMessage += "The Total Monthly Debt should include the Proposed Monthly Housing Expense based on the Qualifying Interest Rate, plus all other monthly debt payments.";

    alert(strMessage);
}

function showTotalDebtHelp()
{
    alert("'Total Debt' is a monthly sum including all recurring debts, and the Subject Property Proposed PITI.");
}

function showNonTraditionalCreditHelp()
{
    var strMessage;
    
    strMessage = "A Borrower qualifies for Non-Traditional Credit if:\n";
    strMessage += "     -They do not have a valid Representative FICO score\n";
    strMessage += "     -They have 4 credit references, each with a 1 year payment history (3 credit references is acceptable if the housing payment includes utilities)\n";
    strMessage += "     -They make periodic payments on these referenced accounts, with no delinquencies the prior year";
    
    alert(strMessage);
}
function showMortgageOriginatedByHelp()
{
    var strMessage;
    
    strMessage = "In order for a loan to qualify as Retail, the same entity, with their own personnel, must perform ALL of the following functions:\n";
    strMessage += "     -Originate and process; and\n";
    strMessage += "     -Underwrite (contract underwriting or having the loan underwritten by the investor is permissible); and\n";
    strMessage += "     -Fund and close in their own name; and\n";
    strMessage += "     -Order mortgage insurance coverage under their own RMIC Master Policy.\n\n";
    strMessage += "Loans must be funded from a warehouse line in the lender's name or using the lender's own funds. \"Table-funded\" loans are considered non-Retail loans. The originating lender may sell or assign the closed loan to an aggregator or investor and still be considered Retail. A correspondent who performs ALL of the above functions is considered Retail.";
    
    alert(strMessage);
}

function showDocumentationTypeHelp()
{
    var strMessage;
    
    strMessage = "Full/Alternative: Verified Income, Assets, and Employment\n\n";
    strMessage += "SIVA or VISA: SIVA - Stated Income/Verified Assets and Employment; VISA - Verified Income and Employment/Stated Assets\n\n";
    strMessage += "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";
    strMessage += "SISA: Stated Income and Stated Assets/Verified Employment\n\n";
    strMessage += "NINA: No Income or Assets Stated or Verified/Verified Employment\n\n";
    strMessage += "No Doc: No Income or Assets Stated or Verified/No Employment Verified\n\n";
    strMessage += "For more information refer to RMIC's Reduced Documentation and underwriting guidelines at www.rmic.com.";

    alert(strMessage);
}

function clearScreen(f1)
{
	if (window.confirm("Selecting Clear will abandon all of your changes.  Are you sure you want to continue?"))
	{
		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
			switchImage(oCurrElement.name + "Img", "/images/spacer.gif");

			switch (oCurrElement.type.substr(0,3))
			{
				case "sel":
					oCurrElement.options.selectedIndex = 0;
					break;
				case "che":
					oCurrElement.checked = false;
					break;
				case "rad":
					break;
				case "hid":
					break;
				default:
					oCurrElement.value = "";
			}
		}
		//TODO: Follow up with Mark on this
		//setAcknowledgement(document.RateEstimateForm.quoteType.value);
	}
}

function nontraditionalCredit_OnChange()
{
    if (($get("nontraditionalCredit").value=="Y") && ($get("representativeFICO").value==""))
    {
        $get("representativeFICO").value="0";
    }
}

function printResults()
{
    var wPrint = window.open("printwindow.htm","printWin","width=680,height=500,scrollbars=1,screenX=1,screenY=1");
    wPrint.focus();
}

function submitForm(f1) 
{
   setPaddingWidth();

   var objErrors = validateForm(f1);

    if (!objErrors.IsEmpty()) 
    {
        objErrors.DisplayErrors();
        return false;
    } 
    else 
    {
        return true;
    }
}

function validateRateQuoteForm(htmlForm, errors)
{
    var salesPriceMessage = null;
    var strErrorText = "";
    
    salesPriceMessage = validateSalesPrice(htmlForm);
    
    if (salesPriceMessage!=null)
    {
        errors.AddError("<em>Sales Price</em> " + salesPriceMessage, htmlForm.salesPrice.name);
    }

    if (htmlForm.ltv && (htmlForm.ltv.value == ""))
    {
        strErrorText = " could not be calculated.  Please verify valid values are entered for Sales Price, Appraised Value and Base Loan Amount.";
        errors.AddError("<em>LTV %</em>" + strErrorText, htmlForm.ltv.name);
    }
    
    validateFICO(htmlForm.representativeFICO, errors);           
}

function validateSalesPrice(htmlForm)
{
    var validationMessage = null;
    var purchase = prefixAndSuffixWithPipe("1");
    var purchaseConstruction = prefixAndSuffixWithPipe("1|4|8");
	var fieldValue = prefixAndSuffixWithPipe(htmlForm.loanPurpose.value);
    
    if (htmlForm.salesPrice.value.length!=0)
    {
        if (isValueCriteriaMet(purchaseConstruction, fieldValue, "In", "Alpha")!=criteriaPass)
        {
            validationMessage = "is not valid for Refinances.";
        }
    }
    
    return validationMessage;    
}

function validateFICO(element, errors)
{
	var htmlForm = element.form;
	var nonTraditionalCredit = $get("nontraditionalCredit").value;
	var value = element.value;
	
	var message = "";
	
	if (!formatCheck_isValidInteger(value))
    {
        return;
    }
    
	if (nonTraditionalCredit == "Y")
	{
		if(value == 0)
		{
			return (true);
		}	
		else
		{
			message = "<em>Loan Representative FICO</em> must be '0' if the Non-Traditional Credit field is 'Yes'."
			errors.AddError(message, element.name);
			return (false);
		}
	}
	else
	{
	    if (formatCheck_isValidFICO(value))
	    {
		    return (true);
		}
		else
	    {
            message = "<em>Loan Representative FICO</em> must be either 0, or between 350 and 900.";
            errors.AddError(message, element.name);
            return false;	    
	    }
	}
}

function window_onload(f1)
{
    Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(beginRequest);
    Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(pageLoaded);
    Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequest);       
    
    configureDataEntryControls(f1); 		
}

var postbackElement;

function beginRequest(sender, args) 
{
    postbackElement = args.get_postBackElement();
    
    if (typeof(postbackElement) != "undefined")
    {
        switch (postbackElement.id)
        {
            case "submitButton":
            {
                handleOnUpdating();
                break;
            }
        }
    }
}

function endRequest(sender, args)
{
   if (args.get_error() != undefined)
   {
       /*
       if (args.get_response().responseAvailable && args.get_response().get_statusCode() == '200')
       {
           errorMessage = args.get_error().message;
       }
       else
       {
           // Error occurred somewhere other than the server page.
           
       }
       */
       var errorMessage = 'The Rate Estimator is unable to process your request at this time. Please resubmit your Rate Estimate request.';
       
       args.set_errorHandled(true);
       
       alert(errorMessage);
       handleOnUpdated();
   }
}

function pageLoaded(sender, args)
{
    if (args.get_error != undefined && args.get_error().httpStatusCode == '500')
    {
       var errorMessage = args.get_error().message
       args.set_errorHandled(true);
       ToggleAlertDiv('visible');
       $get(messageElem).innerHTML = '"' + errorMessage + '" ' + errorMessageAdditional;
    }

    if (typeof(postbackElement) != "undefined")
    {
        switch (postbackElement.id)
        {
            case "submitButton":
            {
                handleOnUpdated();
                break;
            }
            case "changeCriteria":
            case "changeCriteriaTop":
            {
                configureDataEntryControls(document.RateEstimateForm); 	
                window.scrollTo(0, 0);
                break;
            }
        }
    }
    
    return;
}

function handleOnUpdating()
{
    if (postbackElement!=null && postbackElement.id=='submitButton')
    {
        var panel1 = $get('mainUpdatePanel'); 
        panel1.style.display = 'none';
        
        setTimeout('$get("hiddenPanel").style.display="inline";',10);
    }
}

function handleOnUpdated()
{
    if (postbackElement!=null && postbackElement.id=='submitButton')
    {
        var panel = $get('mainUpdatePanel'); 
        panel.style.display = 'inline';
        
        var panel2 = $get('hiddenPanel');
        panel2.style.display = 'none';
    }
}

function cancelQuoteRequest()
{
    var requestManager = Sys.WebForms.PageRequestManager.getInstance();
  
    requestManager.abortPostBack();
    
    handleOnUpdated();
}

function configurePaymentOption()
{
    var paymentOptionField = $get("paymentOption");
    var originalValue = paymentOptionField.value;
    
    clearList(paymentOptionField);
    
	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;
	
	setDropDownValue(paymentOptionField, originalValue);
}

function configureRefundOption()
{
    var refundOptionField = $get("refundOption");
    var originalValue = refundOptionField.value;
    
    var optionName = null;
    
    clearList(refundOptionField);
    
	optionName = new Option("Refund","R");
	refundOptionField.options[1] = optionName;
	
	optionName = new Option("No Refund","N");
	refundOptionField.options[2] = optionName;
	
	setDropDownValue(refundOptionField, originalValue);
}

function configureRenewalOption()
{
    var renewalOptionField = $get("renewalOption");
    var optionName = null;
    var originalValue = renewalOptionField.value;
    var specialRateType = $get("specialRateType").value;
    
    clearList(renewalOptionField);
    
	if ($get("paymentOption").value=="S")
	{
		optionName = new Option("Single or One Time","N");
		renewalOptionField.options[1] = optionName;
	}
	else
	{
	    if (specialRateType=="P11")
	    {
		    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, originalValue);
}

function configurePaymentRefundRenewal()
{
    configurePaymentOption();
    configureRefundOption();
    configureRenewalOption(); 
}

function configureRenewalRefund()
{
    configureRenewalOption();
    configureRefundOption();
}