jQuery(document).ready(function() {
    jQuery("#MGdialog").dialog({
        position: 'top',
        width: 683,
        height: 550,
        autoOpen: false,
        modal:true,
        open:rateobj.ShowProducts,
        close:function(){
            BrDialogAd.show_ads();
            jQuery('.contact a').css({'cursor':'pointer'});
        },
        hide:"fade"
    });//jQuery('.ui-widget-overlay').click(function(){})
    jQuery(".MGdialog_close").live('click',function(){jQuery("#MGdialog").dialog("close")});
    jQuery("#swMGcontent").show();
    jQuery('#ratefunnelamount').tabs();
    jQuery('#funnellocation').tabs();
    jQuery('#funnellocation').live('tabsselect', function(event, ui) {
        rateobj_StateCityZipSelector.SwitchLocationDisplay(ui.panel.innerHTML)
    });
    jQuery('#searchtabs').tabs();
    jQuery('#searchtabs').live('tabsselect', function(event, ui) {
        rateobj.UpdateMortTab(ui.panel.innerHTML);
    });
    jQuery('.contact a').live('click',function(){
        jQuery('.contact a').css({'cursor':'wait'});
    });
});
var rateobj = function(){
    this.jumboVal = 417000;
    this.kind = 'purchase';
    this.so = false;
	this.UpdateLocalNational=function(value){
       rateobj.is_nat_local=value;
       if(value.toLowerCase() == 'local'){
            jQuery('#rateobj_LocationStateCity').show();
            jQuery('#rateobj_LocationNone').hide();;
        }
        else{
            jQuery('#rateobj_LocationStateCity').hide();
            jQuery('#rateobj_LocationNone').show();
        }
            rateobj.ShowProducts()
    };
    this.UpdateMortTab=function(value){
       rateobj.kind=value;
       if(value.toLowerCase() == 'purchase'){
            jQuery('#rateobj_purchaseTab').className='selected';
            jQuery('#rateobj_refinanceTab').className='';
        }
        else{
            jQuery('#rateobj_refinanceTab').className='selected';
            jQuery('#rateobj_purchaseTab').className='';
        }
            rateobj.ShowProducts()
    };
    this.VerifyIfJumbo = function(){
        this.amt = jQuery("#rateobj_txtLoanAmount").val().replace(/[^0-9]+/g,'');
        if(!this.amt){
           jQuery("#LoanAmountError").show();
        }else{
           jQuery("#rateobj_txtLoanAmount").val('$'+commify(this.amt));
           jQuery("#LoanAmountError").hide();
           rateobj.ShowProducts()
        }
    }
    this.MiniTabs = function(minitab){
        jQuery(".mtg-controls li").removeClass('on');
        jQuery("#"+minitab).addClass('on');
            rateobj.ShowProducts();
    }
    this.ShowProducts=function(){
        if(typeof(arguments[0]) == 'object' &&arguments[0].type == 'dialogopen'){
            jQuery('.ui-widget-overlay').click(function(){jQuery('#MGdialog').dialog('close')});
            BrDialogAd.hide_ads('MGdialog',true);
        }
        if(rateobj.SearchContainerDone == 'working'){
            return;
        }else if(rateobj.SearchContainerDone == true){
            jQuery('.ui-widget-overlay').click(function(){jQuery('#MGdialog').dialog('close')});
            jQuery('.product_checks').hide();
            rateobj.miniTab = jQuery(".mtg-controls .on").attr("id")?jQuery(".mtg-controls .on").attr("id"):'mpcatTab';
            rateobj.down = jQuery("#rateobj_PercentDownCombo").val();
            rateobj.points = jQuery("#rateobj_PointsCombo").val();
            rateobj.amt = jQuery("#rateobj_txtLoanAmount").val().replace(/[^0-9]+/g,'');
            if(rateobj.kind == 'refinance'){
                   rateobj.checkDisplay(mort_prods_json.refi);
            }else{
                   rateobj.checkDisplay(mort_prods_json.purc);
            }
        }else{
            rateobj.SearchContainer();
            rateobj.ShowProducts();
        }
    };
    this.checkDisplay = function(prods){

        var jumkey = (rateobj.amt*1 > rateobj.jumboVal)?0:1;//reversed jumbo = 0
        if(jumkey==0){
            jQuery('#refiTab a').text('Jumbo Refinance');
            jQuery('#purchaseTab a').text('Jumbo Purchase');

            // Check if a jumbo product is selected if this is a jumbo
           if(mort_prods_json[jQuery("input[name='mort_prods']:checked").val()]
              &&  mort_prods_json[jQuery("input[name='mort_prods']:checked").val()].jumbo == 0){
               jQuery("input[name='mort_prods'][value='4']").attr('checked',true);
               this.MiniTabs('mpcatTab');
           }

        }else{
            jQuery('#refiTab a').text('Refinance');
            jQuery('#purchaseTab a').text('Purchase');

           // Check if a normal product is selected if this is not a jumbo
           if(mort_prods_json[jQuery("input[name='mort_prods']:checked").val()]
              &&  mort_prods_json[jQuery("input[name='mort_prods']:checked").val()].jumbo == 1){
               jQuery("input[name='mort_prods'][value='1']").attr('checked',true);
                this.MiniTabs('mpcatTab');
           }
        }
        if( typeof(prods) != 'undefined'){
            jQuery.each(prods,function(id){
                var key = prods[id];
                var mtab = rateobj.miniTab.match(/^(mp|fix|arm|io|all).*/)[1].toUpperCase();
                if( mort_prods_json[key].jumbo == jumkey){jQuery('#product_'+key).attr('checked',false);return;}
                if( mort_prods_json[key][mtab] == 0 ){ return; }
                if( mort_prods_json[key].down*1 != rateobj.down*1 ){ return; }
                if( mort_prods_json[key][rateobj.points] == 0){ return; }
                jQuery("#product_check_div_"+key).show();
            });

        }
    }

    this.SearchContainer = function(){
        rateobj.SearchContainerDone = 'working';
        this.origProducts = new Array;
        if(typeof(rates_rows_params.prods) == 'string'){
            jQuery.each(rates_rows_params.prods.split(','),function(id,key){
                rateobj.origProducts[key]= key;
            });
        }else{
                rateobj.origProducts[rates_rows_params.prods]= rates_rows_params.prods;
        }
        if(rates_rows_params.mtg_tab){
            rateobj.MiniTabs(rates_rows_params.mtg_tab);
        }
        var refiSeen = 0; // see if this is a refi so we can select that tab
        var checkedSeen = 0; // see if this is a refi so we can select that tab

        // Put the products into the box and mark off the ones that were checked
        var sortarray = new Array();
        for(p in mort_prods_json){
            sortarray[p] = mort_prods_json[p];
        }

        // safari and chrome do not keep the order from the json array.
        var sortorder = rates_rows_params.order?rates_rows_params.order:'order';
        nested_sort(sortarray,'n',sortorder);
        for(k=0;k<sortarray.length;k++){
            if(! sortarray[k]){continue;}
            var p = (sortarray[k].id)?sortarray[k].id:null;
            var checked = (this.origProducts[mort_prods_json[p].id])?'checked=checked':'';
            if( this.origProducts[mort_prods_json[p].id] && !rates_rows_params.cd_tab){
                mort_prods_json[p].FIX == 1?this.MiniTabs('fixcatTab'):'';
                mort_prods_json[p].ARM == 1?this.MiniTabs('armcatTab'):'';
                mort_prods_json[p].IO == 1?this.MiniTabs('iocatTab'):'';
                mort_prods_json[p].MP == 1 ?this.MiniTabs('mpcatTab'):'';
            }

            jQuery('#product-container').append(
                    "<div style='' class='product_checks' "
                    +" id='product_check_div_"+mort_prods_json[p].id+"'>"
                    +"<input type='radio' name='mort_prods' id='product_"+mort_prods_json[p].id+"' value='"+mort_prods_json[p].id+"'"
                    +checked+" >"
                    +"<label for='product_"+mort_prods_json[p].id+"' class='checklabel' >"+mort_prods_json[p].desc+"</label>"
                    +"</div>"
            );
            if(checked){
                checkedSeen++;
                // Needed for chrome
                jQuery('#product_'+mort_prods_json[p].id).attr('checked',true);
                rateobj.kind = mort_prods_json[p].refi == 0?'purchase':'refinance';
            }
        }
        if(rateobj.kind ==  'refinance'){
                jQuery('#searchtabs').tabs('select','refiTabData');
        }else{
                jQuery('#searchtabs').tabs('select','purchaseTabData');
        }
        if(rates_rows_params.zip){
            jQuery('#rateobj_StateCityZipSelector_ZipTextBox').val(rates_rows_params.zip);
            rateobj_StateCityZipSelector.ZipKeyUp();
        }else if(rates_rows_params.market){
            //set up the city state from a market
            var cityselect = jQuery('#rateobj_StateCityZipSelector_CitySelector');
            var stateselect = jQuery('#rateobj_StateCityZipSelector_StateSelector');
            jQuery.ajax({
                url: '/wp-admin/admin-ajax.php',
                data:{call:'GetMarketInfoByMarketIDOrMarketType',marketid:rates_rows_params.market,'_ajax_nonce':BR_RATES_GEONONCE,'action':'geo_action'},
                datatype:'json',
                success:function(data,res,req){
                        stateselect.val(data.Table.state);
                        rateobj.statecode = data.Table.state;
                        rateobj_StateCityZipSelector.SwitchLocationDisplay('citystate');
                        GetMarkets(data.Table.state);
                }
            });
            function GetMarkets(state){
                cityselect.attr('disabled','disabled');
                cityselect.html("<option value=''>Loading...</option>");
                jQuery.ajax({
                    url: '/wp-admin/admin-ajax.php',
                    data:{call:'GetMarketsByState',statecode:state,'_ajax_nonce':BR_RATES_GEONONCE,'action':'geo_action'},
                    datatype:'json',
                    success:function(data,res,req){
                        cityselect.html("<option value=''>Select City</option>");
                        var selected;
                        for(key in data.Table){
                            with (row = data.Table[key]){
                                if(row.market_uid == rates_rows_params.market_uid){selected = ' selected="selected" '}
                                cityselect.append("<option value='"+row.market_uid+"'"+selected+">"+row.web_name+"</option>");
                            }
                        }
                        cityselect.val(rates_rows_params.market);
                        stateselect.attr('disabled','');
                        cityselect.attr('disabled','');
                    }
                });
            }
        }
        if(rates_rows_params.points){
            jQuery('#rateobj_PointsCombo').val(rates_rows_params.points);
        }
        if(rates_rows_params.perc){
            jQuery('#rateobj_PercentDownCombo').val(rates_rows_params.perc);
        }
        if(rates_rows_params.loan){
            jQuery('#rateobj_txtLoanAmount').val(rates_rows_params.loan);
            rateobj.VerifyIfJumbo();
        }
        rateobj.SearchContainerDone = true;
    }
    this.searchMortgage = function(){
        var prods = new Array;
        var error = 0;
        var qs='?';
        jQuery("#spanProductError").hide();

        jQuery("input[name=mort_prods]:checked").each(function(id,elem){
            if(rateobj.kind ==  'refinance'){
                if(mort_prods_json[jQuery(elem).val()].refi == 1){
                    prods.push(jQuery(elem).val());
                }
            }else{
                if(mort_prods_json[jQuery(elem).val()].purc == 1){
                    prods.push(jQuery(elem).val());
                }
            }
        });
        jQuery("#product-combobox option:selected").each(function(id,elem){
            if(rateobj.kind ==  'refinance'){
                if(mort_prods_json[jQuery(elem).val()].refi == 1){
                    prods.push(jQuery(elem).val());
                }
            }else{
                if(mort_prods_json[jQuery(elem).val()].purc == 1){
                    prods.push(jQuery(elem).val());
                }
            }
        });

        if(prods.length){
            qs += '&prods='+prods.join(',');
        }else{
            error = 1;
        }

        this.amt = jQuery("#rateobj_txtLoanAmount").val().replace(/[^0-9]+/g,'');
        if(this.amt){
            qs+="&loan="+this.amt;
        }else{this.VerifyIfJumbo();error=1}

        this.zip = jQuery('#rateobj_StateCityZipSelector_ZipTextBox').val().replace(/[^0-9]+/g,'');
        this.zip.replace(/[0-9]{5}.*/g,'$1');
        this.zip = this.zip.length ==5?this.zip:'';
        this.market = jQuery('#rateobj_StateCityZipSelector_CitySelector').val().replace(/[^0-9]+/g,'');
        if(jQuery('#rateobj_StateCityZipSelector_tblStateCitySelect').css('display') == 'block'
            && this.market
        ){
            qs +='&market='+this.market;
        }else if(jQuery('#rateobj_StateCityZipSelector_tblZipCodeSelect').css('display') == 'block'
                && this.zip
                ){
            qs +='&zip='+this.zip;
        }else{
            rateobj_StateCityZipSelector.ZipKeyUp();
            rateobj_StateCityZipSelector.StateChange();
            error=1;
        }

        if(jQuery('#rateobj_PointsCombo').val()){
                qs+='&points='+jQuery('#rateobj_PointsCombo').val();
        }else{error=1}

        if(jQuery('#rateobj_PercentDownCombo').val()){
                qs+='&perc='+jQuery('#rateobj_PercentDownCombo').val();
        }
        if(jQuery('#rate-combobox').val()){
                qs+='&rate-combobox='+jQuery('#rate-combobox').val();
        }
        if(rateobj.kind=='refinance'){
            qs+='&refi=1';
        }
        if(jQuery(".mtg-controls li.on").attr('id')){
            qs+='&mtg_tab='+ jQuery(".mtg-controls li.on").attr('id');
        }
        if(error){
            jQuery("#spanProductError").show();
            return;
        }else{
            if(this.nosubmit == true){
               return {path:location.protocol+'//'+location.host+location.pathname,qs:qs};
            }
            if(! location.pathname.match(/mortgage\/rates/) && this.so == false){
                 document.location.href = location.protocol+'//'+location.host+'/mortgage/rates/?'+qs;
            }else{
               document.location.href = location.protocol+'//'+location.host+location.pathname+qs;
            }
        }
    }
}
rateobj = new rateobj;

var rateobj_StateCityZipSelector = function(){
    this.SwitchLocationDisplay=function(value){
        var validzip=false;
       jQuery('#rateobj_StateCityZipSelector_ZipCodeErrorSpan').hide();
        jQuery('#rateobj_StateCityZipSelector_StateErrorSpan').hide();
        if(value.toLowerCase() == 'zip'){
           jQuery('#rateobj_StateCityZipSelector_tblStateCitySelect').hide();
           jQuery('#rateobj_StateCityZipSelector_tblZipCodeSelect').show();;
           jQuery('#rateobj_StateCityZipSelector_ZipCodeErrorSpan').hide();
           this.selectby='zip';
        }else{
           this.selectby='citystate';
           if(validzip = ValidationManager.CheckZipCode(
                           jQuery('#rateobj_StateCityZipSelector_ZipTextBox'),
                           jQuery('#rateobj_StateCityZipSelector_ZipCodeErrorSpan'),
                           true
                       )
           ){
                //rateobj_StateCityZipSelector.PopulateMarketsFromZip(
                BrGeo.PopulateMarketsFromZip(
                        this,
                        jQuery('#rateobj_StateCityZipSelector_StateSelector'),
                        jQuery('#rateobj_StateCityZipSelector_CitySelector'),
                        jQuery('#rateobj_StateCityZipSelector_ZipTextBox')
                );
               jQuery('#rateobj_StateCityZipSelector_tblStateCitySelect').show();
               jQuery('#rateobj_StateCityZipSelector_tblZipCodeSelect').hide();
            }else{
               jQuery('#rateobj_StateCityZipSelector_tblStateCitySelect').show();
               jQuery('#rateobj_StateCityZipSelector_tblZipCodeSelect').hide();
            }
        }
    };
	this.Initialize=function(){
        var params = window.location.search.toQueryParams();
        if(params['zip'] != null){
           jQuery('#rateobj_StateCityZipSelector_tblStateCitySelect').hide();
           jQuery('#rateobj_StateCityZipSelector_tblZipCodeSelect').show();
        }else{
           jQuery('#rateobj_StateCityZipSelector_tblStateCitySelect').show();
           jQuery('#rateobj_StateCityZipSelector_tblZipCodeSelect').hide();
        }
     };
	this.StateChange=function(){
        ValidationManager.ValidateMarket(
                jQuery('#rateobj_StateCityZipSelector_StateSelector'),
                jQuery('#rateobj_StateCityZipSelector_CitySelector'),
                jQuery('#rateobj_StateCityZipSelector_StateErrorSpan'),
                jQuery('#rateobj_StateCityZipSelector_CityErrorSpan'),
                false
        );
        BrGeo.PopulateMarketsFromState(
                jQuery('#rateobj_StateCityZipSelector_StateSelector'),
                jQuery('#rateobj_StateCityZipSelector_CitySelector')
        );
        rateobj_StateCityZipSelector.OnStateChange(
                rateobj_StateCityZipSelector,
                jQuery('#rateobj_StateCityZipSelector_StateSelector').val()
        )
    };
	this.OnStateChange=function(id,value){};
	this.CityChange=function(){
        ValidationManager.ValidateMarket(
                jQuery('#rateobj_StateCityZipSelector_StateSelector'),
                jQuery('#rateobj_StateCityZipSelector_CitySelector'),
                jQuery('#rateobj_StateCityZipSelector_StateErrorSpan'),
                jQuery('#rateobj_StateCityZipSelector_CityErrorSpan'),true
        );
        rateobj_StateCityZipSelector.marketid=jQuery('#rateobj_StateCityZipSelector_CitySelector').val();
        rateobj_StateCityZipSelector.OnCityChange(
                rateobj_StateCityZipSelector,
                jQuery('#rateobj_StateCityZipSelector_CitySelector').val()
        )
    };
	this.OnCityChange=function(id,value){
        if(value){
           jQuery.get(
               '/wp-admin/admin-ajax.php?call=GetLoanLimitByMarket&market_uid='+value+'&_ajax_nonce=null&action=dict_action',
               function(data){
                   if(typeof(data) == 'object'){
                       rateobj.jumboVal = data.BrDictContent > 10000?data.BrDictContent:rateobj.jumboVal;
                       rateobj.ShowProducts();
                   }
           });
        }
    };
	this.ZipKeyUp=function(){
        var iszipvalid = ValidationManager.CheckZipCode(
                jQuery('#rateobj_StateCityZipSelector_ZipTextBox'),
                jQuery('#rateobj_StateCityZipSelector_ZipCodeErrorSpan'),
                true);
            if(iszipvalid){
                this.zipcode=jQuery('#rateobj_StateCityZipSelector_ZipTextBox').val();
                rateobj_StateCityZipSelector.OnZipChange(
                        rateobj_StateCityZipSelector,
                        jQuery('#rateobj_StateCityZipSelector_ZipTextBox').val());
            }
    };
	this.OnZipChange=function(id,value){
        if(value){
           jQuery.get(
               '/wp-admin/admin-ajax.php?call=GetLoanLimitByZipCode&zip_code='+value+'&_ajax_nonce=null&action=dict_action',
               function(data){
                   if(typeof(data) == 'object'){
                       rateobj.jumboVal = data.BrDictContent > 10000?data.BrDictContent:rateobj.jumboVal;
                       rateobj.ShowProducts();
                   }
           });
        }
    };
}
rateobj_StateCityZipSelector = new rateobj_StateCityZipSelector;

var RateobjClickhandler = {
    Click: function(e,context){
        var row = new Array();
        this.topProducts = new Array();
        this.index = 0;
        this.makeTopProducts = function(results,skipme){
            this.tp = new Array();
            for (p in results)  {
               if(p == skipme || results[p].commentsHyperlinked == "false") continue;
               if(results[p].listingType == "editorial") continue;
               if(!results[p].listingType) continue;
               this.tp.push(results[p]);
               if(this.tp.length > 2) return this.tp;
            }
            return this.tp;
        }
        this.findRowIndex = ClickHandler.findRowIndex;
        if(rates_rows_json[context.result] && rates_rows_json[context.result]['apy']){// Only a single result
            rates_rows_json[context.result][0] =  rates_rows_json[context.result];
        }
        if(typeof context.row == 'object'){
            row = context.row;
            this.index = this.findRowIndex(e,row);
        }else if(typeof context.row == 'string'){
            row = rates_rows_json[context.result][context.row];
            this.topProducts = this.makeTopProducts(rates_rows_json[context.result],context.row);
            this.index = this.findRowIndex(e,row);
        }else if(context.tip){
            row = rates_rows_tips[context.tip];
        }

        // Set up one entry for each type of click that you want to route
        var clickVars =  {
            "contactuslightbox":{
                func:ContextManager.SwitchContext,
                vars:{  row:row,
                        contextName:'MortgageContactUsLightbox',
                        controlID:'MortgageContactUsLightBox',
                        clickType:21,eventType:'open',
                        overrides:this.index+',21,,1',
                        impressions:''
                    }
            },
            "condorcontactuslightbox":{
                func:ContextManager.SwitchContext,
                vars:{  row:row,
                        contextName:'MortgageContactUsLightbox',
                        controlID:'MortgageContactUsLightBox',
                        clickType:21,eventType:'open',
                        overrides:this.index+',29,,1',
                        impressions:''
                    }
            },
            "learnmorelightbox":{
                func:ContextManager.SwitchContext,
                vars:{  row:row,
                        contextName:'MortgageLearnMoreLightbox',
                        controlID:'MortgageLearnMoreLightBox',
                        clickType:15,
                        eventType:'open',
                        overrides:this.index+',15,1,1',
                        impressions:'',
                        topProducts:this.topProducts
                    }
            },
            "advertiser":{
                func:TrackingManager.Track,
                vars:{row:row,clickType:2,eventType:'click',overrides:this.index+',2,,',newWin:false}
            },
            "advertiserlogo":{
                func:TrackingManager.Track,
                vars:{row:row,clickType:8,eventType:'click',overrides:this.index+',8,,',newWin:false}
            },
            "condoradvertiserlogo":{
                func:TrackingManager.Track,
                vars:{row:row,clickType:8,eventType:'click',overrides:this.index+',26,,',newWin:false}
            },
            "quote":{
                func:TrackingManager.Track,
                vars:{row:row,clickType:11,eventType:'click',overrides:this.index+',11,,',newWin:false}
            },
            "condorquote":{
                func:TrackingManager.Track,
                vars:{row:row,clickType:11,eventType:'click',overrides:this.index+',28,,',newWin:false}
            },
            "comments":{
                func:TrackingManager.Track,
                vars:{row:row,clickType:5,eventType:'click',overrides:this.index+',5,,',newWin:false}
            },
            "contactusrelatedprod":{
                func:TrackingManager.Track,
                vars:{row:row,clickType:16,eventType:'lightboxclick',overrides:this.index+',16,1,',newWin:false}
            },
            "contactusrelatedproductquote":{
                func:TrackingManager.Track,
                vars:{row:row,clickType:16,eventType:'lightboxclick',overrides:this.index+',16,1,',newWin:false}
            },
            "contactusquote":{
                func:TrackingManager.Track,
                vars:{row:row,clickType:12,eventType:'lightboxclick',overrides:this.index+',12,1,',newWin:false}
            },
            "contactuslogo":{
                func:TrackingManager.Track,
                vars:{row:row,clickType:9,eventType:'lightboxclick',overrides:this.index+',9,1,',newWin:false}
            },
            "contactusprofile":{
                func:TrackingManager.Track,
                vars:{row:row,clickType:22,eventType:'lightboxclick',overrides:this.index+',22,1,,'+escape(row.url),newWin:false}
            },
            "learnmorequote":{
                func:TrackingManager.Track,
                vars:{row:row,clickType:13,eventType:'lightboxclick',overrides:this.index+',13,,',newWin:false}
            },
            "learnmorelogo":{
                func:TrackingManager.Track,
                vars:{row:row,clickType:10,eventType:'lightboxclick',overrides:this.index+',10,,',newWin:false}
            },
            "learnmorelender":{
                func:TrackingManager.Track,
                vars:{row:row,clickType:23,eventType:'lightboxclick',overrides:this.index+',23,,',newWin:false}
            },
            "tooltip":{
                func:TrackingManager.Track,
                vars:{row:row,eventType:'tip',overrides:'',newWin:false}
            }
        }
        // controller
        clickVars[context.name].func(e,context,clickVars[context.name].vars);
    }
};

var MortgageLearnMoreLightBox = function(){
    this.run = function(from){
        this.row = from.details.row;
        this.details.ads_in_dialog = true;
        this.details = from.details;
        var topProducts = this.details.topProducts;
        // Get the top products and replace the values in the template
        if(typeof(topProducts) == 'object' && topProducts.length > 0){
            this.row.HTML = jQuery('#MortgageLearnMoreTopProducts_tabletop').html();
            var template = jQuery('#MortgageLearnMoreTopProducts_rowtemplate').html();
            for(var i=0;i<topProducts.length;i++){
               this.row.HTML +=  template.replace(/#{(\w+)}/g,function(m,m1){
                            return (topProducts[i][m1] && typeof topProducts[i][m1]!= 'object')?topProducts[i][m1]:'';
                            });
            }
            this.row.HTML += jQuery('#MortgageLearnMoreTopProducts_tablebottom').html();
        }else{
            this.row.HTML = "At this time there are no products available from this institution.";
        }
        this.td= new TemplateDialog;
        this.td.dialogTitle = "LEARN MORE";
        this.td.display(this);
    }
}
var MortgageLearnMoreLightBox =new MortgageLearnMoreLightBox ;

var MortgageContactUsLightBox = function(){
        this.relatedProducts = [];
        this.run = function(from){
            this.from = from;
            this.row = from.details.row;
            this.details = from.details;
            this.row.showcontactinfo = 'infobox';
            this.row.hidecontactinfo = 'off';
            this.row.li_info = '';
            var relatedProducts = '';
            var marketuid = '';
            // Some way of checking for need of marketuid. This is the solution for now
            if(this.row.marketuid){
               marketuid  = this.row.marketuid;
            }else    if(rates_rows_params.zipCode){
                marketuid = rates_rows_params.markets.market_uid;
            }else if(rates_rows_params.marketuid){
                marketuid =rates_rows_params.marketuid ;
            }
            var relatedmgproducts_vars = {
                        productid:this.row.productId,
                        svy_inst_id:this.row.svyinstitutionId,
                        marketuid:marketuid,
                        loanamt:rates_rows_params.loanamount,
                        points:rates_rows_params.pointoption,
                        action:'relatedproducts_action'
                    };
            var key = '';
            for(i in relatedmgproducts_vars){
                if(relatedmgproducts_vars.hasOwnProperty(i)){
                    key+=relatedmgproducts_vars[i].toString().replace(/[^a-zA-Z0-9]+/,"");
                }
            }
            if(MortgageContactUsLightBox.relatedProducts[key]){
                this.do_row(MortgageContactUsLightBox.relatedProducts[key],false);
            }else{
                jQuery.get('/wp-admin/admin-ajax.php',
                        relatedmgproducts_vars,
                        function(data){ MortgageContactUsLightBox.do_row(data,key); }
                );
            }
        }
        // We need to make the related product rows to replace in the template
        this.do_row = function(data,key){
            //Memoize
            if(key){MortgageContactUsLightBox.relatedProducts[key]=data;}
            relatedProducts = brJsonDecode(data);// Funky chicken...
            var products = relatedProducts.Products;
            this.row.HTML = jQuery('#MortgageContactUsLightBox_tabletop').html();
            var template = jQuery('#MortgageContactUsLightBox_rowtemplate').html();
            //rates_rows_json['MortgageContactUsLightBox'] = new Array();
            if(typeof(products) != 'object' || products.length == 0){
                this.row.HTML += "<tr><td colspan='4'>No additional products found.</td></tr>";
                this.row.HTML += jQuery('#MortgageContactUsLightBox_tablebottom').html();
                this.td = new TemplateDialog;
                this.td.dialogTitle = this.row.lender+" - "+this.row.description;
                return this.td.display(this);
            }

            rates_rows_json.MGContactUsLightBox = new Array();
            for(var i=0;i<products.length;i++){
                var prow = eval("(" + products[i] + ")"); // Srsly?
                var trackingData = TrackingManager.GetTrackingData(this);
                for( k in trackingData){
                    prow[k] = trackingData[k];
                }
                rates_rows_json.MGContactUsLightBox.push(prow);
                if(trackingData.e){
                    prow.quoteURL = "<a onclick=\"RateobjClickhandler.Click("
                            +"event,{name:'contactusrelatedproductquote',"
                            +"result:'MGContactUsLightBox',row:'"+(rates_rows_json.MGContactUsLightBox.length-1)+"'})\" >Get Quote</a>";
                }
                            //+"result:'"+this.row.result+"',row:'"+this.row.row+"'})\" >Get Quote</a>";
                comp_method(prow);
                this.row.HTML +=  template.replace(/#{(\w+)}/g,function(m,m1){
                           return (prow[m1] && typeof prow[m1]!= 'object')?prow[m1]:'';
                            });
            }
            this.row.HTML += jQuery('#MortgageContactUsLightBox_tablebottom').html();
            for(i=1;i<4;i++){
                if(this.row['sp'+i] && typeof this.row['sp'+i]!= 'object'){
                    this.row['sp'+i] = this.row['sp'+i].replace(/•/,'');
                    this.row.li_info += "<li>"+this.row['sp'+i];+"</li>";
                }
            }
            this.td = new TemplateDialog;
            this.td.dialogTitle = this.row.lender+" - "+this.row.description;
            this.td.display(this);
        }

}
var MortgageContactUsLightBox = new MortgageContactUsLightBox;

