// Common functions

function NoNum(string) {
	if(isNaN(string)) {
//		alert("Please use numbers only");
		return 0;
	}
	
	return string == null ? 0 : Number(string);
}

function GetValueById(id) {
	return NoNum(document.getElementById(id).value);
}

function SetDocText(id, value){
	document.getElementById(id).innerHTML = value;
}
        
function DecimalValue(value)
{
	return Math.round(value*100)/100  
}

function DecimalAsString(value)
{
	var i = parseFloat(value);
	if(isNaN(i)) { i = 0.00; }
	var minus = '';
	if(i < 0) { minus = '-'; }
	i = Math.abs(i);
	i = parseInt((i + .005) * 100);
	i = i / 100;
	s = new String(i);
	if(s.indexOf('.') < 0) { s += '.00'; }
	if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
	s = minus + s;
	return FormatNumberBy3(s);
}

function FormatNumberBy3(num, decpoint, sep) {
  // check for missing parameters and use defaults if so
  if (arguments.length == 2) {
    sep = ",";
  }
  if (arguments.length == 1) {
    sep = ",";
    decpoint = ".";
  }
  // need a string for operations
  num = num.toString();
  // separate the whole number and the fraction if possible
  a = num.split(decpoint);
  x = a[0]; // decimal
  y = a[1]; // fraction
  z = "";


  if (typeof(x) != "undefined") {
    // reverse the digits. regexp works from left to right.
    for (i=x.length-1;i>=0;i--)
      z += x.charAt(i);
    // add seperators. but undo the trailing one, if there
    z = z.replace(/(\d{3})/g, "$1" + sep);
    if (z.slice(-sep.length) == sep)
      z = z.slice(0, -sep.length);
    x = "";
    // reverse again to get back the number
    for (i=z.length-1;i>=0;i--)
      x += z.charAt(i);
    // add the fraction back in, if it was there
    if (typeof(y) != "undefined" && y.length > 0)
      x += decpoint + y;
  }
  return x;
}

function calculatePMT1(PV, IR, NP) {
  return PMT = (PV * IR) / (1 - Math.pow(1 + IR, -NP));
}

function calculatePMT2(FV, IR, NP) {
  return PMT = FV * IR / (Math.pow(1 + IR, NP) - 1);
}

function calculatePV(PMT, IR, NP) {
  return PV = PMT * (1 - Math.pow(1 + IR, -NP)) / IR;
}

function calculateFV(PMT, IR, NP) {
  return FV = PMT * (Math.pow(1 + IR, NP) - 1) / IR;
}