/*   Note: This calculator has had a major
		overhaul from it's original version by Walter Hooker of Accu Knowledge, Inc.
		in early 2005. AKI's website is www.akinet.com. Come on by! The copyright is
		no longer valid by Infohiway but will be honored for their original effort.
		This version of mortCalc is a Copyright 2005 of Accu Knowledge, Inc.

     Original Copyright Notice: Cut-N-Paste JavaScript from mortCalc
     Toolbox Copyright 1996, Infohiway, Inc.  Restricted use is hereby
     granted (commercial and personal OK) so long as this code
     is not *directly* sold and the copyright notice is buried
     somewhere deep in your HTML document.  A link to our site
     http://www.infohiway.com is always appreciated of course,
     but is absolutely and positively not necessary. ;-)   */

var now;
var curMonth;
var curYear;
var theMonth;
var theYear;

var curPrincipal;
var curInterest;

var minDate = 0;
var maxDate = 0;
var minAmt;
var maxAmt;

var x_Date ;
var a_curPrincipal ;
var a_curInterest;
var a_curLoanAmount;

var fulltable;
var num = 0;
var Loan_Amount = 0;
var Int_Rate=0;
var months=0;
var nls="";
var rr="\r";
var b="                                                     ";
var d="-----------------------------"
+"------------------------------------";
var s="$";
var factor;

function checkpmireq(){
        //alert("checking req");
        ratio = ratio * 100
        if (document.forms["mortCalc"].fixadjust[0].checked){
                //alert("fixed Rate");
                //alert(eval(document.forms["mortCalc"].months.value/12));
                //alert(ratio);

                //alert(ratio);
                if ((document.forms["mortCalc"].months.value/12) > 25){
                        if (ratio<=80)
                                factor=0;
                        if (ratio>80&&ratio<=85)
                                factor=0.32;
                        if (ratio>85&&ratio<=90)
                                factor=0.52;
                        if (ratio>90&&ratio<=95)
                                factor=0.78;
                        if (ratio>95)
                                factor=0.96;
                }
                if((document.forms["mortCalc"].months.value/12) > 20 && (document.forms["mortCalc"].months.value/12) <= 25){
                        if (ratio<=80)
                                factor=0;
                        if (ratio>80&&ratio<=85)
                                factor=0.21;
                        if (ratio>85&&ratio<=90)
                                factor=0.41;
                        if (ratio>90&&ratio<=95)
                                factor=0.67;
                        if (ratio>95)
                                factor=0.85;
                }
                if((document.forms["mortCalc"].months.value/12) >= 15 && (document.forms["mortCalc"].months.value/12) <= 20){
                        if (ratio<=80)
                                factor=0;
                        if (ratio>80&&ratio<=85)
                                factor=0.21;
                        if (ratio>85&&ratio<=90)
                                factor=0.41;
                        if (ratio>90&&ratio<=95)
                                factor=0.67;
                        if (ratio>95)
                                factor=0.85;
                }

        }else{
                if (document.forms["mortCalc"]['ARM-Adjust'][document.forms["mortCalc"]['ARM-Adjust'].selectedIndex].value=="1"){
                if ((eval(document.forms["mortCalc"].months.value)/12) < 25 ){
                        if (ratio<=80)
                                factor=0;
                        if (ratio>80&&ratio<=85)
                                factor=0.26;
                        if (ratio>85&&ratio<=90)
                                factor=0.54;
                        if (ratio>90&&ratio<=95)
                                factor=0.81;
                        if (ratio>95)
                                factor=1.1;
                }else{
                        if (eval(ratio)<=80)
                                factor=0;
                        if (eval(ratio)>80&&eval(ratio)<=85)
                                factor=0.37;
                        if (eval(ratio)>85&&eval(ratio)<=90)
                                factor=0.65;
                        if (eval(ratio)>90&&eval(ratio)<=95)
                                factor=0.92;
                        if (eval(ratio)>95)
                                factor=1.21;
                                //alert(factor);
                }}

                if (document.forms["mortCalc"]['ARM-Adjust'][document.forms["mortCalc"]['ARM-Adjust'].selectedIndex].value=="3"){
                if ((document.forms["mortCalc"].months.value/12) < 25 ){
                        if (ratio<=80)
                                factor=0;
                        if (ratio>80&&ratio<=85)
                                factor=0.22;
                        if (ratio>85&&ratio<=90)
                                factor=0.5;
                        if (ratio>90&&ratio<=95)
                                factor=0.77;
                        if (ratio>95)
                                factor=1.06;
                }else{
                        if (ratio<=80)
                                factor=0;
                        if (ratio>80&&ratio<=85)
                                factor=0.33;
                        if (ratio>85&&ratio<=90)
                                factor=0.61;
                        if (ratio>90&&ratio<=95)
                                factor=0.88;
                        if (ratio>95)
                                factor=1.17;
                }}

                if (document.forms["mortCalc"]['ARM-Adjust'][document.forms["mortCalc"]['ARM-Adjust'].selectedIndex].value=="5"){
                if ((document.forms["mortCalc"].months.value/12) < 25 ){
                        if (ratio<=80)
                                factor=0;
                        if (ratio>80&&ratio<=85)
                                factor=0.21;
                        if (ratio>85&&ratio<=90)
                                factor=0.41;
                        if (ratio>90&&ratio<=95)
                                factor=0.67;
                        if (ratio>95)
                                factor=0.85;
                }else{
                        if (ratio<=80)
                                factor=0;
                        if (ratio>80&&ratio<=85)
                                factor=0.32;
                        if (ratio>85&&ratio<=90)
                                factor=0.52;
                        if (ratio>90&&ratio<=95)
                                factor=0.78;
                        if (ratio>95)
                                factor=0.96;
                }}

                if (document.forms["mortCalc"]['ARM-Adjust'][document.forms["mortCalc"]['ARM-Adjust'].selectedIndex].value=="7"){
                if ((document.forms["mortCalc"].months.value/12) < 25 ){
                        if (ratio<=80)
                                factor=0;
                        if (ratio>80&&ratio<=85)
                                factor=0.21;
                        if (ratio>85&&ratio<=90)
                                factor=0.41;
                        if (ratio>90&&ratio<=95)
                                factor=0.67;
                        if (ratio>95)
                                factor=0.85;
                }else{
                        if (ratio<=80)
                                factor=0;
                        if (ratio>80&&ratio<=85)
                                factor=0.32;
                        if (ratio>85&&ratio<=90)
                                factor=0.52;
                        if (ratio>90&&ratio<=95)
                                factor=0.78;
                        if (ratio>95)
                                factor=0.96;
                }}
                if (document.forms["mortCalc"]['ARM-Adjust'][document.forms["mortCalc"]['ARM-Adjust'].selectedIndex].value=="10"){
                if ((document.forms["mortCalc"].months.value/12) < 25 ){
                        if (ratio<=80)
                                factor=0;
                        if (ratio>80&&ratio<=85)
                                factor=0.21;
                        if (ratio>85&&ratio<=90)
                                factor=0.41;
                        if (ratio>90&&ratio<=95)
                                factor=0.67;
                        if (ratio>95)
                                factor=0.85;
                }else{
                        if (ratio<=80)
                                factor=0;
                        if (ratio>80&&ratio<=85)
                                factor=0.32;
                        if (ratio>85&&ratio<=90)
                                factor=0.52;
                        if (ratio>90&&ratio<=95)
                                factor=0.78;
                        if (ratio>95)
                                factor=0.96;
                }}
        if (document.forms["mortCalc"]['ARM-Adjust'][document.forms["mortCalc"]['ARM-Adjust'].selectedIndex].value=="0")
                alert("Please Select an ARM Type");
        }

}

function iA(){
 this.length=iA.arguments.length;
 for (var i=0;i<this.length;i++){
  this[i]=iA.arguments[i];
  }
 }
var pwr=new iA(10);
var dec=new iA(16);
pwr[0]=1;
for (var i=0;i<9;i++){
 pwr[i+1]=pwr[i]*10;
}
dec[0]=.1;
dec[1]=.01;
dec[2]=.001;
dec[3]=.0001;
dec[4]=.00001;
dec[5]=.000001;
dec[6]=.0000001;
dec[7]=.00000001;
dec[8]=.000000001;
dec[9]=.0000000001;
dec[10]=.00000000001;
dec[11]=.000000000001;
dec[12]=.0000000000001;
dec[13]=.00000000000001;
dec[14]=.000000000000001;
dec[15]=.0000000000000001;

var ns="01234567890";
var cr="";
var str="";

function stn(){
 num=0;
 pos=str.indexOf(".");
 sfx="";
 if (pos>-1){
  sfx=str.substring(pos+1,str.length);
  str=str.substring(0,pos);
  }
 strl=str.length;
 for (var i=strl-1;i>-1;i--){
  cr=str.substring(i,i+1);
  pos=ns.indexOf(cr);
  num+=pos*pwr[strl-i-1];
  }
  if (sfx!=""&&sfx.length>dp){
   pos=ns.indexOf(sfx.charAt(dp+1));
   if (pos>4){
    pos=ns.indexOf(sfx.charAt(dp));
    sfx=sfx.substring(0,dp-1)+(pos+1);
    }
   }
  if (sfx!=""){
   for (var i=0;i<dp;i++){
    cr=sfx.substring(i,i+1);
    pos=ns.indexOf(cr);
    num+=pos*dec[i];
    }
/*    sfx="";
    sfx+=num;
    pos=sfx.indexOf(".");
    sfx=sfx.substring(pos+1,sfx.length);
    if (sfx.charAt(dp+1)=="9"){
     num+=dec[sfx.length-2];
     } */
  }
 }

function calcResults(form){

	 minDate = 999999;
	 maxDate = 0;
	 minAmt  = 999999999.00;
	 maxAmt  = 0.00;

     x_Date = new Array();
     a_curPrincipal = new Array();
     a_curInterest = new Array();
	 a_curLoanAmount = new Array();

     curMonth = eval(document.forms["mortCalc"].Lsd_mm.value);
     curYear  = eval(document.forms["mortCalc"].Lsd_yy.value);

     yearlyTax  = eval(strip(document.forms["mortCalc"].Yearly_Tax.value));
     yearlyIns  = eval(strip(document.forms["mortCalc"].Yearly_Ins.value));
     monthlyTax = yearlyTax / 12;
     monthlyIns = yearlyIns / 12;
     escrow = monthlyTax + monthlyIns;

     // Loan Amount - Loan_Amount
     str=strip(document.forms["mortCalc"].Loan_Amount.value);
     fmtIt();
     bl=str.length+3;
     dp=2;
     stn();
     Loan_Amount=num;
     origLoan_Amount = num;

     // Property Value - prop_val
     str = strip(document.forms["mortCalc"].prop_val.value);
     fmtIt();
     bl=str.length+3;
     dp=2;
     stn();
     prop_val=num;

     // Loan to Property Value - ratio
     ratio = Loan_Amount/prop_val;
     if ((ratio*100) > 120)
            alert("The value of your property is lower than your loan amount.\n\nIs this correct?");

     // Interest Rate - Int_Rate
     str=document.forms["mortCalc"].Int_Rate.value;
     dp=4;
     stn();
     Int_Rate=num;

     // Number of months - months and term_yrs
     str=document.forms["mortCalc"].months.value;
     dp=0;
     stn();
     months=num;
     term_yrs = months.value/12;

     // If values are correct then compute the form with function computeForm
     if (months<1||months>999||Int_Rate<.0001||Int_Rate>99||Loan_Amount<1||Loan_Amount>pwr[9]){
        alrt();
      }
     else {
        computeForm();
     }
}

// calculate the monthly P and I - P_I
function computeForm(){
     ls="";
     i = Int_Rate/12/100;            // set month interest rate as a decimal value

 //       M = P * ( i / (1 - (1 + i)^-N))
 //       M = Monthly P and I
 //       P = Loan Amount
 //       i = monthly interest rate
 //       N = number of monthly payments
     tmp = Loan_Amount * (i / (1 - Math.pow((1 + i), -months)));
     P_I    = Math.round((tmp + .005) * 1000) / 1000;   // store P and I round in global variable

     Total_Int  = ((months*P_I)-Loan_Amount);      // total interest due
     Total_Int += .005;
     Total_Int  = Math.round(Total_Int * 1000) / 1000;

     prtSched();
 }

// rounds number to X decimal places, defaults to 2
function round(number,X) {
     X = (!X ? 2 : X);         // if x is zero make it 2 otherwise use input value
     return Math.round(number*Math.pow(10,X))/Math.pow(10,X);
}

var newpmi;

// print the mortgage loan schedule in text area

function prtSched(){

     saveRatio = ratio * 100;
     if (saveRatio <=80){
             ratioline="No PMI Required. Your LTV is " + round((ratio * 100),2) + "% "
     }else{
             ratioline="PMI Required. Your LTV is " + round((ratio * 100),2) + "% "
     }
     now = new Date();
     theMonth = now.getMonth() + 1;
     theYear  = now.getFullYear();
     monthsToGo = 0;
     yearsToGo = eval(document.forms["mortCalc"].months.value) / 12;
     yearsDone = theYear;
     monthsDone = theMonth;
     newTheYYMM = (theYear * 100) + theMonth;
     newCurYYMM = (curYear * 100) + curMonth;

     if ((curMonth != theMonth || curYear != theYear) && newCurYYMM < newTheYYMM) {
	yearsDone -= curYear;
	monthsDone -= curMonth;
	if (monthsDone < 0) {
	   yearsDone--;
	   monthsDone += 12;
	}

	yearsToGo -= yearsDone;
	if (monthsDone != 0) {
	   yearsToGo--;
	   monthsToGo += 12;
	   monthsToGo -= monthsDone;
	}
     }
     s_yearsToGo = "";                       // setup yearsToGo
     s_yearsToGo += Math.round(yearsToGo);

     s_monthsToGo = "";                       // setup monthsToGo
     s_monthsToGo += Math.round(monthsToGo);


     if (monthsToGo == 0) {
     	if (document.forms["mortCalc"].fixadjust[0].checked){
             loanline="Your loan has " + s_yearsToGo + " years to go at a fixed rate of " + Int_Rate + "%."
     	}else{
             loanline="You have " + s_yearsToGo + " years to go on your "+document.forms["mortCalc"]['ARM-Adjust'][document.forms["mortCalc"]['ARM-Adjust'].selectedIndex].text+" starting at " + Int_Rate + "%."
    	 }
     } else {
     	if (document.forms["mortCalc"].fixadjust[0].checked){
             loanline="Your loan has " + s_yearsToGo + " years and " + s_monthsToGo + " months to go at a fixed rate of " + Int_Rate + "%."
     	}else{
             loanline="You have " + s_yearsToGo + " years and " + s_monthsToGo + " months to go on your "+document.forms["mortCalc"]['ARM-Adjust'][document.forms["mortCalc"]['ARM-Adjust'].selectedIndex].text+" starting at " + Int_Rate + "%."
    	 }
     }
     monthly_intrate=Int_Rate/12/100; // monthly interest rate

     // build first line thru end of headings for output

     s_Total_Int = dlrFmt(Total_Int);

     ls=  "Amortization Schedule: " + document.forms["mortCalc"].months.value
     + " months to repay " + document.forms["mortCalc"].Loan_Amount.value
     + " at " + document.forms["mortCalc"].Int_Rate.value+"%." + rr + d + rr
     + loanline + rr + ratioline + rr + "Total Interest " + s_Total_Int + rr + d + rr ;

     s_escrow = dlrFmt(Math.round(escrow  * 1000) / 1000);

     s_monthlyIns = dlrFmt(Math.round(monthlyIns  * 1000) / 1000);

     s_monthlyTax = dlrFmt(Math.round(monthlyTax  * 1000) / 1000);

     s_P_I = dlrFmt(Math.round(P_I  * 1000) / 1000);

     s_totalPayment = dlrFmt(P_I + escrow);

     checkpmireq();                 // check to see if PMI is required

     ls += "  Monthly Payment Break Down:" + rr
	   + "              P&I:" + b.substring(0,11-s_P_I.length) + s_P_I + rr
	   + "           Escrow:" + b.substring(0,11-s_escrow.length) + s_escrow + "  (Tax: " + s_monthlyTax + " Ins: " + s_monthlyIns + " )" + rr
	   + "  Monthly Payment:" + b.substring(0,11-s_totalPayment.length) + s_totalPayment + rr;

     if (saveRatio > 80){
        aPmi = (origLoan_Amount * factor * .01) / 12;
        s_aPmi = dlrFmt(Math.round((aPmi + .005)  * 100) / 100);
	   	ls += "      PMI Payment:" + b.substring(0,11-s_aPmi.length) + s_aPmi + " may be required. See Schedule." + rr;
     }

     ls += d + rr + "Payment    Payment   Interest   Principal     PMI       Balance"
                  + rr
                  + " Date       Amount    Amount    Reduction   Payment       Due"
     + rr + d + rr;

     yearlyInt = 0;
     yearlyPrn = 0;
     yearlyPmi = 0;

     for (var j=0;j<months;j++){

         tmpvar = Loan_Amount/prop_val; // percent of property value to loan balance

         // set PMI if required
         if (tmpvar > 0.78){
                  newpmi = (eval(origLoan_Amount)*eval(factor)*.01)/12;
         } else {
                  newpmi=0;
         }

         newpmi = Math.round((newpmi + .005) * 100) / 100;
		 if (newpmi < .02) {
			newpmi = 0;
		 }
		 yearlyPmi += newpmi;

         // calculate current month interest
         monthly_interest = (Loan_Amount*monthly_intrate) + .005;
         monthly_interest = Math.round(monthly_interest * 1000) / 1000;            // round monthly interest

         // calculate current month principal
         monthly_principal = P_I - monthly_interest;
         if (monthly_principal > Loan_Amount){
            monthly_principal=Loan_Amount;
         }
         monthly_principal = Math.round((monthly_principal * 1000) + 1) / 1000;   // round monthly principal
         if (P_I != (monthly_principal + monthly_interest)) {
            monthly_interest = P_I - monthly_principal;
         }

		 aval  = curYear;
		 aval  = aval * 100;
		 aval += curMonth;

		 if (monthly_principal < .019) { monthly_principal = 0.00; }
		 if (monthly_interest < .019) { monthly_interest = 0.00; }

         if (minDate > aval) { minDate = aval; }
         if (maxDate < aval) { maxDate = aval; }
         if (minAmt > monthly_principal) { minAmt = monthly_principal; }
         if (maxAmt < monthly_principal) { maxAmt = monthly_principal; }
         if (minAmt > monthly_interest) { minAmt = monthly_interest;  }
         if (maxAmt < monthly_interest) { maxAmt = monthly_interest;  }

		 x_Date[j]  = aval;
	 	 yearlyPrn += monthly_principal;
	 	 yearlyInt += monthly_interest;
		 a_curPrincipal[j] = monthly_principal;
		 a_curInterest[j]  = monthly_interest;

         //    alert (P_I + " " + monthly_interest + " " + monthly_principal );
         s_monthly_interest = dlrFmt(monthly_interest);

         s_monthly_principal = dlrFmt(monthly_principal);

         Loan_Amount -= monthly_principal;    // Reduce loan balance
         if (Loan_Amount < .019) { Loan_Amount = 0.00; }

		 a_curLoanAmount[j] = Loan_Amount;

         s_Loan_Amount = dlrFmt(Math.round(Loan_Amount  * 1000) / 1000);

         // Is it the last payment?
         if (P_I > (monthly_interest + monthly_principal)){
             P_I = monthly_interest + monthly_principal;
         }

         s_P_I = dlrFmt((P_I + newpmi));

         str = "";
         str += curMonth;     // rolling date
         s_curMonth = str;
         str = "";
         str += curYear;      // rolling date
         s_curYear = str;

         extraZero = "";
		 if (s_curMonth.length < 2) {
			 extraZero = "0";
			 }
		 s_curMonthYear = extraZero + s_curMonth + "/" + s_curYear;

         s_newpmi = dlrFmt(newpmi);
		 if (s_newpmi == "$0.00") {
				 s_newpmi = " ";
			 }
		 if (document.forms["mortCalc"].detlsumm[1].checked){
				// set up body of print line
				ls += b.substring(0,1) + s_curMonthYear
				+ b.substring(0,11-s_P_I.length) + s_P_I
				+ b.substring(0,11-s_monthly_interest.length) + s_monthly_interest
				+ b.substring(0,11-s_monthly_principal.length) + s_monthly_principal
				+ b.substring(0,11-s_newpmi.length) + s_newpmi
				+ b.substring(0,13-s_Loan_Amount.length) + s_Loan_Amount
				+ rr;
		 }

		 if (curMonth == 12) {
			total_ln();
		 }

		 curMonth++;
		 if (curMonth > 12) {
			 curMonth = 1;
			 curYear++;
		 }


     }                                     // end of for loop for main body of report

     if (curMonth != 1) {
		total_ln();
     }

     if (document.forms["mortCalc"].detlsumm[0].checked){
		ls += rr;
     }

     // set body of print in to textarea and put disclaimer at end of report

     document.forms["mortCalc"].sched.value = ls + d + rr
     		+ "  * Minor rounding errors may occur. DHSCH is not liable for any"
	 	 	+ rr + "    errors or for any actions taken in reliance thereon."
	 		+ rr + d + rr;
}

function total_ln(){
    s_yearlyPrn = dlrFmt(Math.round(yearlyPrn  * 1000) / 1000);
    s_yearlyInt = dlrFmt(Math.round(yearlyInt  * 1000) / 1000);
    s_yearlyPmi = dlrFmt(Math.round(yearlyPmi  * 1000) / 1000);
    if (s_yearlyPmi == "$0.00") {
		s_yearlyPmi = " ";
    }
    ls += b.substring(0,1) + "   Total " + s_curYear + ":"
       	+ b.substring(0,4)
       	+ b.substring(0,11-s_yearlyInt.length) + s_yearlyInt
       	+ b.substring(0,11-s_yearlyPrn.length) + s_yearlyPrn
		+ b.substring(0,11-s_yearlyPmi.length) + s_yearlyPmi;

    if (document.forms["mortCalc"].detlsumm[0].checked){
		ls += b.substring(0,13-s_Loan_Amount.length) + s_Loan_Amount;
    }

    ls += rr;

    if (document.forms["mortCalc"].detlsumm[1].checked){
    	ls += rr;
    }

	curPrincipal += yearlyPrn;
	curInterest  += yearlyInt;

    yearlyPrn = 0;
    yearlyInt = 0;
    yearlyPmi = 0;
}
// format numeric fields changed to strings to have two decimals
function fmtIt(){
     pos = str.indexOf(".");

     if (pos == 0){
        str = "0" + str;
        pos++;
     }
     if (pos < 0){
        str += ".00";
        pos = str.indexOf(".");
     }
     str += "00";
     str = str.substring(0, pos+3);
}

function s_fmtIt(){
     pos = str.indexOf(".");

     if (pos == 0){
        str = "0" + str;
        pos++;
     }
     if (pos < 0){
        str += ".00";
        pos = str.indexOf(".");
     }
     str += "00";
     str = str.substring(0, pos+3);
     pos = str.indexOf(".");
     if (pos > 3) {
        str = str.substring(0, pos-3) + "," + str.substring(pos-3, pos+3);
     }
}


function alrt(){
     alert("The number of months must be between"
     + " 1 and 999. The loan amount must be between 1 and " + pwr[9]
     + " and the interest rate must be between .001 and 99%.");
}


function dlrFmt(dlrInput) {
     str = "";                       // setup Total Interest
     str += dlrInput;
     s_fmtIt();

     return (s + str);
}

function format(anum) {
  var negative = false;

  if (anum < 0) {
    anum = anum*-1;
    negative = true;
  }

  var thestring = new String(anum);
  var decindex = thestring.indexOf('.');
  var intstring = "";
  var decstring = "";
  var buildstring = "";
  var numstring = "";

  if (decindex > -1) {
        intstring = thestring.substring(0,decindex);
        decstring = thestring.substring(decindex,thestring.length);
  }else{
        intstring = thestring;
  }

  var numlen = intstring.length;

  var curidx = numlen;

        if (numlen > 3) {
           while (curidx > -1) {
                        buildstring = intstring.charAt(curidx) + buildstring;
                        numstring = intstring.charAt(curidx) + numstring;
                        curidx--;
                        if (numstring.length == 3) {

                                if (curidx != -1) {

                                buildstring = "," + buildstring;

                                numstring = "";
                            }
                        }
           }
           //prepend first digit
          // buildstring = intstring.charAt(0) + buildstring;
        }else{
          buildstring = intstring;
        }
  buildstring = "$" + buildstring + decstring;

  if (negative) {
     buildstring = "-" + buildstring;
  }

  return(buildstring);
}

function strip(astring) {

 var newstring = "";
 var achar = "XXX";

 for (i=0;i<astring.length;i++) {
    achar = astring.charAt(i,1);

    if (achar != "$" && achar != "," && achar != "%") {
        newstring += achar
    }
 }

 if (newstring == "") { newstring = "0"; }

 return (newstring);
}

function chartCalculate() {

  if (minDate == 0 && maxDate == 0) {
   		calcResults() }

  // browser detection code
  var bwr = navigator.appName
  var uagt = navigator.userAgent.toLowerCase()
  if (bwr=="Netscape") abwr = "ns"
	else if (bwr=="Microsoft Internet Explorer") abwr = "ie"
	else abwr = bwr;

  atch = "";
  if (abwr == "ie") {
    atch = "_parent"}

  gtype ="lne";						// set type of graph pix = pixel and lne = line

  var xc_prin = 0;					// cordinates of from point for lines
  var xc_int  = 0;
  var yc_prin = 0;
  var yc_int  = 0;
  var xcs_prin = 0;
  var ycs_prin = 0;
  var xcs_str  = "";
  var xcsPass = 0;

  _DiagramTarget=window.open("",atch,
  			"width=700, height=500, menubar=no,toolbar=no, locationbar=yes,resizable=yes,status=yes,scrollbars=no");
  with (_DiagramTarget.document)
  { open();
   	write('<html><head><title>DHSC Homes - Mortgage Amortization Calculator</title><BR>');
  	write('</head><body background=\"img/DHSCH_background.gif\">');
  	if (abwr == "ie") {
  		write('<A Href=\"javascript:history.go(-1)\">Return To Calculator</a>');
  	}
  	write('<TABLE border=\"0\">');
  	write('<TR><TD><img src=\"img/DHSCHLogoSmall.gif\"><BR><Div valign=\"left\" align=\"Center\"></td></tr><td><B>Visit out website at: <A Href=\"http://www.DKHughesHomes.com\" style=\"color:blue\">http://www.DKHughesHomes.com</A></B></DIV></TD>');
  	write('<TD>&nbsp;</TD></TR>');
  	write('<TR><TD colspan=\"2\">');

	var minyy = Math.round(minDate / 100);
	var minmm = Math.round(minDate - (minyy * 100)) - 1;
	var maxyy = Math.round(maxDate / 100);
	var maxmm = Math.round(maxDate - (maxyy * 100)) - 1;

	var smlAmt = Math.round(minAmt);
	var lrgAmt = Math.round(maxAmt);

    var dleft   = 80;
    var dtop    = 160;
    var dright  = 540;
    var dbottom = 460;

//	alert("minyy " + minyy + " minmm " + minmm + " maxyy " + maxyy + " maxmm " + maxmm);
//	alert(" minAmt " + smlAmt + " maxAmt " + lrgAmt);

	var Dcht = new Diagram();
	Dcht.SetFrame(dleft, dtop, dright, dbottom);

	Dcht.SetBorder(Date.UTC(minyy, minmm, 1, 0,0,0),
				   Date.UTC(maxyy, maxmm, 1, 0,0,0),
				   smlAmt, lrgAmt);

	Dcht.SetText("", " $", "<B>Mortgage Payment Calculation<BR /></B>");

	Dcht.XScale="2";
	Dcht.YScale="$"
	Dcht.YSubGrids=2;
	Dcht.SetGridColor("#dddddd", "#eeeeee");
	Dcht.Draw("#CCEEFF", "#000000", false);

	var i, j, k, av, xfwd, intPrn, intInt, m, x;
	x = Math.round(months);

	xFactor = minmm - 1;

	for (i = 0; i < x; i++)
	{
	  av = (dright-dleft) / x;              // refer to the SetFrame state above parameter 1 and 3
	  av2 = ((i+1)*av) + dleft;          // x distance plus the offeset of  parameter 1 of SetFrame
	  xfwd = Math.round(av2);

	  var xyy = Math.round(x_Date[i] / 100);
	  var xmm = Math.round(x_Date[i] - (xyy * 100)) - 1;
	  var xendmm = 11;

	  intPrn = Math.round(a_curPrincipal[i]);
	  intInt = Math.round(a_curInterest[i]);

	  j= Dcht.ScreenY(intPrn);
	  if (gtype == "pix") {
		  new Pixel(xfwd, j, "#FF0000");
	  	  xc_prin = xfwd;
	  	  yc_prin = j;
	  } else {
	  	if (i > 0 && xmm == xendmm) {
			str = graphNote("Year End: ",x_Date[i], a_curPrincipal[i], a_curInterest[i], a_curLoanAmount[i]);
	  		new Line(xc_prin, yc_prin, xfwd, j, "#ff0000", 1, str);
	  		xc_prin = xfwd;
	  		yc_prin = j;
		}
		if (i == 0) {
	  		xc_prin = xfwd;
	  		yc_prin = j;
	  	}
	  }
	  if (xmm == xendmm) {
			str = graphNote("Year End: ",x_Date[i], a_curPrincipal[i], a_curInterest[i], a_curLoanAmount[i]);
	  		new Dot(xfwd, j, 6, 6, "#FF0000", str);
	  }
	  if (a_curLoanAmount[i] < .019) {
			str = graphNote("The End: ",x_Date[i], a_curPrincipal[i], a_curInterest[i], a_curLoanAmount[i]);
	  		new Dot(xfwd, j, 14, 'img/smile.gif', "", str);
	  }

	  j= Dcht.ScreenY(intInt);

	  if (gtype == "pix") {
		  new Pixel(xfwd, j, "#0000ff");
	  	  xc_int = xfwd;
	  	  yc_int = j;
	  } else {
	  	if (i > 0 && xmm == xendmm) {
			str = graphNote("Year End: ",x_Date[i], a_curPrincipal[i], a_curInterest[i], a_curLoanAmount[i]);
	  		new Line(xc_int, yc_int, xfwd, j, "#0000ff", 1, str);
	  		xc_int = xfwd;
	  		yc_int = j;
	  		if (xcs_prin != 0 && xcsPass == 2) {
	  			new Dot(xcs_prin, ycs_prin, 14, 'img/smile.gif', "", xcs_str);
	  			xcs_prin = 0;
	  		}
	  		if (xcs_prin != 0) { xcsPass++; }
		}
		if (i == 0) {
	  		xc_int = xfwd;
	  		yc_int = j;
	  	}
	  }

	  if (xmm == xendmm) {
			str = graphNote("Year End: ",x_Date[i], a_curPrincipal[i], a_curInterest[i], a_curLoanAmount[i]);
  			new Dot(xfwd, j, 6, 6, "#0000ff", str);
	  }

	  if (i > 0 && a_curPrincipal[i-1] < a_curInterest[i-1] && a_curPrincipal[i] > a_curInterest[i]) {
         //    alert (P_I + " " + monthly_interest + " " + monthly_principal );

			str = graphNote("P&I Cross: ",x_Date[i], a_curPrincipal[i], a_curInterest[i], a_curLoanAmount[i]);
	  		new Dot(xfwd, j, 14, 'img/smile.gif', "", str);
	  		xcs_prin = xfwd;
	  		ycs_prin = j;
	  		xcs_str = str;
	  }
	}
	new Bar(560, 175, 690, 195, "#ffffff", "Monthly", "#000000");
	new Bar(560, 200, 690, 220, "#0000ff", "Interest", "#FFFFFF");
	new Bar(560, 225, 690, 245, "#FF0000", "Principal", "#ffffff");

   	write('</TD></TR></TABLE>');
   	write('</body></html>');

   	close();

  }

}

function graphNote(xText, xDate, prinPay, intPay, loanAmt){

			x_dateStr1 = "";                            // format year
			x_dateStr1 += Math.round(xDate / 100);

			x_dateStr = x_dateStr1;
			if (xText != "Year End: ") {
			   x_dateStrMonth = "";
			   x_dateStrMonth = xDate - (Math.round(xDate / 100) * 100);
			   x_dateStr = "";
			   x_dateStr = x_dateStrMonth + "/" + x_dateStr1;
			}

			c_Principal = dlrFmt(prinPay);

			c_Interest = dlrFmt(intPay);

			c_LoanAmount = dlrFmt(Math.round(loanAmt  * 1000) / 1000);

			var bwrg = navigator.appName
			if (bwrg=="Netscape") this.bwrg = "ns"
				else if (bwrg=="Microsoft Internet Explorer") this.bwrg = "ie"
				else this.bwrg = bwrg;

			if (this.bwrg == "ie") {
			str =  xText + x_dateStr + "\n" +
				   "Loan    : " + c_LoanAmount + "\n" +
			       "P Pay   : " + c_Principal + "\n" +
			       "I Pay   : " + c_Interest;
			} else {
				str = xText + x_dateStr + ", " +
					  "Loan: " + c_LoanAmount + ", " +
				      "P Pay: " + c_Principal + ", " +
				      "I Pay: " + c_Interest;
			}
			return (str);
}

function printPage(){

   if (minDate == 0 && maxDate == 0) {
   		calcResults() }

   var fulltable = document.forms["mortCalc"].sched.value;
   document.open();
   document.writeln('<html><head><title>Dave Hughes Signature Custom Homes - Loan Amortization Calculator</title></head><body><A Href=\"javascript:history.go(-1)\">Return To Calculator</a><BR>');
   document.writeln('<TABLE border=\"0\" background="img/DHSCH_background.gif">');
   document.writeln('<TR><TD><img src=\"img/DHSCHomesFullLogoAndName.gif\"><BR><Div align=\"Center\"></td></tr><td><B>Visit out website at: <A Href=\"http://www.DKHughesHomes.com\" style=\"color:blue\">http://www.DKHughesHomes.com</A></B></DIV></TD>');
   document.writeln('<TD>&nbsp;</TD></TR>');
   document.writeln('<TR><TD colspan=\"2\">');
   document.writeln('<pre>'+ fulltable +'</pre>');
   document.writeln('</TD></TR></TABLE>');
   document.writeln('<BR><A Href=\"javascript:history.go(-1)\">Return To Calculator</a></body></html>');
   print(document);
   document.close();
}

function buildform(){

   now = new Date();
   curMonth = now.getMonth() + 1;
   curYear  = now.getFullYear();

   s_line_month = curMonth + " size=\"2\">";
   s_line_year  = curYear  + " SIZE=\"4\"></td></tr>";
   document.write('<DIV align="center">');
   document.write('<FORM name="mortCalc">');
   document.write('<table border=1 bordercolor=black CELLPADDING="2" CELLSPACING="1" width="80%"><tr><td><TABLE border="0" width="100%" bordercolor=#cceeff bgcolor="#cceeff" align="center" style="font-size:10pt">');
   document.write('<TR><TD align="center"><img src="img/DHSCHLogoSmall.gif"></TD>');
   document.write('<td colspan="3"> Use this mortgage calculator to make an amortization schedule for a loan of any term, rate, and size. Do not use commas in the fields below.</td></TR><TR><TD colspan="4" height="3"><HR color="black" width="100%"></TD></TR>');
   document.writeln('<td colspan="2"><font style="font-size:9pt; font-weight : Bold; ">Estimated Property Value:');
   document.write('</font></td><td>&nbsp&nbsp&nbsp;<input type="text" name="prop_val" size="24" value="$250,000" onChange="document.mortCalc.prop_val.value = format(strip(document.mortCalc.prop_val.value))"></td></TR>');
   document.writeln('<TR><TD colspan="2"><font style="font-size:9pt; font-weight : Bold; ">Loan Type:</font>');
   document.writeln('&nbsp&nbsp<font style="font-size:9pt;"><input type="radio" name="fixadjust" value="FRM" onclick="document.forms[\'mortCalc\'][\'ARM-Adjust\'].disabled=true;" checked>Fixed&nbsp;Rate');
   document.write('<input type="radio" name="fixadjust" value="ARM" onclick="document.forms[\'mortCalc\'][\'ARM-Adjust\'].disabled=false;">Adjustable</font>');
   document.write('</td><td>&nbsp&nbsp&nbsp;<Select Name="ARM-Adjust" style="font-size:8pt" disabled><option value="0">If ARM Please Select</option><Option value="1">1/1 ARM</Option><Option value="3">3/1 ARM</Option><Option value="5">5/1 ARM</Option><Option value="7">7/1 ARM</Option><Option value="10">10/1 ARM</Option></SELECT></TD>')
   document.write('<TR valign="top">');
   document.write('<TR><TD>&nbsp;</TD><TD colspan="2">Month(mm) Year(yyyy)</TD></TR>');
   document.write('<TR><TD><font style="font-size:9pt; font-weight : Bold; ">Payment Start Date</font></TD>');
   document.writeln('<td colspan="2">&nbsp&nbsp&nbsp;<INPUT TYPE="text" style="text-align:right;" NAME="Lsd_mm" VALUE=')
   document.write(s_line_month);
   document.writeln('&nbsp&nbsp;/&nbsp&nbsp;<INPUT TYPE="text" style="text-align:right;" NAME="Lsd_yy" VALUE=');
   document.write(s_line_year);
   document.write('<TR valign="top">');
   document.write('<Td><font style="font-size:9pt; font-weight : Bold;">Interest Rate</font></td>');
   document.write('<td>&nbsp&nbsp&nbsp;<INPUT TYPE="text" style="text-align:right;" NAME="Int_Rate" VALUE="5.375" SIZE="6">%</td>');
   document.write('<td align="right"><font style="font-size:9pt; font-weight : Bold; ">Number of Monthly Payments</font></td>');
   document.write('<td><INPUT TYPE="text" style="text-align:right;" NAME="months" VALUE="360" SIZE="5">&nbsp;Months</TD></tr>');
   document.write('<TR valign="top">');
   document.write('<Td><font style="font-size:9pt; font-weight : Bold;">Loan Amount</font></td>');
   document.write('<td colspan="2">&nbsp&nbsp&nbsp;<INPUT TYPE="text" NAME="Loan_Amount" VALUE="$200,000" SIZE="25" onChange="document.mortCalc.Loan_Amount.value = format(strip(document.mortCalc.Loan_Amount.value))"></TD></TR>');
   document.write('<TR valign="top">');
   document.write('<Td><font style="font-size:9pt; font-weight : Bold;">Est. Yearly Property Tax</font></td>');
   document.write('<td colspan="2">&nbsp&nbsp&nbsp;<INPUT TYPE="text" NAME="Yearly_Tax" VALUE="$7,500" SIZE="15" onChange="document.mortCalc.Yearly_Tax.value = format(strip(document.mortCalc.Yearly_Tax.value))"></TD></TR>');
   document.write('<TR valign="top">');
   document.write('<Td><font style="font-size:9pt; font-weight : Bold;">Est. Yearly Ins Premium</font></td>');
   document.write('<td colspan="2">&nbsp&nbsp&nbsp;<INPUT TYPE="text" NAME="Yearly_Ins" VALUE="$1,500" SIZE="15" onChange="document.mortCalc.Yearly_Ins.value = format(strip(document.mortCalc.Yearly_Ins.value))"></TD></TR>');
   document.write('<TR>');
   document.write('<TD colspan="4" align="center" valign="middle">');
   document.writeln('<BR /><font style="font-size:9pt;"><input type="radio" name="detlsumm" value="SUM" checked>Summary Report');
   document.write('<input type="radio" name="detlsumm" value="DTL">Detail Report</font><br />');
   document.write('<br /><INPUT TYPE="button" VALUE="Click To Calculate Mortgage" onClick="calcResults(this.form)">');
   document.write('<BR>');
   document.write('<DIV STYLE="text-align:center; margin-left:4em; margin-right:4em; margin-top:1em">');
   document.write('<A Href="#" onclick="printPage();return false;">Printable Version</A>&nbsp - &nbsp<A Href="" onclick="chartCalculate();return false;">Chart Version</A><br />(you must have a schedule in the box below)');
   document.write('</DIV>');
   document.write('');
   document.write('<TEXTAREA NAME="sched" ROWS="16" COLS="68" style="font-size:8pt; font-family: monospace;"></TEXTAREA>');
   document.write('</TD></TR>');
   document.write('<TR><TD width="30%" height="1px">&nbsp;</TD><TD width="15%" height="1px">&nbsp;</TD><TD width="35%" height="1px">&nbsp;</TD><TD width="20%" height="1px">&nbsp;</TD></TR>');
   document.write('<TR>');
   document.write('<TD colspan="4" align="center" valign="middle" style="color:#000080">');
   document.writeln('Copyright &copy; 2004, DHSCH<small><small>&copy;</small></small>. All rights reserved.');
   document.write('</TD></TR>');
   document.write('</TABLE></td></tr></table>');
   document.write('');
   document.write('</FORM>');
   document.write('</DIV>');

}
// <!  -->