function validateMoney(moneyValue)
{
	if(!moneyValue.match(/^[0-9]{1,}\.[0-9]{1,2}$/) && !moneyValue.match(/^[0-9]{1,}$/))
	{
		return false;
	}
	else
	{
		return true;
	}
}

function validatePercent(percentValue)
{
	if(!percentValue.match(/^[0-9]{1,}\.[0-9]{1,2}$/) && !percentValue.match(/^[0-9]{1,}$/))
	{
		return false;
	}
	else
	{
		return true;
	}
}

function validateInteger(integerValue)
{
	if(!integerValue.match(/^[0-9]{1,}$/))
	{
		return false;
	}
	else
	{
		return true;
	}
}

function displayCommas(theValue)
{
	theValue += '';
	x = theValue.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while(rgx.test(x1))
	{
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

function displayTwoDecimals(theFloat)
{
	var theFloat2 = theFloat.toString();
	var theFloatReturn = "";
	var theFloatSplit = theFloat2.split(".");
	if(theFloatSplit.length != 2)
	{
		theFloatReturn = theFloat2 + '.00';
	}
	else
	{
		var theFloatDecimal = theFloatSplit[1];
		if(theFloatDecimal.length == 0)
		{
			theFloatReturn = theFloat2 + '.00';
		}
		else if(theFloatDecimal.length == 1)
		{
			theFloatReturn = theFloat2 + '0';
		}
		else
		{
			theFloatReturn = theFloat2;
		}
	}
	
	return theFloatReturn;
}

function roundToDecimals(num, dec)
{
	var result = Math.round(num*Math.pow(10, dec))/Math.pow(10, dec);
	return result;
}

function calculatePayment()
{
	var price = document.getElementById('price').value;
	var down = document.getElementById('down').value;
	var rate = document.getElementById('rate').value;
	var term = document.getElementById('term').value;
	var priceResult = validateMoney(price);
	var downResult = validateMoney(down);
	var rateResult = validatePercent(rate);
	var termResult = validateInteger(term);
	var errorString = new Array();

	if(!priceResult)
	{
		errorString.push('Price');
	}
	if(!downResult)
	{
		errorString.push('Cash/Trade');
	}
	if(!rateResult)
	{
		errorString.push('Rate');
	}
	if(!termResult)
	{
		errorString.push('Term');
	}
	if(errorString.length > 0)
	{
		alert('There is an error with the entered values. Please check the following fields: ' + errorString.join(', ') + ' (numbers and decimals only).');
	}
	else
	{
		if(term == 0)
		{
			term = 1;
		}
		rate = rate/(12*100);
		var difference = price - down;
		var uno = 1.0 + parseFloat(rate);
		var dos = 0 - parseInt(term);
		var bottom = 1 - Math.pow(uno, dos);
		if(rate == 0)
		{
			var monthly = difference/term;
		}
		else
		{
			var monthly = difference * (rate/bottom);
		}
		var total = monthly * term;
		var outmonthly = roundToDecimals(monthly, 2);
		document.getElementById('total').innerHTML = '$' + displayCommas(displayTwoDecimals(outmonthly));
	}
}
