$(function(){
	$('#mcPrice').val('100000'); // Default Loan Amount
	$('#mcRate').val('6'); // Default Interest Rate
	$('#mcAmort').click(
		function () {
			$('#mCalc').attr('target', '_blank');
			if ( !isNaN($('#mcPrice').val()) || !isNaN($('#mcPrice').val()) ) {
			$('#mCalc input[name=l]').val($('#mcPrice').val());
			$('#mCalc input[name=i]').val($('#mcRate').val());
			$('#mCalc input[name=t]').val($('#mcTerm').val());
			$('#mCalc input[name=pt]').val($('#mcPayTerm').val());
			$('#mCalc input[name=d]').val($('#mcYear').val());
			$('#mCalc').submit(); 
			}else { 
				 alert("There was an error.")
				} 
		});

		
	$("#mcCalculate").click(function(){ 


	// INPUTTED VALUES FROM FORM
	var Loan; // The Loan/Mortgage amount or Initial Principal.
	var interest; // The Annual Interest rate.  Bare in mind Canadian Interest is compounded Semi-Annually so this variable is only a general placeholder.
	var term; // The Amortization Period (Years) the mortgage has been taken out for.  Generally Canadian mortgages do not exceed 25 years.
    var months; // Months to Amortization
	
	// CALCULATED VALUES
	var EAR; // Effective Annual Rate (2 decimals.)  This is the actual rate compounded semi-annually.
	var PMI; // Periodic Monthly Interest calculated based on the interest rate
	var payments; // Calculated Payments.  This is the output of the formula.


	Loan = parseInt($("#mcPrice").val()); 
	interest = parseFloat($("#mcRate").val()) / 100;
	term = parseInt($("#mcTerm").val());
	months = term * 12;

	// PMI = ((1+(interest/2))^2)^(1/12)-1 rounded to 2 Decimal Places
	PMI = (Math.pow(Math.pow((1+(interest/2)),2), (1/12))-1);
	// EFF ((1+PMI)^12)-1
	EAR = (Math.pow((1+PMI),12)-1);
		
				
				
				
	// payments = (Loan * PMI) / (1-(1+PMI)^(-months))
	payments = (Loan*PMI) / (1- ( Math.pow((1+PMI),(-months)) ));



	if(!isNaN(payments)) { 
		$("#mcPayment").val((payments/$('#mcPayTerm').val()).toFixed(2));
		//$('#mcAnnualRate').val((EAR.toFixed(4)*100));
		//$('#mcPMI').val(PMI.toFixed(2));
		//$('#mcAmort').val(months);
		}else { 
			$("#mcPayment").val('Error'); 
			} 
		return false; 
	}); 
	
	$('#mcReset').click(function(){
		$('#mcYear').val('2011');
		$('#mcPrice').val('100000');
		$('#mcRate').val('6');
		$('#mcTerm').val('25');
		$('#mcPayment').val('');
		});

});

