// this file has dependency on master.js
(function(){
  // remove 'opttm' and 'optwnd' cookies, they are no longer needed
  BLOOMBERG.util.Cookie.removeCookies(['opttm', 'optwnd'],'/', 'bloomberg.com');
  // remove cookies used by non stop news bucket testing, it's already finished
  BLOOMBERG.util.Cookie.removeCookies(['nonstopnews', 'nonstopnewsdt'], '/', 'bloomberg.com');
  // remove cookies used by Bloomberg homepage phase 2 GA bucket testing, it's already finished
  BLOOMBERG.util.Cookie.removeCookies(['hptest201103', 'hptest2011time'], '/', 'bloomberg.com');
  //remove cookies used by Bloomberg for the market snapshot more/less test, it's already finished
  BLOOMBERG.util.Cookie.removeCookies(['snapshottest', 'snapshottest_tm'], '/', 'bloomberg.com');
  //remove cookies used by Bloomberg for the view vs opinion in global nav test, it's already finished
  BLOOMBERG.util.Cookie.removeCookies(['bviewopn', 'bviewopn_tm'], '/', 'bloomberg.com');

  // Remove cookies for the homepage recommendations test started in 10/2011 which is finished now
  BLOOMBERG.util.Cookie.removeCookies(['hprec201108', 'hprec201108_tm'], '/', 'bloomberg.com');
})();

(function(){
  var bucket_test = BLOOMBERG.namespace('bucket_test');
  var bucket_collection_list = BLOOMBERG.namespace('bucket_collection_list');
  var cookie_ns = BLOOMBERG.util.Cookie;
  var cookieDomain = "bloomberg.com";
  var expireDate = Date.nextYear().toGMTString();
  // please specify all settings for your test
  function get_bkt_set_time(time_cookie_key){
    var val = cookie_ns.get(time_cookie_key);
    if (val){ return new Date(val * 1000); }
    return -1;
  }
  function debug_info(test_name, str, debug_mode){
    if (debug_mode) { console.log('[' + test_name + '] ' + str); }
  }
  function refresh_cookie_expire_date(cookie_key){
    var val = cookie_ns.get(cookie_key);
    if (val !== ''){ cookie_ns.set(cookie_key, val, expireDate, '/', cookieDomain); }
  }

  bucket_test.run_test = function(test_config){
    // first_time_fn = function(cookie_value) { ... } this function will be called when assigning cookie for the 1st time
    var default_config = {
      'test_name':'test_name',
      'roll_time_key':'roll_time_key',
      'value_key':'value_key',
      'percentage':0,
      'bucket_values':['0', '1'],
      'debug':false,
      'after_set_cookie_fn':null
    };
    $.extend(default_config, test_config);
    if (default_config['debug']){
      console.log('****' + default_config['test_name'] + '****');
      console.log(default_config);
    }

    var cookie_bkt_set_time = get_bkt_set_time(default_config['roll_time_key']);
    if (cookie_bkt_set_time < 0){
      cookie_ns.set(default_config['roll_time_key'], Math.floor((new Date()).getTime()/1000), expireDate, "/", cookieDomain);
      var whichSide = Math.random() * 100;
      debug_info(default_config['test_name'], 'side: ' + whichSide, default_config['debug']);
      if (whichSide < default_config['percentage']){
        var cookie_value = default_config['bucket_values'][Math.floor(Math.random() * default_config['bucket_values'].length)];
        debug_info(default_config['test_name'], 'cookie_value: ' + cookie_value, default_config['debug']);
        cookie_ns.set(default_config['value_key'], cookie_value, expireDate, "/", cookieDomain);
        if (default_config['after_set_cookie_fn']) { default_config['after_set_cookie_fn'](cookie_value); }
      }else{
        debug_info(default_config['test_name'], 'not_in_bucket', default_config['debug']);
      }
    }
    refresh_cookie_expire_date(default_config['value_key']);
    refresh_cookie_expire_date(default_config['roll_time_key']);
  };

})();

(function(){
    var old_market_page_path = "/markets";
    var new_market_page_path = "/markets/home_v2";

    function is_bucket_group() {
        var val = BLOOMBERG.util.Cookie.get(companypage_test_config['value_key']);
        if(!val || val == "0") {
            return false;
        }
        return true;
    }

    function is_quote_page() {
        var current_url = window.location.href;
        return (current_url.indexOf("/apps/quote?ticker") != -1) || (current_url.indexOf("/quote/") != -1);
    }

    function is_pb_page() {
        var current_url = window.location.href;
        return (current_url.indexOf("/apps/quote?ticker") != -1);
    }

    function is_currency_page(){
        var current_url = window.location.href;
        return (current_url.search(/(:cur)/i) != -1);
    }

    function is_old_market_page() {
        var path_o = window.location.pathname;
        return (path_o == old_market_page_path) || (path_o == old_market_page_path+"/")
    }

    function is_new_market_page() {
        var path_n = window.location.pathname;
        return (path_n == new_market_page_path) || (path_n == new_market_page_path+"/")
    }

    var bucket_test_ns = BLOOMBERG.bucket_test;

    var companypage_test_config = {
        'test_name':'companypage_test',
        'roll_time_key':'companypage_tm1',
        'value_key':'companypage',
        'percentage':parseInt(BLOOMBERG.global_var.quote_ab_bucket_size),
        'bucket_values':['0', '1'],
        'debug':false,
        'after_set_cookie_fn':null
    };

    bucket_test_ns.run_test(companypage_test_config);

    var bucket_group = is_bucket_group();
    var is_quote_page = is_quote_page();
    var pb_page = is_pb_page();

    if (BLOOMBERG.global_var.quote_enable_ab_testing == "true"){
        if ((bucket_group && pb_page && is_quote_page) || (!bucket_group && is_currency_page())) { // cookie exist && pb pages
            // show new pages
            var ticker = window.location.href.split("=")[1];
            ticker = ticker.replace("%2F", "+");
            ticker = ticker.replace("/", "+");
            ticker = ticker.replace(".", "!");
            var o_path = window.location.host;
            window.location =  window.location.protocol + "//" + o_path + "/quote/" + ticker;
        } else if (!bucket_group && !pb_page && is_quote_page) {   // cookie doesn't exist && new page
            if (!is_currency_page()){
                // show old pages
                var ticker = window.location.href.split("/")[4];
                ticker = ticker.replace("+", "/");
                ticker = ticker.replace("!", ".");
                var o_path = window.location.host;
                window.location =  window.location.protocol + "//" + o_path +  "/apps/quote?ticker=" + ticker;
            }
        } else if(bucket_group && is_old_market_page()) {
            window.location.pathname = new_market_page_path;
        } else if(!bucket_group && is_new_market_page()) {
            window.location.pathname = old_market_page_path;
        }
    } else{
        if (pb_page){
            // show new pages
            var ticker = window.location.href.split("=")[1];
            ticker = ticker.replace("%2F", "+");
            ticker = ticker.replace("/", "+");
            ticker = ticker.replace(".", "!");
            var o_path = window.location.host;
            window.location =  window.location.protocol + "//" + o_path + "/quote/" + ticker;
        }
        if (is_old_market_page()){
            window.location.pathname = new_market_page_path;
        }
    }

    var old_2_new = {
        "/markets/currencies" : "/markets/currencies_v2",
        "/markets/currencies/americas" : "/markets/currencies_v2/americas",
        "/markets/currencies/europe-africa-middle-east" : "/markets/currencies_v2/europe-africa-middle-east",
        "/markets/currencies/asia-pacific" : "/markets/currencies_v2/asia-pacific",
        "/markets/currencies/cross-rates" : "/markets/currencies_v2/cross-rates"
    };
    var new_2_old = {};
    for(var prop in old_2_new){
        new_2_old[old_2_new[prop]] = prop;
    }
    function get_current_path_without_trailing_slash(){
        return window.location.pathname.replace(/\/$/, '');
    }
    var cur_path_name = get_current_path_without_trailing_slash();
    if (!bucket_group){
        var target_path_name = new_2_old[cur_path_name];
    }
    else{
        var target_path_name = old_2_new[cur_path_name];
    }
    if (typeof(target_path_name) != 'undefined'){
        window.location.pathname = target_path_name + "/";
    }
    //prevent non-bucketed users from seeing the new etfs or the new currency converter page
    if(!bucket_group){
        if(cur_path_name == "/markets/currencies_v2/etfs"){
            window.location.pathname = "/markets/etfs/currency/";
        }
        if(cur_path_name == "/markets/currencies_v2/currency-converter"){
            window.location.pathname = "/personal-finance/calculators/currency-converter/";
        }
    }
})();

(function(){
  var bucket_test_ns = BLOOMBERG.bucket_test;
  var test_config = {
    'test_name':'top_rails_stories_test',
    'roll_time_key':'morestories201112_tm',
    'value_key':'morestories201112',
    'percentage':100,
    'bucket_values':["a1", "a2", "a3", "a4", "a5", "rsch6", "qn7", "qn8", "qn9", "qn10", "qn11", "qn12", "dm13", "dm14", "dm15", "dm16", "dm17", "int18", "int19", "int20", "int21", "int22", "rsch23", "rsch24", "rsch25", "rsch26", "rsch27", "rsch28", "rsch29", "rsch30", "rsch31", "rsch32", "dm33", "dm34", "dm35", "dm36", "dm37", "dm38", "dm39", "dm40", "dm41", "qn42", "qn43", "qn44", "qn45", "qn46", "qn47", "qn48", "qn49", "qn50"],
    'debug':false,
    'after_set_cookie_fn': null
  };
  bucket_test_ns.run_test(test_config);
})();

(function() {
  var bucket_test_ns = BLOOMBERG.bucket_test;
  var test_config = {
    'test_name':'homepage_recommendations',
    'roll_time_key':'hprec201202_tm',
    'value_key':'hprec201202',
    'percentage':100,
    'bucket_values':['rd1', 'rd2', 'rd3', 'rd4', 'rd5', 'rd6', 'rd7', 'idx8', 'dm9', 'qn10'],
    'debug':false,
    'after_set_cookie_fn': null
  };
  bucket_test_ns.run_test(test_config);
})();

(function() {
  var ab_test = BLOOMBERG.namespace("ab_test");

  ab_test.set_bucket = function(cookie, value) {
    var expireDate = Date.nextYear().toGMTString();
    BLOOMBERG.util.Cookie.set(cookie, value, expireDate, "/", "bloomberg.com");
//    window.location.href = "/";
    window.location.reload();
  };
})();

