/*************************************
DECLARE GLOBAL VARIABLES
*************************************/

//Browser settings
var browser;
var version;
var OS;

//Temp variables
var prodNameIn='';
var prodRateIn='';
var prodAprIn='';

//Lowest Rate
var lowestRateProdName='';
var lowestRate='';
var lowestRateApr='';

//Lowest fixed rate
var lowestFixedRateName='';
var lowestFixedRate='';
var lowestFixedRateApr='';

//Location of the data file
var dataFile = '/mortgages/data/hrbmc_rates.xml';

var xml_doc;

/*************************************
RATE APR TABLE VARIABLES
*************************************/
var productRow0;
var rateRow0;
var aprRow0;

var productRow1;
var rateRow1;
var aprRow1;

var productRow2;
var rateRow2;
var aprRow2;

var productRow3;
var rateRow3;
var aprRow3;


/*************************************
This function added for MOO to Scriptaculous changes.
*************************************/


function addEvent( obj, type, fn ) {
  if ( obj.attachEvent ) {
   obj['e'+type+fn] = fn;
   obj[type+fn] = function(){obj['e'+type+fn]( window.event );}
   obj.attachEvent( 'on'+type, obj[type+fn] );
 } else
    obj.addEventListener( type, fn, false );
}
function removeEvent( obj, type, fn ) {
 if ( obj.detachEvent ) {
  obj.detachEvent( 'on'+type, obj[type+fn] );
  obj[type+fn] = null;
 } else
  obj.removeEventListener( type, fn, false );
}


/*************************************
This function loads the file.
*************************************/
function importXMLRateTable()
{   
    //alert("importXMLRateTable(): browser == '"+browser+"'");
    
    if(browser=="Explorer")
    {
        //This method only works with browser version greater than 5
        if(version > 5)
        {
             var ie = (typeof window.ActiveXObject != 'undefined');
             if (ie)
             {
                 xml_doc = new ActiveXObject("Microsoft.XMLDOM");
                 xml_doc.onreadystatechange = function()
                 {
                    if (xml_doc.readyState == 4) setTimeout(readFileRatesTablePageIE,0)
                 }
                 xml_doc.load(dataFile);
             }
            }
            else
            {
                alert("This version of Internet Explorer, version " + version + ", is currently not supported at this time. Please try again later.");
            }
        }
        else if(browser=="Firefox" || browser=="Mozilla")
        {   
            var moz = (typeof document.implementation != 'undefined') && (typeof document.implementation.createDocument != 'undefined');
                //alert("importXMLRateTable(): moz == '"+moz+"'.  true only if (typeof document.implementation != 'undefined')==TRUE:'"+(typeof document.implementation != 'undefined')+"' and (typeof document.implementation.createDocument != 'undefined')==TRUE:'"+(typeof document.implementation.createDocument != 'undefined')+"'");
        if (moz)
        {
            xml_doc = document.implementation.createDocument("", "", null);
            xml_doc.onload = readFileRatesTablePageMoz;
            xml_doc.load(dataFile);
        }
        //else
        //    {
        //        alert("importXMLRateTable(): this else added by greg");
        //    }
    }else if(browser=="Safari"){
        //alert("The " + browser + " browser is not supported at this time. Please try again later.");
        return;
    }else if(browser=="OmniWeb"){
        //alert("The " + browser + " browser is not supported at this time. Please try again later.");
        return;
    }else if(browser=="Opera"){
        //alert("The " + browser + " browser is not supported at this time. Please try again later.");
        return;
    }else if(browser=="iCab"){
        //alert("The " + browser + " browser is not supported at this time. Please try again later.");
        return;
    }else if(browser=="Konqueror"){
        //alert("The " + browser + " browser is not supported at this time. Please try again later.");
        return;
    }else if(browser=="Camino"){
        //alert("The " + browser + " browser is not supported at this time. Please try again later.");
        return;
    }else if(browser=="Netscape"){
        //alert("The " + browser + " browser is not supported at this time. Please try again later.");
        return;
    }else{
        //alert("This browser is not supported at this time. Please try again later.");
        return;
    }
}

function calculateCashBack(){
    //Display rate and apr
    setRateAprInfo('calcCashRate', 'calcCashApr', lowestRate, lowestRateApr);
    

    //Get inputs
    var currPropValueInputValue = document.getElementById("propValId").value;
    var amtOwedOnPropInputValue = document.getElementById("amtValId").value;

    currPropValueInputValue = currPropValueInputValue.toString().replace(/\$|\,/g,''); 
    amtOwedOnPropInputValue = amtOwedOnPropInputValue.toString().replace(/\$|\,/g,'');  
    
    currPropValueInputValue = currPropValueInputValue.toString().replace(/[^0-9]+/g,''); 
    amtOwedOnPropInputValue = amtOwedOnPropInputValue.toString().replace(/[^0-9]+/g,'');
    

    var currPropValueInput = Number(currPropValueInputValue);
    var amtOwedOnPropInput = Number(amtOwedOnPropInputValue);

    //Convert and validate inputs
    var currPropValue=0.0;
    var amtOwedOnProp=0.0;
    if(isNaN(currPropValueInput)){
        reset();
        return
    }else{
       currPropValue  = Number(currPropValueInput);
    }
    if(isNaN(amtOwedOnPropInput)){
        reset();
        alert('The amount owned on the property must be entered as a number. Please re-enter amount.');
        return
    }else{
       amtOwedOnProp = Number(amtOwedOnPropInput);
    }

    //Calculate
    var cashOut = currPropValue - amtOwedOnProp;
    if(cashOut < 0){
       cashOut = 0;
    }
    var loanAmt = amtOwedOnProp + cashOut;
    var monthlyPayment = getMonthlyPayment(loanAmt, lowestRate, lowestRateProdName);

    //Output calculation
    var moz = (typeof document.implementation != 'undefined') && (typeof document.implementation.createDocument != 'undefined');
    var ie = (typeof window.ActiveXObject != 'undefined')
    if (moz){
        document.getElementById("monthlyPayment").firstChild.nodeValue = formatRemoveCents(formatCurrency(monthlyPayment));
        document.getElementById("cashBack").firstChild.nodeValue = formatRemoveCents(formatCurrency(cashOut));
    }else if (ie){
        document.getElementById("monthlyPayment").innerText = formatRemoveCents(formatCurrency(monthlyPayment));
        document.getElementById("cashBack").innerText = formatRemoveCents(formatCurrency(cashOut));
    }
}

function calcLowerMonthlyPayment(){
    //Display rate and apr
    setRateAprInfo('calcLowerMthlyRate', 'calcLowerMthlyApr', lowestRate, lowestRateApr);
    //Get inputs
    
    var refinanceLoanAmtValue = document.getElementById("refinanceLoanAmtId").value;
    var currMnthlyPayAmtValue = document.getElementById("currMnthlyPayAmtId").value;    
    
    refinanceLoanAmtValue = refinanceLoanAmtValue.toString().replace(/\$|\,/g,''); 
    currMnthlyPayAmtValue = currMnthlyPayAmtValue.toString().replace(/\$|\,/g,'');
    
    refinanceLoanAmtValue = refinanceLoanAmtValue.toString().replace(/[^0-9]+/g,''); 
    currMnthlyPayAmtValue = currMnthlyPayAmtValue.toString().replace(/[^0-9]+/g,'');        
    
    var refinanceLoanAmtInput = Number(refinanceLoanAmtValue);
        var currMnthlyPayAmtInput = Number(currMnthlyPayAmtValue);
    
    
    //Convert inputs
    var refinanceLoanAmt=0.0;
    var currMnthlyPayAmt=0.0;
    refinanceLoanAmt = Number(refinanceLoanAmtInput);
    currMnthlyPayAmt = Number(currMnthlyPayAmtInput);
    //Calculate
    var monthlyPayment = getMonthlyPayment(refinanceLoanAmt, lowestRate, lowestRateProdName);
    var amtSavingMonthly = currMnthlyPayAmt - monthlyPayment;
    if(amtSavingMonthly < 0){
        amtSavingMonthly = 0;
    }

    //Output calculation
    var moz = (typeof document.implementation != 'undefined') && (typeof document.implementation.createDocument != 'undefined');
    var ie = (typeof window.ActiveXObject != 'undefined')
    if (moz){
        document.getElementById("monthlyPaymentToLower").firstChild.nodeValue = formatRemoveCents(formatCurrency(monthlyPayment));
        document.getElementById("amtSavingMonthly").firstChild.nodeValue = formatRemoveCents(formatCurrency(amtSavingMonthly));
    }else if (ie){
        document.getElementById("monthlyPaymentToLower").innerText = formatRemoveCents(formatCurrency(monthlyPayment));
        document.getElementById("amtSavingMonthly").innerText = formatRemoveCents(formatCurrency(amtSavingMonthly)); 
    }
}

function calcFixedRate(){
    setRateAprInfo('calcFixedRate', 'calcFixedApr', lowestFixedRate, lowestFixedRateApr);


    var refinToFixLoanAmtInputValue  = document.getElementById("refinanceToFixLoanAmtId").value;
    refinToFixLoanAmtInputValue      = refinToFixLoanAmtInputValue.toString().replace(/\$|\,/g,''); 
    refinToFixLoanAmtInputValue      = refinToFixLoanAmtInputValue.toString().replace(/[^0-9]+/g,'');
    
    //Get inputs
    var refinToFixLoanAmtInput = Number(refinToFixLoanAmtInputValue);

    //Convert inputs
    var refinanceFixLoanAmt=0.0;
    refinanceFixLoanAmt = Number(refinToFixLoanAmtInput);

    //Calculate
    var monthlyPayment = getFixedMonthlyPayment(refinanceFixLoanAmt, lowestFixedRate, lowestFixedRateName);

    //Output calculation
    var moz = (typeof document.implementation != 'undefined') && (typeof document.implementation.createDocument != 'undefined');
    var ie = (typeof window.ActiveXObject != 'undefined')

    if (moz){
        document.getElementById("monthlyPaymentForFixed").firstChild.nodeValue = formatRemoveCents(formatCurrency(monthlyPayment));
    }else if (ie){
        document.getElementById("monthlyPaymentForFixed").innerText = formatRemoveCents(formatCurrency(monthlyPayment));
    }
}

function setRateAprInfo(rateField, aprField, rate, apr){
    var moz = (typeof document.implementation != 'undefined') && (typeof document.implementation.createDocument != 'undefined');
    var ie = (typeof window.ActiveXObject != 'undefined')

    importXMLRateTable();

    if (moz){
        document.getElementById(rateField).firstChild.nodeValue = rate;
        document.getElementById(aprField).firstChild.nodeValue = apr;
    }else if (ie){
        document.getElementById(rateField).innerText = rate;
        document.getElementById(aprField).innerText = apr;
    }
}



/*************************************
These functions read and output the mortgage home page.
*************************************/

//Rates Table in Navigation pane
function readFileRatesTablePageIE(){
    readFileIE();
    outputRateTableIE();
}
function readFileRatesTablePageMoz(){
    readFileMoz();
    outputRateTableMoz();
}

//Rates Table in Navigation pane
function readFileMortgageHomePageIE(){
    readFileIE();
}

function readFileMortgageHomePageMoz(){
    readFileMoz();
}

/*******************************************************************************
                                INPUT FUNCTIONS
********************************************************************************/

/*************************************
MOZILLA - EXTRACT NODE INFORMATION
*************************************/

function readFileMoz()
{
    try
    {
        node_list = xml_doc.getElementsByTagName("PRODUCT_RATE");

        for (i = 0; i <= node_list.length-1; i++){
        prodNameIn = node_list[i].childNodes[1].childNodes[0].nodeValue;
        prodRateIn = node_list[i].childNodes[3].childNodes[0].nodeValue;
        prodAprIn = node_list[i].childNodes[5].childNodes[0].nodeValue;

        //Lowest overall rate
        if(lowestRate==''){
                lowestRate=prodRateIn;
                lowestRateApr=prodAprIn;
                lowestRateProdName=prodNameIn;
            }else if(lowestRate!='' && lowestRate>prodRateIn){
                lowestRate=prodRateIn;
                lowestRateApr=prodAprIn;
                lowestRateProdName=prodNameIn;
            }

            //Lowest overall fixed rate
            if(lowestFixedRate=='' && (prodNameIn.toLowerCase()).indexOf('fix') != -1){
               lowestFixedRateName=prodNameIn;
               lowestFixedRate=prodRateIn;
               lowestFixedRateApr=prodAprIn;
            }else if(lowestFixedRate !='' && lowestFixedRate>prodRateIn && (prodNameIn.toLowerCase()).indexOf('fix') != -1){
               lowestFixedRateName=prodNameIn;
               lowestFixedRate=prodRateIn;
               lowestFixedRateApr=prodAprIn;
            }

            if(i==0){
                productRow0 = node_list[i].childNodes[1].childNodes[0].nodeValue;
            rateRow0 = node_list[i].childNodes[3].childNodes[0].nodeValue;
            aprRow0 = node_list[i].childNodes[5].childNodes[0].nodeValue;
            }else if(i==1){
            productRow1 = node_list[i].childNodes[1].childNodes[0].nodeValue;
            rateRow1 = node_list[i].childNodes[3].childNodes[0].nodeValue;
            aprRow1 = node_list[i].childNodes[5].childNodes[0].nodeValue;
            }else if(i==2){
            productRow2 = node_list[i].childNodes[1].childNodes[0].nodeValue;
            rateRow2 = node_list[i].childNodes[3].childNodes[0].nodeValue;
            aprRow2 = node_list[i].childNodes[5].childNodes[0].nodeValue;
            }else if(i==3){
            productRow3 = node_list[i].childNodes[1].childNodes[0].nodeValue;
            rateRow3 = node_list[i].childNodes[3].childNodes[0].nodeValue;
            aprRow3 = node_list[i].childNodes[5].childNodes[0].nodeValue;
        }
        }
    }
    catch(e)
    {
    }

}

/*************************************
INTERNET EXPLORER - EXTRACT NODE INFORMATION
*************************************/
function readFileIE(){
    node_list = xml_doc.getElementsByTagName("PRODUCT_RATE");
    
    for (i = 0; i <= node_list.length-1; i++){
        prodNameIn = node_list[i].childNodes[0].childNodes[0].nodeValue;
        prodRateIn = node_list[i].childNodes[1].childNodes[0].nodeValue;
        prodAprIn = node_list[i].childNodes[2].childNodes[0].nodeValue;
        //Lowest overall rate
        if(lowestRate==''){
            lowestRate=prodRateIn;
            lowestRateApr=prodAprIn;
            lowestRateProdName=prodNameIn;
        }else if(lowestRate!='' && lowestRate>prodRateIn){
            lowestRate=prodRateIn;
            lowestRateApr=prodAprIn;
            lowestRateProdName=prodNameIn;
        }

        //Lowest overall fixed rate
        if(lowestFixedRate=='' && (prodNameIn.toLowerCase()).indexOf('fix') != -1){
           lowestFixedRateName=prodNameIn;
           lowestFixedRate=prodRateIn;
           lowestFixedRateApr=prodAprIn;
        }else if(lowestFixedRate !='' && lowestFixedRate>prodRateIn && (prodNameIn.toLowerCase()).indexOf('fix') != -1){
           lowestFixedRateName=prodNameIn;
           lowestFixedRate=prodRateIn;
           lowestFixedRateApr=prodAprIn;
        }

        if(i==0){
            productRow0 = node_list[i].childNodes[0].childNodes[0].nodeValue;
            rateRow0 = node_list[i].childNodes[1].childNodes[0].nodeValue;
            aprRow0 = node_list[i].childNodes[2].childNodes[0].nodeValue;
        }else if(i==1){
            productRow1 = node_list[i].childNodes[0].childNodes[0].nodeValue;
            rateRow1 = node_list[i].childNodes[1].childNodes[0].nodeValue;
            aprRow1 = node_list[i].childNodes[2].childNodes[0].nodeValue;
        }else if(i==2){
            productRow2 = node_list[i].childNodes[0].childNodes[0].nodeValue;
            rateRow2 = node_list[i].childNodes[1].childNodes[0].nodeValue;
            aprRow2 = node_list[i].childNodes[2].childNodes[0].nodeValue;
        }
        else if(i==3){
            productRow3 = node_list[i].childNodes[0].childNodes[0].nodeValue;
            rateRow3 = node_list[i].childNodes[1].childNodes[0].nodeValue;
            aprRow3 = node_list[i].childNodes[2].childNodes[0].nodeValue;    
            }
        

    }


}

/*******************************************************************************
                                OUTPUT FUNCTIONS
********************************************************************************/

/*************************************
INTERNET EXPLORER - OUTPUT INFORMATION
*************************************/

function outputRateAprMoz(){
    document.getElementById("rateRow").firstChild.nodeValue = lowestRate;
    document.getElementById("aprRow").firstChild.nodeValue = lowestRateApr;
}


function outputRateTableMoz(){
    try {
        document.getElementById("productRow0").firstChild.nodeValue = productRow0;
        document.getElementById("rateRow0").firstChild.nodeValue = rateRow0;
        document.getElementById("aprRow0").firstChild.nodeValue = aprRow0;
        
        document.getElementById("productRow1").firstChild.nodeValue = productRow1;
        document.getElementById("rateRow1").firstChild.nodeValue = rateRow1;
        document.getElementById("aprRow1").firstChild.nodeValue = aprRow1;
        
        document.getElementById("productRow2").firstChild.nodeValue = productRow2;
        document.getElementById("rateRow2").firstChild.nodeValue = rateRow2;
        document.getElementById("aprRow2").firstChild.nodeValue = aprRow2;
        
        document.getElementById("productRow3").firstChild.nodeValue = productRow3;
        document.getElementById("rateRow3").firstChild.nodeValue = rateRow3;
        document.getElementById("aprRow3").firstChild.nodeValue = aprRow3;
    } catch(e) {
        //alert(e);
    }
}

function outputRateAprIE(){
    document.getElementById("rateRow").innerText = lowestRate;
    document.getElementById("aprRow").innerText = lowestRateApr;
}

function outputRateTableIE(){
    try {
        document.getElementById("productRow0").innerText = productRow0;
        document.getElementById("rateRow0").innerText = rateRow0;
        document.getElementById("aprRow0").innerText = aprRow0;
    
        document.getElementById("productRow1").innerText = productRow1;
        document.getElementById("rateRow1").innerText = rateRow1;
        document.getElementById("aprRow1").innerText = aprRow1;
    
        document.getElementById("productRow2").innerText = productRow2;
        document.getElementById("rateRow2").innerText = rateRow2;
        document.getElementById("aprRow2").innerText = aprRow2;
    
        document.getElementById("productRow3").innerText = productRow3;
        document.getElementById("rateRow3").innerText = rateRow3;
        document.getElementById("aprRow3").innerText = aprRow3;
    } catch(e) {
        //alert(e);
    }
}

function roundNumber(num, dec) {
    var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
    return result;
}

function getMonthlyPayment(loanAmt, rate, rateProd){
    var r = rate/1200;
    var years = parseInt(rateProd);
    var months = 12 * 30;
    return (loanAmt*r*(Math.pow((1+r),months)))/(Math.pow((1+r),months)-1);
}

function getFixedMonthlyPayment(loanAmt, rate, rateProd){
    var r = rate/1200;
    var years = parseInt(rateProd);
    var months = 12 * 15;
    return (loanAmt*r*(Math.pow((1+r),months)))/(Math.pow((1+r),months)-1);
}

function initMortgageHomePage(){
    importXMLHomePage();
}

function formatCurrency(num) {
    var num = num.toString().replace(/\$|\,/g,'');
    if(isNaN(num)){
        num = "0";
    }
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num*100+0.50000000001);
    cents = num%100;
    num = Math.floor(num/100).toString();
    if(cents<10){
        cents = "0" + cents;
    }
    for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
    num = num.substring(0,num.length-(4*i+3))+','+
    num.substring(num.length-(4*i+3));
    return (((sign)?'':'-') + '$' + num + '.' + cents);
}

function showDiv(objectID) {
    var theElementStyle = document.getElementById(objectID);

    if(theElementStyle.style.display == "none"){
        theElementStyle.style.display = "block";
    }else{
        theElementStyle.style.display = "none";
    }
}

function reset(){
    var cashBackCloseImage = document.getElementById('calcCashRestCloseImage');
    var cashBackOpenImage  = document.getElementById('calcCashRestCloseImage');
    var monthlyPayment = document.getElementById('monthlyPayment').innerText = '0';
    var cashBack = document.getElementById('cashBack').innerText = '0';
    cashBackCloseImage.style.display = "block";
    cashBackOpenImage.style.display = "none";
    cashBackCalcSlider.hide();
}

function formatRemoveCents(calcAmt){
     var temp = calcAmt;
     var indexDec =  calcAmt.indexOf('.');
     if(indexDec != -1){
         temp = calcAmt.substr(0, indexDec);
     }
     return temp;
}

function getPathName(){
    var sPath = window.location.pathname;
    return sPath;
}

/*************************************
This function displays the popup when
user selects WV or NM state
*************************************/

function dispPopup(obj){
    if ((obj.value == 32) || (obj.value == 40) || (obj.value == 48)){
        obj.selectedIndex=0;
        newwindow=window.open('/mortgages/popupex.html','tagore','resizable, toolbar=no, location=no, status=no, scrollbars=no, menubar=no, titlebar=no, height=150, width=550, screenX=50, screenY=200, left=350, top=200');
        if (window.focus) {
            newwindow.focus()
        }
    }
}

/*************************************
This function dectects the browser type
*************************************/

var BrowserDetect = {
    init: function () {

        browser = this.searchString(this.dataBrowser) || "An unknown browser";
        version = this.searchVersion(navigator.userAgent)
            || this.searchVersion(navigator.appVersion)
            || "an unknown version";
        OS = this.searchString(this.dataOS) || "an unknown OS";
    },
    searchString: function (data) {
        for (var i=0;i<data.length;i++) {
            var dataString = data[i].string;
            var dataProp = data[i].prop;
            this.versionSearchString = data[i].versionSearch || data[i].identity;
            if (dataString) {
                if (dataString.indexOf(data[i].subString) != -1)
                    return data[i].identity;
            }
            else if (dataProp)
                return data[i].identity;
        }
    },
    searchVersion: function (dataString) {
        var index = dataString.indexOf(this.versionSearchString);
        if (index == -1) return;
        return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
    },
    dataBrowser: [
        {   string: navigator.userAgent,
            subString: "OmniWeb",
            versionSearch: "OmniWeb/",
            identity: "OmniWeb"
        },
        {
            string: navigator.vendor,
            subString: "Apple",
            identity: "Safari"
        },
        {
            prop: window.opera,
            identity: "Opera"
        },
        {
            string: navigator.vendor,
            subString: "iCab",
            identity: "iCab"
        },
        {
            string: navigator.vendor,
            subString: "KDE",
            identity: "Konqueror"
        },
        {
            string: navigator.userAgent,
            subString: "Firefox",
            identity: "Firefox"
        },
        {
            string: navigator.vendor,
            subString: "Camino",
            identity: "Camino"
        },
        {       // for newer Netscapes (6+)
            string: navigator.userAgent,
            subString: "Netscape",
            identity: "Netscape"
        },
        {
            string: navigator.userAgent,
            subString: "MSIE",
            identity: "Explorer",
            versionSearch: "MSIE"
        },
        {
            string: navigator.userAgent,
            subString: "Gecko",
            identity: "Mozilla",
            versionSearch: "rv"
        },
        {       // for older Netscapes (4-)
            string: navigator.userAgent,
            subString: "Mozilla",
            identity: "Netscape",
            versionSearch: "Mozilla"
        }
    ],
    dataOS : [
        {
            string: navigator.platform,
            subString: "Win",
            identity: "Windows"
        },
        {
            string: navigator.platform,
            subString: "Mac",
            identity: "Mac"
        },
        {
            string: navigator.platform,
            subString: "Linux",
            identity: "Linux"
        }
    ]

};