/* #################################################################
    Copyright 2005 BBB Systems, LLC, All rights reserved
################################################################## */

var plusImg = new Image( );
plusImg.src = "/images/plus.gif";
var minusImg = new Image( );
minusImg.src = "/images/minus.gif";

function init( ){
    initInputButtons( );
    initA( );
    initClock( );
    initBlocks( );
}

function initIframe( ){
    window.scroll(0, 0);
}

function initInputButtons( ){
    if(document.getElementsByTagName){
        var inputs = document.getElementsByTagName("INPUT");
        for(var i = 0; i < inputs.length; i++){
            if((inputs[i].type == "submit" || inputs[i].type == "reset" || inputs[i].type == "button") && inputs[i].className == "button"){
                inputs[i].onmouseover = inputOver;
                inputs[i].onmouseout = inputOut;
            }
        }
        var buttons = document.getElementsByTagName("BUTTON");
        for(var i = 0; i < buttons.length; i++){
            if((buttons[i].type == "submit" || buttons[i].type == "reset" || buttons[i].type == "button") && buttons[i].className == "button"){
                buttons[i].onmouseover = inputOver;
                buttons[i].onmouseout = inputOut;
            }
        }
        var uls = document.getElementsByTagName("UL");
        for(var i = 0; i < uls.length; i++){
            if(uls[i].id.match(/tdiv_\d/)){
                var tmp = uls[i].id.replace(/tdiv_/, "");
                tmp = tmp * 100;
                uls[i].style.left = tmp + "px";
            }
        }
    }
}

function initBlocks( ){
    if(document.getElementsByTagName){
        SetCookie('domSupport','1');
        var imgs = document.getElementsByTagName("img");
        var bcnt = 0;
        for(var i = 0; i < imgs.length; i++){
            var img = imgs[i];
            if(img.src.match(/\/images\/minus\.gif/) || img.src.match(/\/images\/plus.gif/) || img.src.match(/\/images\/blank.gif/)){
                //get the parent
                var iparent = img.parentNode;
                while(iparent){
                    if(iparent.tagName == 'div' || iparent.tagName == 'DIV'){
                        break;
                    }
                    iparent = iparent.parentNode;
                }
                if(!iparent){ continue };
                var iblock = iparent.nextSibling;
                while(iblock){
                    if(iblock.tagName == 'div' || iblock.tagName == 'DIV'){
                        break;
                    }
                    iblock = iblock.nextSibling;
                }
                if(!iblock){ continue; }
                if(iblock.className != 'blockA'){ continue; }

                var atags = iblock.getElementsByTagName('a');
                var doBlock = false;
                for(var j = 0; j < atags.length; j++){
                    var a = atags[j];
                    if(window.location == a.href){
                        doBlock = true;
                    }
                }
                if(bcnt == 0 || doBlock){
                    iblock.style.display = "block";
                    bcnt++;
                }
                else{
                    iblock.style.display = "none";
                }

                if(iblock.style.display == "none"){
                    img.src = plusImg.src;
                }
                else{
                    img.src = minusImg.src;
                }

                iparent.onclick = function( ){
                    var iblock = this.nextSibling;
                    while(iblock.tagName != 'div' && iblock.tagName != 'DIV'){
                        iblock = iblock.nextSibling;
                    }

                    if(iblock.style.display == "none" || iblock.style.display == "NONE"){
                        iblock.style.display = 'block';
                        this.getElementsByTagName('img')[0].src = img.src = minusImg.src;
                    }
                    else{
                        iblock.style.display = 'none';
                        this.getElementsByTagName('img')[0].src = img.src = plusImg.src;
                    }
                }

                iparent.onmouseover = function( ){
                    this.style.textDecoration = 'underline';
                }

                iparent.onmouseout = function( ){
                    this.style.textDecoration = 'none';
                }

                if(document.all){
                    //the ie way
                    iparent.style.cursor = 'hand';
                }
                else{
                    //every other way
                    iparent.style.cursor = 'pointer';
                }
            }
        }
    }
    else{

    }
}

function initA( ){
    var closedImg = "http://armlsidx.vstone.com/images/functions/expandminus.gif";			//image used for collapsed item in callExpand()
    var expandImg = "http://armlsidx.vstone.com/images/functions/expandplus.gif";			//image used for expanded item in callExpand()

    if(document.getElementsByTagName){
        var as = document.getElementsByTagName("A");
        for(var i = 0; i < as.length; i++){
            if(!as[i].href.match(/(ramsey)/) && !as[i].href.match(/(sonoran)/) && !as[i].href.match(/(lukeafb)/)){
                as[i].target = "_blank";
            }

            //This section is to interface with the mls scripts expand feature.
            //The original only worked in ie, this was a complete re-write of the
            //function that they wrote and works with all modern browsers using
            //standards based javascript features instead of proprietary features.
            if(as[i].className=="expand"){
                as[i].onclick = function( ){
                    if(window.event){
                        if(window.event.returnValue){
                            window.event.returnValue = false;
                        }
                    }

                    var pnode = this;
                    //can't use pnode.tagName.toLowerCase: tagName may be undefined
                    //let's just hope they don't "upgrade" their HTML
                    while(pnode.tagName != 'tr' && pnode.tagName != 'TR'){
                        pnode = pnode.parentNode;
                    }
                    pnode = pnode.nextSibling;
                    while(pnode.tagName != 'tr' && pnode.tagName != 'TR'){
                        pnode = pnode.nextSibling;
                    }
                    pnode = pnode.firstChild;
                    while(pnode.tagName != 'td' && pnode.tagName != 'TD'){
                        pnode = pnode.nextSibling;
                    }
                    pnode = pnode.firstChild;
                    while(pnode.tagName != 'div' && pnode.tagName != 'DIV'){
                        pnode = pnode.nextSibling;
                    }

                    var oImg = this.getElementsByTagName("img")[0];

                    if(pnode.style.display == "none") {
                        pnode.style.display = "block";
                        if (oImg != null) oImg.src = closedImg;
                    }
                    else {
                        pnode.style.display = "none";
                        if (oImg != null) oImg.src = expandImg;
                    }
                }
            }
        }
    }
}

function inputOver(e){
    this.className = "buttonOver";
}

function inputOut(e){
    this.className = "button";
}

function imageSelectPopUp(pwinvar){
    imgSelectPopUp = window.open("./imageselect.php?mode=1&fieldID=" + pwinvar, "ImageSelector", "width=780,height=480, scrollbars=0, status=no,toolbar=no,resizable=no");
    imgSelectPopUp.focus( );
}

function openUploader( ){
    var imgSelectPopUp = window.open("./imageselect.php", "ImageSelector", "width=780,height=480, scrollbars=0, status=no,toolbar=no,resizable=no");
    imgSelectPopUp.focus( );

    return false;
}

function openFUploader( ){
    var imgSelectPopUp = window.open("./fileselect.php", "FileSelector", "width=780,height=480, scrollbars=0, status=no,toolbar=no,resizable=no");
    imgSelectPopUp.focus( );

    if(document.all){
        window.event.cancelBubble = true;
    }
    else{
        e.stopPropagation( );
        e.preventDefault( );
    }
    return false;
}

//drop down menus ##################################################
var CurMenu = null; var isDropped = false; var isHideCheck = false;
var subCurMenu = null; var subIsDropped = false; var subIsHideCheck = false;
function pageON(index){ if(document.getElementById){ show("tdiv_" + index, index); } }
function pageOFF(index){ if(document.getElementById){ if(!isHideCheck) hideMenu( ); } }
function show(menuID, ind){ if(CurMenu){ CurMenu.style.visibility = "hidden"; } var menu = document.getElementById(menuID); menu.style.visibility = "visible"; isDropped = true; CurMenu = menu; }
function hideMenu( ){ if(CurMenu){ isDropped = false; isHideCheck = true; setTimeout('checkDropped( );', 500); isHideCheck = false; } }
function checkDropped( ){ if(!isDropped) CurMenu.style.visibility = "hidden"; }
//############################################################

function printView(plink) {
    var plink2 = "/print/p/" + plink;
    window.open(plink2, "ShoppingList", "width=620,height=400,status=yes,toolbar=no,resizable=yes,raised=yes,scrollbars=yes");
}

function printPage(buttonID) {
    var printButton = document.getElementById(buttonID);
    printButton.style.visibility = "hidden";
    window.print();
    window.close();
}

function checkShippingInfo() {
	var check_box = document.form.sSameAsBilling;
	if (check_box.checked) {
		document.form.sStreet1.disabled = true;
		document.form.sStreet2.disabled = true;
		document.form.sCity.disabled = true;
		document.form.sState.disabled = true;
		document.form.sZIP.disabled = true;
		document.form.sStreet1.style.backgroundColor = "#BBBBBB";
		document.form.sStreet2.style.backgroundColor = "#BBBBBB";
		document.form.sCity.style.backgroundColor = "#BBBBBB";
		document.form.sState.style.backgroundColor = "#BBBBBB";
		document.form.sZIP.style.backgroundColor = "#BBBBBB";
	}
	else {
		document.form.sStreet1.disabled = false;
		document.form.sStreet2.disabled = false;
		document.form.sCity.disabled = false;
		document.form.sState.disabled = false;
		document.form.sZIP.disabled = false;
		document.form.sStreet1.style.backgroundColor = "";
		document.form.sStreet2.style.backgroundColor = "";
		document.form.sCity.style.backgroundColor = "";
		document.form.sState.style.backgroundColor = "";
		document.form.sZIP.style.backgroundColor = "";
    }
}

function SetCookie(cookieName,cookieValue){
    var dateNow = new Date( );
    var expire = new Date();
    expire.setTime(dateNow.getTime() + 3600000);
    document.cookie = cookieName + "=" + escape(cookieValue) + ";expires=" + expire.toGMTString() + ";path=/";
}

//###################################################################

/**
 * 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);
}

