//Cleans the number passed to insure correct calculations
function CleanNumber(Dollar, title) {
	//Return notice that the value is not a number
	if(isNaN(Dollar)){
		alert('Please enter digits only in the ' + title + ' box');
		return;
	}
	
	//return 0 if empty as required
	if(Dollar == ''){
		return 0;
	}
	
	//trim out all non-numeric characters
	var nInd;
	var strLeft, strRight, strFormat;
	var DLen = Dollar.length;
	
	nInd = Dollar.indexOf(",", 0);
	strLeft = "";
	strRight = Dollar.substring(0);
	if(nInd == -1){
		return Dollar;
	}
	
	while(nInd != -1){
		strLeft		= strLeft + strRight.substring(0, nInd);
		strRight	= strRight.substring(nInd + 1);
		nInd		= strRight.indexOf(",", 0)
	}
	
	strFormat = strLeft + strRight;
	return strFormat;
}

//Calculate payment value
function MakeCurrency(){
	var fPrinc = CleanNumber(document.getElementById("txtPrincipal").value, 'Principal');
	var tmpDownp = 0;
	if(document.getElementById("txtDownpayment").value.length > 0){
		tmpDownp = document.getElementById("txtDownpayment").value;
	}
	var fDownp = CleanNumber(tmpDownp, 'Downpayment');
	var fInter = parseFloat(document.getElementById("cboInterest").options[document.getElementById("cboInterest").selectedIndex].value);
	var fPeriod = parseFloat(document.getElementById("cboPeriod").value);
	var objPayment = document.getElementById("txtPayments");
	
	var cntr, NumOfPays , MIntrst, Cmpnd, Prncpl, MPayment, Downpymnt;
	
	//Prevent calculation if not cleannumbers
	if(!fPrinc){return;}
	
	Prncpl = fPrinc.length == 0 ? 0 : parseFloat(fPrinc);
	Downpymnt = fDownp.length == 0 ? 0.2 * parseFloat(Prncpl) : parseFloat(fDownp);

	if (Downpymnt >= Prncpl) {
		alert("To use this calculator your Principal amount has to be higher than your Downpayment!");
		return;
	}
	//Amount Borrowed
	Prncpl = Prncpl - Downpymnt;
	
	//Number of Payments in the Loan Period
	NumOfPays = fPeriod * 12;
	
	//Monthly Interest
	MIntrst = fInter / 1200;
	
	//Compounded Interest
	Cmpnd = 1;
	
	for(cntr = "0" ; cntr < NumOfPays; cntr++) {
		Cmpnd = Cmpnd * (1 + MIntrst);	
	}
	
	MPayment = (Prncpl * Cmpnd * MIntrst)/(Cmpnd - 1);
	objPayment.value = parseInt(MPayment, 10 );
}