(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
module.exports = (function () {
  var productApi = require("./product");
  var ajaxRequest = require("../utilities").ajaxRequest;

  var Cart;
  var cartApi = "/api/v3/carts/-1/";
  var hasSubmitOrderOverride = false;
  var onCheckout = [];

  function returnCart() {
    return Cart || window.angular.element(document.body).injector().get('Cart');
  }

  function updateCart() {
    Cart = returnCart();
    Cart.get({}, Cart.updateCart);
  } 

  function applyCoupon(couponCode, callback) {
    ajaxRequest(cartApi + "coupon", "PUT", {
      couponCode: couponCode,
      email: currentUser.email
    }, function(response) {
      updateCart();
      callback(response);
    });
  }

  function getCart(callback) {
    ajaxRequest(cartApi, "GET", null, function(response) {
      updateCart();
      callback(response);
    });
  }

  function addProductToCart(product, callback) {

    if(product.numberOfPrepaid) {
      productApi.getProduct(product.productId, function(pcInfo) {
        var subscriptionSetting = _.find(pcInfo.subscriptionSettings, {
          frequency: product.frequency, 
          numberOfPrepaid: product.numberOfPrepaid
        });

        if(subscriptionSetting) {
          product.subscriptionSettingId = subscriptionSetting.id;
          ajaxRequest(cartApi + "line-items", "POST", product, function(response) {
            updateCart();
            callback(response);
          });
        } else {
          callback({err: 'no such subscription setting available'});
        }
      });
    } else {
      ajaxRequest(cartApi + "line-items", "POST", product, function(response) {
        updateCart();
        callback(response);
      });
    }
  }

  return {
    update: updateCart,
    get: getCart,
    addProduct: addProductToCart,
    applyCoupon: applyCoupon
  }
})();
},{"../utilities":17,"./product":3}],2:[function(require,module,exports){
module.exports = (function () {
  var cartApi = require("./cart");
  var productApi = require("./product");

  SymphonyAPI(["page", function(p) {
    window.dataLayer = window.dataLayer || [];
    p && window.dataLayer.push({ "event": p.type });
  }]);

  var API = {};

  API.cart = cartApi;
  API.cart.addProduct = cartApi.addProduct;
  API.cart.get = function(callback) {
    typeof SymphonyAPI === 'function' 
      ? SymphonyAPI(["cart",  callback])
      : cartApi.getCart(callback);
  }

  API.products = productApi;
  API.products.getCurrent = function(callback) {
    typeof SymphonyAPI === 'function' 
      ? SymphonyAPI(["product",  callback])
      : console.error("SymphonyAPI does not exist");
  }

  return API;
})();
},{"./cart":1,"./product":3}],3:[function(require,module,exports){
module.exports = (function () {
  function getById(id, callback) {
    $.getJSON('/productcluster/' + id, callback);
  }

  return {
    getById: getById
  }
})();
},{}],4:[function(require,module,exports){
module.exports = (function () {
  var watch = require("../utilities/watchObjects");
  
  function track(type, value) {
    switch (type) {
      case "newsletter":
        trackAnonSubscribe();
      break;

      case "purchasing-channel":
        trackPurchasingChannel(value);
      break;

      case "subscriptions":
        trackUserHasSubscriptions();
      break;

      case "inventory-levels":
        watch("selectedVariants", function(variants) {
          if (variants.length === 1 && variants[0].inventory <=0) {
            var eventName = variants[0].allowBackOrder ? 'Variant Back-Order' : 'Variant OOS';
            window.ga && ga("send", "event", eventName, variants[0].name, variants[0].id.toString());
            window._gaq && _gaq.push(['_trackEvent', eventName, variants[0].name, variants[0].id.toString()]);
          } 
        })
      break;
    }
  }

  function trackUserHasSubscriptions() {
    SymphonyAPI(["page", "order", function(page, o) {
      if (page.type === 'order') {
        var filter = _.filter(o.lineItems, function(item) {
          return item.type === "SUBSCRIPTION" && item.fulfillmentStatus !== 'CANCELLED';
        });

        if (filter.length > 0) {
          window.analytics && analytics.identify(o.customer.email, {
            "Has Subscriptions": true
          });
        }
      } else {
        window.currentUser && $.getJSON("/api/v1/subscriptions", function(subs) {
          var activeSub = 0;
          _.each(subs, function(val, index) {
            if (val.subscriptionState.status === 'ONGOING') {
              activeSub += 1;
            }
          });

          window.analytics && analytics.identify(currentUser.email, {
            "Has Subscriptions": activeSub > 0 ? true : false
          });
        });
      }
    }]);
  }

  function trackAnonSubscribe() {
    var $footerSubscribe = $(".footer-subscribe-container").add(".sp-subscribe");
    $footerSubscribe.find("button").on("click", function() { 
      var email = $footerSubscribe.find("input").val();  
      window.analytics && analytics.identify(email); 
    });
  }
  
  function trackPurchasingChannel(propertyName) {
    var property = propertyName || "Purchasing Channel";
    watchObjects.watchCurrentUser(function(user) { 
      user && window.analytics && analytics.identify(user.email, {
          property: user.purchasingChannel.name
      });
    });
  }

  return {
   track: track
  }
})();
},{"../utilities/watchObjects":21}],5:[function(require,module,exports){
module.exports = (function () {
  var countdownUtils = require("../utilities/countdown");
  var defaultConfig = {};
  var productConfig = {};
  var celeryAppUrl = '/celery';

  function init(config, product, callback) {
    defaultConfig = config;
    var celeryProductConfig = {};

    var attr = product.pc.attributes;
    celeryProductConfig = _.object(_.map(attr, function(a) {
      return[a.name, a.value];
    }));

    if(typeof celeryProductConfig['internal_celery'] === 'undefined') {
      return callback('no valid celery product'); 
    }

    _.merge(productConfig, defaultConfig, celeryProductConfig);

    callback(null, productConfig);
  }

  function updatePurchaseButton() {
    $('.product-attributes').addClass('celery-hidden');
    $('.quantity-main').addClass('celery-hidden');
    $('.add-to-cart-main button').addClass('celery-hidden');
    $('.add-to-cart-main').append(
      $('<form class="add-to-cart-wrapper celery"></form>').append(
        $('<button class="add-to-cart"></button>').append(
          $('<span>Pre-Order</span>')
        ).attr('data-celery', productConfig['internal_celery']).attr('data-celery-version', 'v2')
      )
    );
  }

  function getShippingCallout(callback) {
    return defaultConfig.shipping_callout+' '+productConfig['internal_celery_shipping'];
  }

  function getPreOrderCountdown(callback) {
    countdownUtils.countdown(productConfig['internal_celery_countdown'], callback);
  }

  function getOrderCountByProduct(callback) {
    $.getJSON(celeryAppUrl+'/celery/'+defaultConfig.brand+'/order/count?line_items.product_id='+productConfig['internal_celery'])
      .success(function(orders) {
        callback(null, orders.data.total/productConfig['internal_celery_units']*100);
      })
      .error(callback);
  }

  return {
    init: init,
    updatePurchaseButton: updatePurchaseButton,
    getShippingCallout: getShippingCallout,
    getPreOrderCountdown: getPreOrderCountdown,
    getOrderCountByProduct: getOrderCountByProduct
  }
})();
},{"../utilities/countdown":15}],6:[function(require,module,exports){
module.exports = (function () {
  function init(config) {
  	loadScript();
    em('set', 'campaign', config.exitMonitor);
  }

  function loadScript() {
    (function(a,e,f,g,b,c,d){
      a[b] = a[b]||function() {
        (a[b].q=a[b].q||[]).push(arguments)
      }
        c=e.createElement(f);
        d=e.getElementsByTagName(f)[0];
        c.async=1;c.src=g;
        d.parentNode.insertBefore(c,d);
    })(window,document,"script","//cdn.app.exitmonitor.com/em.js","em");
  }

	return {
    init: init,
    loadScript: loadScript
  };
})();
},{}],7:[function(require,module,exports){
module.exports = (function () {
  function init(config) {
    var widget = config.widgetId;
    window.friendbuy = window.friendbuy || [];
    window.friendbuy.push(['widget', widget]);

    SymphonyAPI(['user', 'order', function(user, order) {
      window.friendbuy = window.friendbuy || [];
      var siteUrl = config.siteId;

      //Initialize user info with defaults
      var userInfo = {
          id: user ? user.id : null,
          email: user ? user.email : null
      };

      if(order) {
          //override customer info if we have order.customer
          if(order.customer) {
              userInfo.id = order.customer.id;
              userInfo.email = order.customer.email;
          }

          var orderInfo = { 
              id: order.id,
              amount: order.total/100
          }

          var productsInfo = _.map(order.lineItems, function(lineItem) {
              return {
                  sku: lineItem.productSku, 
                  price: lineItem.memberPrice/100,
                  quantity: lineItem.quantity
              }
          });

          window.friendbuy.push(['track', 'order', orderInfo]);
          window.friendbuy.push(['track', 'products', productsInfo]);
      }

      window.friendbuy.push(['site', siteUrl]);
      window.friendbuy.push(['track', 'customer', userInfo]);
      loadScript();
    }]);
  }

  function loadScript() {
    (function (f, r, n, d, b, y) {
      b = f.createElement(r), 
      y = f.getElementsByTagName(r)[0];
      b.async = 1;
      b.src = n;
      y.parentNode.insertBefore(b, y);
    })(document, 'script', '//djnf6e5yyirys.cloudfront.net/js/friendbuy.min.js');
  }

  return {
    init: init,
    loadScript: loadScript
  }
})();
},{}],8:[function(require,module,exports){
module.exports = (function () {
  var analytics = require("./analytics");
  var exitmonitor = require("./exitmonitor");
  var friendbuy = require("./friendbuy");
  var celery = require('./celery');
  var yotpo = require('./yotpo');

  analytics.track("newsletter");
  var Apps = {};

  Apps.analytics = analytics;
  Apps.friendbuy = friendbuy;
  Apps.exitmonitor = exitmonitor;
  Apps.celery = celery;
  Apps.yotpo = yotpo;

  function init(appName, config) {
    Apps[appName].init(config);
  }

  function loadScript(appName) {
    Apps[appName].loadScript();
  }

  Apps.init = init;
  Apps.loadScript = loadScript;
  
  return Apps;
})();
},{"./analytics":4,"./celery":5,"./exitmonitor":6,"./friendbuy":7,"./yotpo":9}],9:[function(require,module,exports){
module.exports = (function (config) {
  function loadScript() {
  	(function e(){
      var e=document.createElement("script");
      e.type="text/javascript",e.async=!0, e.src="//staticw2.yotpo.com/u4r4V2hoTMpliPd6JXa4YEQa0qICMk7ZHcsyLLry/widget.js";
      var t=document.getElementsByTagName("script")[0]; 
      t.parentNode.insertBefore(e,t)}
    )();
  }

	return {
    loadScript: loadScript
  };
});
},{}],10:[function(require,module,exports){
Symphony.bundlesReady(function() {
	Symphony.API = require("./api");
	Symphony.Apps = require("./apps");
	Symphony.Utils = require("./utilities");
	//Symphony.Overrides = require("./overrides");
	//Symphony.Pixels = require("./pixels");

	require("./jqueryPlugins/waitUntilExists");
});
},{"./api":2,"./apps":8,"./jqueryPlugins/waitUntilExists":11,"./utilities":17}],11:[function(require,module,exports){
module.exports = (function ($, window) {
  var intervals = {};
  var removeListener = function(selector) {
    if (intervals[selector]) {
      
      window.clearInterval(intervals[selector]);
      intervals[selector] = null;
    }
  };
  var found = 'waitUntilExists.found';
  $.fn.waitUntilExists = function(handler, shouldRunHandlerOnce, isChild) {
    var selector = this.selector;
    var $this = $(selector);
    var $elements = $this.not(function() { return $(this).data(found); });
    
    if (handler === 'remove') {
      removeListener(selector);
    }
    else {
      $elements.each(handler).data(found, true);
      
      if (shouldRunHandlerOnce && $this.length) {
        removeListener(selector);
      }
      else if (!isChild) {
        intervals[selector] = window.setInterval(function () {
          $this.waitUntilExists(handler, shouldRunHandlerOnce, true);
        }, 500);
      }
    }
  
    return $this;
  };
}(jQuery, window));
},{}],12:[function(require,module,exports){
module.exports = (function () {
	function safeApply($scope, applyFn) {
      !$scope.$$phase ? $scope.$apply(applyFn) : applyFn();
    }
    
    function compile(target) {
		//recompile injected html
		var compile = window.angular.element(document.body).injector().get('$compile');
		var scope = window.angular.element(target).scope();
		if (scope) {
			compile(target)(scope);
		} else {
			console.error(target, " scope is: ", scope)
		}
    }

    return {
    	safeApply: safeApply,
    	compile: compile
    }
})();
},{}],13:[function(require,module,exports){
module.exports = function (callback, attempts, condition, timeout) {
  (function checkCondition() {
    if (condition()) {
      callback(null, true);
    } else if (attempts > 0) {
        --attempts;
      setTimeout(checkCondition, (timeout || 500));
    } else if (attempts <= 0 ) {
      callback(true, null);
    }
  })();
}
},{}],14:[function(require,module,exports){
module.exports = (function () {
	function get(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);
        } 
    }
  }

  function drop(name, days, value) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
  }

  return {
    get: get,
    drop: drop
  }
})();

},{}],15:[function(require,module,exports){
module.exports = function (toDate, callback) {
  if(typeof callback !== 'function') {
    return false;
  }

  var toDate = new Date(toDate).getTime();

  var t = setInterval(function() {
    var dateDiff = Math.floor((toDate - new Date().getTime())/1000);

    if(dateDiff <= 0) {
      clearInterval(t);
      return callback(true);
    }

    var numDays = Math.floor(dateDiff/86400);
    var numHours = Math.floor((dateDiff - numDays*86400)/3600);
    var numMinutes = Math.floor((dateDiff - numDays*86400 - numHours*3600)/60);
    var numSeconds = Math.floor(dateDiff - numDays*86400 - numHours*3600 - numMinutes*60);

    callback(null, {
      days: numDays,
      hours: numHours,
      minutes: numMinutes,
      seconds: numSeconds
    });
  }, 1000);
}
},{}],16:[function(require,module,exports){
module.exports = function (file, isObject, callback) {
  // The array we're going to build
  var array   = [];
  // Break it into rows to start
  var rows    = file.split(/\15/);
  if (rows.length === 1) {
    rows    = file.split(/\n/);
  }

  
  

  // Loop through remaining rows
  for(var rowIndex = 0; rowIndex < rows.length; ++rowIndex){
    var rowArray  = rows[rowIndex].split(',');

    // Create a new row object to store our data.
    if (isObject) {
      // Take off the first line to get the headers, then split that into an array
      var headers = rows.shift().split(',');
      var rowObject = array[rowIndex] = {};
      // Then iterate through the remaining properties and use the headers as keys
      for(var propIndex = 0; propIndex < rowArray.length; ++propIndex){
        // Grab the value from the row array we're looping through...
        var propValue =   rowArray[propIndex].replace(/^"|"$/g,'').replace(/^[\r\n]+|\.|[\r\n]+$/g, "");
        // ...also grab the relevant header (the RegExp in both of these removes quotes)
        var propLabel = headers[propIndex].replace(/^"|"$/g,'').replace(/^[\r\n]+|\.|[\r\n]+$/g, "");

        rowObject[propLabel] = propValue;
      }
    } else {
      array[rowIndex] = rowArray[0].replace(/^"|"$/g,'').replace(/^[\r\n]+|\.|[\r\n]+$/g, "");
    }
  }

  callback(array);
}
},{}],17:[function(require,module,exports){
module.exports = (function () {
  /*UTILITIES*/
  var whenAvailable = require("./whenAvailable");
  var siteDetails = require("./siteDetails");
  var checkReadyState = require("./checkReadyState");
  var watchObjects = require("./watchObjects");
  var cookieUtils = require("./cookies");
  var stringUtils = require("./strings");
  var angularUtils = require("./angular");
  var csvToArray = require("./csvToArray");
  var urlUtils = require("./urls");
  var countdownUtils = require('./countdown');

  function pushDataLayerEvent(name) {
    window.dataLayer = window.dataLayer || [];
    window.dataLayer.push({
      event: name+"Ready"
    });
  }

  function ajaxRequest(url, type, data, callback) {
    $.ajax({
        type: type,
        url: url,
        datatype: "json",
        data: JSON.stringify(data),
        headers: {
          "Content-Type": "application/json",
          "Accept": "application/json"
        },
        success: callback,
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log("Error Occured!" + " | " + XMLHttpRequest.responseText +
                   " | " + textStatus + " | " +  errorThrown);
        }
      });
  }

  /\/order\//.test(window.location.href) 
    && whenAvailable("order", pushDataLayerEvent);

  var Utils = {};

  Utils.ajaxRequest = ajaxRequest;
  Utils.siteDetails = siteDetails;
  Utils.whenAvailable = whenAvailable;
  Utils.checkReadyState = checkReadyState;

  Utils.csvToArray = csvToArray;
  Utils.watch = watchObjects;
  Utils.cookies = cookieUtils;
  Utils.str = stringUtils;
  Utils.url = urlUtils;
  Utils.angular = angularUtils;
  Utils.countdown = countdownUtils;

  return Utils;
})();

},{"./angular":12,"./checkReadyState":13,"./cookies":14,"./countdown":15,"./csvToArray":16,"./siteDetails":18,"./strings":19,"./urls":20,"./watchObjects":21,"./whenAvailable":22}],18:[function(require,module,exports){
module.exports = function (callback) {
  var ignoreVals = ["www", "com", "demo", "store"];
  var host = window.location.host.split('.');
  var env;
  var site = _.find(host, function(val) {
    return !_.contains(ignoreVals, val)
  })

  if (/sites/.test(site)) {
    //pod?
    env = site.replace("sites", "partner");
    site = 'kittydemo';
  } else if (/release/.test(site)) {
    var split = site.split('-');
    env = 'manage-release';
    site = split[0];
  } else {
    env = 'prod';
  }

  callback({
    site: site,
    env: env
  });
}
},{}],19:[function(require,module,exports){
module.exports = (function () {
	function replaceAll(find, replace, str) {
    return str.replace(new RegExp(find, 'g'), replace);
  }

  function pad(n, width, z) {
    z = z || '0';
    n = n + '';
    return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
  }

  function commaSeparateNumber(val){
    while (/(\d+)(\d{3})/.test(val.toString())){
      val = val.toString().replace(/(\d+)(\d{3})/, '$1'+','+'$2');
    }
    return val;
  }

  function isJSON(str) {
    try {
        JSON.parse(str);
    } catch (e) {
        return false;
    }
    return true;
  }

  return {
    replaceAll : replaceAll,
    pad : pad,
    commaSeparateNumber : commaSeparateNumber,
    isJSON : isJSON
  }
})();
},{}],20:[function(require,module,exports){
module.exports = (function() {
	function getUrlParameters(qs) {
	    qs = qs.split('+').join(' ');

	    var params = {},
	        tokens,
	        re = /[?&]?([^=]+)=([^&]*)/g;

	    while (tokens = re.exec(qs)) {
	        params[decodeURIComponent(tokens[1])] = decodeURIComponent(tokens[2]);
	    }

	    return params;
	}

    function openInNewTab(url) {
      var win = window.open(url, '_blank');
      win.focus();
    }

    return {
    	getUrlParameters: getUrlParameters,
    	openInNewTab: openInNewTab
    }
})();

},{}],21:[function(require,module,exports){
module.exports = (function() {
  var checkReadyState = require("./checkReadyState");
  function watch(typeSelector, object, callback) {
    if (typeof object === 'function') {
      callback = object;
    }

    switch (typeSelector) {
      case "currentUser":
        watchScopeObject('[ng-controller="AppCtrl"]', "currentUser", callback);
      break;

      case "productListSpinner":
        watchScopeObject('.product-list-spinner', "pageLoading", callback);
      break;

      case "activeVariants":
        watchScopeObject('[ng-controller="ProductAttrCtrl"]', "productInfo.products", callback);
      break;

      case "cart":
        watchScopeObject('[ng-controller="CheckoutCtrl"]', "cart", callback);
      break;

      default:
        watchScopeObject(typeSelector, object, callback);
      break;
    }
  }

  function watchScopeObject(ctrlSelector, object, callback) {
    function condition() { 
      return (window.angular 
        && window.angular.element(ctrlSelector) 
        && window.angular.element(ctrlSelector).scope()); 
    }

    checkReadyState(function(error, result) {
      if (result) {
        var scope = window.angular.element(ctrlSelector).scope();
          scope.$watch(object, function() {
            callback && callback(scope[object]);
          });
      }
    }, 50, condition, null);
  }

  return watch;
})();


},{"./checkReadyState":13}],22:[function(require,module,exports){
module.exports = function (name, callback) {
    var interval = 100; // ms
    var attempts = 0;
    var maxAttempts = 50;
    window.setTimeout(function() {
        if (window[name]) {
            callback(name);
        } else {
            attempts < maxAttempts && window.setTimeout(arguments.callee, interval);
            attempts++;
        }
    }, interval);
}
},{}]},{},[10]);
