// JavaScript Document
/***************************
(c) 2008 www.TUFaT.com
All Rights Reserved. Please
do not re-sell/re-distribute
this software.
***************************/
window.onerror=null
bState = true
oReq = new Collection("PriceHome","Cash","RATE","PTR","HIR","LO","PP","PMI","Closing","MRP","IR","ITR","EI","HA","FSC","Assoc")
oVal = new Collection("PriceHome","Cash","RATE","PTR","HIR","LO","PP","PMI","Closing","MRP","IR","ITR","EI","HA","FSC","Assoc")
oTst = new Collection("N","N","N","N","N","N","N","N","N","N","N","N","N","N","N","N")

function controller(oForm, oBtn) {
   while (bState) {
      if (!Required(oForm))
         break
      if (!Validate(oForm))
         break
      if (!SetValue(oForm))
         break
      if (bState) {
          bState = false
      }
   }
   bState = true
}

function Required(oView) {
   for (i in oView) {
      for (j in oReq) {
        if (i==oReq[j]) {
           if (isMissing(oView[i])) {
               return(false)
           }
        }
     }
  }
  return(true)
}

function Validate(oView) {
   for (i in oView) {
      for (j in oVal) {
        if (i==oVal[j] && oTst[j]=="N") {
           if (isTest(oView[i], oTst[j])) {
               return(false)
           }
        }
     }
  }
  return(true)
}

function SetValue(oView) {
   var Mortgage = new Loan(oView.PriceHome.value, oView.Cash.value, oView.RATE.value, get_selection(oView.YEARS), oView.PTR.value, oView.HIR.value, oView.LO.value, oView.PP.value, oView.PMI.value, oView.Closing.value, oView.Assoc.value, oView.MRP.value, oView.IR.value, oView.ITR.value, oView.EI.value, oView.HA.value, oView.FSC.value)
   Mortgage.calcDP()
   Mortgage.calcMortgage()
   Mortgage.calcLO()
   Mortgage.calcPointPaid()
   Mortgage.calcPMI();
   Mortgage.calcPeriods()
   Mortgage.calcPayment()
   Mortgage.calcInterest()
   oView.DP.value = calcRound(Mortgage.DP)
   oView.LO2.value = calcRound(Mortgage.LOAmount)
   oView.PP2.value = calcRound(Mortgage.PointPaid)
   oView.Closing2.value = calcRound(Mortgage.Closing)
   oView.Cash2.value = calcRound(0)
   //oView.INTEREST.value = calcRound(Mortgage.Interest)
   //setCookie("_Prin", Mortgage.Amount)
   //setCookie("_Int", Mortgage.Rate)
   //setCookie("_Year", Mortgage.Term)
   //setCookie("_Tot", Mortgage.Interest)
   Mortgage.NewPage()
   return(true)
}

function isMissing(oCtrl) {
   if (oCtrl.value == "") {
      alert("You have left a required value blank. Please type a number")
      oCtrl.focus()
      oCtrl.select()
      return(true)
   } else {
      return(false)
   }
}

function isTest(oCtrl, oTest) {
   if (oTest=="N" && !isNumber(oCtrl.value) ) {
      alert(oCtrl.value+" contains an invalid character. Please type a number")
      oCtrl.focus()
      oCtrl.select()
      return(true)
   } else {
      return(false)
   }
}

function isNumber(input) {
   for (var i=0;i<input.length;i++) {
       var oneChar = input.substring(i, i+1)
       if (oneChar < "0" || oneChar > "9") {
          if (oneChar != "." ) {
             return(false)
          }
       }
   }
   return(true)
}

function Collection(item1, item2, item3, item4, item5, item6, item7, item8, item9, item10, item11, item12, item13, item14, item15, item16) {
   this.item1 = item1
   this.item2 = item2
   this.item3 = item3
   this.item4 = item4
   this.item5 = item5
   this.item6 = item6
   this.item7 = item7
   this.item8 = item8
   this.item9 = item9
   this.item10 = item10
   this.item11 = item11
   this.item12 = item12
   this.item13 = item13
   this.item14 = item14
   this.item15 = item15
   this.item16 = item16
}

function Loan(PriceHome, Cash, RATE, YEARS, PTR, HIR, LO, PP,PMI,Closing, Assoc, MRP, IR, ITR, EI, HA, FSC ) {
   this.Price = PriceHome
   this.CashOnHand = Cash
   this.Rate = Number(RATE)
   this.Term = YEARS
   this.PTR = PTR
   this.HIR = HIR
   this.LO = LO
   this.PP = PP
   this.PMI = PMI
   this.Closing = Closing
   this.Assoc = Assoc
   this.MRP = MRP
   this.IR = IR
   this.ITR = ITR
   this.EI = EI
   this.HA = HA
   this.FSC = FSC
   this.calcDP = calcDP
   this.calcMortgage = calcMortgage
   this.calcLO = calcLO
   this.calcPointPaid = calcPointPaid
   this.calcPMI = calcPMI
   this.calcPeriods = calcPeriods
   this.calcPayment = calcPayment
   this.calcInterest = calcInterest
   this.NewPage = NewPage
}

function calcDP(){
//dp = (cash on hand - closing cost - (lo+point)* total) / (1-lo-point)
	this.DP = (Number(this.CashOnHand) - Number(this.Closing) -(Number(this.LO)+Number(this.PP))/100*Number(this.Price)) / (1-(Number(this.LO)+Number(this.PP))/100)
	this.DP = Math.ceil(this.DP)
}

function calcMortgage(){
	this.MortgageValue = Number(this.Price) - Number(this.DP)
}

function calcLO(){
	this.LOAmount = Number(this.LO) / 100 * Number(this.MortgageValue)
	this.LOAmount = Math.ceil(this.LOAmount)
}

function calcPointPaid(){
	this.PointPaid = Number(this.PP) / 100 * Number(this.MortgageValue)
	this.PointPaid = Math.ceil(this.PointPaid)
}

function calcPayment() {
   this.Payment = (Number(this.MortgageValue)*((Number(this.Rate)/(Number(this.Periods)*100))/(1-(Math.pow(1+(Number(this.Rate)/(this.Periods*100)),((Number(this.Term)*this.Periods)*-1))))))
}

function calcPMI(){
	this.PMIAmount = Number(this.PMI)/100*Number(this.MortgageValue)
}

function calcPITI(){
}

function calcInterest() {
   this.Interest = ((this.Payment*(this.Term*this.Periods))-this.Amount)
}

function calcPeriods() {
   this.Periods=12
}

function calcRound(num) {
	negNumber = false;
	if(num<0){
		negNumber = true;
		num=Math.abs(num)
		result="$"+Math.floor(num)+"."
	}
	else{
   		result="$"+Math.floor(num)+"."
   }
   n = result.length
   if (Math.abs(num)>1000 && Math.abs(num)<999999) {
   	if(num<0){
   		num = Math.abs(num)
   		negNumber = true;
		result="$"+result.substring(1,n-4)+","+result.substring(n-4,n)
	}
	else{
     result="$"+result.substring(1,n-4)+","+result.substring(n-4,n)
     }
   }
   if (Math.abs(num)>1000000) {
   	if(num<0){
   		negNumber = true;
   		num = Math.abs(num)
		result = "- $"+result.substring(1,n-7)+","+result.substring(n-7,n-4)+","+result.substring(n-4,n)
	}
	else{
     	result = "$"+result.substring(1,n-7)+","+result.substring(n-7,n-4)+","+result.substring(n-4,n)
     }
   }
   var cents=100*(num-Math.floor(num))+0.5
   result += Math.floor(cents/10)
   result += Math.floor(cents%10)
   if(negNumber){
		result = "-" + result
	}
   return(result)
}

function select_item(name, value) {
   this.name = name
   this.value = value
}

function get_selection(select_object) {
   contents = new select_item()
   for(var i=0;i<select_object.options.length;i++)
      if(select_object.options[i].selected == true) {
        contents.name = select_object.options[i].text
        contents.value = select_object.options[i].value
      }
   return(contents.name)
}

function setCookie (name, value ) {
  document.cookie = name + "=" + escape (value) + "; path=/";
}

function NewPage() {
	text = '<hr>';
	
	if((this.Price * 0.2)>this.DP){
		text = text + "<p>Down payment less than 20%, so will include PMI: " + calcRound(this.PMIAmount/this.Periods) + '</p>';
		IncludePMI = true;
	}
	else{
		text = text + '<p>Down payment More than 20%, so will not include PMI.</p>';
		IncludePMI = false;
	}
	text = text + 'Property Tax: ' + this.PTR +' % per Year.<br />';
	text = text + 'Home Insurance Rate: ' + this.HIR +' % per Year.<br />';
	text = text + 'Assoc. dues & maintenance: ' + calcRound(this.Assoc) + ' per Month.<br />';
    text = text + '  <table width="100%" border="0">'
    text = text + '    <tr valign="middle">';
    text = text + '      <th scope="col" bgcolor="#EEEEEE">Nbr &nbsp;</th>';
    text = text + '      <th align="center" scope="col" bgcolor="#EEEEEE">House Payment (PITI)</th>';
    text = text + '      <th align="center" scope="col" bgcolor="#EEEEEE">Payment After Tax Saving</th>';
    text = text + '      <th align="center" scope="col" bgcolor="#EEEEEE">Rent Payment</th>';
    text = text + '      <th align="center" scope="col" bgcolor="#EEEEEE">Value Of Investment</th>';
    text = text + '      <th align="center" scope="col" bgcolor="#EEEEEE">Home Equity</th>';
    text = text + '    </tr>';

	waktu = this.Term * this.Periods;
	HomeValue = this.Price;
	PropTax = HomeValue * this.PTR/100
	HomeIns = HomeValue * this.HIR / 100
	RentPayment = this.MRP
	SalesCom = HomeValue * this.FSC / 100
	valueInvestRent = this.CashOnHand
	CurrentMortage = this.MortgageValue
	CurrentHome = HomeValue
	BreakTime=0
	colorrow=0;
	for(counter=0;counter<waktu;counter++){
		if(counter!=0 && counter % 12 ==0){
			HomeValue = HomeValue * (1+this.HA/100)
			PropTax = HomeValue * this.PTR/100
			HomeIns = HomeValue * this.HIR / 100
			RentPayment = RentPayment * (1+this.EI / 100)
			SalesCom = HomeValue * this.FSC / 100
		}
		
		CurrentInt = CurrentMortage * this.Rate / this.Periods/100
		CurrentMortage = CurrentMortage - (this.Payment-CurrentInt)
		CurrentHome =  CurrentHome * (1+this.HA/100/this.Periods)
		HomeEquity = CurrentHome - CurrentMortage - SalesCom
		
		if(CurrentMortage<= 0.08 * this.Price){
			IncludePMI = false;
		}
		if(IncludePMI){
			CurrentPITI = this.Payment + PropTax / this.Periods + HomeIns / this.Periods + Number(this.Assoc) + Number(this.PMIAmount) / this.Periods
		}
		else{
			CurrentPITI = this.Payment + PropTax / this.Periods + HomeIns / this.Periods + this.Assoc
		}
		
		TaxSave = (CurrentInt + PropTax / this.Periods) * this.ITR / 100 
		
		CurrentAfterTax = CurrentPITI - TaxSave;
		
		valueInvestRent  = valueInvestRent * (1+this.IR/ this.Periods / 100) - RentPayment + CurrentAfterTax
		
		if(valueInvestRent<HomeEquity && BreakTime==0){
			BreakTime = counter + 1;
		}
		if(colorrow==0){
			colorrow=1;
			text = text + " <tr>"
			text = text + "<td>"+ (counter+1)+ "</td>"
	    	text = text + "<td>"+ calcRound(CurrentPITI)+"</td>"
	    	text = text + "<td>"+ calcRound(CurrentAfterTax)+"</td>"
		    text = text + "<td>"+calcRound(RentPayment)+"</td>"
    		text = text + "<td>"+calcRound(valueInvestRent)+"</td>"
	    	text = text + "<td>"+calcRound(HomeEquity)+"</td>"
    		text = text + "    </tr>";
    	}
    	else{
			colorrow=0
			text = text + " <tr>"
			text = text + '<td bgcolor="#EEEEEE">'+ (counter+1)+ "</td>"
	    	text = text + '<td bgcolor="#EEEEEE">'+ calcRound(CurrentPITI)+"</td>"
	    	text = text + '<td bgcolor="#EEEEEE">'+ calcRound(CurrentAfterTax)+"</td>"
		    text = text + '<td bgcolor="#EEEEEE">'+calcRound(RentPayment)+"</td>"
    		text = text + '<td bgcolor="#EEEEEE">'+calcRound(valueInvestRent)+"</td>"
	    	text = text + '<td bgcolor="#EEEEEE">'+calcRound(HomeEquity)+"</td>"
    		text = text + "    </tr>";
		}
	}
	

    text = text + "  </table>      "
    text = text + "  <p>&nbsp;</p>";
    text = text + "<strong>Your home purchase breaks even in approximately "+ Math.round(BreakTime/12*10)/10 +" years.</strong>"
    document.getElementById("results").innerHTML=text;
	document.getElementById("results").style.display='block';
    
}

function makeTable(oView) {
   var currInt = 0
   var currPrin = 0
   prevBalance = Mortgage.Amount
   InterestRate = ( Mortgage.Rate /100) / Mortgage.Periods
   MonthlyPayment = Mortgage.Payment
   currStart = get_selection(oView.START)
   for(i=1;i<=30;i++) {
      for(j=1;j<=Mortgage.Periods;j++) {
         periodInt = prevBalance * InterestRate
         periodPrin = MonthlyPayment - periodInt
         currBal = prevBalance - periodPrin
         currInt += periodInt
         currPrin += periodPrin
         prevBalance = currBal
      }
      if( currBal <= 0 ){
         currBal = 0
      }
	 if (i % 2) {
      text = (text +"<TR><TD ALIGN=CENTER>"+ currStart +"</TD><TD ALIGN=RIGHT>"+ calcRound(currInt) +"&nbsp;</TD><TD ALIGN=RIGHT>"+ calcRound(currPrin) +"&nbsp;</TD><TD ALIGN=RIGHT>"+ calcRound(currBal)+"&nbsp;</TD></TR>");
	  } else {
	  text = (text +"<TR bgcolor='#EEEEEE'><TD ALIGN=CENTER>"+ currStart +"</TD><TD ALIGN=RIGHT>"+ calcRound(currInt) +"&nbsp;</TD><TD ALIGN=RIGHT>"+ calcRound(currPrin) +"&nbsp;</TD><TD ALIGN=RIGHT>"+ calcRound(currBal)+"&nbsp;</TD></TR>");
	  }
      currInt = 0
      currPrin = 0
      currStart = parseInt(currStart)
      currStart += 1
      if(currBal<=0) {
         return(true)
      }
   }
   return (true)
}

function setfocus() {
   document.MORTGAGE.AMOUNT.focus()
   document.MORTGAGE.AMOUNT.select()
}