//Income and Debt Obligations
var monthlyGrossIncome;
var targetHouseValue;

//New Loan Assumption
var country;
var stateInterestRate;
var effectiveInterestRate;
var mortgageTermInYear;
var downPayment;
var frontEndRatio = 32; // 32%
var endRatio = 40; //40%

//Calculation Results
var totalExpense;
var netIncome;
var debtToIncomeRatio;
var maxPercentageForMortgage;
var backEndRatioPayment;
var minRatioPayment;
var monthlyPayment;
var numPayment;
var maxAllowedMortgage
var affordableHomeValue;
var proposedMonthlyPayment;
var frontEndRatioPayment;

function getInputs() {
	//Income and Debt Obligations
	monthlyGrossIncome = parseInt($('#form_combinedIncome').val());
	if (monthlyGrossIncome <= 0) monthlyGrossIncome = 1;
	
	targetHouseValue = parseInt($('#form_targetHouseValue').val());
	
	totalExpense = 0;
	$(".expenses").each(function() {
		totalExpense += parseInt($(this).val());
	})

	//New Loan Assumption
	country = $("input[name='rate']:checked").val();
	stateInterestRate = parseFloat($('#form_mortgageRate').val());
	stateInterestRate = stateInterestRate.toFixed(2);	
	mortgageTermInYear = parseInt($('#ac_form_mortgageTerm').val());
	downPayment = parseInt($('#form_downPayment').val());
	
}


function calculateAffordability(){
	
	frontEndRatioPayment = monthlyGrossIncome * frontEndRatio / 100;
	debtToIncomeRatio = totalExpense / monthlyGrossIncome * 100;

	maxPercentageForMortgage = endRatio - debtToIncomeRatio;
	if (maxPercentageForMortgage < 0) maxPercentageForMortgage = 0;
	
	backEndRatioPayment = monthlyGrossIncome * maxPercentageForMortgage / 100;
	minRatioPayment = min(frontEndRatioPayment,backEndRatioPayment);
	monthlyPayment = minRatioPayment;
	
	//Mortgage formula
	//M = P * [i(1+i)^n] / ((1+i)^n - 1)
	//where M is the monthly mortgage payment, i is the monthly interst compound annually,
	//n is the number of payments
	// Source: http://en.wikipedia.org/wiki/Amortization_calculator
	if (country == "us" ) {
			effectiveInterestRate = (stateInterestRate / 100) / 12;
	} else {
			//Effective Interest Rate
			// r = (1 + i/n)^n - 1
			// where r is the effecive annual rate, i is the nominal rate
			// and n is the number of compounding periods per year
			// Source: http://en.wikipedia.org/wiki/Effective_annual_rate
			effectiveInterestRate = stateInterestRate / 100;
			effectiveInterestRate = Math.pow((1 + effectiveInterestRate/2), 2) - 1;
			effectiveInterestRate = effectiveInterestRate / 12;
	}
	
	if (effectiveInterestRate == 0) effectiveInterestRate = 1;
	
	numPayment = mortgageTermInYear * 12;
	maxAllowedMortgage = monthlyPayment * (Math.pow(1 + effectiveInterestRate, numPayment) - 1)/ 
							(effectiveInterestRate*(Math.pow(1 + effectiveInterestRate, numPayment)));
	proposedMonthlyPayment = Math.round(targetHouseValue * (effectiveInterestRate*(Math.pow(1 + effectiveInterestRate, numPayment))) / 
							(Math.pow(1 + effectiveInterestRate, numPayment) - 1));
	affordableHomeValue = maxAllowedMortgage + downPayment;
}

function recommend(){
	
	if (targetHouseValue <= affordableHomeValue) {
		$('#recommend').html('Congratulation, you can afford your target house value <strong>$<span id="targetHouseValue"></span></strong> within ' + mortgageTermInYear 
					+ ' years. In fact, your monthly payment will be <strong>$<span id="proposedMonthlyPayment"></span></strong>.');
		formatResults('targetHouseValue',targetHouseValue);
		formatResults('proposedMonthlyPayment',proposedMonthlyPayment);
	} else {
		proposedMonthlyPayment = Math.round(targetHouseValue * (effectiveInterestRate*(Math.pow(1 + effectiveInterestRate, numPayment))) / 
											(Math.pow(1 + effectiveInterestRate, numPayment) - 1));
		var diff = proposedMonthlyPayment - monthlyPayment;
		
		$('#recommend').html('Unfortunately, you can not afford your target house value <strong>$<span id="targetHouseValue"></span></strong> within '
		 			+ mortgageTermInYear + ' years. In fact, your monthly payment will be <strong>$<span id="proposedMonthlyPayment"></span></strong>.  You can afford this home if you increase your income or decrease your expenses by <strong>$<span id="diff"></span></strong> a month.');
		formatResults('targetHouseValue',targetHouseValue);
		formatResults('proposedMonthlyPayment',proposedMonthlyPayment);
		formatResults('diff',diff);
	}
	
}
function resetResults(){
	$('#monthlyGrossIncome').html(0);
	$('#frontEndRatio').html(0);
	$('#frontEndRatioPayment').html(0);
	

	//Back-end Ratio
	$('#totalExpense').html(0);
	$('#debtToIncomeRatio').html(0);
	$('#maxPercentageForMortgage').html(0);  // must be positive
	$('#backEndRatioPayment').html(0);
	
	
	//Payment Calculation
	$('#monthlyPayment').html(0);
	$('#maxAllowedMortgage').html(0);
	$('#downPayment').html(0);
	$('#affordableHomeValue').html(0);
	$('#recommend').html('');
}

function formatResults(id, value){
	return $('#' + id).html(Math.round(value)).format({format:"#,###", locale:"ca"});
}

function displayResults(){
	
	//Front-end Ratio
	formatResults('monthlyGrossIncome', monthlyGrossIncome);
	formatResults('frontEndRatio', frontEndRatio);
	formatResults('frontEndRatioPayment', frontEndRatioPayment)

	//Back-end Ratio
	formatResults('totalExpense', totalExpense);
	formatResults('debtToIncomeRatio', debtToIncomeRatio);
	formatResults('maxPercentageForMortgage', maxPercentageForMortgage);
	formatResults('backEndRatioPayment', backEndRatioPayment);
	
	
	//Payment Calculation
	formatResults('monthlyPayment', monthlyPayment);
	formatResults('maxAllowedMortgage', maxAllowedMortgage);
	formatResults('downPayment', downPayment);
	formatResults('affordableHomeValue', affordableHomeValue);
}

function min(a,b){
	if (a >= b) return b;
	else return a;
}

//////////////////////////////////////////////////////////////////////////////////////////////////////

//Loan Information
var loanAmount;
var stateInterestRate;
var effectiveInterestRate;
var mortgageAmortization;
var mortgageTerm;
var mortgageInsurance = 0.0215; // CMHC offers insurance rate between 0.5% to 3.75% , average is 2.15%
var extraExpenses;
var country;

//Others
var beginningBalance;
var monthlyPayment;
var paidPrincipal;
var paidInterest;
var sumPaidPrincipal;
var sumPaidInterest;
var endingBalance; 
var numPayments;

//For graphing purposes
var gBeginningBalance = [];
var gSumPaidPrincipal =[];
var gSumPaidInterest =[];

function toggleGraph(){
	$("#placeholder").toggle();
	$("#showGraph").toggle();
	$("#hideGraph").toggle();
	
	return false;
}

function toggleInfo(){
    $("#show").toggle();
	$("#hide").toggle();
}

function mc_getInputs() {
	//Loan Information
	loanAmount = parseInt($('#form_loanAmount').val());
	stateInterestRate = parseFloat($('#form_interestRate').val());
	stateInterestRate = stateInterestRate.toFixed(2);
	mortgageAmortization = parseInt($('#form_mortgageAmortization').val());
	mortgageTerm = parseInt($('#form_mortgageTerm').val());
	country = $("input[name='rate']:checked").val();
}

function mc_displayResults(){
	$('#mc_monthlyPayment').html(Math.round(monthlyPayment)).format({format:"#,###.00", locale:"ca"});
	$('#totalInterest').html(Math.round(sumPaidInterest)).format({format:"#,###.00", locale:"ca"});
}

function mc_resetResults(){
	$('#mc_monthlyPayment').html(0);
	$('#totalInterest').html(0);
}

function drawGraph(){
	
	setTimeout( function(){
			$.plot($("#placeholder"), [
		        {
					label: 'Remaining Balance',
		            data: gBeginningBalance,
		            lines: { show: true }
		        },
				{
					label: 'Paid Principal ',
		            data: gSumPaidPrincipal,
		            lines: { show: true }	          
	        	},
			 	{
					label: 'Paid Interest',
		            data: gSumPaidInterest,
		            lines: { show: true }
		        }
		    ]);
	}, 100);
}

function resetGraph(){
	gBeginningBalance = [];
	gSumPaidPrincipal = [];
	gSumPaidInterest = [];
	
	$.plot($("#placeholder"), [
		{
			data: gBeginningBalance,
			lines: {show: true},
			points: {show: true}
		},
		{
			data: gSumPaidPrincipal,
			lines: {show: true},
			points: {show: true}
		},
		{
			data: gSumPaidInterest,
			lines: {show: true},
			points: {show: true}
		}
	]);
}

function calculateMortgage(){
	
	//Mortgage formula
	//M = P * [i(1+i)^n] / ((1+i)^n - 1)
	//where M is the monthly mortgage payment, i is the monthly compounded interest,
	//n is the number of payment
	// Source: http://en.wikipedia.org/wiki/Amortization_calculator
	
	//calculate effectiveInterestRate
	if (country == "us" ) {
		effectiveInterestRate = (stateInterestRate / 100) / 12;
	} else {
		//Effective Interest Rate
		// r = (1 + i/n)^n - 1
		// where r is the effecive annual rate, i is the nominal rate
		// and n is the number of compounding periods per year
		// Source: http://en.wikipedia.org/wiki/Effective_annual_rate
		effectiveInterestRate = stateInterestRate / 100;
		effectiveInterestRate = Math.pow((1 + effectiveInterestRate/2), 2) - 1;
		effectiveInterestRate = effectiveInterestRate / 12;
	}
	
	//calculate monthly payment
	numPayments = mortgageAmortization * 12;
	extraExpenses = mortgageInsurance * loanAmount;
	loanAmount += extraExpenses;
	if (effectiveInterestRate == 0) {
		if (mortgageAmortization <= 0) mortgageAmortization = 1;
		monthlyPayment = loanAmount / mortgageAmortization; // is the same either compound monthly or semi-annual
	} else {
		monthlyPayment = loanAmount * (effectiveInterestRate*(Math.pow(1 + effectiveInterestRate, numPayments))) / 
											(Math.pow(1 + effectiveInterestRate, numPayments) - 1);
	}
	
	//init
	beginningBalance = loanAmount;
	sumPaidPrincipal = 0;
	sumPaidInterest = 0;
	
	var year;
	var index;
	
	var yearPrincipal = 0;
	var yearInterest = 0;
	var yearBeginning = 0;
	
	var yearIndex = 0;
	for (var month = 1; month <= numPayments && yearIndex <= mortgageTerm; month++) {
		year = Math.floor((month - 1) / 12);
		firstMonth = year * 12 + 1;

		paidInterest = effectiveInterestRate * beginningBalance;
		paidPrincipal = monthlyPayment - paidInterest;
		sumPaidPrincipal += paidPrincipal;
		sumPaidInterest += paidInterest;
		endingBalance = beginningBalance - paidPrincipal;

		//calculate for year 
		yearPrincipal += paidPrincipal;
		yearInterest += paidInterest;
		
		if (month % 12 == 0) {
			//special case when month = 12 (i.e. first year)
			if (month / 12 == 1){
				index = 1;
			} else {
				index = month - 12 + 1;
			}

			$('#' + firstMonth).before("<tr class='remove'><td bgcolor='#333333' style='color:#FFFFFF; font-weight:bold; '>" + month/12 + "</td><td bgcolor='#D7D7D7'>" + Math.round(yearBeginning) + "</td><td bgcolor='#D7D7D7'>" + Math.round(monthlyPayment) + "</td>\
							<td bgcolor='#D7D7D7'>" + Math.round(yearPrincipal) + "</td><td bgcolor='#D7D7D7'>" + Math.round(yearInterest) + "</td>\
							<td bgcolor='#D7D7D7'>" + Math.round(sumPaidPrincipal) + "</td><td bgcolor='#D7D7D7'>" + Math.round(sumPaidInterest) + "</td>\
							<td bgcolor='#D7D7D7'>" + Math.round(endingBalance) + "</td><td><a id='show' href='#' onclick='showMonths(\"" + year + "\"); return false;' class='redButton'>More info</a> <a id='hide' href='#' style='display:none' onclick='hideMonths(\"" + year + "\"); return false;' class='redButton'>Hide Info</a></td></tr>");
						
			yearPrincipal = 0;
			yearInterest = 0;
		} else if (month % 12 == 1) {
			yearBeginning = beginningBalance;
			yearIndex++;
		} 
			
		if (month % 12 == 1){
			$('#outputTable').append("<tr class='remove year" + year + "' id='" + month + "' style='display:none;visibility:hidden;'><td bgcolor='#666666' style='color:#FFFFFF; font-weight:bold;'>" + month + "</td>\
				<td bgcolor='#EBEBEB'>" + Math.round(beginningBalance) + "</td><td bgcolor='#EBEBEB'>" + Math.round(monthlyPayment) + "</td>\
				<td bgcolor='#EBEBEB'>" + Math.round(paidPrincipal) + "</td><td bgcolor='#EBEBEB'>" + Math.round(paidInterest) + "</td>\
				<td bgcolor='#EBEBEB'>" + Math.round(sumPaidPrincipal) + "</td><td bgcolor='#EBEBEB'>" + Math.round(sumPaidInterest) + "</td>\
				<td bgcolor='#EBEBEB'>" + Math.round(endingBalance) + "</td></tr>");	
		} else if (month % 12 == 0){
			$('#outputTable').append("<tr class='remove year" + year + "' id='" + month + "' style='display:none;visibility:hidden;'><td bgcolor='#666666' style='color:#FFFFFF; font-weight:bold;'>" + month + "</td>\
				<td bgcolor='#EBEBEB'>" + Math.round(beginningBalance) + "</td><td bgcolor='#EBEBEB'>" + Math.round(monthlyPayment) + "</td>\
				<td bgcolor='#EBEBEB'>" + Math.round(paidPrincipal) + "</td><td bgcolor='#EBEBEB'>" + Math.round(paidInterest) + "</td>\
				<td bgcolor='#EBEBEB'>" + Math.round(sumPaidPrincipal) + "</td><td bgcolor='#EBEBEB'>" + Math.round(sumPaidInterest) + "</td>\
				<td bgcolor='#EBEBEB'>" + Math.round(endingBalance) + "</td></tr>");	
		} else {
			$('#outputTable').append("<tr class='remove year" + year + "' id='" + month + "' style='display:none;visibility:hidden;'><td bgcolor='#666666' style='color:#FFFFFF; font-weight:bold;'>" + month + "</td>\
				<td bgcolor='#EBEBEB'>" + Math.round(beginningBalance) + "</td><td bgcolor='#EBEBEB'>" + Math.round(monthlyPayment) + "</td>\
				<td bgcolor='#EBEBEB'>" + Math.round(paidPrincipal) + "</td><td bgcolor='#EBEBEB'>" + Math.round(paidInterest) + "</td>\
				<td bgcolor='#EBEBEB'>" + Math.round(sumPaidPrincipal) + "</td><td bgcolor='#EBEBEB'>" + Math.round(sumPaidInterest) + "</td>\
				<td bgcolor='#EBEBEB'>" + Math.round(endingBalance) + "</td></tr>");
		}
		beginningBalance = endingBalance;
	}
 	drawGraph();
}

function calculateForGraph(){
	
	beginningBalance = loanAmount;
	sumPaidPrincipal = 0;
	sumPaidInterest = 0;
	
	for (var month = 1; month <= numPayments; month++) {
		paidInterest = effectiveInterestRate * beginningBalance;
		paidPrincipal = monthlyPayment - paidInterest;
		sumPaidPrincipal += paidPrincipal;
		sumPaidInterest += paidInterest;
		endingBalance = beginningBalance - paidPrincipal;
		
		gBeginningBalance.push([month, beginningBalance]);
		gSumPaidPrincipal.push([month, sumPaidPrincipal]);
		gSumPaidInterest.push([month, sumPaidInterest]);
		
		beginningBalance = endingBalance;
	}
	drawGraph();
}

function showMonths(year) {
	$('tr.year' + year).each(function(index) {
		$(this).css('display', '');
		$(this).css('visibility', 'visible');
	});
}

function hideMonths(year) {
	$('tr.year' + year).each(function(i) {
		$(this).css('display', 'none');
		$(this).css('visibility', 'hidden');
	});
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////

jQuery.validator.setDefaults({
	debug: true,
	success: "valid"
});;


$(document).ready(function(){
	// Submit action and empty field validation
	// jQuery Validation plugin detects empty field only when submit button is clicked
	// for the first time, any consequential occurrence will be automatically detected.
	
	$("input").click( function() {
		if ($(this).val() == 0 || $(this).val() == '') $(this).val('');
	});
	
	$(".mc_finalResults").click( function() {
		if ($("#loanForm").validate({
			submitHandler: function(form) {
		 		form.submit();	
			 }
		}).form() == true) {
			$(".remove").each(function() {
			 		$(this).remove();
			 });
			mc_getInputs();
			calculateMortgage();
			calculateForGraph();
			mc_displayResults();
		}
	});
	
	$(".input").click( function() {
		$(".remove").each(function() {
		 		$(this).remove();
		 });
		mc_resetResults();
		resetGraph();
	});
	
	// Validation 
	$("#loanForm input").change(function(){
		$("#loanForm").validate({
			rules : {
				"loanAmount": {
					required: true,
					digits: true,
					min: 1
				},
				
				"interestRate": {
					required: true,
					range: [1, 30]
				},
				
				"mortgageAmortization": {
					required: true,
					digits: true,
					min: 1
				},
				
				"mortgageTerm": {
					required: true,
					digits: true,
					range: [1, 7]
				}
			}
		});
	 });
	
	$("#showGraph").click(function () {
		return toggleGraph();
	});
	
	$("#hideGraph").click(function () {
		return toggleGraph();
	});

	$("#show").live("click", function () {
		$(this).toggle();
		$(this).siblings().toggle();
	});

	$("#hide").live("click", function () {
		$(this).toggle();
		$(this).siblings().toggle();
	});
});

/////////////////////////////////////////////////////////////////////////////////////

$(document).ready(function(){
	
	$(".ac_finalResults").click( function() {
			if ($("#calcForm").validate({
			submitHandler: function(form) {
			form.submit();	
			}
		}).form() == true) {
			getInputs();
			calculateAffordability();
			displayResults();
			recommend();
		}
	});

	// Validation 
	$("#calcForm input").change(function(){
		$("#calcForm").validate({
			rules : {
				"combinedIncome": {
					required: true,
					digits: true,
					min: 1
				},
				"targetHouseValue": {
					required: true,
					digits: true,
					min: 1
				},
				"autoPayments": {
					required: true,
					digits: true
				},

				"ccPayments": {
					required: true,
					digits: true
				},

				"combinedUtilitiesPayments": {
					required: true,
					digits: true
				},

				"mortgageRate": {
					required: true,
					range: [1, 30]
				},

				"downPayment": {
					required: true,
					digits: true
				}
			}
		});
	});

	$("#calcForm .removeButton").live('click', function() {
		$curr = $(this).closest('tr');
		$prev = $curr.prev();
		$curr.remove();
		$prev.remove();
	});


	$("#calcForm .addButton").click(function() {
		$('#extraDebt').append("<tr>\
		<td colspan='3' align='center' ><input type='text' name='textField' class='required' value='Expense Category' size='15'  style='width: 240px; height: 18px; border:1px; border-color: 666; margin: 0px 5px 15px 0px;'/></td></tr>\
		<tr><td align='right' valign='top' class='tabDollars' >$ </td>\
		<td align='left' valign='top' style='padding: 0px 0px 0px 5px;' ><input type='text' name='inputField' class='expenses required digits' value='0' size='8'  style='width: 135px; height: 18px; border:1px; border-color: 666; margin: 0px 5px 15px 0px;'/></td>\
		<td align='left' valign='top' ><input type='button' name='button5' class='removeButton' value='Remove' /></td>\
		</tr>");
	});
});

$(function(){
	$('.back-link').click(function(){
		history.back();
		return false;
	});
});

