var personalisationFn = {
  ready: false,
  fetchData: function(url, doneCB, failCB){
    var url = url;
    $.ajax({url:url, dataType: 'json'}).then(doneCB, failCB);
  },
  formatCommand: function(input) {
    var inputMod = input.replace(new RegExp('topBanner', 'g'), 'personalisationFn.topBanner');
    inputMod = inputMod.replace(new RegExp('cartTotalCostBanner', 'g'), 'personalisationFn.cartTotalCostBanner');
    inputMod = inputMod.replace(new RegExp('eStorePhoneDeviceMessage', 'g'), 'personalisationFn.eStorePhoneDeviceMessage');

    return inputMod;
  },
  check: function (conditions, command) {

    if (conditions != 'all' && conditions != '') {
      var conditionCheck = false;

      // If in cart + inCart exists in check statement, check for cart items
      if((conditions.indexOf('inCart') > 0 || conditions.indexOf('bundleInCart') > 0) && (window.location.href.indexOf('/cart') != -1 || window.location.href.indexOf('/checkout') != -1  || window.location.href.indexOf('/upgrades/new_upgrade_cart') != -1 || window.location.href.indexOf('/upgrades/checkout') != -1)) {
        // fix this returning undefined
        conditionCheck = personalisationFn.checkCart(conditions, command);

      } else if((conditions.indexOf('inCart') > 0 || conditions.indexOf('bundleInCart') > 0) && (window.location.href.indexOf('/cart') == -1 || window.location.href.indexOf('/checkout') == -1 || window.location.href.indexOf('/upgrades/new_upgrade_cart') == -1 || window.location.href.indexOf('/upgrades/checkout') == -1)){
        conditionCheck = true;
        // Replace simple functions to point to the correct function, helps with read-ability of the call from target
        // var commandMod = command.replace(new RegExp('topBanner', 'g'), 'personalisationFn.topBanner');
        var commandMod = personalisationFn.formatCommand(command);

          eval(commandMod);
      } else {

        // Replace simple functions to point to the correct function, helps with read-ability of the call from target
        var commandMod = personalisationFn.formatCommand(command);
          eval(commandMod);
      }


    } else {
      // Replace simple functions to point to the correct function, helps with read-ability of the call from target
      var commandMod = personalisationFn.formatCommand(command);
        eval(commandMod);
    }

  },
  checkCart: function (conditions, command) {
    var cartJSONData;

    if (window.location.href.indexOf('/cart') != -1 || window.location.href.indexOf('/checkout') != -1 || window.location.href.indexOf('/upgrades/new_upgrade_cart') != -1 || window.location.href.indexOf('/upgrades/checkout') != -1) {
      // $.getJSON('https://shop.vodafone.com.au/cart/web/modules/cartasjson.jsp', function(data) {
        // cartJSONData = data;
        var conditonsMod = conditions.replace(new RegExp('bundleInCart', 'g'), 'personalisationFn.bundleInCart');
        var conditonsMod = conditonsMod.replace(new RegExp('inCart', 'g'), 'personalisationFn.inCart');
        var conditonsMod = conditonsMod.replace(new RegExp('notpersonalisationFn.inCart', 'g'), 'personalisationFn.notinCart');
        var conditionCheck = eval(conditonsMod);
        console.log('Personalisation cart check: ' + conditionCheck);
        if (conditionCheck) {
          var commandMod = personalisationFn.formatCommand(command);
          if (conditionCheck) {
                eval(commandMod);
          }
        } else {
          return false;
        }
      // });
    }

  },

  // Check if items are in the cart JSON
  // Category is the json patt from the bundledItems object, and item is the item to find
  inCart: function (category, item) {

      var bundledItems = cartJSONData.bundledItems;

      function resolve(obj, path){
          path = path.split('.');
          var current = obj;
          while(path.length) {
              if(typeof current !== 'object') return undefined;
              current = current[path.shift()];
          }
          return current;
      }

      for (var i = 0; i < bundledItems.length; i++) {
        var testCategory = resolve(bundledItems[i],category);
        if (testCategory == item) {
          return true;
        }
      }
      return false;
  },
  bundleInCart: function (categories, items) {
    var bundledItems = cartJSONData.bundledItems;

    function resolve(obj, path){
        path = path.split('.');
        var current = obj;
        while(path.length) {
            if(typeof current !== 'object') return undefined;
            current = current[path.shift()];
        }
        return current;
    }
    for (var i = 0; i < bundledItems.length; i++) {
      var allMatch = 0;
      for (var j = 0; j < items.length; j++) {
        var testCategory = resolve(bundledItems[i],categories[j]);
        if (testCategory == items[j]) {
          allMatch = allMatch + 1;
        }
      }
      if (allMatch == items.length) {
        return true;
      }
    }
    return false;
  },
  notinCart: function (category, item) {

      var bundledItems = cartJSONData.bundledItems;

      function resolve(obj, path){
          path = path.split('.');
          var current = obj;
          while(path.length) {
              if(typeof current !== 'object') return undefined;
              current = current[path.shift()];
          }
          return current;
      }

      for (var i = 0; i < bundledItems.length; i++) {
        var testCategory = resolve(bundledItems[i],category);
        if (testCategory == item) {
          return false;
        }
      }
      return true;
  },

  // Function to call to apply top banner personalisation
  // Style - related to a CSS class to apply to the top banner + logo
  // Content - copy of the banner itself
  topBanner: function (style, content, link) {
    if ($('.top-banner-carousel').length == 0) {
      // var banner = "<div id=\"SERV-personalisation\" class=\"top-banner-carousel\"><div class=\"top-banner "+style+"-top-banner\"><div class=\"banner-wrapper\"><span class=\""+style+"-logo\"></span> | "+content+"</div></div></div>"
      if (typeof link == 'undefined') {
        var banner = '<div id="SERV-personalisation" class="top-banner-carousel ' + style + '-style"><div class="top-banner"><div class="banner-wrapper"><span class="banner-logo"></span><span class="banner-content">' + content + '</span></div></div></div>';
      } else {
        var banner = '<div id="SERV-personalisation" class="top-banner-carousel ' + style + '-style"><div class="top-banner"><div class="banner-wrapper"><a onclick=\'croWD.utils.sendTrackingCRO("'+style+'_banner_logo_click","","",this.href);\' href = "'+link+'" style = "border-bottom:none;"> <span class="banner-logo"></span></a><span class="banner-content"> ' + content + '</span></div></div></div> ';
      }
      

      if ($('.page-container .mega-menu-v2').eq(0).length > 0 ) {
        $('.page-container .mega-menu-v2').eq(0).after(banner);
      } else if ($('.spl-topnav-container').eq(0).length > 0) {
        $('.spl-topnav-container').eq(0).after(banner);
      }
      croWD.utils.sendCampaignTracking(
        'personalisation:content:all:serv-personalisation:personalisation-' + style
      );
    }
  },
  cartTotalCostBanner: function (style, content, link) {
    if ($('.alert-box').length == 0) {
      var banner = '<div id="SERV-personalisation" class="alert-box ' + style + '-style"><div class="colour"><div class="icon"></div></div><div class="banner-content">' + content + '</div></div>';

      
      $('.cart-total-cost-header').eq(0).after(banner);
      $('.shop-minicart').eq(0).after(banner);
      
      croWD.utils.sendCampaignTracking(
        'personalisation:content:all:serv-personalisation:personalisation-' + style
      );
    }
  },
  eStorePhoneDeviceMessage: function (style, content, link) {
    if ($('.alert-box').length == 0) {
      var banner = '<div id="SERV-personalisation" class="alert-box ' + style + '-style"><div class="colour"><div class="icon"></div></div><div class="banner-content">' + content + '</div></div>';

      
      $('.PostpaidDeviceContainer__button').eq(0).after(banner);
      croWD.utils.sendCampaignTracking(
        'personalisation:content:all:serv-personalisation:personalisation-' + style
      );
    }
  }
}
// If on cart/checkout, load cart data into variable for other functions to access
var cartJSONData;

 // Upgrades
if (window.location.href.indexOf('/upgrades/new_upgrade_cart') != -1 || window.location.href.indexOf('/upgrades/checkout') != -1){
  $.getJSON('https://shop.vodafone.com.au/upgrades/new_upgrade_cart/web/ajax/order_data_ajax_call.jsp', function(data) {
    cartJSONData = data;
    personalisationFn.ready = true;
  });
// New AQ
} else if (window.location.href.indexOf('/cart') != -1 || window.location.href.indexOf('/checkout') != -1) {
  $.getJSON('https://shop.vodafone.com.au/cart/web/modules/cartasjson.jsp', function(data) {
    cartJSONData = data;
    personalisationFn.ready = true;
  });
} else {
  personalisationFn.ready = true;
}