window.name = "bloomberg";
/**
 * Define namespace BLOOMBERG
 */

if (typeof BLOOMBERG === "undefined" || !BLOOMBERG) {
    var BLOOMBERG = {};

}
if (typeof(BLOOMBERG.global_var) === "undefined"){
    BLOOMBERG.global_var = {};
}
if (typeof(BLOOMBERG.chartData) === "undefined"){
    BLOOMBERG.chartData = {};
}
if (typeof image_domain === "undefined"){ image_domain = ""}
//For new navigation bar
(function(){
    new_nav_event_registered = false;
    new_ext_nav_events_registered = false;
    BLOOMBERG.register_nav_events = function(){
        if(new_nav_event_registered)
            return; //return if those events were already registered.
        try{
            if ($("#primary_navigation .nav_menu_item_with_dropdown .menu_icon").length > 0){
                var dropdown_icon = $("#primary_navigation .nav_menu_item_with_dropdown .menu_icon");
                dropdown_icon.hover(function(){
                    $(this).closest(".nav_menu_item_with_dropdown").addClass("menu_icon_mouse_over");
                },function(){
                    $(this).closest(".nav_menu_item_with_dropdown").removeClass("menu_icon_mouse_over");
                });
                dropdown_icon.click(function(){
                    $("#primary_navigation .nav_menu_item_with_dropdown").not($(this).closest(".nav_menu_item_with_dropdown")).removeClass("show_sub_menu");
                    $(this).closest(".nav_menu_item_with_dropdown").toggleClass("show_sub_menu");
                    return false;
                });
                $("body").click(function(){
                    dropdown_icon.closest(".nav_menu_item_with_dropdown").removeClass("show_sub_menu");
                });
                new_nav_event_registered = true;
            }
        }catch(err){
            
        }
    };
    BLOOMBERG.register_ext_nav_events = function(){
        var  timer_enter,
             timer_leave,
             active_tab;

        function clear_timers(self){
            if(timer_leave &&  active_tab == self) {
                clearTimeout(timer_leave);
                clearTimeout(timer_enter);
                timer_leave = null;
                timer_enter = null;
            }
        }

        function nav_open(self){
            self.addClass('show_sub_menu');
            active_tab = self;
        }
        if(new_ext_nav_events_registered)
            return;
        try{
            var nav_items = $('#ext_primary_navigation .nav_menu_item_with_dropdown, #ext_primary_navigation_v2 .nav_menu_item_with_dropdown ');
            nav_items.each(function(){
               var $self = $(this),
                   tab = $self.find('.menu_tab'),
                   drop = $self.find('.div_dropdown_container'),
                   isiPad = navigator.userAgent && (navigator.userAgent.match(/iPad/i) != null),
                   delay_leave =  150,
                   delay_enter = 250;

               if(!isiPad){
                   tab.mouseenter(function(){
                       clear_timers($self);
                       if(timer_enter) {
                           clearTimeout(timer_enter);
                           timer_enter = null;
                       }
                       timer_enter =  setTimeout(function() {
                           nav_open($self)
                       }, delay_enter);


                   });
                   drop.mouseenter(function(){
                       clear_timers($self);
                   });
               }else{
                   tab.click(function(){
                       if (!$self.hasClass('show_sub_menu')){
                           $self.addClass('show_sub_menu');
                           return false;
                       }
                   });
               }
               $self.mouseleave(function(){
                   if(timer_leave) {
                       clearTimeout(timer_leave);
                       timer_leave = null;
                   }
                   if(timer_enter) {
                       clearTimeout(timer_enter);
                       timer_enter = null;
                   }
                   timer_leave =  setTimeout(function() {
                        nav_items.removeClass('show_sub_menu');
                   }, delay_leave);

               });
            });
            $("body").click(function(){
                nav_items.removeClass("show_sub_menu");
            });
            new_ext_nav_events_registered = true;
        }catch(err){

        }
    }
})();
/**
 * namespace
 */
(function () {
    BLOOMBERG.namespace = function(name){
        var nameArray = [],
            nameObject,
            i;

        nameArray = name.split(".");

        nameObject = BLOOMBERG;

        if (nameArray[0] === "BLOOMBERG") {
            nameArray.shift();
        }

        for (i = 0; i < nameArray.length; i++) {
            if(typeof  nameObject[nameArray[i]] === "undefined"){
                nameObject[nameArray[i]] = {};
            }
            nameObject = nameObject[nameArray[i]];
        }

        return nameObject;
        
    };
})();

//extend existing classes
(function(){
    Array.prototype.contains = function(obj){
        for (var i = 0; i < this.length; i++){
            if (obj === this[i]){ return true; }
        }
        return false;
    };
    String.prototype.strip = function(){
        return this.replace(/^\s+|\s+$/g, '');
    };
    String.prototype.starts_with = function(str){
        return this.indexOf(str) == 0;
    };
    String.prototype.ends_with = function(str){
        return (this.lastIndexOf(str)>=0) && (this.lastIndexOf(str) == (this.length - str.length));
    };
    Date.nextYear = function(){
        var curDT = new Date();
        return new Date(curDT.getFullYear() + 1, curDT.getMonth(), curDT.getDate(), curDT.getHours(), curDT.getMinutes(), curDT.getSeconds(), curDT.getMilliseconds());
    };
})();
// namespace for url related methods
(function(){
    var bbg = BLOOMBERG,
        url = bbg.namespace("url");
    // if path1 ends with '/', and path2 starts with '/', it'll remove one of them
    url.CombinePath = function(path1, path2){
        if (typeof(path1) == 'undefined'){
            return path2;
        }
        if (typeof(path2) == 'undefined'){
            return path1;
        }
        if (path1.ends_with('/') && path2.starts_with('/')){
            return path1 + path2.slice(1);
        }else{
            return path1 + path2;
        }
    };
})();

(function() {
    var bbg = BLOOMBERG,
        video = bbg.namespace('video');
    video.generate_url_from_fvid = function(fvid) {
        return bbg.global_var.video_domain + fvid + '.flv';
    };

    /**
     * creates a query string from an array
     * { a : 1, b : 2} -> a=1&amp;b=2
     * - values are escaped
     * @param arr array with values
     */
    function makeQS(arr) {
        var s = "";
        for ( var e in arr )
        {
           s += "&amp;" + e + "=" + escape( arr[e] );
        }
        return s.substring(5);
    }

    /**
     * generates video <object> with <embed> with a specific fvid
     * @param fvid the flash video id to play in the embed code
     * @param options various options you can override
     *      includes: height, width, site (ad), zone (ad), poster_url
     */
    video.generate_embed = function(fvid, options){
        var settings = {
            height: 360,
            width: 640,
            site: "blp.embed",
            zone: "vod",
            poster_url: ""
        };
        $.extend(settings,options);

        var vid_options = {
            file_url: video.generate_url_from_fvid(fvid),
            autoplay: false,
            site: settings.site,
            zone: settings.zone,
            EnableLogging: "true",
            LoggingDomain: "www.bloomberg.com",
            sz: "1x1",
            tile: "1",
            poster_url: settings.poster_url
            },
            vid_options_qs = makeQS(vid_options),
            player = "http://cdn.gotraffic.net/flash/BloombergMediaPlayer.swf";

        return "<object width=\"" + settings.width + "\" height=\"" + settings.height + "\">"+
                  "<param name=\"movie\" value=\""+ player +"\"></param>" +
                  "<param name=\"allowFullScreen\" value=\"true\"></param>" +
                  "<param name=\"allowscriptaccess\" value=\"always\"></param>" +
                  "<param name=\"flashvars\" value=\""+ vid_options_qs +"\"></param>" +
                  "<embed src=\""+ player + "\" " +
                      "flashvars=\"" + vid_options_qs + "\" " +
                      "type=\"application/x-shockwave-flash\" " +
                      "allowscriptaccess=\"always\" " +
                      "allowfullscreen=\"true\" " +
                      "width=\"" + settings.width + "\" " +
                      "height=\"" + settings.height + "\" " +
                      "wmode=\"opaque\">" +
                  "</embed>" +
                  "</object>";
    };

    /**
     * function for generating video embed code, via textarea, and binding behavior
     * Selection should be to a jquery selection result where click binding happens to the child 'a' element
     * @param target the target element id that embed code will be inserted
     */
    video.bind_video_embed = function(target) {
        return this.each(function(){
           var $self = $(this),
               $target = $('#' + target),
               $link = $self.find("a"),
               gen = function (){
                   var $label = $('<span>Embed Code</span>'),
                       $textarea = $('<textarea></textarea>'),
                       $closebtn = $('<a href="#close" class="close">X</a>'),
                       poster_url = $('meta[property="og:image"]').attr('content'),
                       options = {poster_url: poster_url, zone: BLOOMBERG._zone},
                       $container = $('<div class="video_embed_code"></div>');
                   //defaults to the video id that's on the page
                   $textarea.val(video.generate_embed(bbg._fvid_id, options));
                   $textarea.click(function(){this.select();});
                   $closebtn.click(togg);
                   $container.append($label).append($textarea).append($closebtn);
                   $target.html($container).show();
                   // replacing click generation with toggling, don't need to generate more than once
                   $link.unbind('click',gen).click(togg);
                   //console.log("in gen");
                   return false;
               },
               togg = function(){
                   $target.toggle();
                   //console.log("in togg");
                   return false;
               };
            // initial click binding, to generate the code
            $link.click(gen);
        });
    };
})();


(function(){
    /**
     * Attaching video generation plugin to jquery for ease of use 
     */
    $.fn.bindVideoEmbed = BLOOMBERG.video.bind_video_embed;
})();

/**
 * BLOOMBERG.console.log
 * @description Bloomberg namespace logger
 */
(function(){
    var bbg = BLOOMBERG;

    bbg.console = {};
    if ((!BLOOMBERG.global_var.enable_console_functions) || (typeof console =="undefined"))
        bbg.console.log = function(){};
    else
        bbg.console.log = console.log;
})();

/**
 * util.Cookie
 */

(function () {
    var bbg = BLOOMBERG,
            util = bbg.namespace("util");

    util.Cookie = (function () {
        var self;

        function setCookie(name, value, date, path, domain) {
            var date = new Date(date),
                    expires;

            if (date) {
                expires = "; expires=" + date.toGMTString();
            }
            else {
                expires = "";
            }

            if (typeof path === "undefined") {
                path = "; path=/";
            } else {
                path = "; path=" + path;
            }

            if (typeof domain === "undefined") {
                domain = "";
            } else {
                domain = "; domain=" + domain;
            }
            document.cookie = name + "=" + value + expires + path + domain;
        }

        function setEndOfSessionCookie(name, value, path, domain) {
            var expires;
            expires = "";
            if (typeof path === "undefined") {
                path = "; path=/";
            } else {
                path = "; path=" + path;
            }

            if (typeof domain === "undefined") {
                domain = "";
            } else {
                domain = "; domain=" + domain;
            }
            document.cookie = name + "=" + value + expires + path + domain;
        }

        function getCookieValue(name) {
            var matches = document.cookie.match("(^|;) ?" + name + "=([^;$]*)");
            if (matches)
                return matches[2];

            return "";
        }

        function getCookie(name) {
            return getCookieValue(name);
        }

        function getOptCookie(name) {
            return getCookieValue(name);
        }

        function removeCookie(name, path, domain) {
            var p = path || '/';
            setCookie(name, "", -1, p, domain);
        }

        self = {
            set: function (name, value, date, path, domain) {
                setCookie(name, value, date, path, domain);
            },
            setEndOfSession: function(name, value, path, domain) {
                setEndOfSessionCookie(name, value, path, domain);
            },
            get: function (name) {
                return getCookie(name);
            },
            getOpt: function(name) {
                return getOptCookie(name);
            },
            erase: function (name) {
                removeCookie(name, '/', 'bloomberg.com');
            },
            remove: function(name, path, domain) {
                removeCookie(name, path, domain);
            },
            removeCookies: function(keys, path, domain) {
                for (var i = 0; i < keys.length; i++) {
                    removeCookie(keys[i], path, domain);
                }
            }
        };

        return self;
    })();
})();

/**
 * num.pad
 * @description namespace number utils
 */
(function(){
    var bbg = BLOOMBERG;

    bbg.num = (function(){
        var self;
        function padNumber(number, length){
            var str = '' + number;
            while (str.length < length) {
                str = '0' + str;
            }
            return str;
        }
        self = {
            pad: function(number, length){
                return padNumber(number, length);
            }  
        };
        return self;
    })();
})();

(function(){
    var bbg = BLOOMBERG,
        date = bbg.namespace("date");
    date.ago_time_format = function(time){
        var cur_time = new Date();
        if (cur_time - time < 120000){
            return '1 minute ago';
        }else if(cur_time - time < 3600000){
            return Math.floor((cur_time - time)/60000) + " minutes ago";
        }else if (cur_time - time < 7200000){
            return '1 hour ago';
        }else if(cur_time - time < 18000000){
            return Math.floor((cur_time - time)/3600000) + " hours ago";
        }
        return '';
    };
    date.localTimezoneOffset = (new Date()).getTimezoneOffset() * 60 * 1000;
    
    /*
     *   Used in formatting dates, xaxis, as part of the market snapshot deluxe
     *   @param val - date value, leverages Highcharts.dateFormat
     **/
    date.chartDateFormatter = function(val){
      var shifted_val = new Date(val - date.localTimezoneOffset);
      
      var label = "",
          hour = Highcharts.dateFormat('%H', shifted_val); // 24 hour representation
        if (hour == "00") {
          label = Highcharts.dateFormat('%b %d', shifted_val);
        }
        else {
          label = Highcharts.dateFormat('%l%P', shifted_val);
        }
      return label;
    };

    // this is the formatter for the chart x-axis labels
    date.chartLabelDateFormatter = function(val, period){
        var label = "",
            minutes = Highcharts.dateFormat('%M', val),
            day = Highcharts.dateFormat('%e', val),
            hour = Highcharts.dateFormat('%H', val),
            month = Highcharts.dateFormat('%m', val);
            month = ((month.indexOf('0') == 0) ? month.substring(1) : month); // strips the 0 from 01 for jan
        if (period == "1D" && minutes == "00"){ // if it's 1D and on a full hour
            if(hour == "00"){
                label = month + "/" + day; // display 1/31 if it's midnight
            } else {
                label = Highcharts.dateFormat('%l%P', val);  // display 10AM
            }
        } else if (period == "1M" && hour == "00"){ // if it's 1M and on a full hour
            label = Highcharts.dateFormat('%b %e', val);// display Jan 31
        } else if (period == "1Y"){
            if (month == "1"){ // if it's Jan, display 2011
                label = Highcharts.dateFormat('%Y', val);
            } else {
                label = Highcharts.dateFormat('%b', val); // else display Jun
            }
        }
        return label;
    };

    // this is the formatter for the chart 'time flag' grey marker
    date.chartMarkerDateFormatter = function(val, period){
        var label = "";
        var month = Highcharts.dateFormat('%m', val);
        var day = Highcharts.dateFormat('%e', val);
        month = ((month.indexOf('0') == 0) ? month.substring(1) : month);  // strips the 0 from 01 for jan
        var time = Highcharts.dateFormat('%l:%M:%S %P', val);
        if (period == "1D"){
            label = time ; // display 10:49:21 am
        } else if (period == "1M"){
            label = month + "/" + day; // display 1/31
        }
        else if (period == "1Y"){
            label = Highcharts.dateFormat('%b %e', val);  // display Jan 31
        }
        return label;
    }

})();

/**
 * widget.Filtering
 *
 * @description filtering to only show related data
 * @param {Object} settings The settings for FilterTabs
 * @param {Function} callback function
 */

(function () {
    var bbg = BLOOMBERG,
        widget = bbg.namespace("widget"),
        DEFAULT_SETTINGS;

    DEFAULT_SETTINGS = {
        tabNameArray: [],
        targetDom: null,
        tabGroupDom: null,
        defaultTabName: null
    };

    function FilterTabs(settings, callback) {
        if (!settings || !settings.tabNameArray || !settings.targetDom || !settings.tabGroupDom) {
            return;
        }
        
        $.extend(DEFAULT_SETTINGS, settings);

        function clearAllTabs() {
            settings.targetDom.removeClass(settings.tabNameArray.join(" "));
        }
        if (settings.defaultTabName) {
            clearAllTabs();
            settings.targetDom.addClass(settings.defaultTabName);          
        }
        $(settings.tabNameArray).each(function (){
            var tabName = this.toString();

            settings.tabGroupDom.find("." + tabName).click(function () {
                clearAllTabs();
                settings.targetDom.addClass(tabName);
                if (callback) {
                    callback.call(FilterTabs, tabName);
                }
                return false;    
            });
        });
    }
    
    widget.FilterTabs = function (settings, callback) {
        return new FilterTabs(settings, callback);
    };
})();

/**
 * Bloomberg TV Channel Lookup
 * widget.TvChannelLookup
 * Tested under channel_finder_test.html and channel_finder_tests.js
 */
(function () {
    var bbg = BLOOMBERG,
        widget = bbg.namespace("widget");
    widget.TvChannelLookup = function () {
        var fakeZipLookInput = $("#fake_zip_lookup"),
            zipLookInput = $("#zip_lookup"),
            channelLookupFormDiv = $("#channel_lookup_form"),
            displayData = $("#lookup_results"),
            countrySelect = $("#country_lookup");
        
        function flipZipInput(toReal) {
            if (toReal === true) {
                fakeZipLookInput.hide();
                zipLookInput.show();
                zipLookInput.focus();
            } else {
                zipLookInput.hide();
                fakeZipLookInput.show();            
            }
        }

        zipLookInput.val("");

        countrySelect.val("US").change(function () {
            if ($(this).val() === "US") {
                flipZipInput(false);
            } else {
                fakeZipLookInput.hide();
                zipLookInput.hide();
            }
        });

        fakeZipLookInput.focus(function () {
            flipZipInput(true);   
        });

        zipLookInput.blur(function () {
            if ($(this).val() === "") {
                flipZipInput(false);
            }
        });

        function submitLookup() {
            var zip = zipLookInput.val(),
                country = countrySelect.val(),
                rawData,
                error = $("#channel_finder .lookup_error");

            function showError(msg){
                error.html(msg);
                error.show();
            }

            function clearError(){
                error.html('');
                error.hide();
            }

            function lookupAndDisplay(countryCode, zipCode) {

                var apiUrl = "/chlookup/chan",
                    options = {};

                if (countryCode === "US" && zipCode.length === 5) {
                    options.zip = zipCode;
                } else if (countryCode !== "US") {
                    options.country = countryCode;
                }
                $("#channel_loading_img").show();
                $.ajax({
                    type: "GET",
                    url: apiUrl,
                    data: options,
                    dataType: "json",
                    success: function(data){
                        displayResults(data);
                    },
                    error: function(){
                        //displayResults(testData);
                        showError('Network error.');
                    },
                    complete: function(){
                        $("#channel_loading_img").hide();
                    }
                });
            }

            function getResultsDom(data) {
                var dataTable = $('<table></table>'),
                    providerArray = data["PROVIDER"].concat(data["SATPROVIDER"]),
                    providerTh = $('<th></th>').text("PROVIDERS"),
                    channelTh = $('<th></th>'),
                    disclaimerTr = $('<tr><td class="disclaimer" colspan="2">* Not available in all areas</td></tr>'),
                    hasChannel = false;

                dataTable.append(providerTh).append(channelTh);

                if(providerArray.length > 0) {
                    $.each(providerArray, function (i) {
                        var dataTr = $('<tr></tr>'),
                            providerTd = $('<td></td>').addClass("provider"),
                            channelTd = $('<td></td>').addClass("channels"),
                            channelName = providerArray[i].NAME,
                            channelProvider = getChannels(providerArray[i]);

                        providerTd.text(channelName);
                        channelTd.text(channelProvider);
                        if (channelProvider !== '' && !hasChannel) {
                            hasChannel = true;         
                        }
                        dataTr.append(providerTd).append(channelTd);
                        dataTable.append(dataTr);
                    });
                    dataTable.append(disclaimerTr);
                } else {
                    dataTable.append("<tr><td colspan=\"2\">Unfortunately, there are no providers in "+ data["COUNTRY"].CODE +"</td></tr>");
                }

                if (hasChannel) {
                    channelTh.text("CHANNEL");
                }

                return dataTable;
            }
            function getChannels(data){
                var channels = data.CHANNEL,
                    hdChannels = data.HDCHANNEL,
                    hdChanDisplay = "";

                if (hdChannels !== "") {
                    if (channels !== ""){
                        hdChanDisplay += ", ";
                    }
                    hdChanDisplay += $.map(hdChannels.split(","), function(n){
                        return n + " (HD)";
                    });
                }
                return channels + hdChanDisplay;
            }

            function displayResults(data) {
                var resultDom = getResultsDom(data),
                    changeA = $("#change"),
                    control1 = $("#control1"),
                    control2 = $("#control2"),
                    areaText,
                    chosenCountry = data["COUNTRY"].CODE,
                    countryName = $("#country_lookup :selected").text();

                changeA.click(function (event) {
                    event.preventDefault();
                    control2.hide();
                    control1.show();
                    return false;
                });

                areaText = countryName;
                if (chosenCountry === "US") {
                    areaText +=  " " + $("#zip_lookup").val();
                }
                control1.hide();
                $("#area").text(areaText);
                control2.show();
                displayData.html("").append(resultDom).show();

            }
            clearError();
            if (country === "US" && (!zip || zip.length !== 5)) {
                showError('ZIP is required for U.S. locations');
            } else {
                lookupAndDisplay(country, zip);
            }
        }

        $("#channel_lookup_submit").click(submitLookup);
        
        zipLookInput.keypress(function (e) {
            if(e.keyCode === 13) {
                submitLookup();
                return false;
            }
        });

    };
    
})();
/*
 binding filtering to only show related data
 bind to module (i.e. filtering_index)
 filters are in .tabs
 items are in .news_group
 display rules are handled in the CSS, see .filtered_index
 (this function can be replaced by the FilterTabs widget defined above, by using BLOOMBERG.widget.FilterTabs(...))
 */
$.fn.bindFiltering = function() {
    return this.each(function() {
        var $self = $(this),
                $tabs = $self.find('.tabs'),
                $items = $self.find('.news_group'),
                filters = ["all", "exclusive", "breaking", "businessweek"];

        /* bind event to tabs */
        $(filters).each(function() {
            var filterName = this.toString();
            $tabs.find('.' + filterName).click(function() {
                $self.removeClass('exclusive breaking businessweek all').addClass(filterName);
                return false;
            });
        });
    });
};

/*
    bind module link tracking
    this should be bound to a set of elements that contain links (a tags)
 */
$.fn.bindModuleLinkTracking = function(module, trackHiddenLinks) {
    var links = $(this).find('a:visible');
    if (typeof trackHiddenLinks != "undefined" && trackHiddenLinks) {
        links = $(this).find('a');
    }
    return links.each(function(index, e) {
        $(this).mousedown(function(){
            //console.log('Module Link Tracking - ' + module + index + " - " + this.href);
            var padded_index = BLOOMBERG.num.pad(index,2);
            BLOOMBERG.tracker.EVENTTRACK.record('Module Link Tracking', module + padded_index, this.href);
        });

    })
};

/*
   make same height
   makes elements to be the height of the tallest element
   this should be bound to a set of jquery-selected elements
 */
$.fn.makeSameHeight = function(){
    var $this = $(this),
        maxHeight,
        arr = [];
    $this.each(function(){
        arr.push($(this).height());
    });
    maxHeight = Math.max.apply(Math, arr);
    return $this.each(function(){
        $(this).height(maxHeight);
    });
};

$.fn.dynamicModuleLinkTracking = function(module, trackHiddenLinks)
{
  var module_id = "#" + module;
  var links = "";

  if(typeof trackHiddenLinks != "undefined" && trackHiddenLinks)
  {
    links = $(module_id).find('a');
  }
  else
  {
    links = $(module_id).find('a:visible');
  }

  var current_link = $(this).text();

  links.each(function(index, e) {
    if(current_link == $(this).text())
    {
      var padded_index = BLOOMBERG.num.pad(index, 2);
        BLOOMBERG.tracker.EVENTTRACK.record('Module Link Tracking', module + padded_index, this.href);
    }
  })
};

/*
 bind print story
 */
$.fn.bindPrint = function() {
    return this.each(function() {
        //$(this).click(window.print())
        var $self = $(this),
                $items = $self.find('a');

        /* bind print to each item */
        $($items).each(function() {
            $(this).click(function() {
                window.print();
                return false;
            });
        });
    });
};

$.fn.bindShare = function() {
    return this.each(function() {
        var $self = $(this),
                $link = $self.find("a").not(".options a");
        $link.click(function(e) {
            e.stopPropagation(); // stops the click event from reaching the body (closing menu)
            $self.toggleClass("menu-active");
            return false;
        });
        // remove any active menus
        $("body").click(function() {
            $(".menu-active").removeClass("menu-active");
        });
    });
};

$.fn.bindDaySelection = function(handler) {
    return this.each(function() {
        var $parent = $(this),
                $days = $parent.find("li");

        $days.each(function() {
            var $day = $(this),
                $link = $day.find("a"),
                dayName = $day.attr("id"),
                todayIs = $("#days_of_the_week").attr("class");

            function goToTheDay(dayName){
                $parent.removeClass('monday tuesday wednesday thursday friday saturday sunday').addClass(dayName);
            }

            if (todayIs === dayName) {
                handler(dayName);  

            }

            $link.click(function() {
                goToTheDay(dayName);
                if (typeof handler === 'function'){
                    handler(dayName);                    
                }
                return false;
            });
        });
    });
};

/**
 * Page display tool - text truncator
 */
$.fn.bindTextTruncator = function(limit){
    return this.each(function(){
            var $self = $(this),
                textLength = $self.text().length,
                lessText = $self.text().substring(0,limit),
                $lessText =  $('<p style="display:inline;" class="less_text">' + lessText + '</p>'),
                moreText = $self.text().substring(limit,textLength),
                $moreText = $('<p style="display:inline;" class="more_text">' + moreText + '</p>'),
                $readMore = $('<p style="display:inline;" class="continue">&hellip; </p><a href="#show_more" class="read_more">Read More &#9660;</a>'),
                $readLess = $('<a href="#show_less" class="read_less">Close</a>');
        if(textLength > limit){
            $self.html($lessText).append($readMore).append($moreText).append($readLess);
            $moreText.hide();
            $readLess.hide();
        }
        $self.find('a.read_more').click(function(){
            $self.find('p.continue').hide();
            $readMore.hide();
            $moreText.show();
            $readLess.show();
            return false;
        });
        $self.find('a.read_less').click(function(){
            $self.find('p.continue').show();
            $readMore.show();
            $moreText.hide();
            $readLess.hide();
            return false;
        });
    });
};

(function(){
    var ads = BLOOMBERG.namespace("ads");
    ads.hide_leader_board = function(){
        var topBanner = $("#leader_board");
        var tinyWhiteImages = ["http://imagec12.247realmedia.com/RealMedia/ads/Creatives/default/empty.gif",
            "http://imagec12.247realmedia.com/RealMedia/ads/Creatives/Bloomberg/Slider-test/1x1_bw-no-show-ad.gif",
            "http://imagec12.247realmedia.com/RealMedia/ads/Creatives/Bloomberg/3841153/1x1_bw-no-show-ad.gif/1304978391"];
        if (topBanner.length > 0){
            for(var i=0; i<tinyWhiteImages.length; i++){
                if (topBanner.find("img[src*='" + tinyWhiteImages[i] + "']").length > 0) {
                    topBanner.hide();
                }
            }
        }
    };
    var ads_type_tag_mapping = {
        'StaticResource':'<img>',
        'IFrameResource':'<iframe>'
    };
    ads.parse_display_companion_ads = function(companionAds, ad_site){
        for(var i=0;i<companionAds.length; i++){
            var ad = companionAds[i];
            var target_element = null;
            target_element = $(ad.height <= 100 ? "[id='gpt_unit_"+ad_site+"/live_0']" : "[id='gpt_unit_"+ad_site+"/live_1']");
            target_element.html('');
            if (ad.resourceType === "StaticResource" || ad.resourceType === "IFrameResource"){
                if(ad.creativeType == "application/x-shockwave-flash"){
                    var swf_ad = new SWFObject(ad.url, "swf_companion_" + i, ad.width, ad.height, "10", "#000000");
                    swf_ad.write(target_element.attr('id'));
                }else{
                    var element_tag = ads_type_tag_mapping[ad.resourceType];
                    var a_tag = $("<a>").attr('href', ad.clickThroughUrl).css("text-decoration","none");
                    var creative = $(element_tag).attr('width', ad.width).attr('height', ad.height).
                            attr('scrolling', 'no').attr('src', ad.url).css('border', 'none');
                    if (ad.resourceType === "IFrameResource"){
                        creative.attr('margin', '0').attr('marginwidth', '0').attr('marginheight', '0').attr('frameBorder', '0');
                    }
                    a_tag.append(creative);
                    target_element.append(a_tag);
                }
            }else{
                // if the ad.url already starts with "<iframe", don't create iframe again, because it's causing issue in FF 3.x
                if (/^\s*<\s*iframe\s+/i.test(ad.url)){
                    target_element.html(ad.url);
                }else{
                    var iframe = $("<iframe>").attr('width', ad.width).attr('height', ad.height).
                            attr('scrolling', 'no').css('border', 'none').
                            attr('marginwidth', '0').attr('marginheight', '0').attr('frameBorder', '0');
                    target_element.append(iframe);
                    iframe.contents()[0].write(ad.url);
                }
            }
        }
    };
})();

/**
 * Facebook XFBML version Recommend Button
 */
(fbRecoButton = function(url){
    var chnlUrl = "'" + url + "/channel.html" + "'";
    if ( $.browser.msie == true &&  ( $.browser.version == 8.0 || $.browser.version == 7.0)) {
       chnlUrl = "";
     }

    window.fbAsyncInit = function() {
        FB.init({
          appId  : '100001111898866',
          status : true, // check login status
          cookie : true, // enable cookies to allow the server to access the session
          xfbml  : true,  // parse XFBML
          channelUrl: chnlUrl  
        });
      };
      (function() {
        var e = document.createElement('script');
        e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
        e.async = true;
        $('#fb-root').append(e);
      }());
})();   

(function (){
    var player_ns = BLOOMBERG.namespace('BLOOMBERG.player');
    player_ns.render_video_player = function(container_id, config){
        //var poster_url = $('meta[property="og:image"]').attr('content');
        var videoPlayer = new SWFObject( BLOOMBERG.url.CombinePath(BLOOMBERG.global_var.image_domain, "/flash/BloombergMediaPlayer.swf"), "bbmp", "100%", "100%", "10", "#000000");
        videoPlayer.addParam('allowFullScreen', 'true');
        videoPlayer.addParam("allowscriptaccess","always");
        videoPlayer.addParam('wmode', 'opaque');

        if(config._autoplay){
            videoPlayer.addVariable('autoplay', 'true');
        }
        if(config._video_url){
            videoPlayer.addVariable('file_url', config._video_url);
        }
        else if (config._asset_id){
            videoPlayer.addVariable('asset_ids', config._asset_id);
        }
        else if (config._fvid_id) {
            videoPlayer.addVariable('file_url', BLOOMBERG.video.generate_url_from_fvid(config._fvid_id));
        }
        //poster url
//        if(poster_url) {
//            videoPlayer.addVariable('poster_url', escape(poster_url));
//        }
        //ads
        if(config._site){
            videoPlayer.addVariable('site', config._site);
        }
        if(config._zone){
            videoPlayer.addVariable('zone', config._zone);
        }
        videoPlayer.addVariable('EnableLogging','true');
        videoPlayer.addVariable('LoggingDomain','www.bloomberg.com');
        videoPlayer.addVariable('sz', '1x1');
        videoPlayer.addVariable('tile', '1');

        videoPlayer.addVariable('title', config._title);
        videoPlayer.addVariable('description', config._description);
        videoPlayer.addVariable('GoogleUA', BLOOMBERG.global_var.gaTrackAcct);
        videoPlayer.write(container_id);
    }
})();
/**
 * All the actions are taken when DOM is ready
 */
(function () {
    var bbg = BLOOMBERG,
        widget = bbg.namespace("widget"),
        util = bbg.namespace("util"),
        Cookie = bbg.namespace("util.Cookie"),
        FilterTabs = widget.FilterTabs;
    $(document).ready(function () {
        var liveTvPlayer,
            liveTvPlayerPopup,
            videoPlayer,
            videoPlayerPopup,
            radioPlayer;

        BLOOMBERG.showTvStreaming = function(is_auto_play, use_ooyala){
          if (use_ooyala)
          {
            document.getElementById('ooyala_live_tv').setQueryStringParameters({wmode: "opaque", embedCode: BLOOMBERG.global_var.live_stream_us || "d3MzYwMjoS4f85a0xfQrxDFebezasnkN", "thruParam_doubleclick[tagUrl]": "http://ad.doubleclick.net/pfadx/" + bbg._site + "/" + bbg._zone + ";sz=1x1;tile=1;tp_video=null;dcmt=text/html;ord=" + BLOOMBERG.global_var.random_num, hide:'share', autoplay: is_auto_play == "true" ? 1 : 0})
          }
          else
          {
            liveTvPlayer = new SWFObject( BLOOMBERG.global_var.image_domain + "/flash/BloombergMediaPlayer.swf", "bbmp", "100%", "100%", "10", "#000000");
            liveTvPlayer.addParam('allowFullScreen', 'true');
            liveTvPlayer.addParam("allowscriptaccess","always");
            liveTvPlayer.addParam('wmode', 'opaque');

            //ads, variable: site, zone
            if(bbg._site){
                liveTvPlayer.addVariable('site', bbg._site);
            }
            if(bbg._zone){
                liveTvPlayer.addVariable('zone', bbg._zone);
            }
            liveTvPlayer.addVariable('EnableLogging','true');
            liveTvPlayer.addVariable('LoggingDomain','www.bloomberg.com');
            liveTvPlayer.addVariable('sz', '1x1');
            liveTvPlayer.addVariable('tile', '1');

            liveTvPlayer.addVariable('stream_url', BLOOMBERG.live_tv_stream_url || 'rtmpt://cp87869.live.edgefcs.net/live/us_300@21006');

            liveTvPlayer.addVariable('title', bbg._title);
            liveTvPlayer.addVariable('description', bbg._description);
            if ($('body').hasClass('davos')) {
                liveTvPlayer.addVariable('poster_url', '../images/bumpers/bbtv.png');
            } else {
                liveTvPlayer.addVariable('poster_url', '../images/bumpers/tv-bumper-live.png');
            }

            liveTvPlayer.addVariable('GoogleUA', BLOOMBERG.global_var.gaTrackAcct);
            if (is_auto_play == "true") {
                liveTvPlayer.addVariable('autoplay', 'true');
            }
            liveTvPlayer.write("mediaplayer");
          }
        };
        BLOOMBERG.showRadioStreaming = function(is_auto_play, elem_id){
            radioPlayer = new SWFObject( BLOOMBERG.global_var.image_domain + "/flash/BloombergMediaPlayer.swf", "bbmp", "100%", "100%", "10", "#000000");
		    radioPlayer.addParam("allowFullScreen", "false");
		    radioPlayer.addParam("allowscriptaccess","always");
            radioPlayer.addParam('wmode', 'opaque');
            radioPlayer.addVariable('EnableLogging','true');
            radioPlayer.addVariable('LoggingDomain','www.bloomberg.com');
            radioPlayer.addVariable('fullscreen_ui', "false");
		    radioPlayer.addVariable("stream_url", "rtmpt://cp87869.live.edgefcs.net/live/bbr@21885");

            if ($('body').hasClass('.davos')) {
                radioPlayer.addVariable('poster_url', "../images/bumpers/bbradio.png");
            } else {
                radioPlayer.addVariable('poster_url', "../images/bumpers/radio-bumper-live.png");
            }

            radioPlayer.addVariable('tp_video', '000');
            radioPlayer.addVariable('title', 'Bloomberg Radio');
            radioPlayer.addVariable('description', "Bloomberg Radio");
            radioPlayer.addVariable('GoogleUA', BLOOMBERG.global_var.gaTrackAcct);
            if (is_auto_play == "true") {
                radioPlayer.addVariable('autoplay', 'true');
            }
		    radioPlayer.write(elem_id == null ? "mediaplayer" : elem_id);
        };
        BLOOMBERG.register_nav_events();
        // keep track of user's traveling across the page
        if ($(".story_link")) {
            $(".story_link").mousedown(function (event) {
                var parents = $(this).parents(".news_section"),
                    id_name = (parents.length > 0)?$(parents)[0].id:"";

                Cookie.set("path_cookie", id_name, '', '', '');
                return true;
            });
        }

        // toggle tv schedule
        if ($('#days_of_the_week')) {
            function showSchedule (day) {
                $(".time_table").removeClass("show_today");
                $("#" + day + "_schedule").addClass("show_today");
            }

        $('#days_of_the_week').bindDaySelection(function (day) {
                if (!day) {
                    return;
                }
                showSchedule(day);
            });
        }

        if ($("#channel_finder").length > 0) {
            widget.TvChannelLookup();
        }

        // display BLOOMBERG TV player
        if ($("#bloomberg_tv_live #mediaplayer").length > 0) {
            BLOOMBERG.showTvStreaming();
        }


        // tv region tab filter for Ooyala Player
        if ($("#ooyala_mediaplayer").length > 0) {
            var tvShowFilterTabsSettings = {
                tabNameArray: ["us", "europe", "asia"],
                targetDom: $("#bloomberg_tv_live"),
                tabGroupDom: $("#bloomberg_tv_live .tabs")
            },
            tvShowStreamUrLArray = {
                us: BLOOMBERG.global_var.live_stream_us || "d3MzYwMjoS4f85a0xfQrxDFebezasnkN",
                europe: BLOOMBERG.global_var.live_stream_europe || "41NDYwMjoAX-XqGCy1PYOso_K5JHYUHa",
                asia: BLOOMBERG.global_var.live_stream_asia || "A3NDYwMjrxuAk9iHbmNGbDNGV59SvMRF"
            };

            FilterTabs(tvShowFilterTabsSettings, function (tabName){
                document.getElementById('ooyala_live_tv').setQueryStringParameters({wmode: "opaque", embedCode: tvShowStreamUrLArray[tabName], autoplay:"1","thruParam_doubleclick[tagUrl]": "http://ad.doubleclick.net/pfadx/" + bbg._site + "/" + bbg._zone + ";sz=1x1;tile=1;tp_video=null;dcmt=text/html;ord=" + BLOOMBERG.global_var.random_num, hide:'share'})
            });
        }
        // tv show region tab filter
        if ($("#bloomberg_tv_live").length > 0 && $("#ooyala_mediaplayer").length <= 0) {
            var tvShowFilterTabsSettings = {
                tabNameArray: ["us", "europe", "asia"],
                targetDom: $("#bloomberg_tv_live"),
                tabGroupDom: $("#bloomberg_tv_live .tabs"),
                defaultTabName: BLOOMBERG.live_tv_default_tab || "us"
            },
            tvShowStreamUrLArray = {
                us: "rtmpt://cp87869.live.edgefcs.net/live/us_300@21006",
                europe: "rtmpt://cp87869.live.edgefcs.net/live/uk_300@21008",
                asia: "rtmpt://cp87869.live.edgefcs.net/live/ap_300@21010"
            };

            FilterTabs(tvShowFilterTabsSettings, function (tabName){
                var streamUrl = tvShowStreamUrLArray[tabName];
                liveTvPlayer.addVariable("stream_url", streamUrl);
                liveTvPlayer.write("mediaplayer");
            });
        }

        if($("#radio_guests").length > 0) {

            var guestTabsSettings = {
                tabNameArray: ["recent", "past"],
                targetDom: $("#radio_guests"),
                tabGroupDom: $("#radio_guests .tabs"),
                defaultTabName: "recent"        
            };
            FilterTabs(guestTabsSettings, function (tabName){
                $("#recent_guests_list table").hide();
                $("#recent_guests_list ." + tabName).show();               
            });

        }

        if ($("#bloomberg_radio_live #mediaplayer").length > 0) {
             BLOOMBERG.showRadioStreaming();
        }

        //vod player
        if ($("#bloomberg_vod_player").length > 0 && $('#ooyala_mediaplayer').length <= 0) {
            var poster_url = $('meta[property="og:image"]').attr('content');
            videoPlayer = new SWFObject( BLOOMBERG.url.CombinePath(BLOOMBERG.global_var.image_domain, "/flash/BloombergMediaPlayer.swf"), "bbmp", "100%", "100%", "10", "#000000");
            videoPlayer.addParam('allowFullScreen', 'true');
            videoPlayer.addParam("allowscriptaccess","always");
            videoPlayer.addParam('wmode', 'opaque');

            if(bbg._autoplay){
                videoPlayer.addVariable('autoplay', 'true');
            }
            if(bbg._video_url){
                videoPlayer.addVariable('file_url', bbg._video_url);
            }
            else if (bbg._asset_id){
                videoPlayer.addVariable('asset_ids', bbg._asset_id);
            }
            else if (bbg._fvid_id) {
                videoPlayer.addVariable('file_url', bbg.video.generate_url_from_fvid(bbg._fvid_id));
            }
            //poster url
            if(poster_url) {
                videoPlayer.addVariable('poster_url', escape(poster_url));
            }
            //ads
            if(bbg._site){
                videoPlayer.addVariable('site', bbg._site);
            }
            if(bbg._zone){
                videoPlayer.addVariable('zone', bbg._zone);
            }
            videoPlayer.addVariable('EnableLogging','true');
            videoPlayer.addVariable('LoggingDomain','www.bloomberg.com');
            videoPlayer.addVariable('sz', '1x1');
            videoPlayer.addVariable('tile', '1');

            videoPlayer.addVariable('title', bbg._title);
            videoPlayer.addVariable('description', bbg._description);
            videoPlayer.addVariable('GoogleUA', BLOOMBERG.global_var.gaTrackAcct);
            videoPlayer.write("mediaplayer");

        }

        //Market snapshot tabs
        if ($("#market_snapshot").length > 0) {
            var marketShowFilterTabsSettings = {
                tabNameArray: ["us", "europe", "asia"],
                targetDom: $("#market_snapshot"),
                tabGroupDom: $("#market_snapshot .tabs")

            },
            marketShowStreamUrLArray = {
                us: "",
                europe: "",
                asia: ""
            };

            FilterTabs(marketShowFilterTabsSettings,function(tabName){
                BLOOMBERG.market_summary.set_default_chart();
            });
        }

        if ($("#market_snapshot_table").length > 0) {
            var marketSnapSimpleShowFilterTabsSettings = {
                tabNameArray: ["us", "europe", "asia"],
                targetDom: $("#market_snapshot_table"),
                tabGroupDom: $("#market_snapshot_table .tabs")
            };
            FilterTabs(marketSnapSimpleShowFilterTabsSettings);
        }

        if ($("#non_stop_news_module").length > 0) {
            var marketSnapSimpleShowFilterTabsSettings = {
                tabNameArray: ["more_top_news_header", "non_stop_news_header", "recommended_news_header", "popular_news_header"],
                targetDom: $("#non_stop_news_module_container"),
                tabGroupDom: $("#non_stop_news_module_container .tabs")
            };
            FilterTabs(marketSnapSimpleShowFilterTabsSettings);
        }

        if ($("#market_data_container").length > 0) {
            var marketDataFilterTabsSettings = {
                tabNameArray: ["indexes_header", "futures_header", "currencies_header", "bonds_header"],
                targetDom: $("#market_data_module"),
                tabGroupDom: $("#market_data_module .tabs")
            };
            FilterTabs(marketDataFilterTabsSettings);
        }

        //More dropdown for navigation bar
        if ($(".header_nav #more_navigation_item>a").length > 0){
            $(".header_nav #more_navigation_item>a").click(function(){
                $(".header_nav #more_navigation_item>a").toggleClass("dropdown");
                $(this).parent().find("ul.submenu").toggleClass("hide");
                return false;
            });
            $("body").click(function() {
                $(".header_nav #more_navigation_item>a").removeClass("dropdown");
                $(".header_nav #more_navigation_item>ul").addClass("hide");
            });
        }

        //more navigation for eyebrow
        $('ul.eyebrow_navigation li.has_more a:first').click(
            function(e){
              e.preventDefault();
              e.stopPropagation();
              $(this).toggleClass("open");
              $(this).parent().find('ul.sub_menu').toggleClass('open');
            });
         $("body").click(function() {
                $('ul.eyebrow_navigation li.has_more a').removeClass('open');
                $('ul.eyebrow_navigation li.has_more ul.sub_menu').removeClass('open');
            });

        //Enterprise Company Profile
        if ($("#company_profile_container").length > 0) {
            var enterpriseSnapSimpleShowFilterTabsSettings = {
                tabNameArray: ['blue_star_jets', 'bonobos', 'american_le_mans', 'smashburger', 'bowlmor', 'tequila_avion', 'tough_mudder', 'skull_candy', 'easton_bell'],
                targetDom: $("#company_profile_container"),
                tabGroupDom: $("#company_profile_container .tabs")
            };
            FilterTabs(enterpriseSnapSimpleShowFilterTabsSettings);
        }
        //Risk Takers Bios
        if ($("#risk_taker_bio_container").length > 0) {
            var riskTakersSnapSimpleShowFilterTabsSettings = {
                tabNameArray: ['david_neel','michael_burry','scott_boras','elon_musk','michelle_rhea'],
                targetDom: $("#risk_taker_bio_container"),
                tabGroupDom: $("#risk_taker_bio_container .tabs")
            };
            FilterTabs(riskTakersSnapSimpleShowFilterTabsSettings);
        }
        //Market snapshot tabs
        if ($(".home #data_insights").length > 0) {
            var dataInsightsFilterTabsSettings = {
                //tabNameArray: ["equities", "futures", "currencies", "commodities", "bonds", "key_rates", "muni_bonds"],
                tabNameArray: $(".home #data_insights .tabs li").map(function(){ return this.className }).get(),
                targetDom: $("#data_insights"),
                tabGroupDom: $("#data_insights .tabs")
            };
            FilterTabs(dataInsightsFilterTabsSettings);
        }
       });


//    hide the ad boxes when there are no ad in it and its not dfp ad.
//    tested via: /ads-test/ads_hiding
    
    $(window).bind("load", function () {
        var adBoxesArray = $("div.ad_box").filter(".dfp_ad_box"),
            dfpAdBoxesArray = $("div.dfp_ad_box"),
            microAdBoxesArray = $("div.micro_bar_ad"),
            topBanner = $("#leader_board"),
            url = location.href,
            tinyWhiteImage = "http://imagec12.247realmedia.com/RealMedia/ads/Creatives/default/empty.gif",
            dfpTinyWhiteImage = "http://s0.2mdn.net/viewad/817-grey.gif",
            companion1x1 = "1x1_bw-no-show-ad.gif";

        if (url.indexOf("debug=true") !== -1) {
            return true;
        }

        microAdBoxesArray.filter( function (i) {
            var self = $(this),
                hasDefaultImage =  self.find("img[src*='" + tinyWhiteImage + "']").length > 0,
                hasDefaultDfpImage = self.find("img[src*='" + dfpTinyWhiteImage + "']").length > 0,
                hasOnlyScript = self.children().size() === 1,
                hasOnly1x1Pix = self.find("a").length == 1 && self.find("a img").width() == 1 && self.find("a img").height() == 1;
            return ( hasDefaultImage || hasOnlyScript || hasOnly1x1Pix || hasDefaultDfpImage );
        }).hide();

        adBoxesArray.filter( function (i) {
            var self = $(this),
                hasBlankImg = ((self.find("img[src*='http://ads.bloomberg.com/adstream_nx.ads/']").length > 0) || (self.find("img[src*='" + companion1x1 + "']").length > 0) ),
                hasEmbed = self.find("embed").length > 0,
                hasIframe = self.find("iframe").length > 0,
                hasImg = self.find("img").length > 0,
                hasObject = self.find("object").length > 0,
                hasDivHeight = self.find("div").height() > 2,
                hasCenter = self.find("center").length > 0,
                hasText = self.find("a[class=textadblack]").length > 0, // need to reconsider
                hasGoogle = self.find("div[id*=gpt]").length > 0,
                onlyHasHiddenAd = self.find("a").length == 1 && self.find("a img[src*='" + tinyWhiteImage + "']").length > 0,
                hasHiddenMicroBarContent = self.find("div[class=micro_bar_content]").is(":hidden") || self.find("div[class=micro_bar_content]").height() == 0;

            return (hasBlankImg || hasHiddenMicroBarContent || onlyHasHiddenAd || !(hasEmbed || hasIframe || hasImg || hasObject || hasText || hasCenter || hasDivHeight)) && !hasGoogle;
        }).hide();

        dfpAdBoxesArray.filter( function (i) {
            var self = $(this),
                hasBlankImg = ((self.find("img[src*='http://ads.bloomberg.com/adstream_nx.ads/']").length > 0) || (self.find("img[src*='" + companion1x1 + "']").length > 0) ),
                hasEmbed = self.find("embed").length > 0,
                hasIframe = self.find("iframe").length > 0,
                hasImg = self.find("img").length > 0,
                hasObject = self.find("object").length > 0,
                hasDivHeight = self.find("div").height() > 2,
                hasCenter = self.find("center").length > 0,
                hasText = self.find("a[class=textadblack]").length > 0, // need to reconsider
                hasGoogle = self.find("div[id*=gpt]").length > 0,
                onlyHasHiddenAd = self.find("a").length == 1 && self.find("a img[src*='" + tinyWhiteImage + "']").length > 0,
                onlyHasHiddenDfpAd = self.find("a").length == 1 && self.find("a img[src*='" + dfpTinyWhiteImage + "']").length > 0,
                hasHiddenMicroBarContent = self.find("div[class=micro_bar_content]").is(":hidden") || self.find("div[class=micro_bar_content]").height() == 0;

            return (hasBlankImg || hasHiddenMicroBarContent || onlyHasHiddenAd || onlyHasHiddenDfpAd || !(hasEmbed || hasIframe || hasImg || hasObject || hasText || hasCenter || hasDivHeight)) && !hasGoogle;
        }).hide();



        if ((topBanner.length > 0 && topBanner.find("img[src*='" + tinyWhiteImage + "']").length > 0) || (topBanner.length > 0 && topBanner.find("img[src*='" + dfpTinyWhiteImage + "']").length > 0)) {
            topBanner.hide();
        }

    });
})();

/**
 * Story tool clone function
 */
(function() {
    var bbg = BLOOMBERG,
    storytoolutil = bbg.namespace("storyutil");

     storytoolutil.CLONESTORYTOOL = (function(){
         var self;
         function clonestorytool(){
             var story_copy = $("#story_tools_bottom").clone(true).attr('id','story_tools_top');
             var target_url = $("#story_tools_bottom .linkedin").attr('target_url');
             story_copy.find('.linkedin').html('');
             $("#story_tools_top_holder").replaceWith(story_copy);

             var scr = $('<script/>').attr('type', 'in/share').attr('data-counter','right').attr('data-url', target_url);
             $('#story_tools_top .linkedin').append(scr);
              
          }
         function clonevideotools(anchor_id){
             var el_to_replace = $('#' + anchor_id),
                 story_copy = $("#story_tools_bottom");
             story_copy.find('.linkedin').html('');
             el_to_replace.replaceWith($("#story_tools_bottom"));

             var scr = $('<script/>').attr('type', 'in/share').attr('data-counter','right');
             $('#story_tools_bottom .linkedin').append(scr);
         }
         function clone_google_plusone(){
             var j_set = $("#story_tools_top .google_plusone");
             if (j_set.length > 0){
                 j_set.html('');
                 gapi.plusone.render(j_set[0], {"size": "medium", "href": j_set.attr('target_url')});
             }
         }
          self = {
            clonetool: function (){
                return clonestorytool();
            },
            clonevideotool: function (anchor_id){
                return clonevideotools(anchor_id);
            },
            clone_google_plusone: function(){
                return clone_google_plusone();
            }
        };
        return self;
         
     })();
})();
/**
 * URL Util
 */
(function(){
    var bbg = BLOOMBERG,
        util = bbg.namespace("util");

    function URL(url) {
        var urlParts = url.split("?"),
            paramPairs = urlParts[1] !== ''?urlParts[1].split("&") : [],
            that = this;

        that.pureUrl = urlParts[0];
        that.params = {};

        if (paramPairs.length > 0) {
            $.each(paramPairs, function(key, value) {
                var pairParts = value.split("=");
                that.params[pairParts[0]] = pairParts[1];
            });
        }

    }

    URL.prototype.getParameter = function (param) {
        return this.params[param];        
    };

    URL.prototype.setParameter = function (param, value) {
        this.params[param] = value;
        return this;
    };

    URL.prototype.getUrl = function () {
        var paramString,
            i,
            url = this.pureUrl + '?',
            paramPairs = [];

        for (i in this.params) {
            paramPairs.push(i + "=" + this.params[i]);
        }
        return url +  paramPairs.join('&');
    };

    URL.prototype.getPureUrl = function () {
        return this.pureUrl;
    };

    util.URL = function (url) {
        return new URL(url);
    };
})();

/**
 * SWF Util
 */
(function(){
    var bbg = BLOOMBERG,
        swf = bbg.namespace("swf");

        // @see http://code.google.com/p/doctype/wiki/ArticleDetectFlash
        function getFlashVersion(desc) {
          var matches = desc.match(/[\d]+/g);
          matches.length = 3;  // To standardize IE vs FF
          return matches.join('.');
        }

        var hasFlash = false;
        var flashVersion = '';

        if (navigator.plugins && navigator.plugins.length) {
            var plugin = navigator.plugins['Shockwave Flash'];
            if (plugin) {
                hasFlash = true;
                if (plugin.description) {
                    flashVersion = getFlashVersion(plugin.description);
                }
            }

            if (navigator.plugins['Shockwave Flash 2.0']) {
                hasFlash = true;
                flashVersion = '2.0.0.11';
            }

        } else if (navigator.mimeTypes && navigator.mimeTypes.length) {
            var mimeType = navigator.mimeTypes['application/x-shockwave-flash'];
            hasFlash = mimeType && mimeType.enabledPlugin;
            if (hasFlash) {
                flashVersion = getFlashVersion(mimeType.enabledPlugin.description);
            }

        } else {
            try {
                // Try 7 first, since we know we can use GetVariable with it
                var ax = new ActiveXObject('ShockwaveFlash.ShockwaveFlash.7');
                hasFlash = true;
                flashVersion = getFlashVersion(ax.GetVariable('$version'));
            } catch (e) {
                // Try 6 next, some versions are known to crash with GetVariable calls
                try {
                    var ax = new ActiveXObject('ShockwaveFlash.ShockwaveFlash.6');
                    hasFlash = true;
                    flashVersion = '6.0.21';  // First public version of Flash 6
                } catch (e) {
                    try {
                        // Try the default activeX
                        var ax = new ActiveXObject('ShockwaveFlash.ShockwaveFlash');
                        hasFlash = true;
                        flashVersion = getFlashVersion(ax.GetVariable('$version'));
                    } catch (e) {
                        // No flash
                    }
                }
            }
        }
        swf.hasFlash = hasFlash;
        swf.flashVersion = flashVersion;
})();


/*Login / Logout */

function ilogin() {
    var id="user_navigation",
        buttonURL = "http://"+igetdsld()+".bloomberg.com",
        buttonSURL = "https://"+igetsdsld()+".bloomberg.com",
        uname = "USID",
        ca = document.cookie.split(';'),
        l = 0,
        i,
        LText,
        user,
        un1,
        un;

    for(i = 0;i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)===' ') {
            c = c.substring(1,c.length);
        }
        if (c.indexOf(uname)===0) {
            user = c.split(':');
            un1 = user[0].split('=');
            un = un1[1].split('%3A');
            l = 1;
        }
    }

    if (l == 1) {
        LText = '<li id="name_navigation_item" class="first">' + un[0] + '<li id="profile_navigation_item"><a href="' + buttonSURL +'/apps/subscriber/access?action=profile&previewaction=preview">Profile</a></li><li id="portfolio_tracker_navigation_item"><a href="/apps/subscriber/webport">Portfolios</a></li><li id="logout_navigation_item"><a onClick="ilogout();" href="#">Log out</a></li>';
    } else {
        LText = '<li id="login_navigation_item" class="first"><a href="#" onclick="ilredirect(); return false;">Log in</a></li>';

    }

    $("#user_navigation").html(LText);
}

function ilredirect() {

    var buttonSURL="https://"+igetsdsld()+".bloomberg.com",
        today = new Date(),
        domain=".bloomberg.com",
        p = "/",
        expires = 1;

    today.setTime( today.getTime() );
    
    if (expires){
        expires = expires * 1000 * 60 * 60;
    }
    var expires_date = new Date( today.getTime() + (expires) );
    document.cookie = "BTOG=" + window.location.href + "|" +
            ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
            ( ( p ) ? ";path=" + p : "" ) +
            ( ( domain ) ? ";domain=" + domain : "" );
    window.location = buttonSURL+"/log-in/index.html";
}

function iredirect() {
    window.location="http://"+igetdsld()+".bloomberg.com";
}

function ilogout() {
    var uname = "USID",
        ca = document.cookie.split(';');

    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while(c.charAt(0) === ' ') {
            c = c.substring(1,c.length);
        }
        if(c.indexOf(uname)===0) {
            var ex = c + "; expires=Sun, 4 Jan 1970 12:00:00 UTC; path=/;domain=.bloomberg.com ";
            document.cookie = ex;
        }
    }
    iredirect();
}

function igetdsld(){
    return location.hostname.match('wbetest1')?'wbetest1':'preview';
}

function igetsdsld(){
    return location.hostname.match('wbetest1')?'wbetest1':'software';
}

///* FB and Twitter clicks tracking */
//
function recordOutboundLink(link, category, action) {
  try {
    var ga_account= BLOOMBERG.global_var.gaTrackAcct;
    var pageTracker=_gat._getTracker(ga_account);
    pageTracker._trackEvent(category, action);
    setTimeout('document.location = "' + link.href + '"', 500)
  }catch(err){}
}

//Event Tracking

(function(){

   var bbg =  BLOOMBERG,
       tracker = bbg.namespace("tracker");

    tracker.EVENTTRACK = (function(){
        var self;
        function getActionFromEvent(e){
            if (e.which == 1) {
                return "left click";
            } else if (e.which == 2) {
                return "middle click";
            } else if (e.which == 3) {
                return "right click";
            } else
            return "click";
        }

        function trackEvent(category, action, opt_label, opt_value, track_in_comscore) {
            try {
                // track_in_comscore is true by default
                if (typeof(track_in_comscore) == 'undefined' || track_in_comscore){
                    try{ BLOOMBERG.comscore.internalLinkTrack(category, action, "text"); }catch(e){}
                }
                _gaq.push(['_setAccount', BLOOMBERG.global_var.gaTrackAcct]);
                _gaq.push(['_trackEvent', category, action, opt_label, opt_value]);
                if (category == "Outbound"){
                    setTimeout(function(){}, 500);
                }
            } catch(err){}
            return true;
        }
        function recordOutBound(event, category, opt_label, opt_value){
                var e = (event instanceof jQuery.Event) ? event : $.event.fix(event),
                    action = getActionFromEvent(e);
                trackEvent(category, action, opt_label, opt_value);
            }
        //Internal links are only for related items now, and they send them to
        function initInternal() {
            $("#related_stories a.story_link").live("click",function(e){
                try {
                    var suid = $(e.target).attr("suid");
                    BLOOMBERG.tracker.EVENTTRACK.record("more_stories", "click-bk" + getcombo_ga(), e.originalTarget.href  );

                    if( suid != undefined && suid != "" ) {
                         var url = "/apps/_t/b/" + related_items + "/s/" + groupid  + "/d/" + suid;
                          $.ajax({ url: url });
                    }
                    setTimeout('document.location = "' + e.originalTarget.href + '"', 150);
                    e.preventDefault();
                    return false;
                    } catch(err){}
                return true;
            });
        }
        function initExternal() {
            $("a[rel*=external]").live("mousedown", function(e){
                var self = $(this),
                    category= "Outbound",
                    att_id = self.attr("id"),
                    separator = (att_id == "") ? "" :  " - ",
                    label = att_id + separator + self.attr("href");
                recordOutBound(e, category, label);
            });
        }

      function bindPrimaryContentTracking()
      {
        bindPrimaryColumnTracking_v2();

        // track tetris box and secondary column in home page
        trackGroupsOfItems(group_of_items_tracking_list);
        trackSecondaryColumnItems(secondary_column_items_tracking_list, true);
      }
      function bindQuickViewContentTracking(){
        bindQuickViewNavTracking();
      }
      function bindMarketsHomeContentTracking(){
          $('#market_data_module h2').click(function(){
              BLOOMBERG.tracker.EVENTTRACK.record('Module Link Tracking', "world_markets_tabs", $(this).text()+' Tab');
          });
          trackGroupsOfItems("#indexes_data_table, #futures_data_table, #currencies_data_table, #bonds_data_table", true);
          $('#market_news').bindModuleLinkTracking('market_news_module');
          $('.markets_v2 .standard_mini_data_module').bindModuleLinkTracking('market_home_fon data_module');
          $("#accordion_news_module").bindModuleLinkTracking('market_home_accordion_news');
      }
      function bindQuotePageContentTracking(){
        $('.quote_navigation').bindModuleLinkTracking('quotepage_navbar');
          $('#quote_main_panel .quote_content_main').bindModuleLinkTracking('quotepage_main_panel');
          $('#quote_main_panel .quote_content_secondary').bindModuleLinkTracking('quotepage_secondary_panel');
      }
      function bindPrimaryColumnTracking_v2()
      {
        $('#customized_breaking_news').bindModuleLinkTracking('customized_breaking_news');
        $('#breaking_news').bindModuleLinkTracking('breaking_news');
        $('#breaking_news_combo').bindModuleLinkTracking('breaking_news_combo');

        $('#top_headline').bindModuleLinkTracking('top_news');
        $('#more_top :not(".news")').bindModuleLinkTracking('more_top_news_links');
        $('#more_top .news').bindModuleLinkTracking('more_top_news');

        $('#hot_dog_featured_news').bindModuleLinkTracking('hot_dog_featured_news');

        $('#trending').bindModuleLinkTracking('highlights');

        $('#hot_dog_social').bindModuleLinkTracking('hot_dog_social');

        $('#featured_videos').bindModuleLinkTracking('featured_videos');
        $('#they_said_it').bindModuleLinkTracking('custom_promo');
        $('#custom_promo_exclusive').bindModuleLinkTracking('custom_promo_exclusive');

      }
      function bindQuickViewNavTracking()
      {
        $('#quick_view_menu').bindModuleLinkTracking('quick_view_menu');

      }

        function initCustomHomepageTracking(){
            $(document).ready(function(){
                bindPrimaryContentTracking();
            });
        }
        function initQuickViewTracking(){
            $(document).ready(function(){
                bindQuickViewContentTracking();
            });
        }
        function initMarketsHomeV2Tracking(){
            $(document).ready(function(){
                bindMarketsHomeContentTracking();
            });
        }
        function initQuotePageTracking(){
            $(document).ready(function(){
                bindQuotePageContentTracking();
            });
        }
        function initNavigationTracking(){
            $(document).ready(function(){
                trackGroupsOfItems(navigation_tracking_list, true); //global nav and footer
            })
        }

        function initFlavorpillModuleTracking(){
            $(document).ready(function(){
                var fp_mod = $('#flavorpill_stories');
                if(fp_mod.length > 0){
                    fp_mod.bindModuleLinkTracking('flavorpill_stories'); //module tracking of links
                    BLOOMBERG.tracker.EVENTTRACK.record('Module Link Tracking', "flavorpill_stories_load", window.location.href); //track that module shows up
                }
            })
        }
        function initLiveTVRegionTracking(){
            $(document).ready(function(){
                var live_tv_regions = '#live_tv_us, #live_tv_europe, #live_tv_asia';
                $(live_tv_regions).each(function(){
                    $(this).mousedown(function(){
                        BLOOMBERG.tracker.EVENTTRACK.record('Live TV Link Tracking', 'live_tv_load', $(this).html());
                    });
                });
            });
        }
        function initBViewTracking(){
            $(document).ready(function(){
                var columnist_group_selector = ".view #columnist_group ul";
                // track author name click
                $(columnist_group_selector).each(function(out_index, e){
                    $(this).find(".columnist a").each(function(index, e){
                        $(this).mousedown(function(){
                            var padded_index = BLOOMBERG.num.pad(index,2);
                            var module = 'columnists_p' + out_index + '_';
                            var author_name = $(this).find('p').text();
                            BLOOMBERG.tracker.EVENTTRACK.record('Module Link Tracking', module + padded_index, author_name);
                        });
                    });
                });
                // track author article
                // TODO: to be updated after Clairine finishes her update to this module
                var columnist_article_group_selector = ".view #columnist_latest_posts ul";
                $(columnist_article_group_selector).each(function(index, e){
                    // the ul should have <author_name> id
                    $(this).find('li:not(:first)').bindModuleLinkTracking($(this).attr('id'));
                });
                // columnists pagination tracking
                $(".view .columnist_pagination").bindModuleLinkTracking('columnist_pagination');
                // tracking for social band
                $(".view .social_band").bindModuleLinkTracking('social_band');
                // tracking pagination
                $(".view_tab #news_pagination_top").bindModuleLinkTracking('pagination_top');
                $(".view_tab #news_pagination_bottom").bindModuleLinkTracking('pagination_bottom');
            });
        }
        function trackGroupsOfItems(to_track, trackHiddenLinks){
            $(to_track).each(function(){
                    var section_id = $(this).attr('id');
                    $(this).bindModuleLinkTracking(section_id, trackHiddenLinks);
            });
        }
        function trackSecondaryColumnItems(to_track, trackHiddenLinks){
            $(to_track).each(function(){
                    var section_id = $(this).attr('id');
                    $(this).bindModuleLinkTracking(section_id, trackHiddenLinks);
            });
        }
        function trackOmnitureEvent(event_name){
            // do nothing
        }

        function trackOmnitureExitEvent(event_name, object) {
            // do nothing
        }

        self = {
            init: function (){
                initInternal();//[MC]
                initExternal();
                initCustomHomepageTracking();
                initNavigationTracking();
                initFlavorpillModuleTracking();
                initLiveTVRegionTracking();
                initBViewTracking();
                initQuickViewTracking();
                initMarketsHomeV2Tracking();
                initQuotePageTracking();
            },
            // you should explicitly pass track_in_comscore to false if this event tracking is called before window.load
            // because comscore is using end of session cookie to save tracking info and send this tracking info in window.onload event
            // if you modify the event cookie before onload, it'll mess up comscore event tracking.
            record: function (category, action, opt_label, opt_value, track_in_comscore){
                trackEvent(category, action, opt_label, opt_value, track_in_comscore);
            },
            bindPrimaryContentTracking: function(){
                bindPrimaryContentTracking()
            },
            trackOmnitureEvent: function(event_name){
                trackOmnitureEvent(event_name);
            },
            trackOmnitureExitEvent: function(event_name, object) {
                trackOmnitureExitEvent(event_name, object);
          }
        };

        return self;
    })();

  var navigation_tracking_list = "",
      group_of_items_tracking_list = "",
      secondary_column_items_tracking_list = "";

    navigation_tracking_list = '#nav_home, #nav_quick, .nav_menu_item_with_dropdown, #footer_more, #footer_company, #copyright_statement, #utility_navigation';
    group_of_items_tracking_list = '#teaser_topic_opinion, #teaser_topic_election_2012, #teaser_topic_politics, #teaser_topic_personal_finance, #teaser_topic_sports, #teaser_topic_businessweek_com, #teaser_topic_bloomberg_markets, #teaser_topic_view, #teaser_topic_leaders, #teaser_topic_entrepreneurs, #teaser_topic_muse_arts_and_culture, #teaser_topic_health_care, #teaser_topic_technology, #teaser_topic_economy, #teaser_topic_science';
    secondary_column_items_tracking_list = '.home #market_snapshot_deluxe, .home #on_air, .home #most_popular_stories, .home #magazines, .home #more_top_news_container';

  tracker.EVENTTRACK.init();

})();

(function(){
    var search_assist = BLOOMBERG.namespace("tracker.SearchAssist");
    search_assist.trackEvent = function(action, label){
        BLOOMBERG.tracker.EVENTTRACK.record('Search Assist Tracking', action, label, '', false);
//        debug("action:" + action);
//        debug("label:" + label);
    };
    function bindEvents(list, action){
        list.each(function(index, e){
            var first_a = $(this).find('a:first');
            var target_url = first_a.size() > 0 ? first_a[0].href : '';
            $(this).mousedown(function(){
                var padded_index = BLOOMBERG.num.pad(index,2);
                search_assist.trackEvent(action + padded_index, target_url);
            })
        });
    }
    search_assist.registerRowEvent = function(table){
        bindEvents($(table).find('tr.symac_symbols'), 'symbols');
        bindEvents($(table).find('tr.symac_topics'), 'topics');
        bindEvents($(table).find('tr.symac_news'), 'news');
    };
    search_assist.triggerRowEvent = function(dom_ele){
        $(dom_ele).trigger('mousedown');
    };
//    function debug(msg){
//        console.log(msg);
//    }
})();

/* for Market summary chart */
(function(){
    chart_data_ns = BLOOMBERG.namespace("market_summary");
    function trim_string(str){
        return str.replace(/^\s+|\s+$/g, '');
    }
    function swap_chart(ticker_symbol, ticker_name){
        $("#market_summary_chart").attr("src",MARKET_SUMMARY_CHART_URL+ticker_symbol+".png?" + CHART_TIME_STAMP);
        $("#market_summary_chart_link").attr("href",QUOTE_URL+ticker_symbol+':IND');
        $("#marekt_summary_chart_title").html(ticker_name.toUpperCase());
    }
    chart_data_ns.set_default_chart = function(){
        var cur_container = $(".filtered_index.us #market_snap_us, .filtered_index.europe #market_snap_europe, .filtered_index.asia #market_snap_asia");
        var ticker_name = trim_string(cur_container.find(".bsym_ticker a").html());
        var ticker_symbol = trim_string(cur_container.find(".ticker_symbol").val());
        swap_chart(ticker_symbol,ticker_name);
    };
    $("tr.market_summary_tr").live("mouseover",function(){
        $(this).attr("id","chart_mouseover_tmp_id");
        var ticker_name = trim_string($(this).find(".bsym_ticker a").html());
        var ticker_symbol = trim_string($(this).find(".ticker_symbol").val());
        swap_chart(ticker_symbol,ticker_name);
    });
    $("tr.market_summary_tr").live("mouseout",function(){
        $(this).removeAttr("id");
    });
})();

(function() {
    var cookie_expire_date = new Date();
    cookie_expire_date.setFullYear(cookie_expire_date.getFullYear() + 1);
    var mobile_ns = BLOOMBERG.namespace("mobile"),
            mobile_url = "http://mobile.bloomberg.com/",
            cookie_key = "bbmobile",
            new_cookie_key = "bbmobv2",
            cookie_value = "1",
            cookieDomain = "bloomberg.com",
            expireDate = cookie_expire_date.toGMTString(),
            test_browser_info = null,
            test_referrer = null;
    //#######################DEBUG########################
    //test_browser_info = "770s whatever";
    //test_referrer = "mobile.bloomberg.com";
    //#######################END########################

    mobile_ns.is_bb_mobile_set = function() {
        return BLOOMBERG.util.Cookie.get(cookie_key) == '1' || BLOOMBERG.util.Cookie.get(new_cookie_key) == '1';
    };

    mobile_ns.unset_bb_mobile = function() {
        BLOOMBERG.util.Cookie.set(cookie_key, "", -1, "/", cookieDomain);
        BLOOMBERG.util.Cookie.set(new_cookie_key, "", -1, "/", cookieDomain);
    };

    mobile_ns.is_mobile = function() {
//        var browser_info = test_browser_info || navigator.userAgent||navigator.vendor||window.opera;
        //this feature is turned off, to see original regular expression (not BOSS approved), check history
        return false;
    };

    mobile_ns.redirect_to_mobile = function() {
        var prefer_full_site = mobile_ns.is_bb_mobile_set();
        var is_mobile = mobile_ns.is_mobile();
        if (is_mobile && !prefer_full_site) {
            window.location = mobile_url;
        }
    };

    // try to set cookie for mobile device
    mobile_ns.drop_prefer_cookie = function() {
        var is_mobile = mobile_ns.is_mobile();
        //use from=mobile to determine if current visit is from mobile.bloomberg.com
        var is_query_from_mobile_site = /(\?|&)(from=mobile)/ig.test(window.location.search);
        var url_referrer = test_referrer || document.referrer;
        var is_linked_from_mobile_site = /^((http|https):\/\/)?mobile.bloomberg.com/i.test(url_referrer);
        if (is_mobile && (is_query_from_mobile_site || is_linked_from_mobile_site)) {
            BLOOMBERG.util.Cookie.set(cookie_key, cookie_value, expireDate, "/", cookieDomain);
            BLOOMBERG.util.Cookie.set(new_cookie_key, cookie_value, expireDate, "/", cookieDomain);
        }
    };

    // try to set cookie and redirect to mobile site
    mobile_ns.drop_cookie_or_redirect = function() {
        mobile_ns.drop_prefer_cookie();
        mobile_ns.redirect_to_mobile();
    };

    mobile_ns.register_mobile_link = function() {
        $("#link_to_mobile_bb_com").live("click", function() {
            //erase cookie
            mobile_ns.unset_bb_mobile();
            window.location = this.href;
            return false;
        });
    };

    // Extend expire date of the cookie to 1 year from now, everytime the user visits the page (making it a non-expiring cookie)
    mobile_ns.extend_cookie_expire_date = function() {
        var value = BLOOMBERG.util.Cookie.get(cookie_key);
        if (value)
            BLOOMBERG.util.Cookie.set(cookie_key, value, expireDate, "/", cookieDomain);
        var new_value = BLOOMBERG.util.Cookie.get(new_cookie_key);
        if (new_value)
            BLOOMBERG.util.Cookie.set(new_cookie_key, new_value, expireDate, "/", cookieDomain);
    };

//  TODO: Modify the javascript to run on document ready to make efficient use of cache
    mobile_ns.show_mobile_redirect_link = function() {
        if (mobile_ns.is_bb_mobile_set()) {
            var $link = $('<a id="link_to_mobile_bb_com" href="http://mobile.bloomberg.com/">Make the mobile site my default</a>');
            $('.mobile-redirect').append($link);
        }
    };
})();

(function(){
    var querystring = BLOOMBERG.namespace("querystring");
    querystring.param_provided = function(param_string){
        return new RegExp("(\\?|&)(" + param_string + ")(=|&)", "ig").test(window.location.search);
    };
})();
/*!
 * Date Format 1.2.3
 * (c) 2007-2009 Steven Levithan <stevenlevithan.com>
 * MIT license
 *
 * Includes enhancements by Scott Trenda <scott.trenda.net>
 * and Kris Kowal <cixar.com/~kris.kowal/>
 *
 * Accepts a date, a mask, or a date and a mask.
 * Returns a formatted version of the given date.
 * The date defaults to the current date/time.
 * The mask defaults to dateFormat.masks.default.
 */

var dateFormat = function () {
	var	token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
        daylightsaving = /([PMCEA])([SDP])(T)/i,
		timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function (val, len) {
			val = String(val);
			len = len || 2;
			while (val.length < len) val = "0" + val;
			return val;
		};

	// Regexes and supporting functions are cached through closure
	return function (date, mask, utc) {
		var dF = dateFormat;

		// You can't provide utc if you skip other args (use the "UTC:" mask prefix)
		if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
			mask = date;
			date = undefined;
		}

		// Passing date through Date applies Date.parse, if necessary
		date = date ? new Date(date) : new Date;
		if (isNaN(date)) throw SyntaxError("invalid date");

		mask = String(dF.masks[mask] || mask || dF.masks["default"]);

		// Allow setting the utc argument via the mask
		if (mask.slice(0, 4) == "UTC:") {
			mask = mask.slice(4);
			utc = true;
		}

		var	_ = utc ? "getUTC" : "get",
			d = date[_ + "Date"](),
			D = date[_ + "Day"](),
			m = date[_ + "Month"](),
			y = date[_ + "FullYear"](),
			H = date[_ + "Hours"](),
			M = date[_ + "Minutes"](),
			s = date[_ + "Seconds"](),
			L = date[_ + "Milliseconds"](),
			o = utc ? 0 : date.getTimezoneOffset(),
			flags = {
				d:    d,
				dd:   pad(d),
				ddd:  dF.i18n.dayNames[D],
				dddd: dF.i18n.dayNames[D + 7],
				m:    m + 1,
				mm:   pad(m + 1),
				mmm:  dF.i18n.monthNames[m],
				mmmm: dF.i18n.monthNames[m + 12],
				yy:   String(y).slice(2),
				yyyy: y,
				h:    H % 12 || 12,
				hh:   pad(H % 12 || 12),
				H:    H,
				HH:   pad(H),
				M:    M,
				MM:   pad(M),
				s:    s,
				ss:   pad(s),
				l:    pad(L, 3),
				L:    pad(L > 99 ? Math.round(L / 10) : L),
				t:    H < 12 ? "a"  : "p",
				tt:   H < 12 ? "am" : "pm",
				T:    H < 12 ? "A"  : "P",
				TT:   H < 12 ? "AM" : "PM",
				Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, "").replace(daylightsaving,"$1$3").replace('UTC','GMT'),
				o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
				S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
			};

		return mask.replace(token, function ($0) {
			return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
		});
	};
}();

// Some common format strings
dateFormat.masks = {
	"default":      "ddd mmm dd yyyy HH:MM:ss",
	shortDate:      "m/d/yy",
	mediumDate:     "mmm d, yyyy",
	longDate:       "mmmm d, yyyy",
	fullDate:       "dddd, mmmm d, yyyy",
	shortTime:      "h:MM TT",
	mediumTime:     "h:MM:ss TT",
	longTime:       "h:MM:ss TT Z",
	isoDate:        "yyyy-mm-dd",
	isoTime:        "HH:MM:ss",
	isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
	isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
	dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
	],
	monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	]
};

// For convenience...
Date.prototype.format = function (mask, utc) {
	return dateFormat(this, mask, utc);
};

/* for pagination Begin */
(function(){
    var pagination_ns = BLOOMBERG.namespace("pagination");
    function generate_group_links_string(group_index, group_size, total_pages, url_pattern){
        var start_page_index = group_index * group_size + 1;
        var end_page_index = start_page_index + group_size - 1;
        if (end_page_index > total_pages)
            end_page_index = total_pages;
        var cur_group_name = start_page_index + '-' + end_page_index;
        var href;
        if (start_page_index == 1){
            href = url_pattern;
        }else{
            href = url_pattern + start_page_index + '/';
        }
        return ' <a href="' + href + '">' + cur_group_name + '</a>';
    }
    pagination_ns.collapse_links = function(container){
        var group_size = 10;
        var page_elements = container.find("*").not(".prev_page, .next_page");
        var total_pages = page_elements.size();
        if (total_pages <= group_size)
            return; // return if # of pages is less than group_size
        var current_page = parseInt(container.find(".current").text());
        var group_left = Math.floor((current_page-1)/group_size);
        var group_right = group_left + 2;
        var url = container.find("a:not('.prev_page, .next_page'):first").attr('href');
        var url_pattern = url.replace(/\d+\/?$/, '');  
        // hide all individual links in group_left and group_right
        page_elements.each(function(index, element){
            var tmp_page = index + 1;
            if (tmp_page <= group_left * group_size || tmp_page > (group_right - 1) * group_size){
                $(this).hide();
            }
        });
        // dynamically create & insert grouped links
        var prefix = '';
        for(var i = 0; i < group_left; i++){
            prefix += generate_group_links_string(i, group_size, total_pages, url_pattern);
        }
        container.find(".prev_page").after(prefix);
        var suffix = '';
        for(var i = group_right - 1; i < Math.ceil((total_pages)/group_size); i++){
            suffix += generate_group_links_string(i, group_size, total_pages, url_pattern);
        }
        container.find(".next_page").before(suffix);
    };
})();
$.fn.paginateCollapse = function(){
    this.each(function(){
        BLOOMBERG.pagination.collapse_links($(this));
    });
};
/* for pagination End */
//for the-mentor
(function () {
    var bbg = BLOOMBERG,
            mentor = bbg.namespace("mentor");

    mentor.switch_mentor_video = function(divname, fvid_id) {
        var videoPlayer = new SWFObject( BLOOMBERG.url.CombinePath(BLOOMBERG.global_var.image_domain, "/flash/BloombergMediaPlayer.swf"), "bbmp", "100%", "100%", "10", "#000000");
        videoPlayer.addParam('allowFullScreen', 'true');
        videoPlayer.addParam("allowscriptaccess","always");
        videoPlayer.addParam('wmode', 'opaque');

        videoPlayer.addVariable('autoplay', 'true');
        videoPlayer.addVariable('file_url', bbg.video.generate_url_from_fvid(fvid_id));

        if(bbg._autoplay){
            videoPlayer.addVariable('autoplay', 'true');
        }
        if(bbg._video_url){
            videoPlayer.addVariable('file_url', bbg._video_url);
        }
        else if (bbg._asset_id){
            videoPlayer.addVariable('asset_ids', bbg._asset_id);
        }
        else if (fvid_id) {
            videoPlayer.addVariable('file_url', bbg.video.generate_url_from_fvid(fvid_id));
        }

        //ads
        if(bbg._site){
            videoPlayer.addVariable('site', bbg._site);
        }
        if(bbg._zone){
            videoPlayer.addVariable('zone', bbg._zone);
        }

        videoPlayer.addVariable('EnableLogging','true');
        videoPlayer.addVariable('LoggingDomain','www.bloomberg.com');
        videoPlayer.addVariable('sz', '1x1');
        videoPlayer.addVariable('tile', '1');

        videoPlayer.addVariable('title', bbg._title);
        videoPlayer.addVariable('description', bbg._description);
        videoPlayer.addVariable('GoogleUA', BLOOMBERG.global_var.gaTrackAcct);
        videoPlayer.write(divname);

    };

})();

(function(){
  var referrer_obj = BLOOMBERG.namespace("referrer");

  referrer_obj.extract_name = function(referrer, prefix)
  {
    if(referrer == null)
      return "";

    var name = "";

    if(referrer.starts_with(prefix))
    {
      name = referrer.replace(prefix, "");
      if(name.ends_with("/"))
      {
        name = name.substring(0, name.length-1);
      }
      if (name.indexOf('/') != -1){
          name = name.substring(0, name.indexOf('/'));
      }
    }

    return name;
  };

  var sponsor_referrer_mapping = [
      {'reg':/^https?:\/\/([^.]*\.)*?bloomberg.com(:\d+)?\/q$/, 'sponsor':'queue'},
      {'reg':/^https?:\/\/([^.]*\.)*?bloomberg.com(:\d+)?\/presidential-election-2012/, 'sponsor':'peterson'}
  ];
  referrer_obj.sponsor_referrer = function()
  {
    if (typeof(document.referrer) != 'undefined' && document.referrer != "") {
      for (var i=0;i<sponsor_referrer_mapping.length;i++){
          if (document.referrer.match(sponsor_referrer_mapping[i].reg)) {
              return sponsor_referrer_mapping[i].sponsor;
          }
      }
    }
    return null;
  };

  referrer_obj.topic_referrer = function()
  {
    var topic = referrer_obj.extract_name(document.URL, BLOOMBERG.global_var.topic_links_prefix);
    var shows_prefix = BLOOMBERG.global_var.inSite + "/tv/shows/";
    if(topic != null && topic != "")
      return topic;

      // #mingle 4789186 - adding tv show pages as topic page referrers, consider moving out to separate param
    return referrer_obj.extract_name(document.referrer, BLOOMBERG.global_var.topic_links_prefix) || referrer_obj.extract_name(document.referrer, shows_prefix);
  };
})();

(function(){
  var bbp2_obj = BLOOMBERG.namespace("bbp2");

  bbp2_obj.is_phase_2 = function()
  {
    var ret_val;

    switch(BLOOMBERG.util.Cookie.get(BLOOMBERG.global_var.phase_2_cookie_key))
    {
      case "0":
      {
        ret_val = 0;
        break;
      }
      case "1":
      {
        ret_val = 1;
        break;
      }
      default:
      {
        ret_val = -1;
        break;
      }
    }

    return ret_val;
  };
})();

(function(){
    var switch_ns = BLOOMBERG.namespace("bbswitch");
    var in_obj = {};
    var qunit_mode = typeof(QUnit) != "undefined";
    if (qunit_mode)
        switch_ns.internal_obj = in_obj;
    var cookie_ns = BLOOMBERG.util.Cookie;
    // !! only add new key to the end of the following names, don't remove keys
    in_obj.cookie_domain = "Bloomberg.com";
    var persistent_switch_cookie_key = 'bb_scp';   // persistent cookie name
    var end_of_session_switch_cookie_key = 'bb_sct';  // end of session key name
    var number_of_keys_in_each_group = 30;
    // convert switch names from array to hash for fast search
    var persistent_switch_names_hash = {};
    var end_of_session_switch_names_hash = {};
    //**********private functions****************
    function set_cookie(key, val, end_of_session){
        if (end_of_session){
            cookie_ns.setEndOfSession(key, val, "/", in_obj.cookie_domain);
        }else{
            var cookie_expire_date = new Date();
            cookie_expire_date.setFullYear(cookie_expire_date.getFullYear() + 1);
            cookie_ns.set(key, val, cookie_expire_date, "/", in_obj.cookie_domain);
        }
    }
    function get_cookie_group_index(key_index){
        return Math.floor(key_index / number_of_keys_in_each_group);
    }
    function get_cookie_int_value(group_cookie_key, refresh_expire_date){
        var current_cookie_value = cookie_ns.get(group_cookie_key);
        if (refresh_expire_date && current_cookie_value.length > 0)
            set_cookie(group_cookie_key, current_cookie_value);
        if (current_cookie_value.length == 0)
            current_cookie_value = "0";
        return parseInt(current_cookie_value);
    }
    function set_bit_flag_true(cookie_value_int, key_index){
        var value_to_merge = Math.pow(2, key_index);
        return (cookie_value_int | value_to_merge);
    }
    function set_bit_flag_false(cookie_value_int, key_index){
        var value_to_merge = Math.pow(2, number_of_keys_in_each_group) - 1 - Math.pow(2, key_index);
        return (cookie_value_int & value_to_merge);
    }
    function set_value(key, value, end_of_session){
        var group_key_prefix = end_of_session ? end_of_session_switch_cookie_key : persistent_switch_cookie_key;
        var switch_hash = end_of_session ? end_of_session_switch_names_hash : persistent_switch_names_hash;

        var key_index = switch_hash[key];
        if (typeof(key_index) == 'undefined'){
            return;     // does nothing if this key doesn't exist
        }
        var group_index = get_cookie_group_index(key_index);
        key_index = key_index % number_of_keys_in_each_group;

        var cookie_key = group_key_prefix + group_index;
        var cookie_value_int = get_cookie_int_value(cookie_key);
        if (value){
            cookie_value_int = set_bit_flag_true(cookie_value_int, key_index);
        }else{
            cookie_value_int = set_bit_flag_false(cookie_value_int, key_index);
        }
        set_cookie(cookie_key, cookie_value_int, end_of_session);
    }
    // if the bit is "1", return true, else false
    function get_bit_flag(cookie_value_int, key_index){
        var value_to_merge = Math.pow(2, key_index);
        return (cookie_value_int & value_to_merge) > 0;
    }
    function get_value(key, end_of_session){
        var group_key_prefix = end_of_session ? end_of_session_switch_cookie_key : persistent_switch_cookie_key;
        var switch_hash = end_of_session ? end_of_session_switch_names_hash : persistent_switch_names_hash;

        var key_index = switch_hash[key];
        if (typeof(key_index) == 'undefined')
            return false;     // return empty if this key doesn't exist
        var group_index = get_cookie_group_index(key_index);
        key_index = key_index % number_of_keys_in_each_group;
        var cookie_key = group_key_prefix + group_index;
        var cookie_value_int = get_cookie_int_value(cookie_key, !end_of_session);
        var ret = get_bit_flag(cookie_value_int, key_index);
        return ret;
    }
    //****************public functions********************
    switch_ns.initialize = function(options){
        var settings = {'p_switch_names':[], 't_switch_names':[]};
        $.extend(settings, options);
        for(var i = 0; i < settings.p_switch_names.length; i++){
            var key = settings.p_switch_names[i];
            persistent_switch_names_hash[key] = i;
        }
        for(var i = 0; i < settings.t_switch_names.length; i++){
            var key = settings.t_switch_names[i];
            end_of_session_switch_names_hash[key] = i;
        }
    };
    switch_ns.set = function(key, value){
        var end_of_session = typeof(persistent_switch_names_hash[key]) == 'undefined';
        set_value(key, value, end_of_session);
    };
    switch_ns.get = function(key){
        var end_of_session = typeof(persistent_switch_names_hash[key]) == 'undefined';
        return get_value(key, end_of_session);
    };
    // initialize data
    if (BLOOMBERG.global_var && BLOOMBERG.global_var.switch_config)
        switch_ns.initialize(BLOOMBERG.global_var.switch_config);
})();

(function(){
    var lead_video = BLOOMBERG.namespace("lead_video");
    lead_video.is_iphone_ipad_user = function(){
        var ua = navigator.userAgent||navigator.vendor||window.opera;
        return /\bipad\b/i.test(ua) || /\biphone\b/i.test(ua);
    };
    lead_video.vil_receiveOoyalaEvent = function(playerId, eventName, eventParams){
        if (playerId !== 'vil_blp_ooyala_player')
            return;
        switch(eventName){
            case "playerEmbedded":
                BLOOMBERG.global_var.vid_playing = true;
                break
            case "playComplete":
                BLOOMBERG.global_var.vid_playing = false;
                break;
        }
    };
    lead_video.initialize = function(event_label){
        $("#lead_video_play").mousedown(function(){
            var video_url = $("#vil_video_url").attr('href');
            BLOOMBERG.tracker.EVENTTRACK.record('Module Link Tracking', event_label, video_url);
        });
        $("#lead_video_play").click(function(){
            $("#lead_video_container").show();
            $("#lead_video_play").hide();
        });
        // hide LIVE STREAM player for iPad & iPhone users (Mingle# 4788994)
        if (lead_video.is_iphone_ipad_user()){
            if ($("#lead_video_container.liv_player").length > 0){
                if ($("#lead_video_play").length > 0)
                    $("#lead_video_play").hide();
                if ($("#lead_video").length > 0)
                    $("#lead_video").hide();
                if ($(".with_lead_video").length > 0)
                    $(".with_lead_video").removeClass("with_lead_video");
            }
        }
    };
})();
//Noir transition test
// moved from ab.js to here.
(function(){
    // *********** Private variables ***************
    var qunit_mode = typeof(QUnit) != "undefined";
    var noir_trans = BLOOMBERG.namespace('test.noir_trans');
    // this variable is used to preload msg content
    var OPT_COOKIE_NAME = "opt",
            NO_OPT = 'no-opt',
            noir_bucket_cookies = ['opt-out', 'C1'];
    var cookie_ns = BLOOMBERG.util.Cookie;
    var cookieDomain = "bloomberg.com",
            expireDate = Date.nextYear().toGMTString();
    if (qunit_mode) // set cookie domain to empty if it's in QUnit testing mode
        cookieDomain = '';
    // user's opt cookie value will never be empty, because it'll be set in BLOOMBERG.test.AB.init()
    var opt_in_out_config = {
        'C1':'C1S',
        'B1':'B1S',
        'W1':'W1S',
        'C1S':'C1',
        'B1S':'B1',
        'W1S':'W1',
        'opt-in':'opt-out',
        'opt-out':'opt-in',
        // if value is 'no-opt', it's the same as opt-in, because if the user is on black site,
        // it'll be set to opt-out by the code in BLOOMBERG.test.AB.init()
        'no-opt':'opt-out',
        '':'opt-out'
    };
    // ************** private functions ****************
    function get_opt_status(){
        return cookie_ns.get(OPT_COOKIE_NAME);
    }
    function refresh_cookie_expire_date(){
        // default/refresh opt cookie expire date
        var opt_value = cookie_ns.get(OPT_COOKIE_NAME);
        if (opt_value === ''){
            opt_value = NO_OPT;
        }
        cookie_ns.set(OPT_COOKIE_NAME, opt_value, expireDate, "/", cookieDomain);
    }
    // ************ Public functions *************
    noir_trans.get_opt_status = get_opt_status;
    noir_trans.in_black_cds_bucket = function(){
        return get_opt_status() == 'B1';
    };
    noir_trans.in_white_cds_bucket = function(){
        return get_opt_status() == 'W1';
    };
    noir_trans.in_noir_bucket = function(){
        var opt_value = get_opt_status();
        return noir_bucket_cookies.contains(opt_value);
    };
    noir_trans.is_in_cds_bucket = function(){
        var opt_value = get_opt_status();
        return (['B1', 'W1']).contains(opt_value);
    };
    noir_trans.is_in_popup_bucket = function(){
        var opt_value = get_opt_status();
        return (['B1', 'W1', 'B1S', 'W1S']).contains(opt_value);
    };
    noir_trans.is_in_noir_trans_bucket = function(){
        var opt_value = get_opt_status();
        return (['B1', 'W1', 'C1', 'B1S', 'W1S', 'C1S']).contains(opt_value);
    };
    noir_trans.in_std_white_from_cds=function(){
        var opt_value = get_opt_status();
        return (['B1S', 'W1S']).contains(opt_value);
    };
    // set opt in/out for current user
    noir_trans.opt_in_out = function(){
        var opt_value = get_opt_status();
        var new_opt_value = opt_in_out_config[opt_value];
        if (new_opt_value)
            cookie_ns.set(OPT_COOKIE_NAME, new_opt_value, expireDate, "/", cookieDomain);
        return new_opt_value;
    };
    noir_trans.set_opt_bucket = function(opt_value){
        cookie_ns.set(OPT_COOKIE_NAME, opt_value, expireDate, "/", cookieDomain);
        window.location.href = BLOOMBERG.global_var.inSite;
    };
    refresh_cookie_expire_date();
})();

(function(){
    var noir_2_qv = BLOOMBERG.namespace('noir_2_qv'),
        noir_trans = BLOOMBERG.namespace('test.noir_trans'),
        switch_ns = BLOOMBERG.namespace("bbswitch"),
        querystring = BLOOMBERG.namespace("querystring");
    var qunit_mode = typeof(QUnit) != "undefined";
    var in_obj = {};
    if (qunit_mode){
        noir_2_qv.internal_obj = in_obj;
    }
    var nav_modified = false;
    //**************private functions*****************
    function is_on_www_homepage(){
        var white_url = (BLOOMBERG.global_var && BLOOMBERG.global_var.whiteSiteHN) || "www.bloomberg.com";
        return window.location.hostname == white_url && window.location.pathname == '/';
    }
    in_obj.redirect_user = function(){
        // redirect user to /quickview/ if he is on homepage and have like_qv = true and qv querystring is not provided
        if (is_on_www_homepage() && switch_ns.get('like_qv') && !querystring.param_provided('qv')){
            window.location.pathname = '/quickview/';
        }
    };
    //**************public functions******************
    noir_2_qv.modify_nav_link = function(){
        // don't try to modify nav again if it's already modified
        if (nav_modified)
            return;
        if (switch_ns.get('like_qv')){
            var new_url = $("#nav_home a").attr('href') + '?qv=1';
            $("#nav_home a").attr('href', new_url);
        }
        nav_modified = true;
    };
    noir_2_qv.initialize = function(){
        var set_qv_4_noir_users = false;
        if (BLOOMBERG.global_var && BLOOMBERG.global_var.disable_noir_www_redirect){
            set_qv_4_noir_users = noir_trans.in_noir_bucket();
        }
        // run this once for users in condensed buckets or ex-noir buckets(opt-out, C1), set like_qv to true
        if ((noir_trans.is_in_cds_bucket() || set_qv_4_noir_users) && !switch_ns.get('noir_2_qv')){
            switch_ns.set('noir_2_qv', true);
            switch_ns.set('like_qv', true);
        }
        // try to redirect user
        in_obj.redirect_user();
    };
    noir_2_qv.initialize();
    // to modify nav link, this function is for PB pages, the nav will be modified when document.ready
    $(function(){
        if (!qunit_mode){
            noir_2_qv.modify_nav_link();
        }
    });
})();
(function(){
    var ind_job_widget = BLOOMBERG.namespace('ind_job_widget');
    ind_job_widget.initialize = function(){
        var input_boxes = $("#ind_job_widget .ind_job_search input.search_input");

        input_boxes.each(function(){
            if ($(this).val() === ''){
                $(this).val($(this).attr('data-default'));
            }
            if ($(this).val() != $(this).attr('data-default')){
                $(this).addClass('focus_text');
            }
        });
        
        input_boxes.focus(function(){
            if ($(this).val() === $(this).attr('data-default')){
                $(this).val('');
            }
            $(this).addClass('focus_text');
        });
        input_boxes.blur(function(){
            if ($(this).val() === ''){
                $(this).val($(this).attr('data-default'));
            }
            if ($(this).val() == $(this).attr('data-default')){
                $(this).removeClass('focus_text');
            }
        });
    };
    ind_job_widget.pre_process = function(){
        var input_boxes = $("#ind_job_widget .ind_job_search input.search_input");
        input_boxes.each(function(){
            if ($(this).val() === $(this).attr('data-default')){
                $(this).val('');
            }
        });
    }
})();
(function(){
    var live_stream = BLOOMBERG.namespace('live_stream');
    var in_obj = {};
    var qunit_mode = typeof(QUnit) != "undefined";
    if (qunit_mode)
        live_stream.internal_obj = in_obj;
    var embed_code_config = {
        us: BLOOMBERG.global_var.live_stream_us || "d3MzYwMjoS4f85a0xfQrxDFebezasnkN",
        europe: BLOOMBERG.global_var.live_stream_europe || "41NDYwMjoAX-XqGCy1PYOso_K5JHYUHa",
        asia: BLOOMBERG.global_var.live_stream_asia || "A3NDYwMjrxuAk9iHbmNGbDNGV59SvMRF"
    };
    in_obj.get_default_tab_key = function(default_tab_key){
        var hash = window.location.hash.toLowerCase();
        if (hash.length > 0){
            hash = hash.substring(1);
            if (typeof(embed_code_config[hash]) === 'undefined'){
                hash = default_tab_key;
            }
        }else{
            hash = default_tab_key;
        }
        return hash;
    };
    in_obj.is_on_tv_page = function(){
        var path_name = window.location.pathname.toLowerCase();
        return path_name == '/tv/' || path_name == '/tv';
    };
    /*************public functions****************/
    live_stream.set_default_tab = function(selector){
        // don't do anything if it's not on tv page
        if (!in_obj.is_on_tv_page())
            return;
        var default_tab = in_obj.get_default_tab_key('us');
        $(selector).addClass(default_tab);
    };
    live_stream.get_embed_code = function(default_embed_code){
        // return default embed code if it's not on tv page
        if (!in_obj.is_on_tv_page())
            return default_embed_code;
        var default_tab = in_obj.get_default_tab_key('');
        if (default_tab.length > 0){
            var ret = embed_code_config[default_tab];
            if (typeof(ret) === 'undefined')
                ret = default_embed_code;
            return ret;
        }else{
            return default_embed_code;
        }
    };
})();
// for indeed tree view on jobs.bloomberg.com
(function(){
    var ind_tv_ns = BLOOMBERG.namespace('ind_tree_view');
    ind_tv_ns.initialize = function(){
        $("#ind_tree_view .ind_category").addClass('ind_collapse');
        $("#ind_tree_view h3").click(function(){
            var parent = $(this).closest('li');
            var hidden = parent.hasClass('ind_collapse');
            $("#ind_tree_view .ind_category").addClass('ind_collapse');
            if (hidden)
                parent.removeClass('ind_collapse');
            else
                parent.addClass('ind_collapse');
        });
    };
})();
// dynamically centers the text in the child_sel in the parent_sel
$.fn.centerText = function(setting){
    return this.each(function(){
        var default_setting = {'parent_sel':'a','child_sel':'p'};
        $.extend(default_setting,setting);
        var $self = $(this),
                topM = ($self.find(default_setting['parent_sel']).height() - $self.find(default_setting['child_sel']).height()) / 2;
        $self.find(default_setting['child_sel']).css('padding-top', topM + "px");
    })
};
	  //tabbed video widget
(function(){
    var tabbed_video_widget = BLOOMBERG.namespace('tabbed_video_widget');
    function generate_left_list(line_up){
        $('.tabbed_video .tabbed_content ul').html('');
        var ll = line_up.length;
        for (var i =0; i<=ll; i++){
            var playing = (i ==0) ? 'playing' : '';
            var secs = parseFloat(line_up[i].time);
            var minutes_string = Math.floor(secs / 60) + ":" + Math.ceil(secs % 60);
            var desc_date_split = line_up[i].description.split('(');
            $('.tabbed_video .tabbed_content ul').append('<li><a href="#'+line_up[i].embedCode+'" class="'+playing+'">'+line_up[i].title+'<span>('+minutes_string+') '+desc_date_split[0]+'</span></a></li>');
        }
        $('.tabbed_video .tabbed_content').removeClass('loading');
    }
    tabbed_video_widget.tabbed_video_callback = function(playerId, eventName, eventParams){
        switch(eventName)
        {
            case "apiReady":
                var line_up = document.getElementById("tabbed_ooyala_player").getLineup();
                if (line_up != null) {
                  generate_left_list(line_up);
                }

                break;
            case "embedCodeChanged":
                //currentItemEmbedCodeChanged
                break;
            case "loadComplete":
                break;
            default:
            //do nada
        }
    }
    function change_tabbed_embed_code(e){
        e.preventDefault();
        $(this).parents('ul').find('a.playing').removeClass('playing');
        $(this).addClass('playing');
        var new_embed_code = $(this).attr('href').split('#');
         //alert(new_embed_code[1]);
        document.getElementById("tabbed_ooyala_player").setQueryStringParameters({embedCode:new_embed_code[1],autoplay:1});
    }
    function change_module_tab(e){
        e.preventDefault();
        $(this).parents('ul').find('a.active').removeClass('active');
        $(this).addClass('active');
        $('.tabbed_video .tabbed_content ul').html('');
        $('.tabbed_video .tabbed_content').addClass('loading');
        var new_embed_code = $(this).attr('href').replace('#','');
       // alert(new_embed_code);
        document.getElementById("tabbed_ooyala_player").setQueryStringParameters({embedCode:new_embed_code,autoplay:0});
    }
    tabbed_video_widget.init = function(){
        $('.tabbed_video .tabbed_content ul li a').live('click',change_tabbed_embed_code);
        $('.tabbed_video ul.tabs li a').bind('click',change_module_tab);
    };

    $(document).ready(function () {
        BLOOMBERG.tabbed_video_widget.init();
    });

})();

$.fn.extend({
  tabificate: function() {
    var tab_root = $(this);

    $(this).find('.tabs a').bind('click', function(e) {
      e.preventDefault();
      tab_root.find('.tabs a').removeClass('active');
      tab_root.find('.panes>div').hide();
      $(this).addClass('active');
      tab_root.find('.panes>div').eq($(this).parent().index()).show();
    });
      
    $(this).find('.tabs a').eq(0).addClass('active');
    $(this).find('.panes>div').hide();
    $(this).find('.panes>div').eq(0).show();
      
    return this;
  } 
});

(function(){
    var election_ns = BLOOMBERG.namespace('election');
    var current_tab = "";
    function trim_string(str){
        return str.replace(/^\s+|\s+$/g, '');
    }
    function update_comment(selected_id){
        $("#comment_area").removeClass("elect_bloomberg_view elect_fact_check");
        $("#comment_area").addClass(selected_id);
        var selected_tab = $("#" + selected_id);
        var url;
        if (selected_tab.attr('data-tab-type') == 'disqus'){
            var config_item = {'sn':'bloombergelection', 'identifier':selected_tab.attr('data-tab-comment-info'), 'title':trim_string(selected_tab.text())};
            url = "/javascripts/comment.html?sn=" + config_item.sn + "&identifier=" + config_item.identifier + "&title=" + config_item.title + "&hide_cmt_box=1";
        }else if (selected_tab.attr('data-tab-type') == 'local') {
            url = "/presidential-election-2012/comments/" + selected_tab.attr('data-tab-comment-info') + "/";
        }else {
            return;
        }
        current_tab = selected_id;
        $("#elect_bloomberg_view_tab_info, #elect_fact_check_tab_info").hide();
        $("#" + selected_id + "_tab_info").show();
        $("#comment_frame iframe").attr('src', url);
        $("#comment_frame iframe").hide();
        $("#comment_frame #loading_div").show();
    }
    election_ns.initialize = function(){
        $("#comment_frame iframe").load(function(){
            $("#comment_frame iframe").show();
            $("#comment_frame #loading_div").hide();
        });
        $("#elect_bloomberg_view, #elect_fact_check").click(function(obj){
            var new_tab = $(obj.target).attr('id');
            if (current_tab === new_tab)
                return;
            update_comment(new_tab);
        });
    };
    election_ns.set_default_tab = function(){
        // set default tab
        var default_tab = $("#comment_area .tabs h2:visible:first").attr("id");
        update_comment(default_tab);
    };
    election_ns.archive_update_ui = function(data_type, live_blog_data, reality_check_data){
        (live_blog_data || "").length == 0 ? $("#elect_bloomberg_view").hide() : $("#elect_bloomberg_view").show();
        (reality_check_data || "").length == 0 ? $("#elect_fact_check").hide() : $("#elect_fact_check").show();
        $("#elect_bloomberg_view").attr('data-tab-type', data_type);
        $("#elect_bloomberg_view").attr('data-tab-comment-info', live_blog_data);
        $("#elect_fact_check").attr('data-tab-type', data_type);
        $("#elect_fact_check").attr('data-tab-comment-info', reality_check_data);
        var current_tab = $("#comment_area .tabs h2:visible:first").attr("id");
        update_comment(current_tab);
    };
    election_ns.initialize_archive = function(){
        var a_tag = $("#debate_conversation_list li.selected a");
        election_ns.archive_update_ui(a_tag.attr('data-type'), a_tag.attr('data-live-blog'), a_tag.attr('data-reality-check'))
    };
})();

// for ComScore tracking
(function(){
    var comscore_account = "3005059";
    var comscore_ns = BLOOMBERG.namespace('comscore');
    var cookie_ns = BLOOMBERG.util.Cookie;
    var escape_str = (typeof encodeURIComponent != "undefined" ? encodeURIComponent : escape);
    var unescape_str = (typeof decodeURIComponent != "undefined" ? decodeURIComponent : unescape);
    var uid_cookie_name = "bdfpc";
    var cookie_domain = "Bloomberg.com";
    var internal_link_key = "comScore";
    // private methods
    function comScore(t){var b="comScore",o=document,f=o.location,a="",e="undefined",g=2048,s,k,p,h,r="characterSet",n="defaultCharset",m=(typeof encodeURIComponent!=e?encodeURIComponent:escape);if(o.cookie.indexOf(b+"=")!=-1){p=o.cookie.split(";");for(h=0,f=p.length;h<f;h++){var q=p[h].indexOf(b+"=");if(q!=-1){a="&"+unescape(p[h].substring(q+b.length+1))}}}t=t+"&ns__t="+(new Date().getTime());t=t+"&ns_c="+(o[r]?o[r]:(o[n]?o[n]:""))+"&c8="+m(o.title)+a+"&c7="+m(f&&f.href?f.href:o.URL)+"&c9="+m(o.referrer);if(t.length>g&&t.indexOf("&")>0){s=t.substr(0,g-8).lastIndexOf("&");t=(t.substring(0,s)+"&ns_cut="+m(t.substring(s+1))).substr(0,g)}if(o.images){k=new Image();if(typeof ns_p==e){ns_p=k}k.src=t}else{o.write(["<","p","><",'img src="',t,'" height="1" width="1" alt="*"',"><","/p",">"].join(""))}};
    function get_var_val(var_name){
        return eval("(typeof(" + var_name + ")!='undefined') ? " + var_name + " : ''");
    }
    function param_2_tracking_url(params){
        var default_params = {
            'bb_userid':cookie_ns.get(uid_cookie_name),
            'bb_bregid':unescape_str(cookie_ns.get('breg')).split(":")[0], //prop32
            'name':get_var_val('Description').replace(/\//g,":"),
            'bb_groupid': get_var_val("groupid"), //prop6
            'bb_author':get_var_val("story_author_name"),
            'bb_pub_d':get_var_val("story_pub_time")
        };
        $.extend(default_params, params);
        var param_url = "";
        for (var p in default_params){
            param_url += "&" + escape_str(p) + "=" + escape_str(default_params[p]);
        }
        var ret_url = 'http'+(document.location.href.charAt(4)=='s'?'s://sb':'://b')+'.scorecardresearch.com/p?c1=2&c2=' + comscore_account;
        ret_url += param_url;
        return ret_url;
    }
    function generate_update_bdfpc(){
        var cookie_domain = "Bloomberg.com";
        var val = cookie_ns.get(uid_cookie_name);
        if (val.length == 0){
            val = "001." + BLOOMBERG.num.pad(Math.floor(Math.random()*10000000000), 10) + "." + Math.floor((new Date()).getTime()/1000);
        }
        // set/refresh cookie value/expiry
        cookie_ns.set(uid_cookie_name, val, Date.nextYear().toGMTString(), "/", cookie_domain);
    }
    function escape_tracking_value(str){
        return escape_str(str.strip().replace("=", "").replace("&", ""));
    }
    /***************************public methods********************************/
    // params: {'new_variable_name':'value', ...}
    comscore_ns.track = function(params){
        comScore(param_2_tracking_url(params));
        comscore_ns.clearTrackCookie();
    };
    comscore_ns.clearTrackCookie = function(){
        cookie_ns.set(internal_link_key, "", -1, "/", cookie_domain);
    };
    comscore_ns.internalLinkTrack = function(text, link_pos, link_type){
        var val = "bb_linkname=" + escape_tracking_value(text) + "&bb_linkpos=" + escape_tracking_value(link_pos) + "&bb_linktype=" + escape_tracking_value(link_type);
        cookie_ns.setEndOfSession(internal_link_key, val, "/", cookie_domain);
    };
    // create/update bdfpc cookie Mingle # 4789120
    generate_update_bdfpc();

})();

//methods for creating a sticky navigation menu. Assumes css classes 'pinned' and 'unpin' exist.
//the container is included to ensure floating objects will remain in place while scrolling and
//are not necessary for all navigation bars.

//navigation: navigation bar class/id name
//stopper: object class/id name that should stop scrolling
//content: main content on page class/id name
//navigation_container: navigation container class/id name
//container height: height container should be, in px
(function(){
    var nav_ns=BLOOMBERG.namespace('navigation');
    nav_ns.sticky_navigation = function sticky_nav(options){
        var defaults = {'navigator': '',
          'stopper': '#footer',
          'top_element': '',
          'navigation_container': '',
          'top_padding': 0};
        for(var index in defaults) {
		    if(typeof options[index] == "undefined") options[index] = defaults[index];
	    }
        var $stopping_at = $(options['stopper']);
        var $navigation_menu = $(options['navigator']);
        if (options['navigation_container'] !== ''){
            var height = $(options['navigator']).height();
            $(options['navigation_container']).height(height);
        }

        $(window).scroll(function(){
            $navigation_menu.removeClass('pinned');
            if($(window).scrollTop() > $(options['top_element']).offset().top + $(options['top_element']).outerHeight() + options['top_padding']){
                $navigation_menu.addClass('pinned');
            }
            if($(window).scrollTop() > ($stopping_at.offset().top)-$navigation_menu.outerHeight()){
                $navigation_menu.addClass('unpin');
                var stop_at = $stopping_at.offset().top-$navigation_menu.outerHeight();
                $navigation_menu.offset({top: stop_at, left:$navigation_menu.offset().left});
            }else{
                $navigation_menu.removeClass('unpin');
                $navigation_menu.removeAttr('style')
            }
        });
    }
})();

//(function() {
//
//    $(document).ready(function() {
//        $('.section_tracking').each(function() {
//            var section_name = $(this).attr('section_name');
////            console.log("Section Name : " + section_name);
//            var links = $(this).find('a:visible');
//
//            links.each(function(index, e) {
////                var old_href = $(this).attr('href');
////                $(this).attr('href', old_href + "#" + section_name + "&" + index);
//                $(this).click(function(event){
////                    event.preventDefault();
//                    BLOOMBERG.util.Cookie.set("section_slot",section_name+"|"+index,"","/");
//                    alert("Section Name : " + section_name + " - Slot Number : " + index);
////                    window.location = this.href + "#" + section_name + "&" + index
////                    console.log("Index : " + index + " -- Section : " + section_name + " -- URL : " + this.href);
//                });
//                //console.log("Index : " + index + " -- URL : " + this.href);
//            });
//        });
//    });
//
//
//})();
function readCookie(name)
{
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++)
    {
        var c = ca[i];
        while (c.charAt(0) == ' ')c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0)return c.substring(nameEQ.length, c.length);
    }
    return null;
}
function getcombo_ga()
{
    if (document.cookie.indexOf("__utmx=") != -1) {
        var utmxkey = '0168891469';
        var utmx_cookie_value = readCookie('__utmx');
        var cookie_data_array = utmx_cookie_value.split('.');
        var num_cookies = cookie_data_array.length;
        for (i = 1; i < num_cookies; i++) {
            if (cookie_data_array[i].indexOf(utmxkey) != -1) {
                var combination_id = cookie_data_array[i].split(':')[2];
                if (combination_id == undefined)
                    combination_id = '';
            }
        }
    }
    else {
        return ""
    }
    if (combination_id == undefined)
        combination_id = "-1";
    return combination_id;
}


/* news according on markets landing pages */
function init_news_accordion()
{
    if($("#accordion_news_module > div").height() == 0 && interstitialStatus) {
        setTimeout('init_news_accordion()', 200);
    }
    else {
        $("#accordion_news_module").accordion({
                changestart:function(event, ui) {
                    $("#accordion_news_module h3").each(function() {
                            $(this).removeClass("active_news_section")
                                });
                    var active_index = $("#accordion_news_module").accordion("option", "active");
                    var active = $("#accordion_news_module h3:eq(" + active_index + ")");
                    active.addClass("active_news_section");
                },
                    change: function(event, ui) {
                    ui.newContent.css('overflow' , 'auto');
                }
            });
    }
}


