﻿/*
This file is Copyright (c) 2010 Bankrate, Inc.
No part of this file may be modified in any way without expressed written permission from an authorized representative from Bankrate Inc.
*/

var BRMmortgageRateTable = {
    StaticServiceURL: "http://partnerservices.bankrate.com/channels/partners/rates/mortgages/",
    StaticLoanLimitServiceURL: "http://partnerservices.bankrate.com/channels/partners/rates/loanlimit/",
    CheckForIE: false,
    oRow: null,
    RowCount: 1,
    States: null,
    Cities: null,
    Partner: '',
    Key: '',
    UpdateCityAndState: false,
    GeoTargetedState: null,
    GeoTargetedCity: null,
    JumboThreshold: 9999999999,
    DefaultZipOverride: '90033',
    LoanAmount: 165000,
    ReportSuite: null,
    Market: 0,
    widgetWidth: '800',
    widgetHeight: '800',
    ZipCode: '',
    CallUsingZip: true,
    MtgDefaultProd: '1',
    loadTime: true,
    ieVersion: '',
    is_chrome: false,
    ServiceStatus: false,
    WidgetType: false,
    MtgNoRecord: false,

    Init: function () {
        if (typeof (BRMmortgageRateTableVars) != 'undefined' && BRMmortgageRateTableVars != null) {

            var Defaults = BRMmortgageRateTableVars;

            if (typeof (Defaults.Partner) != "undefined" && Defaults.Partner != null && typeof (Defaults.Key) != "undefined" && Defaults.Key != null) {
                this.Partner = Defaults.Partner;
                this.Key = Defaults.Key;
            }

            if (typeof (Defaults.LoanAmount) != "undefined" && Defaults.LoanAmount != null && Defaults.LoanAmount != '') {
                if (!isNaN(Defaults.LoanAmount))
                    this.LoanAmount = parseFloat(this.EnforceProperLoanFormat(Defaults.LoanAmount, false));
            }

            if (typeof (Defaults.ReportSuite) != "undefined" && Defaults.ReportSuite != null && Defaults.ReportSuite != '') {
                this.ReportSuite = Defaults.ReportSuite;
            }

            if (typeof (Defaults.ZipCode) != "undefined" && Defaults.ZipCode != null) {
                if (Defaults.ZipCode != "") {
                    if (this.ValidateZip(Defaults.ZipCode)) {
                        this.ZipCode = Defaults.ZipCode;
                    }
                }
            }

            if (typeof (Defaults.Width) != "undefined" && Defaults.Width != null) {
                if (!isNaN(Defaults.Width.replace('px', '')) && Defaults.Width.replace('px', '') != '') {
                    if (parseInt(Defaults.Width.replace('px', '')) < 470)
                        this.widgetWidth = '470';
                    else if (parseInt(Defaults.Width.replace('px', '')) > 980)
                        this.widgetWidth = '980';
                    else
                        this.widgetWidth = Defaults.Width.replace('px', '');
                }
            }

            if (typeof (Defaults.Height) != "undefined" && Defaults.Height != null) {
                if (!isNaN(Defaults.Height.replace('px', '')) && Defaults.Height.replace('px', '') != '') {
                    if (parseInt(Defaults.Height.replace('px', '')) < 650)
                        this.widgetHeight = '650';
                    else if (parseInt(Defaults.Height.replace('px', '')) > 2000)
                        this.widgetHeight = '2000';
                    else
                        this.widgetHeight = Defaults.Height.replace('px', '');
                }
            }

            if (typeof (Defaults.Product) != "undefined" && Defaults.Product != null) {
                this.MtgDefaultProd = Defaults.Product;
            }
        } else {
            // If no rate table variables are available, assume this is the affiliate center
            try {
                var RateTableValues = WidgetsCommon.GetPIDfromCookie();
                RateTableValues = RateTableValues.split(',');

                this.Partner = RateTableValues[0].substr(2);
                this.Key = RateTableValues[1];
                BRMmortgageRateTable.WidgetType = true;
            } catch (e) {

            }
        }

        var ie = (typeof window.ActiveXObject != 'undefined');
        if (ie) {
            this.CheckForIE = true;
        }

        var match = navigator.userAgent.match('MSIE (.)');
        this.ieVersion = match && match.length > 1 ? match[1] : 'unknown';

        this.is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;

        this.PopulateCities();
        this.PopulateStates();
        this.CreateHTMLwrap();
        document.getElementById('productsDll').selectedIndex = 0;
        document.getElementById('JumboProductsDll').selectedIndex = 0;
        document.getElementById('mortgageLoanAmountTextBox').value = this.LoanAmount;

        this.SetMtgDefaultProduct(this.MtgDefaultProd);

        this.SetStateControls('StateSelector');

        this.FetchRss(true);
    },

    SetMtgDefaultProduct: function (prodVal) {
        var prodSelectedIndex = '';
        var mtgValueNotFound = true;
        for (var i = 0; i < document.getElementById('productsDll').length; i++) {
            if (document.getElementById('productsDll')[i].value == prodVal) {
                document.getElementById('productsDll').selectedIndex = i;
                prodSelectedIndex = i;
                document.getElementById("liProducts").style.display = "block";
                document.getElementById("liJumboProducts").style.display = "none";
                mtgValueNotFound = false;
            }
        }
        if (prodSelectedIndex == '') {
            for (var i = 0; i < document.getElementById('JumboProductsDll').length; i++) {
                if (document.getElementById('JumboProductsDll')[i].value == prodVal) {
                    document.getElementById('JumboProductsDll').selectedIndex = i;
                    document.getElementById("liProducts").style.display = "none";
                    document.getElementById("liJumboProducts").style.display = "block";
                    mtgValueNotFound = false;
                }
            }
        }
        if (mtgValueNotFound) {
            document.getElementById('productsDll').selectedIndex = 0;
            document.getElementById("liProducts").style.display = "block";
            document.getElementById("liJumboProducts").style.display = "none";
        }
    },

    ValidateZip: function (zipValue) {
        zipValue = zipValue.replace(" ", "");
        if (isNaN(zipValue)) {
            return false;
        }
        for (i = 0; i < zipValue.length; i++) {
            var c = zipValue.charAt(i);
            if (c == "-" || ((c < "0") || (c > "9"))) {
                return false;
            }
        }
        if (zipValue != "") {
            if (zipValue.length == 5) {
                return true;
            }
            else {
                return false;
            }
        }
        else {
            return true;
        }
    },

    MtgServiceDownAdjustments: function () {
        if (this.MtgNoRecord) {
            document.getElementById('mrtgResize').style.width = this.widgetWidth + 'px';
            document.getElementById('mrtgResize').style.height = this.widgetHeight + 'px';
        }

        if (this.ieVersion == '7') {
            if (parseInt(this.widgetWidth) < 673) {
                if (parseInt(this.widgetWidth) < 606) {
                    document.getElementById('liProducts').style.paddingTop = "10px";
                    document.getElementById('liJumboProducts').style.paddingTop = "10px";
                    document.getElementById('mtgSearchBtn').style.marginTop = "28px";
                    document.getElementById('mrtgResizeHeight').style.height = (parseInt(this.widgetHeight) - 310);
                }
                else {
                    document.getElementById('liProducts').style.paddingTop = "0px";
                    document.getElementById('liJumboProducts').style.paddingTop = "0px";
                    document.getElementById('mtgSearchBtn').style.marginTop = "18px";
                    document.getElementById('mrtgResizeHeight').style.height = (parseInt(this.widgetHeight) - 300);
                }
            }
            else {
                document.getElementById('liProducts').style.paddingTop = "0px";
                document.getElementById('liJumboProducts').style.paddingTop = "0px";
                document.getElementById('mtgSearchBtn').style.marginTop = "18px";
                document.getElementById('mrtgResizeHeight').style.height = (parseInt(this.widgetHeight) - 270) + 'px';
            }
        }
        else {
            if (parseInt(this.widgetWidth) < 665)
                document.getElementById('mrtgResizeHeight').style.height = (parseInt(this.widgetHeight) - 250) + 'px';
            else
                document.getElementById('mrtgResizeHeight').style.height = (parseInt(this.widgetHeight) - 200) + 'px';
        }

    },

    SetDynamicAdjustments: function () {

        var dynamicSliderInput = document.getElementById("rateTableDynamicWidth");
        if (dynamicSliderInput != null) {
            this.widgetWidth = dynamicSliderInput.value.replace('px', '');
        }

        // check if we are in the affiliate center:
        var dynamicHeightSliderInput = document.getElementById("rateTableDynamicHeight");
        if (dynamicHeightSliderInput != null) {
            this.widgetHeight = dynamicHeightSliderInput.value.replace('px', '');
        }
        if (this.MtgNoRecord) {
            this.MtgServiceDownAdjustments();
        }
        else {
            document.getElementById('liProducts').style.paddingTop = "0px";
            document.getElementById('liJumboProducts').style.paddingTop = "0px";
            document.getElementById('mtgSearchBtn').style.marginTop = "18px";
            var mrtgWidgetHeight = 0;
            if (this.ieVersion == '7') {
                if (parseInt(this.widgetWidth) < 561) {
                    if (BRMmortgageRateTable.WidgetType) {
                        mrtgWidgetHeight = parseInt(this.widgetHeight) - 481;
                    }
                    else {
                        mrtgWidgetHeight = parseInt(this.widgetHeight) - 483;
                    }
                }
                else if (parseInt(this.widgetWidth) < 567 && parseInt(this.widgetWidth) >= 561) {
                    if (BRMmortgageRateTable.WidgetType) {
                        mrtgWidgetHeight = parseInt(this.widgetHeight) - 468;
                    }
                    else {
                        mrtgWidgetHeight = parseInt(this.widgetHeight) - 470;
                    }
                }
                else if (parseInt(this.widgetWidth) < 597 && parseInt(this.widgetWidth) >= 567) {
                    document.getElementById('liProducts').style.paddingTop = "10px";
                    document.getElementById('liJumboProducts').style.paddingTop = "10px";
                    document.getElementById('mtgSearchBtn').style.marginTop = "28px";
                    if (BRMmortgageRateTable.WidgetType) {
                        mrtgWidgetHeight = parseInt(this.widgetHeight) - 464;
                    }
                    else {
                        mrtgWidgetHeight = parseInt(this.widgetHeight) - 465;
                    }
                }
                else if (parseInt(this.widgetWidth) < 606 && parseInt(this.widgetWidth) >= 597) {
                    document.getElementById('liProducts').style.paddingTop = "10px";
                    document.getElementById('liJumboProducts').style.paddingTop = "10px";
                    document.getElementById('mtgSearchBtn').style.marginTop = "28px";
                    if (BRMmortgageRateTable.WidgetType) {
                        mrtgWidgetHeight = parseInt(this.widgetHeight) - 450;
                    }
                    else {
                        mrtgWidgetHeight = parseInt(this.widgetHeight) - 453;
                    }

                }
                else if (parseInt(this.widgetWidth) < 635 && parseInt(this.widgetWidth) >= 606) {
                    if (BRMmortgageRateTable.WidgetType) {
                        mrtgWidgetHeight = parseInt(this.widgetHeight) - 440;
                    }
                    else {
                        mrtgWidgetHeight = parseInt(this.widgetHeight) - 442;
                    }
                }
                else if (parseInt(this.widgetWidth) < 673 && parseInt(this.widgetWidth) >= 635) {
                    mrtgWidgetHeight = parseInt(this.widgetHeight) - 410;
                }
                else if (parseInt(this.widgetWidth) < 741 && parseInt(this.widgetWidth) >= 673) {
                    mrtgWidgetHeight = parseInt(this.widgetHeight) - 380;
                }
                else {
                    mrtgWidgetHeight = parseInt(this.widgetHeight) - 368;
                }
                document.getElementById('mrtgResizeHeight').style.height = mrtgWidgetHeight + "px";
            }
            else {
                if (parseInt(this.widgetWidth) < 479) {
                    mrtgWidgetHeight = parseInt(this.widgetHeight) - 465;
                }
                else if (parseInt(this.widgetWidth) < 564 && parseInt(this.widgetWidth) >= 479) {
                    mrtgWidgetHeight = parseInt(this.widgetHeight) - 457;
                }
                else if (parseInt(this.widgetWidth) < 591 && parseInt(this.widgetWidth) >= 564) {
                    mrtgWidgetHeight = parseInt(this.widgetHeight) - 448;
                }
                else if (parseInt(this.widgetWidth) < 636 && parseInt(this.widgetWidth) >= 591) {
                    mrtgWidgetHeight = parseInt(this.widgetHeight) - 430;
                }
                else if (parseInt(this.widgetWidth) < 644 && parseInt(this.widgetWidth) >= 636) {
                    mrtgWidgetHeight = parseInt(this.widgetHeight) - 425;
                }
                else if (parseInt(this.widgetWidth) < 665 && parseInt(this.widgetWidth) >= 644) {
                    mrtgWidgetHeight = parseInt(this.widgetHeight) - 410;
                }
                else {
                    mrtgWidgetHeight = parseInt(this.widgetHeight) - 360;
                }
                document.getElementById('mrtgResizeHeight').style.height = mrtgWidgetHeight + "px";
            }
            document.getElementById('mrtgResize').style.width = this.widgetWidth + "px";
        }
        var newWidth = parseInt(this.widgetWidth.replace('px', ''));

        //Header adjustment 
        if (this.CheckForIE) {
            if (newWidth <= 600) {
                document.getElementById("mtg_lender_column").style.width = "30%";
                document.getElementById("mtg_apr_column").style.width = "14.5%";
                document.getElementById("mtg_rate_column").style.width = "18%";
                document.getElementById("mtg_cost_column").style.width = "19%";
                document.getElementById("mtgCommentsTh").style.width = "15%";
            }
            else {
                document.getElementById("mtg_lender_column").style.width = "27%";
                document.getElementById("mtg_apr_column").style.width = "12%";
                document.getElementById("mtg_rate_column").style.width = "16%";
                document.getElementById("mtg_cost_column").style.width = "16%";
                document.getElementById("mtgCommentsTh").style.width = "auto";
            }
        }
        else {
            if (newWidth <= 600) {
                document.getElementById("mtg_lender_column").style.width = "31%";
                document.getElementById("mtg_apr_column").style.width = "14%";
                document.getElementById("mtg_rate_column").style.width = "18.5%";
                document.getElementById("mtg_cost_column").style.width = "20%";
            }
            else {
                document.getElementById("mtg_lender_column").style.width = "25%";
                document.getElementById("mtg_apr_column").style.width = "12%";
                document.getElementById("mtg_rate_column").style.width = "15.5%";
                document.getElementById("mtg_cost_column").style.width = "15%";
            }
        }

        this.ShowMtgComments();
    },

    ShowMtgComments: function () {
        var showBottomComments = 0;
        if (this.widgetWidth <= 600) {
            document.getElementById("mtgcommentsThDiv").style.visibility = 'hidden';
            showBottomComments = 1;
        }
        else {
            document.getElementById("mtgcommentsThDiv").style.visibility = 'visible';
            //document.getElementById("mtg_cost_column").className = 'braff-mtg-costs';
        }
        var tdSelections = document.getElementsByTagName('td');
        var len = tdSelections.length;

        if (this.ieVersion == 7) {
            if (this.widgetWidth <= 566) {
                document.getElementById('sControlLi1').style.height = '40px';
                document.getElementById('sControlLi2').style.height = '40px';
                document.getElementById('sControlLi3').style.height = '40px';
                document.getElementById('liProducts').style.height = '40px';
                document.getElementById('liJumboProducts').style.height = '40px';
            }
            else {
                document.getElementById('sControlLi1').style.height = '30px';
                document.getElementById('sControlLi2').style.height = '30px';
                document.getElementById('sControlLi3').style.height = '30px';
                document.getElementById('liProducts').style.height = '30px';
                document.getElementById('liJumboProducts').style.height = '30px';
            }
        }
        else {
            document.getElementById('sControlLi1').style.height = '40px';
            document.getElementById('sControlLi2').style.height = '40px';
            document.getElementById('sControlLi3').style.height = '40px';
            document.getElementById('liProducts').style.height = '40px';
            document.getElementById('liJumboProducts').style.height = '40px';
        }

        for (var i = 0; i < len; i++) {

            if (tdSelections[i].className == "braff-mtg-bottom-comments") {
                tdSelections[i].style.display = showBottomComments == 1 ? "" : "none";
            }

            if (tdSelections[i].className == "comments") {
                if (this.CheckForIE) {
                    tdSelections[i].firstChild.style.display = showBottomComments == 0 ? "block" : "block";
                    if (this.widgetWidth <= 600) {
                        if (this.ieVersion == 7) {
                            tdSelections[i].style.width = "0%";
                        }
                        else {
                            tdSelections[i].style.width = "1%";
                        }
                        tdSelections[i].firstChild.style.display = "none";
                    }
                    else {
                        tdSelections[i].style.width = "17%";
                        tdSelections[i].firstChild.style.display = "block";
                    }
                }
                else {
                    tdSelections[i].firstElementChild.style.display = showBottomComments == 0 ? "block" : "none";
                    if (this.widgetWidth <= 600) {
                        tdSelections[i].style.width = "0%";
                    }
                    else {
                        tdSelections[i].style.width = "20%";
                    }
                }
            }
        }
    },

    GetJSONP: function () {
        var url = this.StaticServiceURL;
        var domainLoc = window.location.hostname == 'localhost' ? 'live.dev.bankrate.com' : window.location.hostname;

        var product = 1, loanamount = this.LoanAmount, points = 'all';
        var marketID = 0;
        if (!this.CallUsingZip) {
            marketID = document.getElementById("CitySelector").value;
            this.ZipCode = '';
        }
        if (document.getElementById('liProducts').style.display != "none") {
            product = document.getElementById("productsDll").value;
        } else {
            product = document.getElementById("JumboProductsDll").value;
        }
        this.MtgDefaultProd = product;
        url += this.Partner + "/" + this.Key + "/" + domainLoc;
        url += "?market=" + marketID + "&products=" + product + "&loanamount=" + loanamount + "&points=" + points + "&def=" + this.DefaultZipOverride;
        url += "&zip=" + this.ZipCode;
        url += "&format=json";
        if (typeof (this.ReportSuite) != "undefined" && this.ReportSuite != null) {
            url += "&omni=true";
        }
        url += "&method=BRMmortgageRateTable.RateTableCallback";
        if (this.Partner == '' || this.Key == '') {
            document.getElementById("MtgLoadingImgDiv").style.display = 'none';
            document.getElementById('mtgServiceTurnOff').style.display = 'block';
        }
        else {
            javascript: setTimeout("BRMmortgageRateTable.MtgCheckServiceStatus()", 15000);
            var script = document.createElement("script");
            script.id = "BRMmortgageRateTableJSONPScript";
            script.setAttribute("src", url);
            script.setAttribute("type", "text/javascript");
            document.getElementsByTagName('head')[0].appendChild(script);
        }
    },

    GetJumboLoanJSONP: function (selectedMarket) {
        var url = this.StaticLoanLimitServiceURL;
        var domainLoc = window.location.hostname == 'localhost' ? 'live.dev.bankrate.com' : window.location.hostname;
        url += this.Partner + "/" + this.Key + "/" + domainLoc + "/";
        url += '?market=' + selectedMarket + '&zip=&method=BRMmortgageRateTable.JumboLoanCallBack';
        var script = document.createElement("script");
        script.id = "BRMmortgageRateTableJSONPJumboScript";
        script.setAttribute("src", url);
        script.setAttribute("type", "text/javascript");
        document.getElementsByTagName('head')[0].appendChild(script);
    },

    RemoveScript: function (scriptToRemove) {
        var s = document.getElementById(scriptToRemove);
        if (s != null && typeof (s) != "undefined") {
            document.getElementsByTagName('head')[0].removeChild(s);
        }
    },

    JumboLoanCallBack: function (result) {
        this.RemoveScript('BRMmortgageRateTableJSONPJumboScript');
        var jumboThreshold = 0;

        try {
            jumboThreshold = parseFloat(result);
        } catch (e) {

        }

        if (jumboThreshold > 0) {
            this.JumboThreshold = jumboThreshold;
            this.ValidateLoanAmount('mortgageLoanAmountTextBox', 'mortgageLoanAmountError', false);
        }
    },

    RateTableCallback: function (strXML) {
        this.ServiceStatus = true;
        document.getElementById('mtgServiceTurnOff').style.display = 'none';
        document.getElementById("MtgLoadingImgDiv").style.display = 'block';
        this.RemoveScript('BRMmortgageRateTableJSONPScript');

        if (strXML != null) {
            document.getElementById('mortgageLoanAmountTextBox').value = this.LoanAmount;
            this.SetMtgDefaultProduct(this.MtgDefaultProd);
            this.FillBody(strXML);
        }
    },

    MtgCheckServiceStatus: function () {
        if (!BRMmortgageRateTable.ServiceStatus) {
            this.MtgNoRecord = true;
            this.SetDynamicAdjustments();
            document.getElementById("MtgLoadingImgDiv").style.display = 'none';
            document.getElementById('mtgServiceTurnOff').style.display = 'block';
        }
    },

    PopulateStates: function () {
        if (this.States == null) {
            states = new Array('AL:AL', 'AK:AK', 'AR:AR', 'AZ:AZ', 'CA:CA', 'CO:CO', 'CT:CT',
				'DE:DE', 'DC:DC', 'FL:FL', 'GA:GA', 'HI:HI', 'IA:IA', 'ID:ID', 'IL:IL', 'IN:IN',
				'KS:KS', 'KY:KY', 'LA:LA', 'MA:MA', 'MD:MD', 'ME:ME', 'MI:MI', 'MN:MN', 'MO:MO',
				'MS:MS', 'MT:MT', 'NC:NC', 'ND:ND', 'NE:NE', 'NH:NH', 'NJ:NJ', 'NM:NM',
				'NV:NV', 'NY:NY', 'OH:OH', 'OK:OK', 'OR:OR', 'PA:PA', 'RI:RI', 'SC:SC', 'SD:SD',
				'TN:TN', 'TX:TX', 'UT:UT', 'VA:VA', 'VT:VT', 'WA:WA', 'WI:WI', 'WV:WV', 'WY:WY');

            this.States = states;
        }

        return this.States;
    },

    PopulateCities: function () {
        if (this.Cities == null) {
            var cities = new Array();
            cities['AK'] = new Array('Aleutians:1412', 'Anchorage:234', 'Barrow:1410', 'Fairbanks:1247', 'Juneau:1306', 'Sitka:498');
            cities['AL'] = new Array('Anninston:1360', 'Auburn-Phenix City:1233', 'Birmingham:108', 'Dothan:1289', 'Eufaula:1129', 'Fairhope:499', 'Florence:406', 'Huntsville:255', 'Mobile:156', 'Montgomery-Selma:1249', 'Tuscaloosa:1312', 'Vernon:1359');
            cities['AR'] = new Array('El Dorado:1371', 'Fayetteville:1131', 'Harrison-Mountain Home:1413', 'Hot Springs:500', 'Jonesboro:1300', 'Little Rock:146', 'McGehee-Chicot Junction:1284', 'W. Memphis-Greenville:1372');
            cities['AZ'] = new Array('Flagstaff:501', 'Ft Defiance-Ganado-Chinle:1361', 'Phoenix-Mesa:40', 'Prescott:502', 'Scottsdale:503', 'Tucson:120', 'Wickenburg:504', 'Yuma:1241');
            cities['CA'] = new Array('Arcadia:505', 'Bakersfield:142', 'Berkeley:506', 'Chico-Redding:1265', 'Downey:967', 'El Centro:1267', 'Escondido:507', 'Eureka:1268', 'Fremont:969', 'Fresno:114', 'Healdsburg:513', 'Huntington Beach:971', 'Irvine:973', 'La Jolla:508', 'Lake Tahoe:1376', 'Los Angeles:4', 'Modesto:196', 'Oakland:269', 'Palm Desert:509', 'Palm Springs:1266', 'Palo Alto:510', 'Pasadena:975', 'Rancho Santa Margarita:977', 'Riverside-San Bernardino:307', 'Sacramento:54', 'Salinas:979', 'San Clemente:208', 'San Diego:30', 'San Francisco:8', 'San Gabriel Valley:241', 'San Jose:273', 'San Luis Obispo:511', 'San Rafael-Novato:271', 'Santa Barbara:295', 'Santa Clara:981', 'Santa Cruz:512', 'Santa Rosa:281', 'Stockton-Lodi:154', 'Sunnyvale:983', 'Thousand Oaks:985', 'Ventura:283', 'Yreka:1375');
            cities['CO'] = new Array('Arvada:514', 'Boulder:321', 'Colorado Springs:184', 'Cortez:1439', 'Denver:44', 'Durango:515', 'Fort Collins-Loveland:516', 'Grand Junction-Montrose:1243', 'Greeley:323', 'Lakewood:517', 'Westminster:987');
            cities['CT'] = new Array('Bridgeport:404', 'Danbury:989', 'Hartford:72', 'New Haven:210', 'Stamford:991', 'Torrington:475');
            cities['DE'] = new Array('Dover:993', 'Lewes:995', 'Ocean View:1378', 'Wilmington:214');
            cities['DC'] = new Array('DC Metro:20', 'Reston-Manassas:265', 'Rockville-Wheaton:261');
            cities['FL'] = new Array('Aventura:518', 'Boca Raton:519', 'Bradenton:617', 'Cape Coral:997', 'Coconut Creek:520', 'Coral Gables:521', 'Crystal River:1133', 'Daytona Beach:178', 'Deerfield Beach:522', 'DeLand:523', 'Delray Beach:524', 'Dunedin:525', 'Ft Lauderdale:259', 'Ft Myers:291', 'Ft Walton Beach:454', 'Gainesville:403', 'Hallandale:526', 'Hobe Sound-Port St. Lucie:311', 'Inverness:528', 'Jacksonville:94', 'Key West:529', 'Lakeland:176', 'Largo:530', 'Margate:531', 'Melbourne-Titusville-Palm Bay:182', 'Miami:22', 'Mount Dora:532', 'N. Ft. Myers:618', 'N. Miami Beach:619', 'Naples:289', 'Ocala:402', 'Ojus:533', 'Orlando:66', 'Ormond Beach:534', 'Panama City:1288', 'Pensacola:456', 'Pompano Beach:535', 'Port Charlotte:536', 'Punta Gorda:999', 'Sarasota:150', 'Siesta Key:537', 'St. Augustine: 538', 'St. Petersburg:341', 'Sunny Isles:539', 'Tallahassee:249', 'Tamarac:540', 'Tampa:42', 'Venice:541', 'Vero Beach:542', 'West Palm Beach:98', 'Winter Haven:569', 'Winter Park:543');
            cities['GA'] = new Array('Albany:1346', 'Athens:544', 'Atlanta:24', 'Augusta:172', 'Columbus:1231', 'Gainesville:545', 'Golden Isles:1135', 'Lawrenceville:317', 'Macon:1246', 'Marietta:313', 'Morganton-Dalton:1379', 'Roswell:315', 'Savannah:327', 'St. Marys:1380', 'Thomasville:1381');
            cities['HI'] = new Array('Hilo:546', 'Honolulu:110');
            cities['IA'] = new Array('Cedar Rapids:1001', 'Davenport:293', 'Des Moines:190', 'Estherville:1382', 'Harlan-Atlantic-Shenandoah:1385', 'Inwood-Allendorf:1383', 'Iowa City:547', 'Keokuk:1317', 'Mason City:1384', 'Ottumwa:1316', 'Sioux City:1238');
            cities['ID'] = new Array('Boise:216', 'Coeur D Alene:551', 'Idaho Falls-Pocatello:1245', 'Moscow:1137', 'Twin Falls:1239');
            cities['IL'] = new Array('Aurora:1107', 'Bloomington:1109', 'Champaign-Urbana:1111', 'Chicago:6', 'East St Louis:253', 'Elgin:277', 'Harrisburg-Mt. Vernon:1315', 'Highland Park:553', 'Kankakee:1115', 'Mt. Carmel-Fairfield-Carmi:1352', 'Naperville:1003', 'Peoria:1005', 'Quincy:1314', 'Rock Island-Moline:1358', 'Rockford:299', 'Waukegan:275', 'Yale-Robinson-Ste. Marie:1388');
            cities['IN'] = new Array('Bloomington:554', 'Brookville-Aurora:1391', 'Elkhart-Goshen:1007', 'Evansville:301', 'Fort Wayne:158', 'Gary:212', 'Indianapolis:58', 'Lafayette:1009', 'Richmond:1345', 'South Bend:1184', 'Tell City-Bedford-Scottsburg:1390', 'Terre Haute:1011');
            cities['KS'] = new Array('Doniphan:1278', 'Glade-Agenda:1394', 'Hays:1139', 'Independence:1393', 'Kansas City:238', 'Lawrence:309', 'Manhattan:1141', 'Overland Park:1013', 'Pittsburg:1318', 'Topeka:1015', 'Wichita:152');
            cities['KY'] = new Array('Ashland-Williamson:1397', 'Bowling Green-Owensboro:1320', 'Covington:434', 'Hopkinsville:1113', 'Lexington:174', 'Louisville:90', 'Paducah:1319', 'Pikeville-Hazard:1396');
            cities['LA'] = new Array('Alexandria:1364', 'Baton Rouge:144', 'Lafayette:1301', 'Lake Charles:1274', 'Monroe:1302', 'New Orleans:64', 'Shreveport - Bossier City:194');
            cities['MA'] = new Array('Amherst:555', 'Barnstable-Yarmouth:451', 'Boston:14', 'Cambridge:1017', 'Chelmsford:331', 'Chestnut Hill:556', 'Lowell:1019', 'Methuen:329', 'New Bedford:1398', 'Norfolk-Norwood:333', 'Northampton:1021', 'Pittsfield-Lenox:1370', 'Plymouth:335', 'Springfield:138', 'Taunton-Attleboro:449', 'Williamstown:1143', 'Worcester:339');
            cities['MD'] = new Array('Annapolos:558', 'Baltimore:36', 'Cumberland:1399', 'Newark:1119', 'Rockville-Wheaton:263', 'Salisbury:1291');
            cities['ME'] = new Array('Bangor:1023', 'Brunswick:559', 'Camden:560', 'Lewiston-Auburn:445', 'Portland:218', 'Presque Isle:1321');
            cities['MI'] = new Array('Adrian-Tecumseh:1401', 'Alpena:1283', 'Ann Arbor:285', 'Benton Harbor-Niles:1400', 'Detroit:12', 'Grand Rapids:92', 'Ishpeming:1341', 'Kalamazoo-Battle Creek:166', 'Lansing-East Lansing:164', 'Livonia:561', 'Marquette:1324', 'Petoskey:1145', 'Saginaw-Bay City-Midland:180', 'Sterling Heights:563', 'Traverse City-Cadillac:1322', 'Warren:1025');
            cities['MN'] = new Array('Duluth:564', 'Mankato:1323', 'Minneapolis:32', 'Moorhead:1027', 'Rochester:1029', 'St. Cloud:1031', 'St. Paul:1182', 'White Bear Lake:1033', 'Woodbury:1035', 'Worthington-Hadley:1403');
            cities['MO'] = new Array('Branson:565', 'Cape Girardeau:1325', 'Columbia:566', 'Hannibal:1326', 'Independence:1037', 'Joplin:1299', 'Kansas City:50', 'Kirksville:1276', 'Mercer:1339', 'Rolla:567', 'Springfield:303', 'St. Joseph:1273', 'St. Louis:34', 'Westboro-Fairfax:1404');
            cities['MS'] = new Array('Biloxi-Gulfport:1304', 'Centreville-Woodville:1357', 'Clarksdale-Batesville-Holly Springs:1407', 'Columbus-Tupelo-West Point:1281', 'Greenwood-Greenville:1285', 'Hattiesburg-Laurel:1277', 'Jackson:186', 'Meridian:1313', 'Oxford:1147', 'Pascagoula:1406', 'Southaven:957');
            cities['MT'] = new Array('Baker-Capitol:1409', 'Billings:220', 'Bozeman:1149', 'Glendive:1327', 'Great Falls:1244', 'Helena:1328', 'Libby:1408', 'Missoula:1151');
            cities['NC'] = new Array('Asheville:552', 'Brevard:570', 'Cary:1039', 'Chapel Hill:1178', 'Charlotte:70', 'Durham:1180', 'Edenton:571', 'Elizabeth City-Murfreesboro:1437', 'Greensboro-Winston Salem-High Pt:80', 'Greenville:572', 'Hayesville-Murphy:1438', 'Hendersonville:573', 'Hickory-Morganton:1041', 'Jacksonville:1043', 'Pinehurst:574', 'Raleigh:102', 'Wilmington:1434');
            cities['ND'] = new Array('Bismarck:1153', 'Fargo:224');
            cities['NE'] = new Array('Chadron:1330', 'Homer-Wynot:1292', 'Lincoln:1045', 'North Platte:1329', 'Omaha:122', 'Scottsbluff:1435', 'Valentine-Elsmere:1436');
            cities['NH'] = new Array('Berlin-Laconia:1433', 'Claremont-Plymouth:1363', 'Concord:1049', 'Hanover:575', 'Keene:1047', 'Manchester:222', 'Nashua:1051', 'Portsmouth:576');
            cities['NJ'] = new Array('Atlantic City-Vineland:202', 'Cherry Hill:245', 'Elizabeth:236', 'Neptune-Lakewood:204', 'Newark:1055', 'Paterson-Paramus:1053', 'Trenton-Princeton:247', 'Washington-Montgomery:206');
            cities['NM'] = new Array('Albuquerque:134', 'Carlsbad:1287', 'Las Cruces:577', 'Raton-Mosquero:1242', 'Santa Fe:578', 'Silver City:579');
            cities['NV'] = new Array('Carson City:557', 'Ely-West Wendover:1414', 'Henderson:1057', 'Las Vegas:104', 'Reno:257');
            cities['NY'] = new Array('Albany:100', 'Binghamton:1303', 'Bronxville:580', 'Buffalo:68', 'Elmira:1248', 'Glens Falls:1059', 'Irondequoit:581', 'Ithaca:582', 'Long Island:251', 'New York Metro:2', 'Oneonta:1155', 'Plattsburgh:1415', 'Poughkeepsie:279', 'Rochester:78', 'Syracuse:116', 'Utica:1331', 'Watertown:1290', 'Yonkers:1061');
            cities['OH'] = new Array('Akron:242', 'Athens-Wellston-Portsmouth:1417', 'Beaver Creek:583', 'Canton-Massillon:188', 'Cincinnati:46', 'Cleveland:26', 'Cleveland Heights:584', 'Columbus:60', 'Dayton:88', 'Lakewood:585', 'Lima:1063', 'Lorain-Elyria:1065', 'Marietta:1332', 'Steubenville:1117', 'Toledo:126', 'Youngstown-Warren:1280', 'Zanesville:128');
            cities['OK'] = new Array('Ada:1309', 'Enid:1067', 'Guymon-Knowles:1286', 'Lawton:1308', 'Miami:1307', 'Oklahoma City:86', 'Smithville-Idabel:1416', 'Tulsa-Muskogee:118');
            cities['OR'] = new Array('Ashland:586', 'Baker City-Mount Vernon-Nyssa:1367', 'Bend:587', 'Enterprise-Flora:1418', 'Eugene:588', 'Grants Pass:589', 'Hermiston-Pendleton:1240', 'Medford:590', 'Portland:52', 'Salem:1069');
            cities['PA'] = new Array('Allentown-Bethlehem:130', 'Bradford:1369', 'Chambersburg-Waynesboro:1419', 'Drexel Hill:591', 'Erie:1071', 'Harrisburg - Lebanon:136', 'Johnstown-Altoona:1293', 'King of Prussia:592', 'Lancaster:170', 'Philadelphia:10', 'Pittsburgh:38', 'Reading:325', 'Scranton-Wilkes Barre:124', 'Sharon:1420', 'State College:593', 'Stroudsburg-Port Jervis:1421', 'Wellsboro:1354', 'York:297');
            cities['RI'] = new Array('Providence:74');
            cities['SC'] = new Array('Aiken-N. Augusta:1365', 'Charleston-North Charleston:148', 'Columbia:160', 'Conway:594', 'Edisto:1157', 'Greenville - Spartanburg:112', 'Hilton Head:595', 'Myrtle Beach:596', 'Seabrook Island:597', 'Walterboro-Beaufort:1423');
            cities['SD'] = new Array('Brookings:598', 'Rapid City:1333', 'Redig-Camp Crook:1424', 'Sioux Falls:226');
            cities['TN'] = new Array('Bristol-Kingsport:162', 'Chattanooga:168', 'Clarksville:1125', 'Franklin:599', 'Jackson:1334', 'Knoxville:140', 'Maryville:1073', 'Memphis:82', 'Nashville:84', 'Paris:600', 'Tri-Cities:1298', 'Union City:1282');
            cities['TX'] = new Array('Abilene-Sweetwater:1258', 'Amarillo:1255', 'Austin - San Marcos:106', 'Beaumont-Port Arthur:1270', 'Carrollton:1075', 'College Station:601', 'Conroe:604', 'Corpus Christi:1261', 'Dallas:18', 'El Paso:132', 'Fort Worth:287', 'Galveston:602', 'Houston:16', 'Kerrville:603', 'Laredo:1260', 'Longview:1425', 'Lubbock:1259', 'Marble Falls:1159', 'McAllen-Edinburg-Mission:192', 'Odessa-Midland:1263', 'Plano:1077', 'Rockport:1161', 'San Angelo:1254', 'San Antonio:62', 'Sherman:1262', 'Texas City:1079', 'Tyler-Lufkin-Nacogdoches:1257', 'Victoria:1264', 'Waco-Temple-Bryan:1256', 'Wichita Falls:1271', 'Wimberley:1163');
            cities['UT'] = new Array('Bountiful:605', 'Ogden:1081', 'Orem:1083', 'Provo:606', 'Salt Lake City:76', 'St. George:607');

            cities['VA'] = new Array('Alexandria:562', 'Arlington:1085', 'Bluefield:1275', 'Charlottesville:608', 'Chesapeake:1087', 'Danville-Martinsville:1337', 'Hampton Roads:56', 'Harrisonburg:1252', 'Lynchburg:1089', 'Reston-Manassas:267', 'Richmond:96', 'Roanoke:305', 'South Hill:1426', 'Sugarland Run:1090', 'Tri-Cities:1250');
            cities['VT'] = new Array('Bennington-Shaftsbury-Dorset:1344', 'Brattleboro-Bellows Falls:1368', 'Burlington:228', 'Middlebury:609');
            cities['WA'] = new Array('Bellevue:1092', 'Bellingham:610', 'Bremerton:1094', 'Olympia:611', 'Port Townsend:612', 'San Juan Islands:613', 'Seattle:28', 'Spokane:200', 'Vancouver-Longview:614', 'Whidbey Island:615', 'Yakima-Pasco-Richland-Kennewick:1253');
            cities['WI'] = new Array('Appleton-Oshkosh-Neenah:1096', 'Eagle River:1167', 'Green Bay:1098', 'Kenosha:1100', 'La Crosse-Eau Claire:1121', 'Madison:198', 'Menomonie:1169', 'Milwaukee:48', 'Racine:319', 'Sheboygan:616', 'Sturgeon Bay:1165', 'Superior:1356', 'Waukesha:1102', 'Wausau-Rhinelander:1232');
            cities['WV'] = new Array('Bluefield-Beckley-Oak Hill:1297', 'Charleston:230', 'Clarksburg-Weston:1294', 'Fort Seybert:1251', 'Huntington:1104', 'Martinsburg:1430', 'Morgantown-Fairmont:1429', 'Parkersburg:1296', 'Wheeling:1295');
            cities['WY'] = new Array('Casper:1173', 'Cheyenne:232', 'Cody:1366', 'Jackson:1335', 'Laramie:1171', 'Newcastle:1347', 'Rock Springs-Green River:1432');

            this.Cities = cities;
        }

        return this.Cities;
    },

    FetchRss: function (updateDropdownValues) {
        try {
            if (this.CheckForIE) {
                document.getElementById("BRrateTB").innerText = '';
            } else {
                document.getElementById("BRrateTB").innerHTML = '';
            }
        } catch (e) {
            var test = true;
        }


        if (updateDropdownValues) {
            this.UpdateCityAndState = true;
        } else {
            this.UpdateCityAndState = false;
        }

        this.GetJSONP();
    },

    SetRowMouseOver: function (rID) {
        document.getElementById(rID).setAttribute('class', 'p');
    },

    SetRowMouseOut: function (rID) {
        document.getElementById(rID).setAttribute('class', 'np');
    },

    SetCities: function (stateid, cityid) {
        var index = document.getElementById(stateid).selectedIndex;
        var selectedMarket = document.getElementById(stateid).options[index].value;

        if (selectedMarket == "") {
            this.CleanCity(cityid);
            this.ChangeSelect(cityid, []);
        }
        else {
            // get the jumbo amount for this market
            var stateSel = document.getElementById(stateid).options[index].text;
            cityList = this.Cities[stateSel];
            this.ChangeSelect(cityid, cityList);
        }
    },

    OnCityChange: function (cityDropDown) {
        this.UpdateJumboLoanThreshold();
    },

    ChangeSelect: function (fieldID, newOptions) {
        if (newOptions == undefined) {
            selectField.options.length = 0;
            return;
        }

        selectField = document.getElementById(fieldID);
        selectField.options.length = 0;

        var geoTargetedIndex;
        var i;
        for (i = 0, len = newOptions.length; i < len; i++) {
            var str = newOptions[i].split(':');
            selectField.options[selectField.length] = new Option(str[0], str[1]);

            if (this.GeoTargetedCity != null) {
                if (selectField.options[selectField.length - 1].text == this.GeoTargetedCity) {
                    geoTargetedIndex = selectField.length - 1;
                }
            }
        }

        if (this.GeoTargetedCity != null) {
            selectField.selectedIndex = geoTargetedIndex;
            this.UpdateJumboLoanThreshold();
        }
    },

    UpdateJumboLoanThreshold: function () {
        var index = document.getElementById("CitySelector").selectedIndex;
        var selectedMarket = document.getElementById("CitySelector").options[index].value;
        this.GetJumboLoanJSONP(selectedMarket);
    },

    CleanCity: function (cityid) {
        var cityControlLen = document.getElementById(cityid).options.length;
        for (var s = cityControlLen - 1; s >= 1; s--) {
            document.getElementById(cityid).remove(s);
        }
    },


    FormatCurrency: function (num) {
        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);
    },

    CustomDate: function (xmlDate) {
        var date = xmlDate.split("/");
        var mydate;

        if (date[2].length > 2)
            mydate = new Date(xmlDate);
        else
            mydate = new Date("20" + date[2], parseInt(date[0]) - 1, parseInt(date[1] - 0));

        var day = mydate.getDay();
        var month = mydate.getMonth();
        var daym = mydate.getDate();

        if (daym < 10)
            daym = "0" + daym;

        var dayarray = new Array("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
        var montharray = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
        var returnDate = dayarray[day] + " " + montharray[month] + " " + daym;
        return returnDate;
    },

    SetStateControls: function (stateid1) {
        var stateSel = document.getElementById(stateid1);
        var i;
        for (i = 0; i < this.States.length; i++) {
            var str = this.States[i].split(':');
            stateSel.options[i + 1] = new Option(str[0], str[1]);
        }
    },

    CreateHTMLwrap: function () {
        document.write("<div  style=\"width:470px\">");
        document.write("<div id=\"mrtgResize\" class=\"braff-brate-maincontainer\">");
        document.write("<span class=\"braff-brate-topright\"></span><span class=\"braff-brate-topleft\"></span>");
        document.write("<div class=\"braff-brate-rail\">");
        document.write("<div id=\"oTableContainer\" class=\"braff-brate-contents\">");
        document.write("<h1 id=\"BRrateHeader\"></h1>");
        document.write("<p id=\"BRrateSeoheading\"></p>");
        document.write("<p id=\"BRcriteriaUsed\"></p>");
        document.write("<div class=\"braff-searchtabs\">");
        document.write("<h3>Change search results</h3>");
        document.write("<div id=\"mtgSearchTabContainer\" class=\"braff-tabcontainer\">");
        document.write("<ul class=\"braff-searchcontrols\">");

        document.write("<li id=\"sControlLi1\" style=\"height:40px\"><span>State:</span>");
        document.write("<select class=\"braff-states\" id=\"StateSelector\" onchange=\"BRMmortgageRateTable.SetCities('StateSelector','CitySelector')\"");
        document.write("name=\"states\">");
        document.write("<option>Select State</option>");
        document.write("</select>");
        document.write("</li>");
        document.write("<li id=\"sControlLi2\" style=\"height:40px\"><span>City nearest to property:</span>");
        document.write("<select class=\"braff-markets\" id=\"CitySelector\" name=\"markets\" onchange=\"BRMmortgageRateTable.OnCityChange(this)\" >");
        document.write("<option value=\"0\">Select City</option>");
        document.write("</select>");
        document.write("</li>");
        document.write("<li id=\"sControlLi3\" style=\"height:40px\"><span>Loan amount ($):</span>");
        document.write("<input name=\"mortgageLoanAmountTextBox\" class=\"braff-lamt\" value='" + BRMmortgageRateTable.LoanAmount + "' id=\"mortgageLoanAmountTextBox\"");
        document.write("onkeyup=\"BRMmortgageRateTable.ValidateLoanAmount('mortgageLoanAmountTextBox','mortgageLoanAmountError', false);\"");
        document.write("type=\"text\" />");
        document.write("</li>");

        document.write("<li id=\"liProducts\" style=\"height:40px\"><span>Products:</span>");
        document.write("<select id=\"productsDll\" class=\"braff-prod\" name=\"prods\" style=\"width:150px\">");
        document.write("<option value=\"1\">30 year fixed</option>");
        document.write("<option value=\"387\">20 year fixed</option>");
        document.write("<option value=\"2\">15 year fixed</option>");
        document.write("<option value=\"388\">10 year fixed</option>");
        document.write("<option value=\"6\">5/1 ARM</option>");
        document.write("<option value=\"9\">7/1 ARM</option>");
        document.write("<option value=\"8\">3/1 ARM</option>");
        document.write("<option value=\"400\">3/1 ARM (IO)</option>");
        document.write("<option value=\"390\">5/1 ARM (IO)</option>");
        document.write("<option value=\"565\">30 year (IO) - 0pt</option>");
        document.write("</select>");
        document.write("</li>");

        document.write("<li id=\"liJumboProducts\" style=\"display:none; height:40px\"><span>Products:</span>");
        document.write("<select id=\"JumboProductsDll\" class=\"braff-prod\" name=\"prods\" style=\"width:150px\">");
        document.write("<option value=\"4\">30 year jumbo</option>");
        document.write("<option value=\"165\">15 year jumbo</option>");
        document.write("<option value=\"7\">5/1 jumbo ARM</option>");
        document.write("<option value=\"462\">7/1 jumbo ARM</option>");
        document.write("<option value=\"460\">3/1 jumbo ARM</option>");
        document.write("<option value=\"461\">3/1 jumbo ARM (IO)</option>");
        document.write("<option value=\"391\">5/1 jumbo ARM (IO)</option>");
        document.write("</select>");
        document.write("</li>");

        document.write("<li  class=\"braff-btn-col\">");
        document.write("<input type=\"button\" id=\"mtgSearchBtn\" class=\"braff-brate-search-btn\" style=\"margin-top:18px\" onclick=\"BRMmortgageRateTable.ShowMtgRateSearchPage('StateSelector','CitySelector','mortgageLoanAmountTextBox','mrtgStateError','mrtgCityError','mortgageLoanAmountError', false)\" />");
        document.write("</li>");
        document.write("</ul>");
        document.write("<div style=\"clear:both; display:none\">");
        document.write("<table>");
        document.write("<tr>");
        document.write("<td>");
        document.write("<span id=\"mrtgStateError\" class=\"braff-brate-form-error\" style=\"display: none;\">*Please select a state</span>");
        document.write("</td>");
        document.write("<td>");
        document.write("<span id=\"mrtgCityError\" class=\"braff-brate-form-error\" style=\"display: none;\">*Please select a city</span>");
        document.write("</td>");
        document.write("<td>");
        document.write("<span id=\"mortgageLoanAmountError\" class=\"braff-brate-form-error\" style=\"display: none;\">*Please enter a valid loan amount</span>");
        document.write("</td>");
        document.write("</tr>");
        document.write("</table>");
        document.write("</div>");
        document.write("</div>");
        document.write("</div>");

        document.write("<table id=\"mortTableHeaders\" class=\"braff-brate-static-header\" cellpadding=\"0\" cellspacing=\"0\" >");
        document.write("<thead>");
        document.write("<tr>");
        document.write("<th id=\"mtg_lender_column\"  class=\"braff-lender\" >");
        document.write("<div id=\"Mtg_lender_header\"  style = \"text-decoration:underline;cursor:pointer; float:left; margin-top:13px;\">Lender</div>");
        document.write("</th>");
        document.write("<th id=\"mtg_apr_column\" class=\"braff-apr\" >");
        document.write("<div id=\"Mtg_apr_header\" style = \"text-decoration:underline;cursor:pointer; float:left;margin-top:13px;\">APR</div>");
        document.write("</th>");
        document.write("<th id=\"mtg_rate_column\" class=\"braff-rate\" >");
        document.write("<div id=\"Mtg_rate_header\" style = \"text-decoration:underline;cursor:pointer; float:left; margin-top:13px; \">Rate</div>");
        document.write("</th>");
        document.write("<th id=\"mtg_cost_column\" class=\"braff-cost\" >");
        document.write("<div id=\"Mtg_cost_header\" style = \"text-decoration:underline;cursor:pointer; float:left; margin-top:13px;\">Costs and fees</div>");
        document.write("</th>");
        document.write("<th id=\"mtgCommentsTh\" class=\"braff-comments\" >");
        document.write("<div id=\"mtgcommentsThDiv\" style=\"color: #024E8A; text-decoration :none; cursor:default; margin-top:13px;\">Comments</div>");
        document.write("</th>");
        document.write("<th class=\"braff-contact\"></th>");
        document.write("</tr>");

        document.write("</thead>");
        document.write("</table>");

        document.write("<div id=\"mrtgResizeHeight\" class=\"braff-brate-results-container\">");

        document.write("<div id=\"MtgLoadingImgDiv\" style = \"display:block; text-align: center\" >"); //added
        document.write("<img src=\"http://www.bankrate.com/system/img/brspin.gif\" />");
        document.write("</div>");
        document.write("<div id=\"mtgServiceTurnOff\" style = \"display:none; text-align: left;font-family:Arial, Helvetica, sans-serif;font-size:12px;font-weight:bold;color:#024E8A;padding:50px;\" >");
        document.write("Sorry, we are experiencing some technical difficulties. Please try again or contact the webmaster.");
        document.write("</div>");

        document.write("<table id=\"oTable\" class=\"braff-brate-results-tbl\" cellpadding=\"0\" cellspacing=\"0\" >");
        document.write("<div id=\"dvMortTableBody\" style = \"display:none\"><tbody id=\"BRrateTB\"></tbody></div>");
        document.write("</table>");
        document.write("</div>");

        document.write("<p id=\"BRmoreInfo\"></p>");
        document.write("<ul id=\"BRadditionalLinks\" class=\"braff-disc-pts\" style=\"font:11px arial\" ></ul>");
        document.write("</div>");
        document.write("</div>");
        document.write("<span class=\"braff-brate-botright\"></span><span class=\"braff-brate-botleft\"></span>");
        document.write("<div class=\"braff-brate-attr\">");
        document.write("<span>Powered by:</span> <a href=" + "http://www.bankrate.com?pid=p:" + this.Partner + " target=\"_blank\"><img height=\"21\" border=\"0\" width=\"114\" src=\"http://www.bankrate.com/images/brm_logos/bankrate-logo.gif\"></a>");
        document.write("</div>");
        document.write("</div>");
        document.write("</div>");
    },

    ValidateLoanAmount: function (mortgageloanVal, lblErrorMsg, usingConfig) {
        this.LoanAmount = parseFloat(this.EnforceProperLoanFormat(mortgageloanVal, true));
        var checkWebpage = document.getElementById("mtgProductsDll");
        if (this.LoanAmount > this.JumboThreshold) {
            if (!usingConfig) {
                document.getElementById("liProducts").style.display = "none";
                document.getElementById("liJumboProducts").style.display = "block";
            }
            if (this.loadTime || usingConfig) {
                if (checkWebpage != null) {
                    document.getElementById("mtgProductsDll").style.display = "none";
                    document.getElementById("mtgJumboProductsDll").style.display = "block";
                }
            }
        } else {
            if (!usingConfig) {
                document.getElementById("liProducts").style.display = "block";
                document.getElementById("liJumboProducts").style.display = "none";
            }
            if (this.loadTime || usingConfig) {
                if (checkWebpage != null) {
                    document.getElementById("mtgProductsDll").style.display = "block";
                    document.getElementById("mtgJumboProductsDll").style.display = "none";
                }
            }
        }

        return true;
    },


    EnforceProperLoanFormat: function (textboxName, check) {
        var textbox = '';
        var num = '';
        if (check) {
            textbox = document.getElementById(textboxName);
            num = textbox.value.toString().replace(/\$|\,/g, '');
        }
        else {
            textbox = textboxName;
            num = textbox.toString().replace(/\$|\,/g, '');
        }
        num = num.replace(/[a-z]/, '');

        if (isNaN(num))
            num = "0";

        var returnVal = num;
        if (check) {
            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));
            }
            textbox.value = (((sign) ? '' : '-') + num);
        }
        return returnVal;
    },
    ShowMtgRateSearchPage: function (StateSelector, CitySelector, mortgageLoanAmountTextBox, mrtgStateError, mrtgCityError, mortgageLoanAmountError, localCallUsingzip) {
        this.RowCount = 1;
        var cityIndex = document.getElementById(CitySelector).selectedIndex;
        var cityValue = "0";
        if (cityIndex >= 0) {
            cityValue = document.getElementById(CitySelector).options[cityIndex].value;
        }

        var mortgageddlIndex = document.getElementById(StateSelector).selectedIndex;
        var mortgageddlValue = document.getElementById(StateSelector).options[mortgageddlIndex].value;
        var result_amount = this.ValidateLoanAmount(mortgageLoanAmountTextBox, mortgageLoanAmountError, false);
        var result = this.ValidateStateCity("StateSelector", cityValue, mrtgStateError, mrtgCityError);
        this.CallUsingZip = localCallUsingzip;
        document.getElementById("mtgServiceTurnOff").style.display = 'none';
        document.getElementById("dvMortTableBody").style.display = 'none';
        document.getElementById("MtgLoadingImgDiv").style.display = 'block';
        this.FetchRss(false);
    },

    ValidateStateCity: function (stateDropDown, cityValue, stateErr, cityErr) {
        var stateIndex = document.getElementById(stateDropDown).selectedIndex;
        var stateValue = document.getElementById(stateDropDown).options[stateIndex].value;
        if (stateValue == "Select State") {
            document.getElementById(stateErr).style.display = "block";
            document.getElementById(cityErr).style.display = "none";
            return false;
        }
        else if (cityValue == "0" || cityValue == "Select City") {
            document.getElementById(cityErr).style.display = "block";
            document.getElementById(stateErr).style.display = "none";
            return false;
        }

        else {
            document.getElementById(stateErr).style.display = "none";
            document.getElementById(cityErr).style.display = "none";
            return true;
        }
    },

    FnInit: function (row, apr, date, aprMax, totalPoints, lock, fees, payment, comments, url, imgId, lenderId,
					commentsHyperlinked, nameHyperlinkAvailable, listingType, defaultSort, lenderSort, aprSort, rateSort, feesSort, count) {

        var oTable = document.getElementById("BRrateTB");
        var oDiv = document.createElement("div");
        var oCell, oCell1, oCell2, oCell3, oCell4, oCell5;
        var i, j;

        var cpcLink = url;

        oRow = document.createElement("tr");
        var rowID = 'oRow' + this.RowCount;

        if (comments.length > 10) {
            oRow.setAttribute('style', 'border-bottom:hidden');
        }

        oTable.appendChild(oRow);
        oCell = document.createElement("td");
        oCell.className = "lender";

        var fixedID = document.createElement('div');
        fixedID.style.display = "none";
        fixedID.innerHTML = count;
        fixedID.setAttribute('id', count);
        oCell.appendChild(fixedID);

        var lenderSortDiv = document.createElement('div');
        lenderSortDiv.style.display = "none";
        lenderSortDiv.innerHTML = lenderSort;
        oCell.appendChild(lenderSortDiv);

        var lenderDiv1 = document.createElement('div');
        lenderDiv1.id = "imgDiv1" + this.RowCount;

        var a = document.createElement('a');
        var clickOnLender = 'lender';
        if (imgId != null && imgId.length != 0) {
            var imeg = document.createElement('img');
            imeg.setAttribute('src', 'http://www.bankrate.com/system/img/inst/' + imgId + '_logo.gif');
            imeg.setAttribute('height', '45');
            imeg.setAttribute('border', '0');
            imeg.setAttribute('width', '125');
            if (listingType.toLowerCase() == 'paid' && nameHyperlinkAvailable.toLowerCase() == 'true') {
                if (this.CheckForIE) {
                    a.onclick = new Function("BRMmortgageRateTable.TrackClick(8, this, '" + cpcLink + "', '" + clickOnLender + "');");
                } else {
                    a.setAttribute("onclick", "BRMmortgageRateTable.TrackClick(8, this, '" + cpcLink + "', '" + clickOnLender + "');");
                }

                a.appendChild(imeg);
                lenderDiv1.appendChild(a);
                oCell.appendChild(lenderDiv1);
            } else {
                lenderDiv1.appendChild(imeg);
                oCell.appendChild(lenderDiv1);
            }
            if (this.CheckForIE) {
                oCell.style.verticalAlign = 'middle';
            }
        }
        else {
            var lenderName = document.createElement('div');
            lenderName.style.width = '125px';
            lenderName.innerHTML = lenderId;
            if (listingType.toLowerCase() == 'paid' && nameHyperlinkAvailable.toLowerCase() == 'true') {
                if (this.CheckForIE) {
                    a.onclick = new Function("BRMmortgageRateTable.TrackClick(2, this, '" + cpcLink + "', '" + clickOnLender + "');");
                } else {
                    a.setAttribute("onclick", "BRMmortgageRateTable.TrackClick(2, this, '" + cpcLink + "', '" + clickOnLender + "');");
                }
                a.appendChild(lenderName);
                lenderDiv1.appendChild(a);
                oCell.appendChild(lenderDiv1);
            } else {
                lenderDiv1.appendChild(lenderName);
                oCell.appendChild(lenderDiv1);
            }
            if (this.CheckForIE) {
                oCell.style.verticalAlign = 'middle';
            }
        }

        oRow.appendChild(oCell);

        oCell1 = document.createElement("td");
        oCell1.className = "mtg-apr";

        var aprDiv1 = document.createElement('div');
        aprDiv1.className = "apr";
        aprDiv1.innerHTML = apr + "%";

        var aprDate1 = document.createElement('div');
        aprDate1.className = "aprDate";
        aprDate1.innerHTML = date;

        var aprDivSort = document.createElement('div');
        aprDivSort.innerHTML = aprSort;
        aprDivSort.style.display = "none";

        oCell1.appendChild(aprDivSort);
        oCell1.appendChild(aprDiv1);
        oCell1.appendChild(aprDate1);

        if (this.CheckForIE) {
            oCell1.style.verticalAlign = 'middle';
        }
        oRow.appendChild(oCell1);

        oCell2 = document.createElement("td");
        oCell2.className = "mtg-rate";
        var rateDiv1 = document.createElement('div');
        //rateDiv1.className = "rate";
        rateDiv1.innerHTML = aprMax + "%";
        var points1 = document.createElement('div');
        points1.className = "points";
        points1.innerHTML = "at " + totalPoints + " pts";
        var lock1 = document.createElement('div');
        lock1.className = "lock";
        lock1.innerHTML = lock + " day rate lock";
        var rateDivSort = document.createElement('div');
        rateDivSort.innerHTML = rateSort;
        rateDivSort.style.display = "none";

        oCell2.appendChild(rateDivSort);
        oCell2.appendChild(rateDiv1);
        oCell2.appendChild(points1);
        oCell2.appendChild(lock1);
        if (this.CheckForIE) {
            oCell2.style.verticalAlign = 'middle';
        }
        oRow.appendChild(oCell2);

        oCell3 = document.createElement("td");
        oCell3.className = "mtg-cost";
        var cost1 = document.createElement('div');
        cost1.innerHTML = "Fees in APR:" + this.FormatCurrency(fees).replace(".00", "");

        var estpmt1 = document.createElement('div');
        estpmt1.innerHTML = "Est payment: " + this.FormatCurrency(payment).replace(".00", "");

        var costDivSort = document.createElement('div');
        costDivSort.innerHTML = feesSort;
        costDivSort.style.display = "none";

        oCell3.appendChild(costDivSort);
        oCell3.appendChild(cost1);
        oCell3.appendChild(estpmt1);

        if (this.CheckForIE) {
            oCell3.style.verticalAlign = 'middle';
        }
        oRow.appendChild(oCell3);


        var dynamicWidgetWidth = parseInt(this.widgetWidth.replace('px', ''));

        var mtgcommentsDiv = document.createElement('div');
        oCell4 = document.createElement("td");
        oCell4.className = "comments";
        if (listingType.toLowerCase() == 'paid' && commentsHyperlinked.toLowerCase() == 'true') {
            var a1 = document.createElement('a');
            var clickOnComments = 'comment';
            if (this.CheckForIE) {
                a1.onclick = new Function("BRMmortgageRateTable.TrackClick(5, this, '" + cpcLink + "', '" + clickOnComments + "');");
            } else {
                a1.setAttribute("onclick", "BRMmortgageRateTable.TrackClick(5, this, '" + cpcLink + "', '" + clickOnComments + "');");
            }

            a1.innerHTML = comments;
            a1.style.cursor = 'pointer';
            a1.setAttribute('target', '_blank');
            mtgcommentsDiv.appendChild(a1);
            oCell4.appendChild(mtgcommentsDiv);
        } else {
            var s1 = document.createElement('span');

            if (comments.length < 1) {
                comments = '&nbsp;';
            }

            s1.innerHTML = comments;
            mtgcommentsDiv.appendChild(s1);
            oCell4.appendChild(mtgcommentsDiv);
        }

        if (this.CheckForIE) {
            oCell4.style.verticalAlign = 'middle';
        }
        oRow.appendChild(oCell4);
        oRow.setAttribute('style', 'border-bottom:1px solid #BFC4C8;');
        oCell5 = document.createElement("td");
        oCell5.className = "contact";
        var imeg1 = document.createElement('img');
        imeg1.setAttribute('src', 'http://www.bankrate.com/system/img/green-go-btn2.gif');
        if (listingType.toLowerCase() == 'paid' && nameHyperlinkAvailable.toLowerCase() == 'true') {
            var a2 = document.createElement('a');
            var clickOnGo = 'go';
            if (this.CheckForIE) {
                a2.onclick = new Function("BRMmortgageRateTable.TrackClick(11, this, '" + cpcLink + "', '" + clickOnGo + "');");
            } else {
                a2.setAttribute("onclick", "BRMmortgageRateTable.TrackClick(11, this, '" + cpcLink + "', '" + clickOnGo + "');");
            }

            a2.appendChild(imeg1);
            oCell5.appendChild(a2);
        } else {
            oCell5.innerHTML = '&nbsp;';
        }
        if (this.CheckForIE) {
            oCell5.style.verticalAlign = 'middle';
        }
        oRow.appendChild(oCell5);

        oRow.setAttribute('id', rowID);

        oRow.className = 'np';
        var boolComment = false;
        var commentRowId = "";
        //bottom comments
        if (comments.length > 6) {
            boolComment = true;
            commentRowId = "comment" + this.RowCount;
            var ancherId = "ancher" + this.RowCount;

            var oCommentRow = document.createElement("tr");
            oTable.appendChild(oCommentRow);
            oCell6 = document.createElement("td");
            oCell6.className = "braff-mtg-bottom-comments";
            oCell6.setAttribute('colSpan', '6');
            oCell6.setAttribute('id', commentRowId);

            var commentsIdDiv = document.createElement('div');
            commentsIdDiv.innerHTML = rowID + "~" + commentRowId + "~" + boolComment + "~" + ancherId + "~" + comments;
            commentsIdDiv.style.display = "none";
            oCell6.appendChild(commentsIdDiv);

            if (this.CheckForIE) {
                oCell6.onmouseover = new Function("BRMmortgageRateTable.MouseOver('" + rowID + "', '" + commentRowId + "', '" + boolComment + "');");
                oCell6.onmouseout = new Function("BRMmortgageRateTable.MouseOut('" + rowID + "', '" + commentRowId + "', '" + boolComment + "');");
            } else {
                oCell6.setAttribute("onmouseover", "BRMmortgageRateTable.MouseOver('" + rowID + "', '" + commentRowId + "', '" + boolComment + "');");
                oCell6.setAttribute("onmouseout", "BRMmortgageRateTable.MouseOut('" + rowID + "', '" + commentRowId + "', '" + boolComment + "');");
            }

            if (listingType.toLowerCase() == 'paid' && commentsHyperlinked.toLowerCase() == 'true') {
                var a1 = document.createElement('a');
                a1.setAttribute('id', ancherId);
                commentsIdDiv.innerHTML = rowID + "~" + commentRowId + "~" + boolComment + "~" + ancherId + "~" + comments + "~" + cpcLink;
                var clickOnBottomComment = 'bottomComment';
                if (this.ieVersion == 7) {
                    a1.onclick = new Function("BRMmortgageRateTable.TrackClick(5, this, '" + cpcLink + "', '" + clickOnBottomComment + "');");
                } else {
                    a1.setAttribute("onclick", "BRMmortgageRateTable.TrackClick(5, this, '" + cpcLink + "', '" + clickOnBottomComment + "');");
                }

                a1.innerHTML = '<u>' + comments + '</u>';
                a1.style.cursor = 'pointer';
                a1.setAttribute('target', '_blank');
                oCell6.appendChild(a1);
            } else {
                var s1 = document.createElement('span');
                s1.innerHTML = comments;
                oCell6.appendChild(s1);
            }
            oCommentRow.appendChild(oCell6);
        }
        if (this.CheckForIE) {
            oRow.onmouseover = new Function("BRMmortgageRateTable.MouseOver('" + rowID + "', '" + commentRowId + "', '" + boolComment + "');");
            oRow.onmouseout = new Function("BRMmortgageRateTable.MouseOut('" + rowID + "', '" + commentRowId + "', '" + boolComment + "');");
        } else {
            oRow.setAttribute("onmouseover", "BRMmortgageRateTable.MouseOver('" + rowID + "', '" + commentRowId + "', '" + boolComment + "');");
            oRow.setAttribute("onmouseout", "BRMmortgageRateTable.MouseOut('" + rowID + "', '" + commentRowId + "', '" + boolComment + "');");
        }
        fixedID.innerHTML = boolComment;
        this.RowCount = this.RowCount + 1;
    },

    MouseOut: function (dataRow, commentRow, commentStaus) {
        document.getElementById(dataRow).className = "np";
        if (commentStaus == 'true') {
            document.getElementById(commentRow).className = "braff-mtg-bottom-comments";
        }
    },

    MouseOver: function (dataRow, commentRow, commentStaus) {
        document.getElementById(dataRow).className = "br-mouseover-data";
        if (this.CheckForIE && this.ieVersion != 7 || this.is_chrome) {
            document.getElementById(dataRow).style.height = '74px';
        }

        if (commentStaus == 'true') {

            document.getElementById(commentRow).className = "br-mouseover-bottom-comments";
            document.getElementById(commentRow).style.borderRight = '1px solid #BFC4C8';
            document.getElementById(commentRow).style.borderLeft = '1px solid #BFC4C8';
        }
    },

    TrackClick: function (clickType, obj, url, clickOnType) {
        var today = new Date(); var year = today.getFullYear(); var month = today.getMonth() + 1; var date = today.getDate();
        var hour = today.getHours(); var minute = today.getMinutes(); var second = today.getSeconds(); var millisecond = today.getMilliseconds();
        var currentDT = month + '/' + date + '/' + year + ' ' + hour + ':' + minute + ':' + second + '.' + millisecond;
        var overrides = '';
        var v38_id = '';
        if (clickOnType == 'lender' || clickOnType == 'comment') {
            overrides = obj.parentNode.parentNode.parentNode.id.replace("oRow", "") + "," + clickType + ",,";
            v38_id = obj.parentNode.parentNode.parentNode.id.replace("oRow", "");
        }
        else if (clickOnType == 'go') {
            overrides = obj.parentNode.parentNode.id.replace("oRow", "") + "," + clickType + ",,";
            v38_id = obj.parentNode.parentNode.id.replace("oRow", "");
        }
        else if (clickOnType == 'bottomComment') {
            overrides = obj.parentNode.id.replace("comment", "") + "," + clickType + ",,";
            v38_id = obj.parentNode.id.replace("comment", "");
        }

        var cpcLink = url;

        if (url.indexOf('||') != -1) {
            var cpcValues = url.split('||');
            cpcLink = cpcValues[0];

            var omniValues = cpcValues[1].split(',');

            this.TrackLink(this, omniValues[0], omniValues[1], omniValues[1], omniValues[2], omniValues[3], omniValues[4], v38_id, omniValues[6], clickType);
        }

        var redirectTo = cpcLink + "&c=" + overrides + '&click_date=' + currentDT + '&ref_url=' + escape(location.href);

        window.open(redirectTo);
    },

    TrimAll: function (sString) {
        while (sString.substring(0, 1) == ' ') {
            sString = sString.substring(1, sString.length);
        }
        while (sString.substring(sString.length - 1, sString.length) == ' ') {
            sString = sString.substring(0, sString.length - 1);
        }
        return sString;
    },

    FillBody: function (json) {
        try {
            if (json.bankrate.data != null && json.bankrate.data != 'undefined') {
                document.getElementById("BRrateHeader").innerHTML = "Find the Best and Latest Mortgage Rates for " + json.bankrate.data.response.global.abbreviatedLocation;

                document.getElementById("BRrateSeoheading").innerHTML = "Compare rates with confidence. Rates are accurate and available as of the date seen " +
				"for Bankrate customers. Identify yourself as a Bankrate consumer to get the Bankrate.com rate. Bankrate.com has today's most competitive mortgage rates.";

                document.getElementById("BRcriteriaUsed").innerHTML = "<b>Criteria used: </b>" +
				json.bankrate.data.response.summary.description + ", Credit Score 700-720, 20% Down Payment";

                document.getElementById("BRmoreInfo").innerHTML = "Many lenders have different rates on their own websites than those posted on Bankrate.com.  " +
				"In order to get the Bankrate.com rate, please identify yourself as a Bankrate.com customer. Rates are subject to change without notice and may vary branch to branch.  " +
				"These quotes are from banks, and thrifts, some of whom have paid for a link to their own Web site where you can find additional information.  " +
				' <a href=\"http://www.bankrate.com/funnel/mortgages/product-criteria.aspx?prodtype=mtg&pid=p:' + this.Partner + "\" target=\"_blank\" style= \"color:#024E8A; font-weight:bold; text-decoration:underline;\">More information</a>."

                document.getElementById("BRadditionalLinks").innerHTML =
				"<li>For more rates, products or information <a href=\"http://www.bankrate.com/compare-rates.aspx?pid=p:" + this.Partner + "\" target=\"_blank\" style= \"color:#024E8A; font-weight:bold; text-decoration:underline;\">click here</a>.</li>" +
				"<li>To see your rates displayed, <a href=\"http://www.bankrate.com/mediakit/contactus.asp?pid=p:" + this.Partner + "\" target=\"_blank\" style= \"color:#024E8A; font-weight:bold; text-decoration:underline;\">click here</a>.</li>" +
				"<li>To add free mortgage content to your own site – rate averages, calculators, or a compare rates widget, <a href=\"http://www.bankrate.com/free-content?pid=p:" + this.Partner + "\" target=\"_blank\" style= \"color:#024E8A; font-weight:bold; text-decoration:underline;\">click here</a>.</li>"

                // this is done to show an initial value in the state and city dropdowns rather than generic 'geo-targeted' text after the page loads for the first time.

                var geoTargetedLocation = json.bankrate.data.response.global.abbreviatedLocation.split(',');
                this.GeoTargetedCity = this.TrimAll(geoTargetedLocation[0]);
                this.GeoTargetedState = this.TrimAll(geoTargetedLocation[1]);

                var stateSelectorDropDown = document.getElementById('StateSelector');
                for (var i = 0; i < stateSelectorDropDown.options.length; i++) {
                    if (stateSelectorDropDown.options[i].text == this.GeoTargetedState) {
                        stateSelectorDropDown.options[i].selected = true;
                    }
                }
                this.SetCities('StateSelector', 'CitySelector');

                if (json.bankrate.data.response.result1 != null && typeof (json.bankrate.data.response.result1.length) != 'undefined') {
                    this.FetchMortgageItemsUsingJson(json.bankrate.data.response.result1, 'paid');
                    this.FetchMortgageItemsUsingJson(json.bankrate.data.response.result1, 'editorial');

                    document.getElementById("MtgLoadingImgDiv").style.display = 'none';
                    document.getElementById("mtgServiceTurnOff").style.display = 'none';
                    document.getElementById("dvMortTableBody").style.display = 'block';
                }
                else {
                    this.MtgNoRecord = false;
                    this.ShowNoRecordsFound();

                }

                var staticText = document.createElement('p');
                staticText.innerHTML = 'The rates on this table are valid for credit scores of 700 and above. For scores from 680 to 699, borrowers would typically see increased fees up to 1% of the loan value, or an adjustment in the rate. If you believe that you have received an inaccurate quote or are otherwise not satisfied with the services provided to you by the lender you choose, please <a href="mailto:qualitycontrol@bankrate.com">click here</a>.';
                if (document.getElementById("oTableContainer").getElementsByTagName("p").length == 0) {
                    document.getElementById("oTableContainer").appendChild(staticText);
                }

                var TableSorter1 = new this.TSorter;
                TableSorter1.initiation('mortTableHeaders');
                this.loadTime = false;
                this.SetDynamicAdjustments();
            }
            else {
                this.MtgNoRecord = true;
                this.ShowNoRecordsFound();
            }
        }
        catch (e) { }
    },

    ShowNoRecordsFound: function () {
        this.SetDynamicAdjustments();
        document.getElementById("MtgLoadingImgDiv").style.display = 'none';
        document.getElementById("mtgServiceTurnOff").style.display = 'block';
        document.getElementById("dvMortTableBody").style.display = 'none';
    },

    FetchMortgageItemsUsingJson: function (items, strListingType) {
        for (var j = 0; j < items.length; j++) {
            var apr = '', aprMax = '', comments = '', date = '', fees = '', payment = '', origPoints = '', lock = '', url = '';
            var imgId = '', lenderId = '', commentsHyperlinked = '', nameHyperlinkAvailable = '', listingType = '';
            var lenderSort = '', aprSort = '', rateSort = '', feesSort = '', defaultSort = '', discPoints = '', totalPoints = '';

            if (typeof (items[j].listingType) != 'undefined' && items[j].listingType != null)
                listingType = items[j].listingType;

            if (listingType.toLowerCase() == strListingType) {
                if (typeof (items[j].apr) != 'undefined' && items[j].apr != null)
                    apr = items[j].apr;
                if (typeof (items[j].rate) != 'undefined' && items[j].rate != null)
                    aprMax = items[j].rate;
                if (typeof (items[j].comments) != 'undefined' && items[j].comments != null)
                    comments = items[j].comments;
                if (typeof (items[j].date) != 'undefined' && items[j].date != null)
                    date = this.CustomDate(items[j].date);
                if (typeof (items[j].fees) != 'undefined' && items[j].fees != null)
                    fees = items[j].fees;
                if (typeof (items[j].payment) != 'undefined' && items[j].payment != null)
                    payment = items[j].payment;
                if (typeof (items[j].origPoints) != 'undefined' && items[j].origPoints != null)
                    origPoints = items[j].origPoints;
                if (typeof (items[j].discPoints) != 'undefined' && items[j].discPoints != null)
                    discPoints = items[j].discPoints;
                if (typeof (items[j].lock) != 'undefined' && items[j].lock != null)
                    lock = items[j].lock;
                if (typeof (items[j].cpc) != 'undefined' && items[j].cpc != null)
                    url = items[j].cpc;
                if (typeof (items[j].img) != 'undefined' && items[j].img != null)
                    imgId = items[j].img;
                if (typeof (items[j].lender) != 'undefined' && items[j].lender != null)
                    lenderId = items[j].lender;
                if (typeof (items[j].commentsHyperlinked) != 'undefined' && items[j].commentsHyperlinked != null)
                    commentsHyperlinked = items[j].commentsHyperlinked;
                if (typeof (items[j].nameHyperlinkAvailable) != 'undefined' && items[j].nameHyperlinkAvailable != null)
                    nameHyperlinkAvailable = items[j].nameHyperlinkAvailable;
                if (typeof (items[j].defaultSort) != 'undefined' && items[j].defaultSort != null)
                    defaultSort = items[j].defaultSort;
                if (typeof (items[j].publishnameSort) != 'undefined' && items[j].publishnameSort != null)
                    lenderSort = items[j].publishnameSort;
                if (typeof (items[j].aprSort) != 'undefined' && items[j].aprSort != null)
                    aprSort = items[j].aprSort;
                if (typeof (items[j].rateSort) != 'undefined' && items[j].rateSort != null)
                    rateSort = items[j].rateSort;
                if (typeof (items[j].feesSort) != 'undefined' && items[j].feesSort != null)
                    feesSort = items[j].feesSort;

                totalPoints = parseFloat(origPoints) + parseFloat(discPoints);
                totalPoints = totalPoints.toFixed(3);

                this.FnInit(j, apr, date, aprMax, totalPoints, lock, fees, payment, comments, url, imgId, lenderId,
					commentsHyperlinked, nameHyperlinkAvailable, listingType, defaultSort, lenderSort, aprSort, rateSort, feesSort, j);
            }
        }
    },
    // Note the TSorter class has been modified from the original copy for this widget.
    TSorter: function () {
        var table = Object;
        var botComments = Array;
        var tempTrs = Array;
        var trs = Array;
        var ths = Array;
        var curSortCol = Object;
        var prevSortCol = '4';
        var sortType = Object;

        //functionget() { }

        function getCell(index) {
            return trs[index].cells[curSortCol]
        }

        this.initiation = function (tableName) {
            headerTable = document.getElementById(tableName);
            ths = headerTable.getElementsByTagName("th");
            for (var i = 0; i < ths.length - 1; i++) {
                var headerID = getHeaderDivId(i);
                if (headerID != '') {
                    document.getElementById(headerID).onclick = function () {
                        sort(this);
                    }
                }
            }

            table = document.getElementById("oTable");
            return true;
        };

        function getHeaderDivId(indx) {
            var headerDivId = '';
            if (indx == 0)
                headerDivId = 'Mtg_lender_header';
            else if (indx == 1)
                headerDivId = 'Mtg_apr_header';
            else if (indx == 2)
                headerDivId = 'Mtg_rate_header';
            else if (indx == 3)
                headerDivId = 'Mtg_cost_header';

            return headerDivId;
        }

        function getHeaderIndex(val) {
            var indx = '';
            if (val == 'Lender')
                indx = 0;
            else if (val == 'APR')
                indx = 1;
            else if (val == 'Rate')
                indx = 2;
            else if (val == 'Costs and fees')
                indx = 3;

            return indx;
        }


        function sort(oTH) {
            sortType = oTH.innerHTML;
            curSortCol = getHeaderIndex(sortType);
            if (sortType != null && sortType != "") {
                tempTrs = table.tBodies["BRrateTB"].getElementsByTagName("tr");
                var trCount = tempTrs.length;

                for (var i = 0; i < trCount; i++) {
                    if (tempTrs[i].className != 'np') {
                        botComments[tempTrs[i - 1].firstChild.firstChild.id] = tempTrs[i].firstChild.innerHTML;
                    }
                }

                for (var i = 0; i < trCount; i++) {
                    if (i < tempTrs.length) {
                        if (tempTrs[i].className != 'np') {
                            table.tBodies["BRrateTB"].deleteRow(i);
                        }
                    }
                }

                trs = table.tBodies["BRrateTB"].getElementsByTagName("tr");

                setGet(sortType);

                if (prevSortCol == curSortCol) {
                    reverseTable();
                }
                else {
                    quicksort(0, trs.length);
                    reverseTable();
                }
                prevSortCol = curSortCol;
            }

            if (botComments.length > 0) {
                for (var i = 1; i <= trs.length; i++) {
                    if (typeof (trs[i - 1]) != "undefined") {
                        if (trs[i - 1].firstChild != null) {
                            if (typeof (botComments[trs[i - 1].firstChild.firstChild.id]) != "undefined") {
                                var dataRowPos = trs[i - 1].id;
                                var rowPos = dataRowPos.replace('oRow', '');
                                oNewCommentRow = document.createElement("tr");
                                oDataCell = document.createElement("td");
                                oDataCell.className = "braff-mtg-bottom-comments";
                                oDataCell.setAttribute('colSpan', '6');
                                oDataCell.setAttribute('background-color', '#F8F8F8');

                                var commentStr = botComments[trs[i - 1].firstChild.firstChild.id];

                                var strToFind = '/div';
                                var divPos = parseInt(commentStr.search(strToFind));
                                var startPos = 28;
                                if (divPos == -1) {
                                    strToFind = '/DIV';
                                    divPos = parseInt(commentStr.search(strToFind));
                                    startPos = 27;
                                }
                                var endPos = divPos + 5;
                                var strIds = commentStr.substring(startPos, endPos - 6);
                                strIds = strIds.replace('>', '').replace('<', '');
                                var arrIds = strIds.split('~');
                                var commentRowPos = 'comment' + rowPos;
                                oDataCell.setAttribute('id', commentRowPos);

                                try {
                                    var commentsIdDiv1 = document.createElement('div');
                                    commentsIdDiv1.innerHTML = strIds;
                                    commentsIdDiv1.style.display = "none";
                                    oDataCell.appendChild(commentsIdDiv1);

                                    if (arrIds.length == 6) {
                                        var a11 = document.createElement('a');
                                        a11.setAttribute('id', 'ancher' + rowPos);
                                        var clickOnBottomComment = 'bottomComment';
                                        if (BRMmortgageRateTable.ieVersion == 7) {
                                            a11.onclick = new Function("BRMmortgageRateTable.TrackClick(5, this, '" + arrIds[5] + "', '" + clickOnBottomComment + "');");
                                        }
                                        else {
                                            a11.setAttribute("onclick", "BRMmortgageRateTable.TrackClick(5,this,'" + arrIds[5] + "', '" + clickOnBottomComment + "');");
                                        }
                                        a11.innerHTML = '<u>' + arrIds[4] + '</u>';
                                        a11.style.cursor = 'pointer';
                                        a11.setAttribute('target', '_blank');
                                        oDataCell.appendChild(a11);
                                    }
                                    else {
                                        var s11 = document.createElement('span');
                                        var tempComment = arrIds[4];
                                        if (arrIds[4].length < 1) {
                                            tempComment = '&nbsp;';
                                        }

                                        s11.innerHTML = tempComment;
                                        oDataCell.appendChild(s11);
                                    }
                                }
                                catch (e) {
                                }

                                if (BRMmortgageRateTable.CheckForIE) {
                                    oDataCell.onmouseover = new Function("BRMmortgageRateTable.MouseOver('" + dataRowPos + "', '" + commentRowPos + "', '" + arrIds[2] + "');");
                                    oDataCell.onmouseout = new Function("BRMmortgageRateTable.MouseOut('" + dataRowPos + "', '" + commentRowPos + "', '" + arrIds[2] + "');");
                                } else {
                                    oDataCell.setAttribute("onmouseover", "BRMmortgageRateTable.MouseOver('" + dataRowPos + "', '" + commentRowPos + "', '" + arrIds[2] + "');");
                                    oDataCell.setAttribute("onmouseout", "BRMmortgageRateTable.MouseOut('" + dataRowPos + "', '" + commentRowPos + "', '" + arrIds[2] + "');");
                                }

                                oNewCommentRow.appendChild(oDataCell);
                                oNewCommentRow.setAttribute('style', 'border-left:1px solid #BFC4C8; border-right:1px solid #BFC4C8');
                                if (typeof (trs[i]) != "undefined") {
                                    table.tBodies["BRrateTB"].insertBefore(oNewCommentRow, trs[i]);
                                }
                                else {
                                    if (BRMmortgageRateTable.CheckForIE) {
                                        table.tBodies["BRrateTB"].appendChild(oNewCommentRow);
                                    }
                                    else
                                        table.tBodies["BRrateTB"].insertBefore(oNewCommentRow, trs[i]);
                                }
                            }
                        }
                    }
                }
                BRMmortgageRateTable.ShowMtgComments();
            }
        }

        function setGet(sortType) {
            switch (sortType) {
                case "Lender":
                    get = function (index) {
                        return parseFloat(getCell(index).childNodes[1].innerHTML);
                    };
                    break;
                case "APR":
                    get = function (index) {
                        return parseFloat(getCell(index).firstChild.innerHTML);
                    };
                    break;
                case "Rate":
                    get = function (index) {
                        return parseFloat(getCell(index).firstChild.innerHTML);
                    };
                    break;
                case "Costs and fees":
                    get = function (index) {
                        return parseFloat(getCell(index).firstChild.innerHTML);
                    };
                    break;
                default:
                    get = function (index) {
                        return parseFloat(getCell(index).firstChild.innerHTML);
                    };
                    break;
            };
        }

        function exchange(i, j) {
            if (i == j + 1) {
                table.tBodies["BRrateTB"].insertBefore(trs[i], trs[j]);
            } else if (j == i + 1) {
                table.tBodies["BRrateTB"].insertBefore(trs[j], trs[i]);
            } else {
                var tmpNode = table.tBodies["BRrateTB"].replaceChild(trs[i], trs[j]);
                if (typeof (trs[i]) == "undefined") {
                    table.appendChild(tmpNode);
                } else {
                    table.tBodies["BRrateTB"].insertBefore(tmpNode, trs[i]);
                }
            }
        }

        function reverseTable() {
            for (var i = 1; i < trs.length; i++) {
                table.tBodies["BRrateTB"].insertBefore(trs[i], trs[0]);
            }

            for (var i = 0; i < trs.length; i++) {
                var botCommentStatus = table.tBodies["BRrateTB"].rows[i].firstChild.firstChild.innerHTML;
                table.tBodies["BRrateTB"].rows[i].setAttribute('id', 'oRow' + (i + 1));
                var rowID1 = 'oRow' + (i + 1);
                var commentRowId1 = ''
                if (botCommentStatus == 'true')
                    commentRowId1 = 'comment' + (i + 1);

                if (BRMmortgageRateTable.CheckForIE) {
                    table.tBodies["BRrateTB"].rows[i].onmouseover = new Function("BRMmortgageRateTable.MouseOver('" + rowID1 + "', '" + commentRowId1 + "', '" + botCommentStatus + "');");
                    table.tBodies["BRrateTB"].rows[i].onmouseout = new Function("BRMmortgageRateTable.MouseOut('" + rowID1 + "', '" + commentRowId1 + "', '" + botCommentStatus + "');");
                } else {
                    table.tBodies["BRrateTB"].rows[i].setAttribute("onmouseover", "BRMmortgageRateTable.MouseOver('" + rowID1 + "', '" + commentRowId1 + "', '" + botCommentStatus + "');");
                    table.tBodies["BRrateTB"].rows[i].setAttribute("onmouseout", "BRMmortgageRateTable.MouseOut('" + rowID1 + "', '" + commentRowId1 + "', '" + botCommentStatus + "');");
                }
            }
        }

        function quicksort(lo, hi) {
            if (hi <= lo + 1) return;

            if ((hi - lo) == 2) {
                if (get(hi - 1) > get(lo)) exchange(hi - 1, lo);
                return;
            }

            var i = lo + 1;
            var j = hi - 1;

            if (get(lo) > get(i)) exchange(i, lo);
            if (get(j) > get(lo)) exchange(lo, j);
            if (get(lo) > get(i)) exchange(i, lo);

            var pivot = get(lo);

            while (true) {
                j--;
                while (pivot > get(j)) j--;
                i++;
                while (get(i) > pivot) i++;
                if (j <= i) break;
                exchange(i, j);
            }
            exchange(lo, j);

            if ((j - lo) < (hi - j)) {
                quicksort(lo, j);
                quicksort(j + 1, hi);
            } else {
                quicksort(j + 1, hi);
                quicksort(lo, j);
            }
        }

        function getDomElementsByClassName() {
            var className = 'np';
            var testClass = new RegExp("(^|\\s)" + className + "(\\s|$)");
            var elements = table.getElementsByTagName('tr');
            var returnElements = [];
            var current;
            var length = elements.length;
            for (var i = 0; i < length; i++) {
                current = elements[i];
                if (testClass.test(current.className)) {
                    returnElements.push(current);
                }
            }
            return returnElements;
        }
    },
    TrackLink: function (obj, s, st, m, pr, a, r, pos, w, h) {
        var sbrm = s_gi(this.ReportSuite);
        sbrm.eVar1 = BRMmortgageRateTable.ConvertToLowerCase(w);
        if (!sbrm.pageType && !sbrm.pageName) {
            var pageName = "";
            if (typeof (s_brm) == 'object' && typeof (s_brm.getPageName) == 'function') {
                pageName = s_brm.getPageName().toLowerCase();
            } else if (typeof (s) == 'object' && typeof (s.getPageName) == 'function') {
                pageName = s.getPageName().toLowerCase();
            } else {
                pageName = sbrm.pageName;
            }
            if (pageName != "") {
                sbrm.pageName = w + '>' + pageName;
                sbrm.eVar21 = sbrm.pageName;
            }
        }
        sbrm.eVar36 = BRMmortgageRateTable.ConvertToLowerCase(s);
        sbrm.eVar38 = BRMmortgageRateTable.ConvertToLowerCase(pos);
        sbrm.eVar39 = BRMmortgageRateTable.ConvertToLowerCase(h);
        sbrm.eVar40 = BRMmortgageRateTable.ConvertToLowerCase(st);
        sbrm.eVar41 = BRMmortgageRateTable.ConvertToLowerCase(m);
        sbrm.eVar42 = BRMmortgageRateTable.ConvertToLowerCase(pr);

        sbrm.products = "CCR;p_" + pr.toLowerCase() + ";1;" + a.toLowerCase();
        sbrm.events = "event6,purchase";
        sbrm.purchaseID = Math.round(Math.random() * 10000000).toString() + new Date().getTime();

        sbrm.tl(obj, 'o', 'Lender Referral');
        sbrm = null;
    },
    ConvertToLowerCase: function (pValue) {
        var lValue = BRMmortgageRateTable.Trim(" " + pValue);
        if ((lValue == null) || (lValue == "undefined")) {
            lValue = "";
        }
        if (lValue != "") {
            if (isNaN(parseFloat(lValue))) {
                return lValue.toLowerCase();
            }
            else {
                return lValue;
            }
        }
        else {
            return lValue;
        }
    },
    Trim: function (pValue) {
        var s;
        s = pValue.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g, "");
        return s;
    }
}



BRMmortgageRateTable.Init();


