<!--

//Copyright(c) 2000 by Go Daddy Software, Inc.  All Rights Reserved.
//Author: Bob Parsons (with much help from Angel Carradus)
//Revision: February 9, 2000 3:30 PM

var sHoldPayment,sHoldAPR,sHoldDownpayment,sHoldTerm,isNetscape;

//Determines which browser is in use for purposes of determining keypress values.
//See onkeypress event handlers

if (navigator.appName == "Netscape") 
  isNetscape = true 
else
  isNetscape = false 
   
  
function StripNonNumeric(sText) {

  var bNumber;
  var bFirstDecPlace = false;
  var sNumericText = "";
  var sText1 = ""; //Let browsers know we're working with a string object
  sText1 = sText;
  if (sText1.length > 0) 
    {
	  for (i=0;i<sText1.length;i++)
	   {
	     bNumber = false;
	     bNumber = !isNaN(sText1.charAt(i));
	     // For some reason !isNaN evaluates a space as a number
	     if (sText1.charAt(i) == ' ') bNumber = false;
	     if ((!bNumber) && (!bFirstDecPlace) && (sText1.charAt(i) == '.'))
	      {
	        bNumber = true;
	        bFirstDecPlace = true;
	      }
	     if (bNumber) sNumericText += sText1.charAt(i); 	     
	   }	
    }
    
    //Set the string to null if it consists only of a decimal place
    if ((sNumericText.length == 1) && (sNumericText.charAt(0) == '.'))
     sNumericText = "";
     
    return sNumericText;
} 

function ReportError(sWay,sLimit,tBox,sHold)
//Displays error msgbox when min/max limits are exceeded.
{
	alert(sWay+"imum value is "+sLimit+".");
	tBox.value = sHold;
	tBox.focus();
	return true
} 

function InsertDecPlaces(sText,iDecPlaces) {
    var i = sText.length;
    var bPlaceFound,iPlaces;
    bPlaceFound = false;
    
    while ((i > -1) && (!bPlaceFound)) {
      i--;
      bPlaceFound = (sText.charAt(i) == '.');
    }
    if (!bPlaceFound) {
       sText += '.';
       i = sText.length - 1; }
       
    iPlaces = sText.length - (i+1);
    while (iPlaces < iDecPlaces) {
      sText += '0';
      iPlaces++;
    }
    
    return sText;
}


function InsertCommas(sText,bPennies)
	{
	  var sCommaText = "";
	  var iDigits = 0;
	  
	  if (bPennies) iDigits = (-3); //two pennies plus decimal point
      for (i=sText.length-1;i>-1;i--)
       {   
           if (iDigits == 3) 
            {
               sCommaText = ','+ sCommaText;
               iDigits = 0;
            }   
            
           sCommaText = sText.charAt(i)+sCommaText;
           iDigits++;
       }
       
       return "$" + sCommaText;
	}

function FloatToString(fValue,iDecPlaces) {
   var sText = "";
   var iValue,iMultiplier;
   
   iMultiplier = 1.0;
   for (i=0;i<iDecPlaces;i++) iMultiplier = iMultiplier * 10;
   
   fValue = fValue * iMultiplier;
   iValue = Math.round(fValue)
   iValue = iValue / iMultiplier;
   
   sText = iValue.toString(10); //Base 10
   return sText;
}

function FormatText(fValue,iDecPlaces,sType) {
   var sText = "";
   
   sText = FloatToString(fValue,iDecPlaces);
   
   if (sType == '$') {
    sText = InsertDecPlaces(sText,iDecPlaces);
    sText = InsertCommas(sText,true);  //Loan Amount
 }
    
   if (sType == '%') {  //Annual Interest Rate
    sText = InsertDecPlaces(sText,iDecPlaces);	
    sText += '%';
  }
    
   if (sType == 'Y') {  //Term of Loan
    sText += " year";
    if (iValue > 1.0) sText += 's';
  
   }
   
   if (sType == 'P') {  //Computed Monthly Loan Payment
    sText = InsertDecPlaces(sText,iDecPlaces);
    sText = InsertCommas(sText,true);
  }
      
   return sText;
}

function ConvertToFloat(sText) {
  sText = StripNonNumeric(sText);
  if ((sText == "") || (sText == ".")) sText = "0";
  return parseFloat(sText);
}

function ResetAnswers() {
 document.formHM.button_Calculate.value = "Calculate";
}

function FormatAndSetText(fValue,iDecPlaces,sType,tBox) {
   var sText = "";
   var iValue,iMultiplier;
   
   iMultiplier = 1.0;
   for (i=0;i<iDecPlaces;i++) iMultiplier = iMultiplier * 10;
   
   fValue = fValue * iMultiplier;
   iValue = Math.round(fValue)
   iValue = iValue / iMultiplier;
   
   sText = iValue.toString(10); //Base 10
   
   if ((sType == '$') || (sType == 'D')) {
    sText = InsertDecPlaces(sText,iDecPlaces);
    sText = InsertCommas(sText,true);  //Monthly Payment or Downpayment
    if (sType == '$') sHoldPayment = sText;
     else sHoldDownpayment = sText; }
    
   if (sType == '%') {  //Annual Interest Rate
    sText = InsertDecPlaces(sText,iDecPlaces);	
    sText += '%';
    sHoldAPR = sText;  }
    
   if (sType == 'Y') {  //Term of Loan
    sText += " year";
    if (iValue > 1.0) sText += 's';
    sHoldTerm = sText;
   }
    
   if (sType == 'A') {  //Affordability
    sText = InsertCommas(sText,false);
    tBox.value = sText;
    } else {
			tBox.value = sText;
			ResetAnswers();
			
			 }
   
   return true;
}
 
function ProcessInput(sText,fMin,fMax,sMin,sMax,iDecPlaces,sType,tBox,sHold) {
  var bError = false;
  fValue = ConvertToFloat(sText);
  if (fValue < fMin) bError = ReportError("Min",sMin,tBox,sHold);
  if (fValue > fMax) bError = ReportError("Max",sMax,tBox,sHold);
  
  if (!bError)
		FormatAndSetText(fValue,iDecPlaces,sType,tBox); 
  return true;
}

function ReturnKey(evt)
{
   var theKeyPressed, bReturnKey;
	if (isNetscape) theKeyPressed = evt.which
   else theKeyPressed = window.event.keyCode;
   bReturnKey = (theKeyPressed == 13);
   return bReturnKey;
}

function EscapeKey(evt)
{
   var theKeyPressed, bEscapeKey;
   if (isNetscape) theKeyPressed = evt.which
   else theKeyPressed = window.event.keyCode;
   bEscapeKey = (theKeyPressed == 27);
   return bEscapeKey;
}   

function InitSelectBox(selectBox,fIncrement,iCount,iDefault) {
 var fValue = 0;
 var ii,sText;
 var newElem;
 for (ii=0;ii<iCount;ii++) {
  sText = " " + FormatText(fValue,2,'%');
  newElem = new Option(sText);
  selectBox.options[ii] = newElem;
  fValue += fIncrement;
 }
 selectBox.selectedIndex = iDefault;
} 

//--ac--ADDED FUNCTION-------------------------------------------------------------------------
// This function will "snag" the query string and store it in a name/value dictionary.
function getArgs()
{
  var args = new Object();
  var query = location.search.substring(1);   // Get the query string.
  var pairs = query.split("&");               // Break at &
  for ( var i = 0; i < pairs.length; i++ )
  {
    var pos = pairs[i].indexOf('=');          // Look for the name/value pair
    if ( pos == -1 ) continue;                // not found so skip it.
    var argname = pairs[i].substring(0, pos); // Extract the name
    var value = pairs[i].substring(pos+1);    // Extract the value
    args[argname] = unescape(value);          // Store as a property
  }
  
  return args;  // Return the object.
}


//--ac--EDITED FUNCTION-------------------------------------------------------------------------
function window_onload() {
  InitSelectBox(document.formHM.select_ClosingCosts,0.05,101,60);
  InitSelectBox(document.formHM.select_MonthlyEscrow,0.05,61,22);
  var args = getArgs();
  if (args.text_Payment)
  {
   document.formHM.text_Payment.value = args.text_Payment;
   document.formHM.text_Downpayment.value = args.text_Downpayment;
   document.formHM.text_APR.value = args.text_APR;
   
   document.formHM.text_Term.value = args.text_Term + " year";
   if (ConvertToFloat(args.text_Term) > 1.0) document.formHM.text_Term.value += 's';
   
   document.formHM.select_ClosingCosts.selectedIndex = args.select_ClosingCosts
   document.formHM.select_MonthlyEscrow.selectedIndex = args.select_MonthlyEscrow
  }  
}


function text_Payment_onchange() {
 ProcessInput(document.formHM.text_Payment.value,50.0,100000.0,"$50","$100,000",2,'$',document.formHM.text_Payment,sHoldPayment);
return true; 
}

function text_Payment_onfocus() {
 document.formHM.text_Payment.select();
 sHoldPayment = document.formHM.text_Payment.value;
 return true;
}

function text_Payment_onkeypress(evt) {
 if (ReturnKey(evt)) text_Payment_onchange(); 
 if (EscapeKey(evt)) document.formHM.text_Payment.value = sHoldPayment;
 return true;      
}

function text_Downpayment_onchange() {
 ProcessInput(document.formHM.text_Downpayment.value,0.0,10000000.0,"zero","$10,000,000",2,'D',document.formHM.text_Downpayment,sHoldDownpayment);
}

function text_Downpayment_onfocus() {
 document.formHM.text_Downpayment.select();
 sHoldDownpayment = document.formHM.text_Downpayment.value;
}

function text_Downpayment_onkeypress(evt) {
 if (ReturnKey(evt)) text_Downpayment_onchange(); 
 if (EscapeKey(evt)) document.formHM.text_Downpayment.value = sHoldDownpayment;
 return true;  
}

function text_APR_onchange() {
 ProcessInput(document.formHM.text_APR.value,1.0,50.0,"1.000%","50.000%",3,'%',document.formHM.text_APR,sHoldAPR);
}

function text_APR_onfocus() {
 document.formHM.text_APR.select();
 sHoldAPR = document.formHM.text_APR.value;
}

function text_APR_onkeypress(evt) {
 if (ReturnKey(evt)) text_APR_onchange(); 
 if (EscapeKey(evt)) document.formHM.text_APR.value = sHoldAPR;
 return true;
}


function MakeLine(sDescrip,fValue,iPlaces) {
 var sText =  FloatToString(fValue,iPlaces);
 
 if (iPlaces == 0) sText = InsertCommas(sText,false)
  else 
   {    sText = InsertDecPlaces(sText,2);
        sText = InsertCommas(sText,true);     }
 
 sDescrip = "<tr><td>" + sDescrip + "</td>";
 sText = "<td align=right>" + sText + "</td></tr>";
  
 return (sDescrip + sText);
  
}

//--ac--ADDED FUNCTION-------------------------------------------------------------------------
// This function will snag the root URL off of a URL string.
// i.e. No query string.
function rootURL()
{
  var baseURL = "";
  var strURL = document.location.toString();
  pos = strURL.indexOf("?");  
  if ( pos != -1 )
    baseURL = strURL.substring(0, pos);
  else
    baseURL = strURL;
    
  return baseURL;
}

function ReportDetails(fAfford,fDown,fLoan,fClosingCosts,fPmt,fEscrow)
{
	var sText = "";
	
	//--ac--ADDED THESE 7 LINES-------------------------------------------------------------------------
	strLocation  = rootURL();
    strLocation += "?text_Payment=" + document.formHM.text_Payment.value;
    strLocation += "&text_Downpayment=" + document.formHM.text_Downpayment.value;
    strLocation += "&text_APR=" + document.formHM.text_APR.value;
    
    sTest = StripNonNumeric(document.formHM.text_Term.value);
    
    strLocation += "&text_Term=" + StripNonNumeric(document.formHM.text_Term.value);
   
    strLocation += "&select_ClosingCosts=" + document.formHM.select_ClosingCosts.selectedIndex.toString(10);
    strLocation += "&select_MonthlyEscrow=" + document.formHM.select_MonthlyEscrow.selectedIndex.toString(10);
    
	sText += "<HTML><HEAD><TITLE>Estimates And Assumptions</TITLE></HEAD><BODY>\n";

	//--ac--EDITED THIS LINE-------------------------------------------------------------------------
	sText += "<a href=" + strLocation + ">Return to Calculator</a>\n";

	sText += "<table align=center valign=top border=0 cellspacing=5 cellpadding=5>\n";
	sText += "<tr><th colspan=2 align=center>"+"Affordability Estimates and Assumptions"+ "</th></tr>\n";
	sText += "<tr><th colspan=2 align=center>"+"Estimated Price of House"+ "</th></tr>\n";
    sText += "<tr><td>&nbsp;</td><td>&nbsp;</td></tr>\n";
  	
	sText += MakeLine("House's estimated sales price",fAfford,0);
	sText += MakeLine("Add: Estimated closing costs",fClosingCosts,0);
	sText += MakeLine("Total",fAfford+fClosingCosts,0);
	sText += MakeLine("Less: Downpayment",fDown,0);
	sText += MakeLine("Estimated mortgage loan required",fLoan,0);

	sText += "<tr><td>&nbsp;</td><td>&nbsp;</td></tr>\n";
    sText += "<tr><th colspan=2 align=center>"+"Loan to Value"+ "</th></tr>\n";
	
	var sLTV = FloatToString((fLoan/fAfford)*100, 2);
  sText += "<tr><td>Loan to Value</td><td align=right>"+InsertDecPlaces(sLTV,2)+"%</td></tr>\n";

	sText += "<tr><td>&nbsp;</td><td>&nbsp;</td></tr>\n";
    sText += "<tr><th colspan=2 align=center>"+"Monthly Payment Estimates"+ "</th></tr>\n";
	
	sText += MakeLine("Estimated payment for taxes & insurance",fEscrow,2);
	sText += MakeLine("Estimated payment for principal & interest",fPmt-fEscrow,2);
	sText += MakeLine("Total monthly housing payment",fPmt,2);
	sText += "</table><BR>\n";
		
	fPerCent = (fDown/(fAfford+fClosingCosts)) * 100;
	fWork = FloatToString(fPerCent,2);
	InsertDecPlaces(fWork,2);
	
	sText += "<table border=0 cellspacing=5 cellpadding=5>\n";
	sText += "</td></tr>\n";
	sText += "<tr><th align=center>"+"The Above Numbers Are Only Estimates"+ "</th></tr>\n";
	sText += "</td></tr>\n";
	sText += "<tr><td>\n";
	sText += "Be aware that the above numbers are only estimates.  The amount of closing costs, \n";
	sText += "homeowner's insurance and property tax can vary widely from one geographic location to \n";
	sText += "another.  Other factors (such as the amount of downpayment, the necessity of mortgage insurance, etc.) \n";
	sText += "will influence how much house you can afford.  The above numbers are provided only as an \n";
	sText += "initial estimate and are only as accurate as the underlying assumptions.  Be sure \n";
	sText += "to consult your realtor and/or mortgage financing source for accurate, up-to-date information \n";
	sText += "as it relates to your particular situation.\n";
	sText += "</td></tr>\n";
	sText += "<tr><th align=center>"+"How The House Price Is Determined"+ "</th></tr>\n";
	sText += "</td></tr>\n";
	sText += "<tr><td>\n";
	sText += "The estimated sales price of the house you can afford is determined by considering the amount \n";
	sText += "the monthly payment and downpayment affords without regard to possible limiting factors such as adequacy \n";
	sText += "of downpayment, your capacity to assume additional debt, etc.  Please be aware that these and other factors may influence \n";
	sText += "the amount of house you can afford.\n";
	sText += "</td></tr>\n";
	sText += "<tr><th align=center>"+"A Word About Mortgage Insurance"+ "</th></tr>\n";
	sText += "</td></tr>\n";
	sText += "<tr><td>\n";
	sText += "The above downpayment is "+fWork+"% of the house's estimated sales price with closing costs. \n";
	sText += "The loan-to-value rate is  "+InsertDecPlaces(sLTV,2)+"%. ";
	sText += "You may be required to pay mortgage insurance on your home if your Loan-to-Value ratio is greater than 80%.  This ratio is computed as the value of the loan divided by the value of the home and indicates how much of the home you actually have a loan for.  A loan-to-value ratio of more than 80% means that you have less than 20% equity in the home you're purchasing, and many lenders will require mortgage insurance.<BR><BR>\n"
	sText += "Mortgage insurance is paid monthly and is added to the monthly escrow (or impound) amount you pay to cover homeowner's insurance and property taxes.  Annual mortgage insurance premiums are usually determined by multiplying the initial loan amount by anywhere from ¼% to 1% or more (depending on the loan-to-value ratio) and then dividing that amount by 12 to get the monthly amount.\n"
	sText += "</td></tr>\n";
	sText += "<tr><th align=center>"+"Many Factors Influence The Ability To Obtain Financing"+ "</th></tr>\n";
	sText += "</td></tr>\n";
	sText += "<tr><td>\n";
	sText += "Many factors influence the cost of and ability to arrange for financing. Some key factors are \n";
	sText += "the price of the house you want to buy versus its appraisal value, your credit history, current debt burden, current employment, employment history, and amount \n";
	sText += "(and sometimes the source) of downpayment.  Please consult with your realtor or \n";
	sText += "mortgage financing source for additional information.\n";
	sText += "</td></tr></table>\n";
	sText += "</BODY></HTML>\n";
	
	document.open("text/html");
	document.write(sText);
	document.close();
	
	//--ac--ADDED THIS LINE-------------------------------------------------------------------------
    return false;
	
}  

function GetSelectBoxValue(selectBox){
 var fValue = 0.0;
 var sText;
 iSelectIndex = selectBox.selectedIndex;
 sText = selectBox.options[iSelectIndex].text;
 return ConvertToFloat(sText);
}

function ComputeHowMuchHousePmtBuys(theButton) {
  var fPmt,fTerm,fRate,fDown,fAfford,fClosingCosts,fEscrow;
  var fPmtFactor,fLoan,fClosingCostsPerCent,fEscrowPerCent;
  var fOldLoan;
  fRate = ConvertToFloat(document.formHM.text_APR.value);
  fTerm = ConvertToFloat(document.formHM.text_Term.value);
  fPmt = ConvertToFloat(document.formHM.text_Payment.value);
  fDown = ConvertToFloat(document.formHM.text_Downpayment.value);
  fClosingCostsPerCent = GetSelectBoxValue(document.formHM.select_ClosingCosts)/100;
  fEscrowPerCent = GetSelectBoxValue(document.formHM.select_MonthlyEscrow)/100;
  
  fRate = fRate/(12.0*100); //Get monthly and convert to decimal equivalent
  fTerm = fTerm * 12.0; //Convert to months
  fEscrowPerCent = fEscrowPerCent/12; //Convert to monthly
  
  fPmtFactor = (fRate/(1.0 - Math.pow((1.0+fRate),-fTerm)));
  
  fLoan = fPmt/fPmtFactor; fOldLoan = 0;
  fEscrow = 0;
  fClosingCosts = 0;
  bFirstPass = true;
  
  //The following loops until the correct loan amount is determined.
  //Since the problem presents itself as a non-linear equation (at least that's
  //what the free equation solvers on the net indicate) the only way to come up
  //with the exact answer is by iteration.
  
  while (Math.abs(fLoan - fOldLoan)>1) {
  if (!bFirstPass) fOldLoan = fLoan; 
  bFirstPass = false;
  //Compute loan amount Note: The afford number will be high
  fLoan = (fPmt - fEscrow) / fPmtFactor;
  //Compute purchase price
  fAfford = fLoan + fDown - fClosingCosts;
  //Compute preliminary closing costs
  fClosingCosts = fAfford * fClosingCostsPerCent;
  //Compute preliminary escrow
  fEscrow = fAfford * fEscrowPerCent;
 }   
 
  FormatAndSetText(fAfford,0,'A',theButton);
  ReportDetails(fAfford,fDown,fLoan,fClosingCosts,fPmt,fEscrow);
}

function DataNotEntered(tBox,sMessage) {
 var bTest = false;
 if (tBox.value == "Entry required") {
  alert(sMessage);
  tBox.focus();
  bTest = true;
 }
 return bTest;
}

function RequiredDataHasBeenEntered() {
 var bError = false;
  if (DataNotEntered(document.formHM.text_Payment,"Monthly payment must be entered.")) 
   bError = true;
  
  if ((!bError) && (DataNotEntered(document.formHM.text_Downpayment,"Downpayment must be entered.  Enter '0' if there is none.")))
   bError = true;
  
  if ((!bError) && (DataNotEntered(document.formHM.text_APR,"Mortgage interest rate must be entered.")))
   bError = true;
  
 return !bError;
}


function button_Calculate_onclick() {
 if (RequiredDataHasBeenEntered()) 
   ComputeHowMuchHousePmtBuys(document.formHM.button_Calculate); 
 
}

function text_Term_onchange() {
 ProcessInput(document.formHM.text_Term.value,1.0,100.0,"1 Year","100 Years",3,'Y',document.formHM.text_Term,sHoldTerm);
}

function text_Term_onfocus() {
 document.formHM.text_Term.select();
 sHoldTerm = document.formHM.text_Term.value;
 return true;
}

function text_Term_onkeypress(evt) {
 if (ReturnKey(evt)) text_Term_onchange(); 
 if (EscapeKey(evt)) document.formHM.text_Term.value = sHoldTerm;
 return true; 
}

function select_ClosingCosts_onchange() {
 ResetAnswers();
}

function select_MonthlyEscrow_onchange() {
 ResetAnswers();
}


//-->