// JavaScript Document
        $(document).ready(function() {
            setCurrentPageTitle("Mortgage Calculators");
            //alert(calculate_simpleamortization(20000,.00625,60));
            $("#monthlyPaymentEstimator .inputField").keyup(function () {       
                $("#txtMonthlyPayment").val(Math.floor(   calculate_simpleamortization($("#txtPrincipal").val(), $("#txtAPR").val()/100, $("#txtYears").val()*12) ));
                $("#monthlyPaymentEstimator .outputField").each(function() {
                    if (  isNaN($(this).val()) || $(this).val()==Infinity  ) {
                        $(this).val("...");
                    }
                });
            });
            $("#PITI .inputField").keyup(function () { 
                var piti = calculate_PITI($("#txtPITILength").val(), $("#txtPITIInterest").val()/100, $("#txtPITIAmount").val(), $("#txtPITIAnnualTax").val(), $("#txtPITIAnnualInsurance").val());
        
                $("#txtPITIPrincipalPlusInterest").val(Math.floor(piti.MonthlyPrincipalPlusInterest));
                $("#txtPITIMonthlyTax").val(Math.floor(piti.MonthlyTax));
                $("#txtPITIMonthlyInsurance").val(Math.floor(piti.MonthlyInsurance));
                $("#txtPITITotalMonthlyPayment").val(Math.floor(piti.TotalMonthlyPayment));
                
                $("#PITI .outputField").each(function() {
                    if (  isNaN($(this).val()) || $(this).val()==Infinity   ) {
                        $(this).val("...");
                    }
                });
            });
        });
        function calculate_simpleamortization(p, r, n) {  //principal, apr (ex: .0625), number of months 
            return Math.pow(1+(r/12),n)*p*(r/12)/(Math.pow(1+(r/12),n)-1);
        }
        function calculate_PITI(years, interest, loanAmount, annualTax, annualInsurance)
        {
            var mi = interest / 12;
            var base = 1;
            var mbase = 1 + mi;
            for (i=0; i<years * 12; i++)
            {
                base = base * mbase
            }
            var monthlyPrincipalPlusInterest = Math.floor(loanAmount * mi / ( 1 - (1/base)))
            var monthlyTax = Math.floor(annualTax / 12)
            var monthlyInsurance = Math.floor(annualInsurance / 12)
            var total = loanAmount * mi / ( 1 - (1/base)) +
            annualTax / 12 + 
            annualInsurance / 12;
            var monthlyPayment = Math.floor(total);
            return {  MonthlyPrincipalPlusInterest: monthlyPrincipalPlusInterest
                   ,MonthlyTax: monthlyTax
                   ,MonthlyInsurance: monthlyInsurance
                   ,TotalMonthlyPayment: monthlyPayment
                 };
        }