jQuery(document).ready( function($){
		/*** Constant ***/
		var EstimateAnnualInsurancePercentage = .0043; /*** Estimate Insurance to 0.43% of Cost ***/
		var EstimatePropertyTaxPercentage = .012; /*** Estimate Tax to 1.2% of Cost ***/
		
		/*** Function ***/
		getPercentage = function(Amount, TotalAmount){
				if(Amount.length > 0 && Amount > 0 && TotalAmount.length > 0 && TotalAmount > 0)
					return "(" +( Math.round( (( Amount / TotalAmount ) * 100) *100 ) / 100 ) + "%)";
				else
					return "";
			};
		calcDownPayment = function (){
			$("#DownPaymentPercentage").html( getPercentage( $("#DownPayment").val(), $("#CostOfHome").val() ) );
		}

		
		calcRecompute = function(){
				calcDownPayment();
				//calcAnnualInsurance();
				//calcPropertyTax();
			};
		
		setNumericOnly = function(){
				/*$("#TermInYears").numeric_only();
				$("#InterestRate").numeric_only();
				$("#CostOfHome").numeric_only();
				$("#DownPayment").numeric_only();*/
			};
			
		getEffectiveInterestRate = function(InterestRate, Compound_Period){
			//((1 + InterestRate/compound_period) ^ (compound_period/periods_per_year))-1
			return ( ( Math.pow( ( 1 + InterestRate/Compound_Period ), ( Compound_Period/12 ) ) ) - 1 );
		}
			
		getPMT = function (InterestRate, MonthsToPay, PrincipalLoan){
				return Math.round((PrincipalLoan * InterestRate / (1 - (Math.pow(1/(1 + InterestRate), MonthsToPay)))) * 100) / 100;
			};
			
		getPMTReverse = function (InterestRate, MonthsToPay, PMT){
				return Math.round(((PMT) /  (InterestRate / (1 - (Math.pow(1/(1 + InterestRate), MonthsToPay))) ) ) * 100) / 100;
			};
			
		getRound = function(OriginalValue,Digits){
				return parseFloat(Math.round( OriginalValue * Digits ) / Digits) ;
			};

		computeMortgage = function(){
				calcRecompute(); /*** Recompute first the input fields before getting the values ***/
				/*** Required Fields **/
				var TermsInMonths = $("#TermInYears").val() * 12;
				var InterestRate = $("#InterestRate").val() / 100;
				var CostOfHome  = $("#CostOfHome").val();
				var DownPayment = $("#DownPayment").val();
				
				var Compound_Period = 2; /*** Interest Compounded Semi Anually ***/
			
				/***********************/
				/***** Computation *****/
				/***********************/
			
				/**** Mortgage ****/

				/*** Mortgage Computation ***/
				var LoanAmount = ( CostOfHome - DownPayment );
				var EffectiveInterestRate = getEffectiveInterestRate( InterestRate, Compound_Period );

				var PrincipalInterest = getPMT( EffectiveInterestRate, TermsInMonths, LoanAmount );
				var TotalPayments = ( PrincipalInterest * TermsInMonths ) ;

				var strLoanAmount = getRound( LoanAmount, 100 ).toFixed(2);
				var strPrincipalInterest = getRound( PrincipalInterest, 100 ).toFixed(2);
				$("#RM_LoanAmount").val( strLoanAmount );
				$("#RM_PrincipalInterest").val( strPrincipalInterest );
				$("#RM_EffectiveInterestRate").val( (EffectiveInterestRate * 100).toFixed(3) );
				$("#RM_TotalPayments").val( getRound( TotalPayments, 100 ).toFixed(2) );
				$("#RM_TotalInterest").val( "" );
				$("#RM_NumberOfPayments").val( TermsInMonths );
				
				$("#results .amortization").html( jQuery("<div class=\"row\"></div>")
					.append(jQuery("<span class=\"number\">&nbsp;</span>"))
					.append(jQuery("<span class=\"payment\">&nbsp;</span>"))
					.append(jQuery("<span class=\"interest\">&nbsp;</span>"))
					.append(jQuery("<span class=\"principal\">&nbsp;</span>"))
					.append(jQuery("<span class=\"balance\">&nbsp;</span>").html( strLoanAmount )));
				
				var RunningBalance = LoanAmount;
				var RunningInterest = PrincipalInterest;
				var RunningPrincipal;
				var strRunningInterest;
				var strRunningPrincipal;
				var TotalInterest = 0;

				for(var x=1;x<=TermsInMonths;x++){
					RunningInterest = getRound(RunningBalance * EffectiveInterestRate, 100 );
					TotalInterest += RunningInterest;
					strPrincipalInterest = (PrincipalInterest <= RunningBalance) ? strPrincipalInterest : getRound( RunningBalance + RunningInterest, 100).toFixed(2) ;
					RunningPrincipal = (PrincipalInterest <= RunningBalance) ? PrincipalInterest - RunningInterest : RunningBalance;
					RunningBalance -= RunningPrincipal;
					strRunningInterest = getRound( RunningInterest, 100 ).toFixed(2);
					strRunningPrincipal = getRound( RunningPrincipal, 100 ).toFixed(2);
					strRunningBalance = getRound( RunningBalance, 100 ).toFixed(2);

					$("#results .amortization").append(jQuery("<div class=\"row\"></div>")
						.append(jQuery("<span class=\"number\"></span>").html( x ))
						.append(jQuery("<span class=\"payment\"></span>").html( strPrincipalInterest ))
						.append(jQuery("<span class=\"interest\"></span>").html( strRunningInterest ))
						.append(jQuery("<span class=\"principal\"></span>").html( strRunningPrincipal ))
						.append(jQuery("<span class=\"balance\"></span>").html( strRunningBalance )) );
				}
				$("#results .amortization").append(jQuery("<div class=\"row\"></div>")
					.append(jQuery("<span class=\"number\">&nbsp;</span>"))
					.append(jQuery("<span class=\"payment\">&nbsp;</span>"))
					.append(jQuery("<span class=\"interest\">&nbsp;</span>"))
					.append(jQuery("<span class=\"principal\">&nbsp;</span>"))
					.append(jQuery("<span class=\"balance\">&nbsp;</span>")) );
				$("#results div.row:odd span").css("background-color","#C3DEEE");
				$("#RM_TotalInterest").val( getRound(TotalInterest, 100 ).toFixed(2) );
			};

		/*** Events Binding ***/
		if( $("#mortgage_form").length>0 ){
			setNumericOnly();
			
				$("#RM_LoanAmount").val( "0.00" );
				$("#RM_PrincipalInterest").val( "0.00" );
				$("#RM_EffectiveInterestRate").val( "0.000" );
				$("#RM_TotalPayments").val( "0.00" );
				$("#RM_TotalInterest").val( "0.00" );
				$("#RM_NumberOfPayments").val( "0" );
			calcRecompute();
			computeMortgage();

			$("#EmailResult").click(function (){
					$("#emailer").show();
					$("#EmailResult").hide();
				});
		
			$("#SendEmailResult").click(function(){
					$("#emailer").hide();
					$("#EmailResult").show();
					
					//getJSON//post
					$.getJSON(
						$("#mortgage_form").attr("action"),
						$("#mortgage_form").serialize(),
						function(data, textStatus){
							if(!data.Status){
								alert(data.Message);
							}else{
								alert(data.Message)
							};
						});

				});
			$("#CalculateNow").click( function (){
					computeMortgage();
					return false;
				});

			$("#DownPayment").keypress( calcDownPayment );
			$("#DownPayment").change( calcDownPayment );
			$("#DownPayment").change( function(){if(this.value.length<=0) this.value=0;} );
			
			$("#CostOfHome").keypress( calcRecompute );
			$("#CostOfHome").change( calcRecompute );
		}
	});
