function formatCurrency(curValue)
{
	var curSymbol = "$";
	var thousandsSeparator = ",";
	var decPlaces = 2;
	var decSeparator = ".";
	var truncateDec = false;
	var blnSymbolAtFront = true;
	


	var strCurrency;
	if (truncateDec) {
	  strCurrency = Math.floor(parseFloat(curValue) * Math.pow(10, decPlaces));
	}else {
	  strCurrency = Math.round(parseFloat(curValue) * Math.pow(10, decPlaces));
	}

	strCurrency = strCurrency.toString();

	while (strCurrency.length <= decPlaces) strCurrency = "0" + strCurrency;

	var decValue = 	strCurrency.substr(strCurrency.length - decPlaces, strCurrency.length);			

	strCurrency = strCurrency.substr(0, strCurrency.length - decPlaces);
	var s;

	if (strCurrency.length > 3) {
			s = strCurrency.substr(strCurrency.length-3, 3);

		for (var i = 4; i <= strCurrency.length; i++){
			   if (((i - 4) % 3) == 0){
				  s = strCurrency.substr(strCurrency.length - i,1) + thousandsSeparator + s;
			} 
			else{
			  s = strCurrency.substr(strCurrency.length - i,1) + s;
			}
	
		}
	} else {
	  s = strCurrency;
	}

	if (decPlaces != 0) {
	  strCurrency =  s + decSeparator + decValue;
	}else{
	  strCurrency =  s;
	}

	return blnSymbolAtFront ? curSymbol + strCurrency : strCurrency + curSymbol;	
}	

function calculate()
{
	// check inputs		

	var AF = parseFloat(document.forms["calculator"].elements["amount"].value.replace(/[^0-9.]/g, ""));
	var IR = parseFloat(document.forms["calculator"].elements["rate"].value) / 1200;
	var NP = parseInt(document.forms["calculator"].elements["term"].value) * 12;
	var RV = (parseInt(document.forms["calculator"].elements["residual"].value) / 100) * AF;
	var AA = parseInt(document.forms["calculator"].elements["advance"].value);
	var TX = parseInt(document.forms["calculator"].elements["gst"].value);
	
	if (isNaN(IR))
	{
		alert("Please enter a valid interest rate");
		document.forms["calculator"].elements["rate"].focus();
		return;
	}

	if (TX == 1)
		AF = AF - AF/11;

	var NR =(RV * IR / (1 + IR) + (AF-RV) / (1+(1-Math.pow((1 /(1+IR)),(NP-1)))/IR))*(1+(IR*AA));
	
	if (TX == 1)
		NR = NR * 1.1;

	if (isNaN(NR))
	{
		if (isNaN(AF)) { alert("Please enter a valid amount"); document.forms["calculator"].elements["tran"].focus(); return; }
		if (isNaN(NP)) { alert("Please select a valid term"); document.forms["calculator"].elements["term"].focus(); return; }
	
		return;	
	}

	document.forms["calculator"].elements["weekly"].value = formatCurrency(NR * 12 / 52);
	document.forms["calculator"].elements["monthly"].value = formatCurrency(NR);
}