var PatternsDict = new Object();
var ErrorsDict = new Object();

PatternsDict.mail = /^[\w\.=-]+@[\w\.-]+\.[a-z]{2,3}$/;  // email
ErrorsDict.mail = 'Please enter a valid e-mail address'
PatternsDict.money = /^\d*$|^\d*\.d{2}$/; // money w/optional decimal point
ErrorsDict.money = 'Please enter a valid currency amount'
PatternsDict.usmoney = /^(\$\d{1,3}(,\d{3})*\.\d{2}$)|(^\(\$d{1,3}(,\d{3})*\.\d{2}\)$)/;  // US Currency
ErrorsDict.usmoney =  'Please enter a dollar amount in the format of "$1,000.00"'
PatternsDict.time = /^([1-9]|1[0-2]):[0-5]\d(:[0-5]\d(\.\d{1,3})?)?$/; // Time
ErrorsDict.time = 'Please enter a valid time format'
PatternsDict.ssn = /^\d{3}\-\d{2}\-\d{4}$/;  // SSN
ErrorsDict.ssn = 'Please enter a SSN in the format of xxx-xx-xxxx'
PatternsDict.phone = /^(\d{10}|\d{3}-\d{3}-\d{4}|\(\d{3}\)\s*\d{3}-\d{4})$/;  // Phone 6125551212, 612-555-5555, (612)555-1212
ErrorsDict.phone = 'Please enter a valid US phone number with area code'
PatternsDict.zip = /(^\d{5}$)|(^\d{5}-\d{4}$)/;  // ZIP 1234 or 55555-1234
ErrorsDict.zip = 'Please enter a valid US zip code'
PatternsDict.letters = /^[a-zA-Z]*$/;  //  Letters Only
ErrorsDict.letters = 'Please use letters only'
PatternsDict.alphanumeric = /^\w*$/;  // Alphanumeric (letters, numbers, underscore)
ErrorsDict.alphanumeric = 'Please use only letters, numbers and underscore'
PatternsDict.numbers = /(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/;  // Numbers only
ErrorsDict.numbers = 'Please use numbers only'
PatternsDict.integer = /^-?\d\d*$/;  // Integer
ErrorsDict.integer = 'Please use whole numbers (integers) only'

// return true if all is well
function validateForm(theForm)
{

	// get all elements of the form into array
	var elArr = theForm.elements;

	for(var i = 0; i < elArr.length; i++)
	
	// for each element of the form...
	with(elArr[i])
	{
		var v = elArr[i].validator; // get validator, if any
		var req = elArr[i].req; // get required, if any
						
		if(req && value == '')
		{
			alert('Please complete the following field');
			elArr[i].focus();
			elArr[i].select();
			return false;
		}
		else if(v)
		{
			var thePat = PatternsDict[v]; // select the validating regular expr
			var theError = ErrorsDict[v];  // select the error mesaage for the regualr expr
			var gotIt = thePat.exec(value); // run it on value of elArr[i]

			if(!gotIt)
			{
				alert('Error ' + theError);
				elArr[i].focus();
				elArr[i].select();
				return false;
			}
		}
	}

	return true;

}

function checkForm(toCheck) {
	
	isNum = true;
	
	for (j = 0; j < toCheck.length; j++) {

		if (((((toCheck.substring(j,j+1) < "0") 
			|| (toCheck.substring(j,j+1) > "9")) && (toCheck.substring(j,j+1) != ",")) 
			|| (toCheck.substring(j,j+1) > "9")) && (toCheck.substring(j,j+1) != ".")){
		
			isNum = false;
		
		}
    
	}
	
	

	if ((isNum == false) || (toCheck.length == 0) || (toCheck == null)) {
	
		//alert("Please enter only numerical data in all fields.");
		return false;
	
	}else{
	
		//alert('I shouldn\'t be here.');
		return true;
	
	}

}     

function formatCurrency(num) {

	num=replaceChar(num);
	num=replaceChars(num);
	
	if ( checkForm(num)){
		num = num.toString().replace(/$|,/g,'');

		if(isNaN(num)) num = "0";
		
		var temp = num.toString();

		if(temp.indexOf('.') >= 0){

			temp = temp.substring(temp.indexOf('.'),temp.length);

			if(temp.length < 3){	
			
				temp = temp.substring(0,temp.indexOf('.')+3);	
	
			}
					
		}else{

			var temp = '';

		}

		num = Math.floor(num).toString();

		for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++){ 
		
			num = num.substring(0,num.length-(4*i+3))+','+num.substring(num.length-(4*i+3));
		
		}	 
		
		return ('$' + num + temp);	
	
	}else{

		return ('$0');

	}

}

function addPct(pct) {

	pct=replacePct(pct);
	pct=parseFloat(pct);		

	if(isNaN(pct)){

		pct=7.5;

	}

	if (checkForm(pct)){
	
		//alert('OK!!! This looks bad.');
		return (pct + '%');
	
	}else{


		//alert('OK!!! This looks good.');	
		return ('7.5%');

	}

}

function replaceChar(entry) {

	out = "$"; 
	add = ""; 
	temp = "" + entry;
	while (temp.indexOf(out)>-1) {
		pos= temp.indexOf(out);
		temp = "" + (temp.substring(0, pos) + add + 
		temp.substring((pos + out.length), temp.length));
	}
	return temp;

}

function replaceChars(entry) {

	out = ","; 
	add = ""; 
	temp = "" + entry;
	while (temp.indexOf(out)>-1) {
		pos= temp.indexOf(out);
		temp = "" + (temp.substring(0, pos) + add + 
		temp.substring((pos + out.length), temp.length));
	}
	return temp;

}

function replacePct(entry) {

	out = "%"; 
	add = ""; 
	temp = "" + entry;

	while (temp.indexOf(out)>-1) {

		pos= temp.indexOf(out);
		temp = "" + (temp.substring(0, pos) + add + 
		temp.substring((pos + out.length), temp.length));

	}

	return temp;

}

function IsMoney(val){

	var number="0123456789$,.";

	for (var i=0;i<val.length;i++)
	{
		if (number.indexOf(val.charAt(i)) == -1)
		{
			return false;
		}
	}
	return true;

}

function IsNumber(val){

	var number="0123456789.";

	for (var i=0;i<val.length;i++)
	{
		if (number.indexOf(val.charAt(i)) == -1)
		{
			return false;
		}
	}
	return true;

}
	
function IsPct(val){

	var number="0123456789.%,";

	for (var i=0;i<val.length;i++)
	{
		if (number.indexOf(val.charAt(i)) == -1)
		{
			return false;
		}
	}
	return true;

}
function clearForm(form) {

	form.income.value = "";
	form.auto.value = "";  
	form.rate.value="";
	form.payment.value = "";
	form.amount.value = "";

}

function housingRatio(income, insurance) {	

	housing = eval(income * .32)
	return housing;

}

function debtRatio(income, auto) {	

	debt = eval(income * .40) - auto;
	return debt;

}

function checkForm(toCheck) {	

	isNum = true;
	for (j = 0; j < toCheck.length; j++) {
		if (((((toCheck.substring(j,j+1) < "0") 
			|| (toCheck.substring(j,j+1) > "9")) && (toCheck.substring(j,j+1) != ",")) 
			|| (toCheck.substring(j,j+1) > "9")) && (toCheck.substring(j,j+1) != ".")){
			isNum = false;
		}
	}
	if ((isNum == false) || (toCheck.length == 0) || (toCheck == null)) {
		alert("Please enter only numerical data in all fields.");
		return false;
	}
	else {
		return true;
	}

}

function computeForm(form) {

	basicedit();

	income = replaceChars(form.income.value);
	income = replaceChar(income);
	if (income <= "0"){ 
		//alert("You need to be employed to finance a house!")
		form.payment.value = "$0";
		form.payment2.value = "$0";
		form.amount.value = "$0";
		form.amount2.value = "$0";
		return false;
	}	
	auto = replaceChars(form.auto.value);
	auto = replaceChar(auto);
	var a = form.rate.value;
	var a = replacePct(a);

	if (a > 20 )	
	{	
		alert ("Interest Rate must not be greater than " + 20 + " percent");			
		form.rate.value=addPct('20');		
		a = form.rate.value;
		a = replacePct(a);	
	}
	else if (a < 1)	
	{	
		alert ("Interest Rate must be greater than " + 1 + " percent");			
		form.rate.value=addPct('1');		
		a = form.rate.value;
		a = replacePct(a);	
	}			
	
	if (checkForm(income) && checkForm(auto) && checkForm(a)){
		
		housingRatioResult = Math.round(housingRatio(income));
		debtRatioResult = Math.round(debtRatio(income, auto));
	
		if (debtRatioResult <= "0") 
		{
			alert("Either your income is too low or your debt is too high!");
			form.payment.value = "$0";
			form.payment2.value = "$0";
			form.amount.value = "$0";
			form.amount2.value = "$0";
			return false;
		}	
	
		if (housingRatioResult>debtRatioResult){
			form.payment.value = formatCurrency(debtRatioResult);
			form.payment2.value = formatCurrency(debtRatioResult);
		}
		else{
			form.payment.value = formatCurrency(housingRatioResult);
			form.payment2.value = formatCurrency(housingRatioResult); 
		}
	
    
		var c = debtRatioResult;
		var d = parseFloat(a / 1200);
		var f = parseFloat(1 + d);
		//var f2 = parseFloat(1 + d);
		var g = parseFloat(Math.pow(f, 300));
		var g2 = parseFloat(Math.pow(f, 180));
		var h = parseFloat(1 / g);
		var h2 = parseFloat(1 / g2);
		var i = parseFloat(1 - h);
		var i2 = parseFloat(1 - h2);
		var j = parseFloat(i / d);
		var j2 = parseFloat(i2 / d);
		var k = parseFloat(c * j);
		var k2 = parseFloat(c * j2);
		form.amount.value = formatCurrency(Math.round(k));
		form.amount2.value = formatCurrency(Math.round(k2));

	}

	return;

}

function basicedit(){
 
	if (!IsMoney(document.frmCalc.income.value) || document.frmCalc.income.value.length ==0)
		document.frmCalc.income.value='$3,500';
		
	if (!IsMoney(document.frmCalc.auto.value) || document.frmCalc.auto.value.length ==0)
		document.frmCalc.auto.value='$400';		

	if (!IsPct(document.frmCalc.rate.value) || document.frmCalc.rate.value.length ==0)
		document.frmCalc.rate.value='7.5%';		

}
