//################## Light Calculator ############################
function validateFields( )
{
    fObj = document.getElementById("fm2");

    if(!fObj.amt.value.match(/^(\d*\.?\d+)$/)){
        alert("Amount Must be Numeric");
        return false;
    }
    else if(!fObj.years.value.match(/^(\d*\.?\d+)$/)){
        alert("Years Must be Numeric");
        return false;
    }
    else if(!fObj.rate.value.match(/^(\d*\.?\d+)$/)){
        alert("Rate Must be Numeric");
        return false;
    }

    return true;
}

function mortgagePayments( ){
    if(!validateFields( )){
        return;
    }

    fObj = document.getElementById("fm2");
    var a = fObj.amt.value;
    var r = fObj.rate.value/1200;
    var t = fObj.years.value*12;

    p = (a*(1200*r)*Math.pow((1+r),t))/(1200*(Math.pow((1+r),t)-1));
    fObj.payment.value = Math.round(p*100)/100;
    p = fObj.payment.value;
}

function mortgageAmount( ){
    if(!validateFields( )){
        return;
    }

    fObj = document.getElementById("fm2");
    var r = fObj.rate.value/1200;
    var t = fObj.years.value*12;
    var p = fObj.payment.value;

    a = (p/((1200*r)*Math.pow((1+r),t))*(1200*(Math.pow((1+r),t)-1)));
    fObj.amt.value = Math.round(a*100)/100;
}

function addMLSNum( ){
    var mlsArray = new Array( );
    var mlsHolding = new Array( );
    if(mlsnumbers.match(/\|/)){
        mlsArray = mlsnumbers.split(/\|/);
    }
    var error = "";
    var mlsnumObj = document.getElementById('mlsnum1');
    var mlsnum = mlsnumObj.value;

    var i = 0;
    if(mlsnum.match(/^(\d{7,8})$/)){

        mlsnumbers = "";
        for(i = 0; i < mlsArray.length; i++){
            if(i == 0){
                mlsnumbers += (mlsnum + "|");
                mlsHolding[mlsnum] = true;
            }

            if(i > 40){
                break;//I think this is enough, don't you?
            }

            var v = mlsArray[i];
            if(!mlsHolding[v] && v != "")
                mlsnumbers += (v + "|");

            mlsHolding[v] = true;
        }
        if(i == 0){
            mlsnumbers += (mlsnum + "|");
            mlsHolding[mlsnum] = true;
        }
        alert("Added " + mlsnum + " to your list");
        //alert(mlsnum);
        //alert(mlsnumbers);
    }
    else if(mlsnum != ""){
        alert("MLS# must be between 7 and 8 digits");
    }
}

//################## Large Calculator ############################

//###################################################################

/**
 * Currency
 * @param money1 Floating-point number to convert to currency format
 * @return Converted number as a string.
 *
 * This function will convert the given floating-point numbre to a currency string of the
 * format: xxxxxx.xx
 */
function Currency(money1) {
    var money = new String(money1);
    var decimal = money.indexOf(".",[0]);
    var money = money.substring(0,decimal+3);
    var money1 = parseFloat(money);
    return money;
}

/**
 * LoanPayment
 * @param P  Principle/Total amount being financed
 * @param IR Interest rate expressed as a decimal (10% = 0.10)
 * @param DP Down payment expressed as an amount (NOT a percent)
 * @param M  Term in months of this loan
 *
 * General Formula:
 *
 *       P ( IR /12 )
 *
 *   ---------------------
 *                    -m
 *   (1 - (1 + IR / 12)  )
 */
function LoanPayment(P, IR, DP, M) {
    P = P - DP;

    var interestRate = IR / 12;
    var negmonth = -1 * M;
    var top = P * interestRate;
    var bottom = 1 - (Math.pow(interestRate + 1, negmonth));
    var monthPay = (top / bottom);

    var startmonth = 3;
    var year = 2005;

    var output = '';

    output += ('<div style="margin: 4px;">Monthly payment = <strong>$' + Currency(monthPay) + "</strong></div>");
    output += ('<table border="0" cellpadding="0" cellspacing="0" style="margin: 0px auto;"><tr><td class="cellHeader">Pmt#</td><td class="cellHeader">Interest</td><td class="cellHeader">Principle</td><td class="cellHeader">Balance</td></tr>');

    for(y = 0; y < M; y++) {
        var cClass = 'cellOdd';
        if(y % 2 == 0){
            cClass = 'cell'
        }

        var interest = (P * interestRate);
        if (interest < 0.0) interest = 0.0;
        var principle = (monthPay - interest);
        if (principle < 0.0) principle = 0.0;

        P = P - principle;
        if (P < 0.0) P = 0.0;

        interest = Currency(interest + 0.005);
        principle = Currency(principle + 0.005);

        output += ('<tr><td class="' + cClass + '">'  + (y+1) + "</td>");
        output += ('<td width="125" class="' + cClass + '">' + '$' + interest + '</td><td width="125" class="' + cClass + '">' + '$' + principle);
        output += ('</td><td class="' + cClass + '">' + "$" + Currency(P) + "</td></tr>");
        startmonth++;
    }

    output += ("</table>");
    return output;
}

function printLoanForm( ){
    if(!document.getElementsByTagName){
        document.write('Your web browser does not support the technology to use this utility');
        return;
    }
    document.write('<div style="text-align: center;"><table border="0" cellpadding="0" cellspacing="0" style="margin: 0px auto; width: 400px;">');
    document.write('<tr><td class="cellHeader" colspan="2">Fill out the form below to calculate payments</td></tr>');
    document.write('<tr><td class="cell">Principle/Total</td><td class="cell"><input type="text" id="principle" value="100000" /></td></tr>');
    document.write('<tr><td class="cellOdd">Interest Rate</td><td class="cellOdd"><input type="text" id="interestRate" value="7.5" /></td></tr>');
    document.write('<tr><td class="cell">Down Payment</td><td class="cell"><input type="text" id="downPayment" value="0" /></td></tr>');
    document.write('<tr><td class="cellOdd">Number of Months</td><td class="cellOdd"><input type="text" id="numberMonths" value="360" /></td></tr>');
    document.write('<tr><td class="cell">&nbsp;</td><td class="cell"><input type="submit" class="button" name="submit" value="Calculate" onclick="updateLoanOutput( )" /></td></tr>');
    document.write('</table></div>');
    document.write('<div style="font-size: 9px; font-weight: bold; text-align: center;">*This calculator is for approximating monthly payments and schedules.</div>');
    document.write('<div>&nbsp;</div>');
    document.write('<div id="amortOutput" style="text-align: center;">&nbsp;</div>');
}

function updateLoanOutput( ){
    var principle = parseFloat(document.getElementById('principle').value.replace(/[\,\$]/, ''));
    var interestRate = parseFloat(document.getElementById('interestRate').value.replace(/[\,\$]/, ''));
    var downPayment = parseFloat(document.getElementById('downPayment').value.replace(/[\,\$]/, ''));
    var numberMonths = parseFloat(document.getElementById('numberMonths').value.replace(/[\,\$]/, ''));
    var amortOutput = document.getElementById('amortOutput');

    if(isNaN(principle)){alert('Principle must be a number'); return;}
    if(isNaN(interestRate)){ alert('Interest Rate must be a number'); return;}
    if(isNaN(downPayment)){ alert('Down Payment must be a number'); return;}
    if(isNaN(numberMonths)){ alert('Number of Months must be a number'); return;}

    if(interestRate > 1){
        interestRate = interestRate / 100;
    }

    amortOutput.innerHTML = LoanPayment(principle, interestRate, downPayment, numberMonths);
}

