function formatPayment(input) {
	var chg, len;
	input += "";
	len = input.indexOf(".");
	if(len == -1) {
		len = input.length;
		chg = "";
	}
	else {
		chg = input.substring(len, input.length);
	}
	while(len > 3) {
		chg = input.substring(len-3, len) + chg;
		chg = "," + chg;
		len -= 3;
	}

	chg = input.substring(0, len) + chg;
	len = chg.indexOf(".");
	if(len>0) {
		chg = chg.substring(0, len+3);
	}
	else {
		chg = chg + ".00"
	}
	return chg;
}

function round(number)
{
   return Math.round(number*Math.pow(10,2))/Math.pow(10,2);
}


function calculate()
{
   //Calculate user inputs
   document.idp.TD.value = round(document.idp.OW1.value) +
   round(document.idp.amt_ow2.value) + round(document.idp.amt_ow3.value) +
   round(document.idp.amt_ow4.value);

   document.idp.TP.value = round(document.idp.mon_pay1.value) +
   round(document.idp.mon_pay2.value) + round(document.idp.mon_pay3.value) +
   round(document.idp.mon_pay4.value);

   //assign values
   document.idp.LA.value = round(document.idp.TD.value);
   document.idp.LA2.value = round(document.idp.TD.value) + round(document.idp.newcash.value);

   var mi = document.idp.IR.value / 1200;
   var base = 1;
   var mbase = 1 + mi;
   for (i=0; i<document.idp.YR.value * 12; i++)
   {
      base = base * mbase;
   }
   document.idp.PI.value = round(document.idp.LA.value * mi / ( 1 - (1/base)));

   //calc comparision numbers
   var min = document.idp.IR.value / 1200;
   var base = 1;
   var mbase = 1 + min;
   for (i=0; i<document.idp.YR.value * 12; i++)
   {
      base = base * mbase;
   }
   document.idp.PIN.value = round(document.idp.LA2.value * min / ( 1 - (1/base)));

   //calc savings
   document.idp.MS.value = round(document.idp.TP.value - document.idp.PI.value);
   document.idp.TS.value = round(document.idp.MS.value * 12);

   //format output
   /*
   document.idp.TD.value = "$" + formatPayment(document.idp.TD.value);
   document.idp.TP.value = "$" + formatPayment(document.idp.TP.value);
   document.idp.LA.value = "$" + formatPayment(document.idp.LA.value);
   document.idp.PI.value = "$" + formatPayment(document.idp.PI.value);
   document.idp.PIN.value = "$" + formatPayment(document.idp.PIN.value);
   document.idp.MS.value = "$" + formatPayment(document.idp.MS.value);
   document.idp.LA2.value = "$" + formatPayment(document.idp.LA2.value);
   document.idp.TS.value = "$" + formatPayment(document.idp.TS.value);
   */

   document.idp.TD.value = formatPayment(document.idp.TD.value);
   document.idp.TP.value = formatPayment(document.idp.TP.value);
   document.idp.LA.value = formatPayment(document.idp.LA.value);
   document.idp.PI.value = formatPayment(document.idp.PI.value);
   document.idp.PIN.value = formatPayment(document.idp.PIN.value);
   document.idp.MS.value = formatPayment(document.idp.MS.value);
   document.idp.LA2.value = formatPayment(document.idp.LA2.value);
   document.idp.TS.value = formatPayment(document.idp.TS.value);
}