function normalize( value ){
  if( value == null || value == "" ) {
	value = 0;
  } else {
	value = value.replace(/,/, "");
	value = value.replace(/$/, "");
  }
  return value;
}


function IsNumeric(strString) {
	//  check for valid numeric strings

	var strValidChars = "0123456789.-,";
	var strChar;
	var blnResult = true;

	if (strString.length == 0) return false;

	//  test strString consists of valid characters listed above
	for (i = 0; i < strString.length && blnResult == true; i++) {
		strChar = strString.charAt(i);
		if (strValidChars.indexOf(strChar) == -1) {
			blnResult = false;
		}
	}
	return blnResult;
}

function initializePaymentCalculator() {
	var rate = 0;
	var cashTrade = 0;
	var price = 0;
	var monthlyPayment = 0;

	if (IsNumeric(document.getElementById("rate").value)) {
		rate = (document.getElementById("rate").value)/(100*12);
	}

	if (IsNumeric(document.getElementById("trade_in").value)) {
		cashTrade = normalize(document.getElementById("trade_in").value);
	}


	if (IsNumeric(document.getElementById("price").value)) {
		price = normalize(document.getElementById("price").value);
	}

	if (IsNumeric(document.getElementById("months").value)) {
		term = normalize(document.getElementById("months").value);
	}

	//alert("price = "+price+"; cashTrade = "+cashTrade+"; rate = "+rate+"; term = "+term);
	monthlyPayment = (price - cashTrade) / ( ( 1 - ( 1 / Math.pow( 1 + rate, term ) ) ) / rate )
	monthlyPayment = Math.floor(parseInt(monthlyPayment * 100)) / 100;
	if (monthlyPayment == "NaN" || monthlyPayment == "NaN.00") { monthlyPayment = 0; }
	if (monthlyPayment < 0 ) { monthlyPayment = 0; }
	document.getElementById("payment").value = monthlyPayment;
}


function totalCalculator() {
	var rate = 0;
	var cashTrade = 0;
	var payment = 0;
	var price = 0;

	if (IsNumeric(document.getElementById("rate2").value)) {
		rate = (document.getElementById("rate2").value)/(100*12);
	}

	if (IsNumeric(document.getElementById("trade_in2").value)) {
		cashTrade = normalize(document.getElementById("trade_in2").value);
	}

	if (IsNumeric(document.getElementById("payment2").value)) {
		payment = normalize(document.getElementById("payment2").value);
	}

	if (IsNumeric(document.getElementById("months2").value)) {
		term = normalize(document.getElementById("months2").value);
	}

	//alert("payment = "+payment+"; cashTrade = "+cashTrade+"; rate = "+rate+"; term = "+term);

	price = (payment * ( ( 1 - ( 1 / Math.pow( 1 + rate, term ) ) ) / rate )) + parseInt(cashTrade);
	
	//alert("price = "+price+"; cashTrade = "+cashTrade);
	
	//price = price  + cashTrade;
	
	//alert("price = "+price);

	price = Math.floor(parseInt(price * 100)) / 100;
	if (price == "NaN" || price == "NaN.00") { price = 0; }
	if (price < 0 ) { price = 0; }
	
	
	document.getElementById("price2").value = price;
}



