var irate, mi, cmi, years, tprinc, princ, paym, cpaym, osp,v,downp,downr;
function calcPaym(){
   var price = document.smpc.tprinc.value.replace(/[^0-9\.]/g, '');
   
   tprinc = round2d(parseFloat(price));
   downp = .01*parseFloat(document.smpc.downp.value);
   if (isNaN(downp)) downp = 0;
   downr = ceil2d(downp*tprinc);
   princ = tprinc-downr;

   document.getElementById('princ').innerHTML = fmt2d(princ,0);
   document.getElementById('downr').innerHTML = fmt2d(downr,0);

   irate = .01*parseFloat(document.smpc.percent.value);
   years=parseFloat(document.smpc.years.value);
   term = parseFloat(document.smpc.term.value);
   if(term > years)term=years;

   if (term==0 || years==0||irate<.0001||princ<1)
   {alert("values must be numeric");}
   else
   {
       mi = 1+(irate/12);
       v = 1/mi;
       paym = ceil2d(princ*(mi-1)/(1-Math.pow(mi,-(years*12))));
       osp = (princ-(v*paym*(1-Math.pow(v,12*term)))/(1-v))/Math.pow(v,12*term);
       if(osp<0)osp = 0;

       document.getElementById('paym').innerHTML = fmt2d(roundToCents(Math.round(paym)*100,0));
       document.getElementById('owed').innerHTML = fmt2d(roundToCents(Math.round(osp),0));
   }
}
function round2d(n){return(.01* Math.round(100*n));}
function floor2d(n){return(.01* Math.floor(100*n));}
function ceil2d(n){return(.01* Math.ceil(100*n));}

function roundToCents(n)
{
	num = n * 100;
	return Math.round(n) / 100;
}

// format number n as string width w with 2 decimal places
function fmt2d(n,w)
{
   var work,dp,sl,dl;

   work = ""+floor2d(n); // force only 2 decimals
   sl=work.length;

   if(-1 == (dp = work.indexOf(".")))work=work+".00";
   else if(3 > sl-dp)work = work+".00".substring(sl-dp,3);
   sl = work.length;
   if(0 != w && w !=sl)
      if(w<sl){work = "*";for(sl=1;sl<w;sl++)work=work+"*";}
      else for(;sl<w;sl++)work=" "+work;
      
   // Add commas
   workString = work.toString();
   x = workString.split('.');
   x1 = x[0];
   x2 = x.length > 1 ? '.' + x[1] : '';
   var rgx = /(\d+)(\d{3})/;
   while (rgx.test(x1)) {
	x1 = x1.replace(rgx, '$1' + ',' + '$2');
   }
   return x1 + x2;
}