function calculate() {
    // Get the user's input from the form. Assume it is all valid.
    // Convert interest from a percentage to a decimal, and convert from
    // an annual rate to a monthly rate. Convert payment period in months
    // to the number of monthly payments.
    var principal = document.loaninput.principal.value;
    var interest = document.loaninput.interest.value / 100 / "12";
    var payments = document.loaninput.months.value;

// Now compute the monthly payment
    var x = Math.pow(1 + interest, payments);
    var monthly = (principal*x*interest)/(x-1);
    var totalpayment = (monthly * payments);
    var totalinterest = ((monthly * payments) - principal);


    // Check that the result is a finite number. If so, display the results
    if (!isNaN(monthly) &&
        (monthly != Number.POSITIVE_INFINITY) &&
        (monthly != Number.NEGATIVE_INFINITY)) {

        document.loaninput.payment.value = currency(monthly);
        document.loaninput.totalpayment.value = currency(totalpayment);
        document.loaninput.totalinterest.value = currency(totalinterest);
    }

    // Otherwise, the user's input was probably invalid, so don't display anything.
    else {
        document.loaninput.payment.value = "";
        document.loaninput.totalpayment.value = "";
        document.loaninput.totalinterest.value = "";
    }
}

function round(number,x) {
return Math.round(number * Math.pow(10,x)) / Math.pow(10,x);
}

function cents(amount, decplaces) {
	// raise incoming value by power of 10 times the
	// number of decimal places; round to an integer; convert to string
	var str = "" + Math.round (eval(amount) * Math.pow(10,decplaces))
	// pad small value strings with zeros to the left of rounded number
	while (str.length <= decplaces) {
		str = "0" + str
	}
	// establish location of decimal point
	var decpoint = str.length - decplaces
	// assemble final result from: (a) the string up to the position of
	// the decimal point; (b) the decimal point; and (c) the balance
	// of the string. Return finished product.

	// return str.substring(0,decpoint) + "." + str.substring(decpoint,str.length);

        return "." + str.substring(decpoint,str.length);
}

function commas(integer) {
  integer = '' + Math.round(integer);

  if (integer.length > 3) {
    var mod = integer.length%3;

    var output = (mod > 0 ? (integer.substring(0,mod)) : '');

    for (i=0 ; i < Math.floor(integer.length/3) ; i++) {
      if ((mod ==0) && (i ==0))
        output+= integer.substring(mod+3*i,mod+3*i+3);
      else
        output+= ',' + integer.substring(mod+3*i,mod+3*i+3);
    }
    return output;
  }
  return integer;
}

function currency(amount) {
  var integer = Math.floor(amount);
 
  return "$" + commas(integer) + cents(amount, 2);
}
