// JavaScript Document
// FOR HOME PURCHASE AFFORDABILITY CALCULATOR

/* BEGIN AFFORDABILITY CALCULATOR FUNCTIONS */
var loanLife = 30;
var pmtFrequency = 12;
var pmtPeriods = loanLife * pmtFrequency;
var minPti = 0.28;
var maxPti = 0.33;
var minDti = 0.36;
var dtiNum = 100*minDti;

function resetAffordBuy() {
	document.getElementById('calculatorResults').style.display = 'none';
}
function fillMonthlyPayment(form) {

	var yrIncome = form.annualIncome;
	var moIncome = 0;
	var moDebt = form.monthlyDebt;
	var proceed = false;
	var cPmt = 0;
	var aPmt = 0;
	
	if(validate_required(yrIncome) && (validate_expression(yrIncome, 'number') || validate_expression(yrIncome, 'float'))) {
		// input is valid, so proceed
		proceed = true;
	} else {
		proceed = false;
	}
	if(proceed) {
		moIncome = parseFloat(yrIncome.value/pmtFrequency);
		if(validate_required(moDebt) && (validate_expression(moDebt, 'number') || validate_expression(moDebt, 'float'))) {
			// input is valid
			dtiRatio = moDebt.value/moIncome;
			if(dtiRatio <= minDti) {
				proceed = true;
			} else {
				proceed = false;
				alert('Your Debt-to-Income ratio is greater than ' + dtiNum + '%');
			}
		} else {
			proceed = false;
		}
		if(proceed) {
			cPmt = formatNumber(((moIncome-moDebt.value)*minPti).toFixed(2), 2, ',', '.', '$', '', '', '');
			aPmt = formatNumber(((moIncome-moDebt.value)*maxPti).toFixed(2), 2, ',', '.', '$', '', '', '');
		} else {
			cPmt = '';
			aPmt = '';	
		}
		form.cMonthlyPayment.value = cPmt;
		form.cMonthlyPayment.style.width = (cPmt.length * 6) + 'px';
		form.aMonthlyPayment.value = aPmt;
		form.aMonthlyPayment.style.width = (aPmt.length * 6) + 'px';
	}
	return proceed;
}

function checkAffordBuy() {
	// check form fields validity
	return true; // temp
}
function calcAffordBuy(form) {
	// calculate affordability
	var valid = checkAffordBuy();
	if(valid) {
		valid = fillMonthlyPayment(form);
	}
	if(!valid) {
		return false;
	}
	var taxIns, periodicIncome, periodicDebt, interestRate, minPmt, maxPmt, minTotalPmt, maxTotalPmt, minLoan, maxLoan, downPayment, minValue, maxValue;
	// periodic (monthly) income
	periodicIncome = form.annualIncome.value/pmtFrequency;
	// periodic (monthly) debt
	periodicDebt = new Number(form.monthlyDebt.value);
	periodicDebt = periodicDebt.toFixed(2);
	interestRate = new Number(form.interestRate.value);
	interestRate = interestRate.toFixed(2);
	// calc taxes & ins
	taxIns = getPeriodicTaxesInsurance(form);	
	
	// lowest max monthly payment bank would allow
	minTotalPmt = periodicIncome * minPti;
	// highest max monthly payment bank would allow
	maxTotalPmt = periodicIncome * maxPti;
	// need to subtract out the taxes and insurance  from the max payment
	// because the bank doesn't include these in calculating the loan amount
	minPmt = minTotalPmt - taxIns;
	maxPmt = maxTotalPmt - taxIns;
	// now get loan amount
	minLoan = getMortgageLoan(interestRate, minPmt);
	maxLoan = getMortgageLoan(interestRate, maxPmt);
	// get home values
	downPayment = new Number(form.downPayment.value);
	minValue = minLoan + downPayment;
	maxValue = maxLoan + downPayment;
	// write to page
	document.getElementById('calculatorResults').style.display = 'block';
	form.affordLower.value = formatNumber(minLoan.toFixed(2), 2, ',', '.', '$', '', '', '');
	form.affordLower.style.width = (form.affordLower.value.length * 6) + 'px';
	form.affordUpper.value = formatNumber(maxLoan.toFixed(2), 2, ',', '.', '$', '', '', '');
	form.affordUpper.style.width = (form.affordUpper.value.length * 6) + 'px';
	form.valuedLower.value = formatNumber(minValue.toFixed(2), 2, ',', '.', '$', '', '', '');
	form.valuedLower.style.width = (form.valuedLower.value.length * 6) + 'px';
	form.valuedUpper.value = formatNumber(maxValue.toFixed(2), 2, ',', '.', '$', '', '', '');
	form.valuedUpper.style.width = (form.valuedUpper.value.length * 6) + 'px';
		
	return false;
}

function getMortgageLoan ( intrate, payment )
{
	var period_intrate, disc_factor, principal;

	// get the interest rate for one period (e.g. month)
	period_intrate = intrate / (pmtFrequency * 100);

	// calculate the discount factor
	disc_factor = ( Math.pow( 1 + period_intrate, pmtPeriods ) - 1 )
								/
		( period_intrate *  Math.pow( 1 + period_intrate, pmtPeriods ) )
	;

	principal = payment * disc_factor;

	return principal;
}

function getPeriodicTaxesInsurance ( form )
{
	var str_taxes, str_ins, yearly_taxes, yearly_ins, periodic_txins;

	str_taxes = form.propertyTax.value;
	str_ins = form.insurance.value;
	if ( str_taxes == "" ) {
		yearly_taxes = 0;
	} else {
		yearly_taxes = parseFloat( str_taxes );
	}
	if ( str_ins == "" ) {
		yearly_ins = 0;
	} else {
		yearly_ins = parseFloat( str_ins );
	}
	periodic_txins = (yearly_taxes + yearly_ins) / pmtFrequency;

	return periodic_txins;
}
/* END AFFORDABILITY CALCULATOR FUNCTIONS */

/* BEGIN BUY HOME FORM FUNCTIONS */
function checkPriceRange(form) {
	var ddl = form.minPrice;
	var idx = ddl.selectedIndex;
	var minVal = parseInt(ddl.options[idx].value);

	ddl = form.maxPrice;	
	idx = ddl.selectedIndex;
	var maxVal = parseInt(ddl.options[idx].value);
	
	if(minVal > maxVal) {
		alert('The price range should go from lowest to highest.');
		form.minPrice.selectedIndex = 0;
		form.maxPrice.selectedIndex = 0;
		return false;
	}
	
	return true;
}
/* END BUY HOME FORM FUNCTIONS */

function updateImage(img, w) {
	document.images.propertyImage.src = img;
	document.images.propertyImage.width = w;
}

