// JavaScript Document

function calculate(resultId) {
	var amount = checkValue(document.loancalc.amount, 1);
	var length = checkValue(document.loancalc.length, 1);
	var rate = checkValue(document.loancalc.rate, 1);
	var deposit = checkValue(document.loancalc.deposit, 0);
	var residual = checkValue(document.loancalc.residual, 0);
	var error = false;
	if (amount == false || length == false || rate == false) {
		error = true;
	}
	if (error == false) {
		var rateNew = rate/1200;
		var months = length*12;
		var topRight = Math.pow((1+rateNew), months);
		var top = ((amount - deposit)*rateNew)*topRight;
		top = top - (residual*rateNew);
		var bottom = topRight - 1;
		var total = top/bottom;
		total = Math.round(total);
		document.loancalc.final_total.value = "$"+total+" /m";
	} else {
		document.loancalc.final_total.value = "0";
	}
}

function calculate2(resultId) {
	var amount = checkValue(document.loancalc2.amount, 1);
	var length = checkValue(document.loancalc2.length, 1);
	var rate = checkValue(document.loancalc2.rate, 1);
	var deposit = checkValue(document.loancalc2.deposit, 0);
	var residual = checkValue(document.loancalc2.residual, 0);
	var error = false;
	if (amount == false || length == false || rate == false) {
		error = true;
	}
	if (error == false) {
		var rateNew = rate/1200;
		var months = length*12;
		var topRight = Math.pow((1+rateNew), months);
		var top = ((amount - deposit)*rateNew)*topRight;
		top = top - (residual*rateNew);
		var bottom = topRight - 1;
		var total = top/bottom;
		total = Math.round(total);
		document.loancalc2.final_total.value = "$"+total+" /m";
	} else {
		document.loancalc2.final_total.value = "0";
	}
}

function checkValue(field, zero) {
	amount = field.value;
	amount = amount.replace("$", "");
	amount = amount.replace(",", "");
	amount = amount.replace(" ", "");
	amount = amount.replace("%", "");
	amount = amount = parseFloat(amount);
	if (zero == 1) {
		if (amount == 0 || isNaN(amount)) {
			return false;
		} else {
			field.value = amount;
			return amount;
		}
	} else { 
		if (amount == 0 || isNaN(amount)) {

			return 0;
		} else {
			field.value = amount;
			return amount;
		}
	}
}
