// Function to add bookmark via js.
// IE,FF,Opera
function bookmarksite(title,url) {
	if (window.sidebar) // firefox
		window.sidebar.addPanel(title, url, "");
	else if(window.opera && window.print) { // opera
		var elem = document.createElement('a');
		elem.setAttribute('href',url);
		elem.setAttribute('title',title);
		elem.setAttribute('rel','sidebar');
		elem.click();
	}
	else if(document.all) {// ie
	window.external.AddFavorite(url, title);
	}
	else{
		alert('Your web browser appears to not support adding a bookmark via Javascript.  Please manually add.');
	}
}

// Function to add print via js.
function printit(){
	var NS = (navigator.appName == "Netscape");
	if (NS) {
	    window.print() ;
	}
	else {
	    window.print();
	}
}

if(!window.console){
    var console = {};
    var methods = ['assert','clear','count','debug','dir','dirxml',
        'error','exception','group','groupCollapsed','groupEnd','info','log','notifyFirebug',
        'profile','profileEnd','table','time','timeEnd','trace','warn'
            ];
    for(var i=0;i<methods.length;i++){
        console[methods[i]] = function(){};
    }
}

// Glossary functions
jQuery(document).ready(function() {

	// Check for cobrand cookie
	getCookie('bcts_cookie');

    // Akamai was caching the url. So lets use cookies!
    if(typeof(myPartner) == 'object'){
        if(myPartner.pid){
            adsrv_url = adsrv_url.replace(/(adstream_mjx.ads\/b\.)\w+/,"$1"+myPartner.pid);
            UACsite = myPartner.pid;
        }
    }

	//Singleton
	var GlossaryAds = new function GlossaryAds(){
	    this.ads = 0;
	    this.hide_ads = function(b){
	    	AdManager.loadAdScripts(adsrv_url, 'lightbox');
	        jQuery('#UAC_AD_1').css("visibility", "hidden");
	        jQuery('#UAC_AD_2').css("visibility", "hidden");
	        jQuery('#UAC_AD_3').css("visibility", "hidden");
	        jQuery('#UAC_AD_4').css("visibility", "hidden");
	        this.ads++;
	    }
	    this.show_ads = function (b){
	        this.ads--;
	        if(this.ads == 0){
	            jQuery('#UAC_AD_1').css("visibility", "visible");
	            jQuery('#UAC_AD_2').css("visibility", "visible");
	            jQuery('#UAC_AD_3').css("visibility", "visible");
	            jQuery('#UAC_AD_4').css("visibility", "visible");
	        }
	    }
	}

	var ComparisonSlider = new function ComparisonSlider(){
	    this.available = 1;
	    this.start_slider = function(b){
		    this.available = 0;
	    }
	    this.slider_done = function (b){
		    this.available = 1;
	    }
	}

	jQuery("#rates-chart-nav ul li a").click(function(){

		if(ComparisonSlider.available) ComparisonSlider.start_slider();
		else return false;

		var comparison_width = 295;

		if($(this).attr('id') == 'compare_next')
		{
			movedirection = '-=' + comparison_width;
			if($("#comparisons").position().left == (-1 * comparison_width * ($('.rates-chart-container').length - 2)))
			{ ComparisonSlider.slider_done(); return false;}
			/* Add one to fix IE */
			else if($("#comparisons").position().left == ((-1 * comparison_width * ($('.rates-chart-container').length - 2))  + 1 ))
			{ ComparisonSlider.slider_done(); return false;}
		}
		else
		{
			movedirection = '+=' + comparison_width;
			if($("#comparisons").position().left == 0)
				{ ComparisonSlider.slider_done(); return false;}
		}

		$("#comparisons").animate({
		    left: movedirection
		  }, 1000, function() {
			ComparisonSlider.slider_done();
		  });
		return false;

	});

	jQuery("#comments_form_lightbox").dialog({
        title: "Post a Comment",
        modal: true,
        autoOpen: false,
        position: 100,
        height: 400,
        width: 450,
        close: function() {
			GlossaryAds.show_ads();}
		});    //end dialog

	jQuery('#post_a_comment').click(function (){
        	GlossaryAds.hide_ads();
        	jQuery( "#comments_form_lightbox" ).dialog('open');
            return false;
        }
    );

	jQuery("#glossary_popup").dialog({
        title: "Title",
        modal: true,
        autoOpen: false,
        position: 100,
        height: 610,
        width: 840,
        close: function() {
			GlossaryAds.show_ads();}
		});    //end dialog

	jQuery('.glossary_link').click(function (){
        	GlossaryAds.hide_ads();
    	    jQuery.ajax({
    	        type: "post",
    	        datatype: "json",
    	        url: MyAjax.ajaxurl,
    	        async: false,
    	        data: {
    	            action: 'glossary',
    	            term: $(this).attr("title"),
    	            _ajax_nonce: MyAjax.search_term_nonce
    	        },
    	        success: function(glossary_result){
    	            //var glossary_result = jQuery.parseJSON(json_string);
    	        	jQuery( ".glossary-word-heading" ).html(glossary_result.name);
    	        	jQuery( ".glossary-word-definition" ).html(glossary_result.description);

    	        	jQuery( "#glossary_popup" ).dialog( 'option', 'title', 'Glossary Definition for: ' + glossary_result.name );
    	        	jQuery( "#glossary_popup" ).dialog('open');
    	        }
    	    }); //close jQuery.ajax
            return false;
        }
    );

/****************************
* Start Compare Rates Functions
*/

	jQuery(".local_radio_button").click(function(){
		if(jQuery(this).val() != 'true')
			jQuery('#local_selection').hide();
		else
			jQuery('#local_selection').show();
	})
	
/***** For home page Cd Rate Module *****/	
    jQuery(".local_radio_button_home_cd").click(function(){
	    
		if(jQuery(this).val() != 'true')
			jQuery('#local_selection_home_cd').hide();
		else
			jQuery('#local_selection_home_cd').show();
	})
/**** End ****/
	jQuery("#cc_select_box").change(function(){
		jQuery('.cctypediv').hide();
		jQuery('.cctypediv select').removeAttr('name');

		jQuery('#cc_'+jQuery(this).val()+'_selection').show();
		jQuery('#cc_'+jQuery(this).val()+'_selection select').attr('name', 'prods');

	});

	jQuery("#zip_select_box").change(function(){
		if(jQuery(this).val() == 'true')
		{
			jQuery('#local_selection').hide();
			jQuery('#zip_code_selection').show();
			jQuery('#zip_text_field').focus();
		}
		else
		{
			jQuery('#zip_code_selection').hide();
			jQuery('#local_selection').show();
		}
	});


	jQuery('#icom_mm11_city').change(function(){
		checkCompareRateCity()
	})
/***** For home page Mortgage and Cd Rate Module *****/	
    jQuery('#icom_mm11_city_home_cd').change(function(){
		checkCompareRateCityCd()
	})
	
	jQuery('#icom_mm11_city_home_mortgage').change(function(){
		checkCompareRateCityMortgage()
	})
/**** End ****/	
	jQuery('#myTextbox').keydown(
	    function(event)
	    {
	        var input = $(this).val();
	        var numberOfWords = input.split(' ').length;
	        if(numberOfWords == 3 && event.keyCode == 32)
	        {
	            return false;
	        }
	    }
	);

	jQuery('#compare_rates_button').click(function(){
		jQuery('.compare-rates-error').remove();
	    if(jQuery('#local_selection').css('display') != 'none')
	    {
	    	if(!checkCompareRateCity())
	    		return false;
	    }
	    else if(jQuery('#zip_code_selection').css('display') != 'none')
	    {
	    	if(!checkCompareRateZip())
	    		return false;
	    }
	});
/***** For home page Mortgage and Cd Rate Module *****/
	jQuery('#compare_rates_button_home_mortgage').click(function(){
		
		jQuery('.compare-rates-error-home-mortgage').remove();
		
	    if(jQuery('#local_selection_home_mortgage').css('display') != 'none')
	    {
	    	
	    	if(!checkCompareRateCityMortgage())
	    		return false;
	    }
	    
	    
	});
	
	jQuery('#compare_rates_button_home_cd').click(function(){
		
		jQuery('.compare-rates-error-home-cd').remove();
		
	    if(jQuery('#local_selection_home_cd').css('display') != 'none')
	    {
	    	
	    	if(!checkCompareRateCityCd())
	    		return false;
	    }
	    
	});
/**** End  ****/
	jQuery('#zip_text_field').keyup(function(){
		jQuery('#zip_code_selection .compare-rates-error').remove();
	  	var pat=/^[0-9]{5}$/;
	  	if ( !pat.test(   jQuery(this).val()   ) )
	    {
	  		jQuery(this).after('<b class="compare-rates-error">*Enter valid zip</b>');
	  		return false;
	  	}
	  	else
	  		return true;
	});


	jQuery('#refi_select_box').change(function(){
		jQuery('#refi_rates_selection select').removeAttr('name');

		if(jQuery('#rate_refinance_selection').css('display') == 'none')
		{
			jQuery('#rate_purchase_selection').hide();
			jQuery('#rate_refinance_selection select').attr('name', 'prods');
			jQuery('#rate_refinance_selection').show();
		}
		else
		{
			jQuery('#rate_refinance_selection').hide();
			jQuery('#rate_purchase_selection select').attr('name', 'prods');
			jQuery('#rate_purchase_selection').show();
		}
	});

});

function checkCompareRateCity(){
	jQuery('#city_selection .compare-rates-error').remove();
	if(jQuery('#icom_mm11_city').val() == '')
	{
		jQuery('#city_selection').append('<b class="compare-rates-error">*Please select a city</b>');
		jQuery('#icom_mm11_city').focus();
		return false
	}
	else
		return true;
}
/***** For home page Mortgage and Cd Rate Module *****/
function checkCompareRateCityCd(){
	jQuery('#city_selection_home_cd .compare-rates-error-home-cd').remove();
	if(jQuery('#icom_mm11_city_home_cd').val() == '')
	{
		jQuery('#city_selection_home_cd').append('<b class="compare-rates-error-home-cd">*Please select a city</b>');
		jQuery('#icom_mm11_city_home_cd').focus();
		return false
	}
	else
		return true;
}

function checkCompareRateCityMortgage(){
	jQuery('#city_selection_home_mortgage .compare-rates-error-home-mortgage').remove();
	if(jQuery('#icom_mm11_city_home_mortgage').val() == '')
	{
		jQuery('#city_selection_home_mortgage').append('<b class="compare-rates-error-home-mortgage">*Please select a city</b>');
		jQuery('#icom_mm11_city_home_mortgage').focus();
		return false
	}
	else
		return true;
}
/*****  End  ***/
function checkCompareRateZip(){
	jQuery('#zip_code_selection .compare-rates-error').remove();
	return jQuery('#zip_text_field').keyup();
}

/****************************
* End Compare Rates Functions
****************************/


// Must be called like this because it is using jquery
// jQuery(document).ready(function() {
//     BrGeo.StateCityPair("#icom_mm11_state","#icom_mm11_city");
// });
//
var BrGeo = {
    rateobj: function(){},
    zips: function(){},
    mystate: {state_abbr:'NJ'},
    PopulateMarketsFromState: function(stateselect,cityselect) {
            this.rateobj.cityselect=cityselect;
            this.rateobj.stateselect=stateselect;
            if( stateselect.val().match(/\w{2}/) ){
                stateselect.attr('disabled','disabled');
                cityselect.attr('disabled','disabled');

                cityselect.html("<option value=''>Loading...</option>");

                jQuery.ajax({
                       url: '/wp-admin/admin-ajax.php',
                       async: false,
                       data:({call:'GetMarketsByState',statecode:stateselect.val(),'_ajax_nonce':'null','action':'geo_action'}),
                       dataType:'json',
                       success:function(){BrGeo.FillMarkets(BrGeo.rateobj,arguments);}
                });
            }else{
                cityselect.html("<option value=''>Select State First</option>");
            }
    },
    FillMarkets: function(){
        this.rateobj = arguments[0];
        this.data = arguments[1][0];
        this.result = arguments[1][1];
        this.obj = arguments[1][2];
        if(this.result == 'success'  && typeof(this.data.Table) == 'object'){
            this.rateobj.cityselect.html("<option value=''>Select City</option>");
           if( this.data.Table.length){
            for(key in this.data.Table){
                this.rateobj.cityselect.append("<option value='"+this.data.Table[key].market_uid+"'>"+this.data.Table[key].web_name+"</option>");
            }
           }else{
                this.rateobj.cityselect.append("<option value='"+this.data.Table.market_uid+"'>"+this.data.Table.web_name+"</option>");
           }
            this.rateobj.stateselect.attr('disabled','');
            this.rateobj.cityselect.attr('disabled','');
        }else{
            this.rateobj.stateselect.attr('enabled','');
            this.rateobj.cityselect.attr('enabled','');
        }
    },
    PopulateMarketsFromZip: function() {
        this.rateobj.passingobj=arguments[0];
        this.rateobj.stateselect=arguments[1];
        this.rateobj.cityselect=arguments[2];
        this.rateobj.txtzipcode=arguments[3];
        if(BrGeo.zips[this.rateobj.txtzipcode.val()]){ // cached
            BrGeo.FillStateMarketsFromZip(BrGeo.rateobj,{0:BrGeo.zips[this.rateobj.txtzipcode.val()]});
        }else if(this.rateobj.txtzipcode.val()){
            jQuery.ajax({
                   url: '/wp-admin/admin-ajax.php',
                   async: false,
                   data:{call:'GetAllMarketsFromZip','zipcode':this.rateobj.txtzipcode.val(),'_ajax_nonce':'null','action':'geo_action'},
                   dataType:'json',
                   success:function(){BrGeo.FillStateMarketsFromZip(BrGeo.rateobj,arguments);}
            });
        }
    },
    FillStateMarketsFromZip: function (){
        this.rateobj = arguments[0];
        this.data = arguments[1][0];
        this.result = arguments[1][1];
        this.obj = arguments[1][2]
        if(typeof(this.data.obj) == 'object')
        {
            BrGeo.zips[this.data.selectedMarket.zip[0]] = this.data;
            if(this.data.obj.Table[0].state.match(/[A-Z]+/))
            {
                this.rateobj.stateselect.val(this.data.obj.Table[0].state);
                this.rateobj.stateselect.attr('disabled','');
            }
            else {
                this.rateobj.stateselect.val('');
            }

            this.rateobj.cityselect.attr('disabled','');
            this.rateobj.cityselect.html("<option value=''>Select City</option>");
            for(key in this.data.obj.Table){
                this.rateobj.cityselect.append("<option value='"+this.data.obj.Table[key].market_uid+"'>"+this.data.obj.Table[key].web_name+"</option>");
            }
            this.rateobj.cityselect.val(this.data.selectedMarket.market_uid[0]);
            if(this.data.selectedMarket.market_uid[0] == ''){
                this.rateobj.cityselect.attr('disabled','disabled');
            }
            this.rateobj.passingobj.marketid=this.data.selectedMarket.market_uid[0];
        }
    },
    FillStates: function(){
        var jquery_dom_selector_state = arguments[0];
        var state_type = arguments[1];

        // If you pass the city value I will enable the city filler for you.
        var jquery_dom_selector_city = arguments[2];

        if(typeof(jquery_dom_selector_city) != 'string' || typeof(state_type) != 'string'){
            return;
        }
        if(state_type.match(/Long/)){
            jQuery(jquery_dom_selector_state).html('');
            for(var state in this.LongStates){
                jQuery(jquery_dom_selector_state).append('<option value="'+state+'">'+this.LongStates[state]+'</option>');
            }
        }else{
            for(var state in this.States){
                console.log('short not implemented yet');
            }
        }

        if(typeof(jquery_dom_selector_city) == 'string'){
            this.StateCityPair(jquery_dom_selector_state,jquery_dom_selector_city);
        }
    },
    StateCityPair: function(){
        var jquery_dom_selector_state = arguments[0];
        var jquery_dom_selector_city = arguments[1];
        if(typeof(jquery_dom_selector_state) == 'string' && typeof(jquery_dom_selector_city) == 'string'){
            jQuery(jquery_dom_selector_state).change(function(){
                BrGeo.PopulateMarketsFromState(jQuery(jquery_dom_selector_state),jQuery(jquery_dom_selector_city));
            });
        }
    },
    SetLocation: function(){
        var jquery_dom_selector_state = arguments[0];
        var geo_location_obj = arguments[1]?arguments[1]:this.InitialState();
        if(typeof(jquery_dom_selector_state) == 'string' && typeof(geo_location_obj) == 'object'){
            jQuery(jquery_dom_selector_state).val(geo_location_obj.state_abbr.toUpperCase()).trigger('change');
        }
    },
    InitialState: function(){
        jQuery.ajax({
            type: 'POST',
            url:'/wp-admin/admin-ajax.php',
                data: { cookie:document.cookie,
                    call:'GetStateMarketByCookie',
                    action:'ipgeo_action',
                    qs:document.location.search
                },
            async:false,
            dataType:'json',
            success:function(d){if(typeof(d)=='object' && d.state_abbr){BrGeo.mystate = d;}}
        });
        return this.mystate;
    },
    States: {"":"Choose a State","AK":"AK","AL":"AL","AR":"AR","AZ":"AZ","CA":"CA","CO":"CO","CT":"CT","DC":"DC","DE":"DE","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"},
    LongStates:{"AL":"Alabama","AK":"Alaska","AZ":"Arizona","AR":"Arkansas","CA":"California","CO":"Colorado","CT":"Connecticut","DE":"Delaware","DC":"District Of Columbia","FL":"Florida","GA":"Georgia","HI":"Hawaii","ID":"Idaho","IL":"Illinois","IN":"Indiana","IA":"Iowa","KS":"Kansas","KY":"Kentucky","LA":"Louisiana","ME":"Maine","MD":"Maryland","MA":"Massachusetts","MI":"Michigan","MN":"Minnesota","MS":"Mississippi","MO":"Missouri","MT":"Montana","NE":"Nebraska","NV":"Nevada","NH":"New Hampshire","NJ":"New Jersey","NM":"New Mexico","NY":"New York","NC":"North Carolina","ND":"North Dakota","OH":"Ohio","OK":"Oklahoma","OR":"Oregon","PA":"Pennsylvania","RI":"Rhode Island","SC":"South Carolina","SD":"South Dakota","TN":"Tennessee","TX":"Texas","UT":"Utah","VT":"Vermont","VA":"Virginia","WA":"Washington","WV":"West Virginia","WI":"Wisconsin","WY":"Wyoming"}

}

function PopupCenter(pageURL,w,h) {
	var left = (screen.width/2)-(w/2);
	var top = (screen.height/2)-(h/2);
	var targetWin = window.open (pageURL, 'icom_child_window', 'toolbar=yes, location=yes, directories=no, status=no, menubar=no, scrollbars=yes, resizable=no, copyhistory=no, width='+w+', height='+h+', top='+top+', left='+left);

}

function PopUnderCenter(pageURL,w,h) {
	var left = (screen.width/2)-(w/2);
	var top = (screen.height/2)-(h/2);
	var targetWin = window.open (pageURL, 'icom_child_window', 'toolbar=yes, location=yes, directories=no, status=no, menubar=no, scrollbars=yes, resizable=no, copyhistory=no, width='+w+', height='+h+', top='+top+', left='+left);
    if(targetWin && targetWin.top){
        targetWin.blur();
    }
    this.window.focus();
}

