﻿function tonum(str) 
{ 
   ret = ""; 
   str = "" + str; 
   for(i = 0; i < str.length; i++){ 
       ch = str.substring(i,i+1); 
       if ((ch >= "0" && ch <= "9") || ch == '.') 
           ret += ch; 
   } 
   if(ret == "") ret = "0"; 
   return parseFloat(ret); 
} 

function format(val, decimal) 
{ 
   scale = 1; 
   if(decimal == null) decimal = 2; 
   for(i = 0;i < decimal;i++) scale*=10; 
   str = "" + Math.round(parseFloat(val) * scale); 
   while(str.length <= decimal) str = "0" + str; 
       point = str.length - decimal; 
       num = ""; 
       i = point-3; 
   while(i >= 0){ 
       num1 = str.substring(i,i+3); 
       if(i != point-3) num1 += "," + num; 
       num = num1; 
       i-=3; 
   } 
   if(i != -3){ 
       num1 = str.substring(0,i+3); 
       if(point > 3) num1 += "," + num; 
       num = num1; 
   } 
   return "$" + num + "." + str.substring(point, str.length); 
} 
function multiplyTheFields(form) 
{ 
   var loan_value = window.document.the_form.amount.value; 
   var down_payment = window.document.the_form.percentDown.value; 
   if (down_payment > 1.0) { 
       down_payment = down_payment / 100.0; 
   } 
   var adjusted_value = loan_value -(loan_value * down_payment); 

   var interest_rate = window.document.the_form.rate.value; 
   if (interest_rate > .000001) 
       { 
           interest_rate = interest_rate / 100.0; 
       interest_rate /=12; 
       var num_periods = window.document.the_form.years.value *12; 
       var pow = 1; 
       for (var j =0;j < num_periods;j++) 
       pow = pow * (1 + interest_rate); 
       var monthly_payments=((adjusted_value * pow * interest_rate) / (pow -1)); 
       } 

   else    { 
       interest_rate = 0;  
       var num_periods = window.document.the_form.years.value *12; 
       var monthly_payments=(adjusted_value/num_periods); 
       }  

   window.document.the_form.field_three.value = format(tonum(adjusted_value)); 
   
   var total = monthly_payments * num_periods; 
   var cumInterest = total - adjusted_value;     
   
   window.document.the_form.amount.value = format(tonum(loan_value)); 
   window.document.the_form.the_answer.value = format(tonum(monthly_payments)); 
   
   
   
}