function getValue(theString)
{
    var noJunk = "";
    var withDollar = "";
    var foundDecimal = 0;
    var foundAlphaChar = 0;
    theString += "";

    for (i=0; i <= theString.length; i++) {
        var thisChar = theString.substring(i, i+1);

        if (thisChar == ".") {
          foundDecimal = 1;
          noJunk = noJunk + thisChar;
        }

        if ((thisChar < "0") || (thisChar > "9")) {
          if ((thisChar != "$") && (thisChar !=".") && (thisChar != ",") && (thisChar != " ") && (thisChar !="")) foundAlphaChar = 1;
        } else {
	   withDollar = withDollar + thisChar
	   noJunk = noJunk + thisChar
	}

	if ((thisChar == "$") || (thisChar == ".") || (thisChar == ",")) {
	  withDollar = withDollar + thisChar
	}
  }

  if (foundDecimal) { return parseFloat(noJunk); }
  else if (noJunk.length > 0) { return parseInt(noJunk); }
  else return 0;
}

function formatUSCurrency(theNumber) {
  var isNegative = 0

  if (theNumber != "") {
    var workingNumber = theNumber + "" // Evaluate to a string

    if (workingNumber.charAt(0) == "-") { 
      isNegative = 1;
      workingNumber = workingNumber.substring(1, workingNumber.length)
    }

    var withoutChars = ""

    for (x=0; x<=((workingNumber.length)-1); x++) {
      thisChar = workingNumber.charAt(x)
      charAsNum = parseInt(thisChar)

      if ( ((thisChar >= "0") & (thisChar <= "9")) || (thisChar == ".")  ) { 
	withoutChars += workingNumber.charAt(x) 
    }
  }

    workingNumber = withoutChars
    decimalPoint = workingNumber.indexOf(".")

    if (decimalPoint == -1) {
      dollarValue = workingNumber
      centsValue = "00"
      } else if (decimalPoint == 0) {
      dollarValue = "0"
      centsValue = workingNumber.substring(decimalPoint + 1, workingNumber.length)
    } else {
        dollarValue = workingNumber.substring(0, decimalPoint)
        if (decimalPoint == (workingNumber.length - 1)) {
	  centsValue = "00";
        } else {
          centsValue = getValue(workingNumber.substring(decimalPoint + 1, workingNumber.length));
          centsValue += "0";
          centsValue = centsValue.charAt(0) + centsValue.charAt(1)
        }
    }

    var theString = dollarValue;
    var totalCommas = Math.floor((theString.length - 1) / 3)
    var dollarAmt = ""
    x=dollarValue.length
    position = 0

    while (x > 0) {
	x = x - 1
        thisChar = dollarValue.charAt(x)
	rounded = Math.round(position/3)
	if ( (position/3 == rounded ) & (position != 0) ) {
           dollarAmt = "," + dollarAmt
	}
        dollarAmt = thisChar +  dollarAmt
	position = position + 1
    }

    if (isNegative) {
      theString = "-$" + dollarAmt + "." + centsValue
      //theString = "($" + dollarAmt + "." + centsValue + ")"
    } else { 
      theString = "$" + dollarAmt + "." + centsValue
    }

    return (theString);
  } else {
    return("$0.00");
  }
}

function formatPercent(theNumber,decimalPlaces) {
  theNumber = getValue(theNumber);

  if (theNumber < 1) { theNumber = theNumber * 100; }
  with (Math) theNumber = (round(theNumber * pow(10,decimalPlaces))) / pow(10,decimalPlaces); 
  return(theNumber + "%");
}

function removeCents(theNumber) {
  var isNegative = 0

  if (theNumber != "") {
    var workingNumber = theNumber + "" // Evaluate to a string

    if (workingNumber.charAt(0) == "-") { 
      isNegative = 1;
      workingNumber = workingNumber.substring(1, workingNumber.length)
    }

    theNumber = getValue(workingNumber)
    theNumber = Math.round(theNumber * 100) / 100;
    theNumber = theNumber + ""
    decimalPoint = theNumber.indexOf(".")

    if (decimalPoint == -1) {
      dollarValue = theNumber
    } else if (decimalPoint == 0) {
      dollarValue = 0
    } else {
      dollarValue = theNumber.substring(0, decimalPoint)
    }

    var dollarAmt = ""
    x=dollarValue.length
    position = 0

    while (x > 0) {
	x = x - 1
        thisChar = dollarValue.charAt(x)
	rounded = Math.round(position/3)

	if ( (position/3 == rounded ) & (position != 0) ) {
        dollarAmt = "," + dollarAmt
	}
        dollarAmt = thisChar +  dollarAmt
	position = position + 1
    }

    if (isNegative == 1) {
      theString = "-$" + dollarAmt
      //theString = "($" + dollarAmt + "." + centsValue + ")"
    } else { 
      theString = "$" + dollarAmt
    }

    dollarValue = "$" + dollarAmt
    return(theString)
  } else {
    return("$0")
  }
}

function calculate() {
    userdata    	 = document.forms[0]
    rentRate		 = getValue(userdata.rentRate.value)
    saveGrowth		 = getValue(userdata.saveGrowth.value)
    term		 = getValue(userdata.term.value)
    percentdown		 = getValue(userdata.percentdown.value)
    appPcent		 = getValue(userdata.appPcent.value)
    taxBracket		 = getValue(userdata.taxBracket.options[userdata.taxBracket.selectedIndex].text)
    price       	 = getValue(userdata.price.value)
    saveGrowth           = getValue(userdata.saveGrowth.value)
    rate        	 = getValue(userdata.rate.value)
    taxes       	 = getValue(userdata.taxes.value)
    insurance   	 = getValue(userdata.insurance.value)
    term        	 = getValue(userdata.term.options[userdata.term.selectedIndex].text)

	////INITIALIZING VARIABLES	
    var mortgage = 0;
    var inflationRate = 0;
    var appreciation = 0;
    appPcent = appPcent/100
    appreciation = appPcent * price;
    inflationRate	= .025
    results = document.forms[0].results

    if (percentdown > 100) {
            results.value  = ('Your down payment should never exceed 100%.  ')
            results.value += ('You have entered a down payment of ' + percentdown + '%.')
    //} else if ( (price == 0) || (percentdown == 0) || (rate == 0) ) {
    } else if ( (price == 0) || (percentdown == 0) || (rate == 0) ) {
            results.value  = ('Sorry...Some important information is missing from your form.  ')
            results.value += ('Please fill-in all necessary fields, and click "Calculate" again.');
    } else {
	    if (percentdown <= 100) {
	        downpayment = (percentdown * price)/100
	    } else {
		downayment = percentdown
	    }

//// SAVINGS GROWTH
///// ALL CALCULATIONS FOR MORTGAGE COMPARATIVE COST ANALYSIS
//// MORTGAGE AND percentdown AMOUNTS

	  ratioDown = downpayment/price * 100

	  if (term >= 25) {
	    if (ratioDown >= 20) {
		MIfactor = 0
	    } else if (ratioDown >= 15) {
		MIfactor = .39
	    } else if (ratioDown >= 10) {
		MIfactor = .52
	    } else if (ratioDown >= 5) {
		MIfactor = .78
	    } else {
		MIfactor = 1.04
	    }

     } else if (term == 20) {

	    if (ratioDown >= 20) {
		MIfactor = 0
	    } else if (ratioDown >= 15) {
		MIfactor = .21
	    } else if (ratioDown >= 10) {
		MIfactor = .41
	    } else if (ratioDown >= 5) {
		MIfactor = .67
	    } else {
		MIfactor = .79
	    }

	  } else {

	    if (ratioDown >= 20) {
		MIfactor = 0
	    } else if (ratioDown >= 15) {
		MIfactor = .21
	    } else if (ratioDown >= 10) {
		MIfactor = .41
	    } else if (ratioDown >= 5) {
		MIfactor = .67
	    } else {
		MIfactor = .79
	    }
	  }

//// INSURANCE RATES - NOT BEING USED
////    propertyInsur = 17.5
////    if (taxes == 0) taxes = propertyInsur
////    homeownersInsur = 3
////    if (insurance == 0) insurance = homeownersInsur
//// MORTGAGE / PAYMENT (MONTHLY P&I) / PITI

		var yearTotal	= 10
	    mortgage       = price - downpayment
	    payment        = monthlyPayment(term, rate, mortgage)
	    monthlyTAX     = (taxes + insurance) / 12
	    monthlyMI 	   =  (MIfactor * mortgage) / 12 / 100
		PITI     	   = payment + monthlyTAX + monthlyMI
	    PITI	       = Math.round(PITI * 100) / 100;
	    payment        = Math.round(payment * 100) / 100;
	    monthlyTAX     = Math.round(monthlyTAX * 100) / 100;
	    monthlyMI      = Math.round(monthlyMI * 100) / 100;

//// YEARLY P&I

	 	var paymentInterest = 0
		paymentInterest = payment * 12

//// LOAN AMOUNT & APR

	    monthly = payment + monthlyMI
	    amountFinanced = mortgage - (mortgage * .01) - 375 - (mortgage * rate / 100 / 365 * 30)
	    loanAmount = price - downpayment
	    APR = figureLoanAPR(term, rate, loanAmount, monthly)

/// DOLLAR DOWN		

		downDollar 	=  price * (percentdown / 100)

///  ESTATE TAX AND HAZARD INSURANCE (MONTHLY)

		totalTax_Ins =  (taxes + insurance) / 12

///  RENT PAID (YEARLY)

		yearRent 	=  rentRate * 12

///  PRINCIPAL VS. INTEREST PAID (YEARLY)

		var interestLoop 	= 0
		var balance 		= 0
		var ratePercent 	= 0
		var monthlyRate 	= 0
		var intPaid		= new Array()
		var totalInt 		= new Array()
		var totalBalance 	= new Array()
		balance = mortgage
		ratePercent = rate / 100
		monthlyRate = ratePercent / 12

		for (y=1; y <= yearTotal; y++) {
		  for (m=1; m <= 12; m++) {
			  intPaid[m]   = monthlyRate * balance
			  balance      = balance * (1 + monthlyRate) - payment
			  interestLoop = interestLoop + intPaid[m]
		  }
		  totalInt[y] 			 = interestLoop
		  interestLoop           = 0
		  totalBalance[y] 		 = balance
		}
 
///  TAXES PAID (YEARLY)

		var taxRate 	  		= 0
		var taxesPaid			= new Array()
		var propertyValue		= new Array()
		taxRate 	  			= taxes / price

		for (y=1; y <= yearTotal; y++) {
			propertyValue[y]    = price  * (1 + appPcent)
			taxesPaid[y]		= propertyValue[y] * taxRate
				if (y != 1) {
					     propertyValue[y] = propertyValue[y-1] * (1 + appPcent)
						 taxesPaid[y]	  = propertyValue[y] * taxRate;
			}
		}

///  TAX ADVANTAGE (YEARLY)

	var taxAdvantage		= new Array()
		for (y=1; y <= yearTotal; y++) {
		taxAdvantage[y]	= (taxesPaid[y] + totalInt[y]) * (taxBracket / 100)
	}

///  INSURANCE RATE

		var insuranceRate = 0;
		insuranceRate = insurance/price

////  INSURANCE PAID (YEARLY)

		var insurancePaid		= new Array()
			for (y=1; y <= yearTotal; y++) {
				insurancePaid[y]	= insuranceRate * propertyValue[y]
		}		

///  PITI (YEARLY)
	 
		 var yearlyMI 	   = 0;		 
		 var principle 	   = 0;
		 var PITIYear	   = new Array()
		 principle		   = payment * 12
		 yearlyMI 		   = monthlyMI * 12

			for (y=1; y <= yearTotal; y++) {
			PITIYear[y]    = principle  + taxesPaid[y] + insurancePaid[y] + yearlyMI
		 }

///  NET MORTGAGE COST (YEARLY)

		 var netMortgage	= new Array()
			for (y=1; y <= yearTotal; y++) {
				netMortgage[y]	= PITIYear[y] - taxAdvantage[y]
		 }	

/// NET MORTGAGE (TEN YEARS) 

		var netMortgageTotal = 0
		var netMortgageTotalNum = 0
		netMortgageTotal = netMortgage[1] + netMortgage[2] + netMortgage[3] + netMortgage[4] + netMortgage[5] + netMortgage[6] + netMortgage[7] + netMortgage[8] + netMortgage[9] + netMortgage[10]
		netMortgageTotalNum = netMortgageTotal

/// EQUITY (YEARLY)

		var equity 	= new Array()

		for (y=1; y <= yearTotal; y++) {
			equity[y]	= propertyValue[y] - totalBalance[y]
		}

/// EQUITY (TEN YEARS) 

		var equityTotal = 0

		for (ind=1; ind <=10; ind++) {
		     equityTotal = equityTotal + equity[ind]
		}

/// ALL CALCULATIONS FOR RENT COMPARATIVE COST ANALYSIS

/// RENT PAID

		var yearlyRent 	= 0
		var rentPaid 	= new Array()
		yearlyRent		= rentRate * 12

		for (y=1; y <= yearTotal; y++) {
			rentPaid[y]		= yearlyRent
				if (y != 1) {
					     rentPaid[y] = rentPaid[y-1] * (1 + inflationRate)
			}
		}
	
/// SAVINGS BALANCE (Compounded Monthly)

		var savingBalance = new Array()
		var savingsRateYr = 0;
		savingsRateYr = saveGrowth/100;
		savingBalance[1] = downpayment;

		for (y=1; y <= yearTotal; y++) {
              for (month = 1; month <= 12; month++) {
				   if (y == 1) {
				        savingBalance[y] =  savingBalance[y] * (1 + (savingsRateYr/12));
				   }
				   if (y != 1) {
				        if (month == 1) {
		   	  	        	savingBalance[y] = savingBalance[y-1] * (1 + (savingsRateYr/12));
						}
						if (month > 1) {
						    savingBalance[y] = savingBalance[y] * (1 + (savingsRateYr/12));
						}
				   }
		      }
		}

/// INTEREST ON SAVINGS (Compounded Monthly)

        var savingInterest = new Array()

		for (y=1; y <= yearTotal; y++) {
		     if (y == 1) {
			     savingInterest[y] = savingBalance[y] - downpayment;
			 }
			 if (y > 1) {
			     savingInterest[y] = savingBalance[y] - savingBalance[y-1];
			 }
		}
	
/// NET COST (YEARLY)

		var netRent 	= new Array()

		for (y=1; y <= yearTotal; y++) {
			netRent[y] = rentPaid[y] - savingInterest[y]
		}

/// NET COST (TEN YEARS) 

		var netRentTotal = 0
		var netRentTotalNum = 0
		netRentTotal = netRent[1] + netRent[2] + netRent[3] + netRent[4] + netRent[5] + netRent[6] + netRent[7] + netRent[8] + netRent[9] + netRent[10]
		netRentTotalNum = netRentTotal	

/// ALL CALCULATIONS FOR RENT VS BUY COST ANALYSIS

/// RENT VERSUS BUY (YEARLY) 

		var rentBuy	 = new Array()

		for (y=1; y <= yearTotal; y++) {
		   rentBuy[y] =  netRent[y] - netMortgage[y]
		}

/// RENT VERSUS BUY (TEN YEARS) 

		var rentBuyTotal = 0
		rentBuyTotal = rentBuy[1] + rentBuy[2] + rentBuy[3] + rentBuy[4] + rentBuy[5] + rentBuy[6] + rentBuy[7] + rentBuy[8] + rentBuy[9] + rentBuy[10]
		rentBuyTotal = Math.abs(rentBuyTotal)  //USE ABSOLUTE VALUE FOR DIPLAY PURPOSES
		
/// EQUITY VERSUS SAVINGS BALANCE AT YEAR TEN

 		var equitySaving = 0
		var equityNum = 0
		var savingBalanceNum = 0
		equitySaving = equity[10] - savingBalance[10]
		equitySaving = Math.abs(equitySaving)  //USE ABSOLUTE VALUE FOR DISPLAY PURPOSES
		equityNum = equity[10]
		savingBalanceNum = savingBalance[10]

///// FORMAT RESULTS

	    rentRate		    	= formatUSCurrency(rentRate)
	    inflationRate		= formatPercent(inflationRate,2)
	    APR				= formatPercent(APR,2)
	    saveGrowth			= formatPercent(saveGrowth,2)
	    rate                	= formatPercent(rate,2)
	    taxes       		= formatUSCurrency(taxes)
	    insurance        		= formatUSCurrency(insurance)
	    price      			= formatUSCurrency(price)
	    downDollar    	    	= formatUSCurrency(downDollar)
	    appreciation        	= formatUSCurrency(appreciation)
	    taxBracket	        	= formatPercent(taxBracket,2)
	    mortgage			= formatUSCurrency(mortgage)
	    paymentInterest   	 	= formatUSCurrency(paymentInterest)
 	    payment	   	 	= formatUSCurrency(payment)
	    monthlyMI			= formatUSCurrency(monthlyMI)
	    PITI          	  	= formatUSCurrency(PITI)
	    totalTax_Ins		= formatUSCurrency(totalTax_Ins)
	    netRentTotal		= formatUSCurrency(netRentTotal)
	    netMortgageTotal		= formatUSCurrency(netMortgageTotal)
	    rentBuyTotal		= formatUSCurrency(rentBuyTotal)
	    netRent[y] 			= formatUSCurrency(netRent[y])
	    savingBalance[y]		= formatUSCurrency(savingBalance[y])
	    equity[y]			= formatUSCurrency(equity[y])
	    equitySaving		= formatUSCurrency(equitySaving)

/// REMOVE CENTS

	    rentBuyTotal		= removeCents(rentBuyTotal)
	    rentRate			= removeCents(rentRate)
	    taxes 	 		= removeCents(taxes)
	    insurance 	 		= removeCents(insurance)
	    price 	 		= removeCents(price)
	    downDollar 	 		= removeCents(downDollar)
	    appreciation 	 	= removeCents(appreciation)
	    mortgage			= removeCents(mortgage)
	    netRentTotal		= removeCents(netRentTotal)
	    netMortgageTotal		= removeCents(netMortgageTotal)
	    equity[10]			= removeCents(equity[10])
	    paymentInterest		= removeCents(paymentInterest)
	    //payment			= removeCents(payment)
	    //PITI			= removeCents(PITI)
	    equitySaving		= removeCents(equitySaving)

        for (ind=1; ind <= 10; ind++) {
		     netMortgage[ind]        = formatUSCurrency(netMortgage[ind])
		     netRent[ind]            = formatUSCurrency(netRent[ind])
		     savingBalance[ind]      = formatUSCurrency(savingBalance[ind])
		     equity[ind] 	     = formatUSCurrency(equity[ind])
		     netMortgage[ind]        = removeCents(netMortgage[ind])
		     netRent[ind]            = removeCents(netRent[ind])
		     savingBalance[ind]      = removeCents(savingBalance[ind])
		     equity[ind] 	     = removeCents(equity[ind])
	    }

/// DISPLAY RESULTS

 	results.value = ('Based on the information provided, here is a comparison of the net cost to rent versus the net cost to own.')
	results.value += ('\r\n\r\n');
	results.value += ('Year   Net Rent Cost   Net Cost to Own\r\n');

	for (ind=1; ind <= 10; ind++) {
results.value += (ind + '      ' + netRent[ind] + '          ' + netMortgage[ind]+'\r\n');
 		}

results.value += ('Total' + '  ' + netRentTotal + '       ' + netMortgageTotal+'\r\n');
results.value += ('\r\n');

			//netMortgageTotalNum = getValue(netMortgageTotalNum)

	if (netMortgageTotalNum == 0) {
results.value += ('After 10 years your net cost to rent will be ' + netRentTotal + ' more than the net cost to own.' + '\r\n');
	} else if (netRentTotalNum >= netMortgageTotalNum) {
results.value += ('After 10 years your net cost to rent will be ' + rentBuyTotal + ' more than the net cost to own.' + '\r\n');
	} else {
results.value += ('After 10 years your net cost to own will be ' + rentBuyTotal + ' more than the net cost to rent.' + '\r\n');	
	}

results.value += ('\r\n\r\n');
results.value += ('Here is a comparison of your anticipated savings growth if you continue to rent versus the estimated equity growth of owning: ')
results.value += ('\r\n\r\n')
results.value += ('Year  Savings Balance  Real Estate Equity\r\n');

	for (ind=1; ind <= 10; ind++) {
results.value += (ind + '     ' + savingBalance[ind] + '           ' + equity[ind]+'\r\n');
        }
results.value += ('\r\n')

	if (savingBalanceNum == equityNum) {
results.value += ('There would appear to be no significant net worth advantage of buying this home versus allowing your savings to grow. ')
results.value += ('\r\n\r\n')
	} else {
	if (equityNum < savingBalanceNum) {
results.value += ('After ten years, you will have ')
results.value += ( equitySaving )
results.value += (' more savings than real estate equity.')
	} else {
results.value += ('After ten years, you will have ')
results.value += ( equitySaving )
results.value += (' more real estate equity than savings.')
	}
results.value += ('\r\n')
	}

results.value += ('\r\n');
results.value += ('The monthly break down of the proposed mortgage would be as follows:')
results.value += ('\r\n');
results.value += ('Principal & Interest:   ' + payment + '\r\n');
results.value += ('Tax & Insurance Escrow:   ' + totalTax_Ins + '\r\n');
results.value += ('Mortgage Insurance:   ' + monthlyMI + '\r\n');
results.value += ('Total Monthly Payment:   ' + PITI + '\r\n');
results.value += ('Est. Annual Percentage Rate:   ' + APR + '\r\n');

    	if (percentdown < 5) {
results.value += ('\r\n')
results.value += ('\r\nPlease note that your anticipated downpayment is less than 5% ');
results.value += ('of the sales price.  Special considerations may apply; subject to availablity. ');
results.value += ('Please consult a mortgage account executive for special details.');
	}
    }
}

function monthlyPayment(term, rate, loanAmount) {
  if (rate > 1) { (rate = rate / 100); }
  rateMonthly = (rate / 12);
  totalPayments = (term * 12);

  if (rate == 0) {
      payment = (loanAmount / totalPayments)
  } else {
      payment = (loanAmount * rateMonthly) / (1 - Math.pow((1+rateMonthly), (-1*totalPayments)) )
  }
  return(payment)
}

function figureLoanAPR (loanYears, iRateAnnual, loanAmount, monthly) {
  loanMonths = loanYears * 12;

  if (iRateAnnual > 1) { (iRateAnnual = iRateAnnual / 100); }
  iRateMonthly = iRateAnnual / 12;
  prepaidFinanceCharges = Math.round(((.01 * loanAmount) + 375 + (((loanAmount * iRateAnnual) / 365) * 30)) * 100) / 100;
  aprPrinciple = Math.round((loanAmount - prepaidFinanceCharges) * 100) / 100;
  compoundX = Math.pow( (1 + iRateMonthly) , (-1 * loanMonths) );
  loanAPR = ((monthly * (1 - (compoundX) )) / aprPrinciple) * 12 * 100;
  loanAPR = Math.round(loanAPR * 1000) / 1000;
  return(loanAPR);
}

function newWindow() {     window.open("rent_vs_purchHELP.htm","Window4","toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=0,copyhistory=0,width=200,height=250");    }
