(function(context,$) {

  "use strict";
  context.JK = context.JK || {};
  context.JK.ShoppingCartScreen = function(app) {

    var logger = context.JK.logger;
    var jamTrackUtils = context.JK.JamTrackUtils;

    var $screen = null;
    var $content = null;
    var totalCost = 0;

    function beforeShow(data) {
      clearContent();
    }

    function afterShow(data) {
      loadShoppingCarts();
    }

    function afterHide() {
      jamTrackUtils.checkShoppingCart();
    }

    function events() {
      $screen.find("a.remove-cart").on('click', removeCart);
      $screen.find("a.proceed-checkout").on('click', proceedCheckout);
    }

    function proceedCheckout(e) {
      e.preventDefault();

      if (totalCost == 0) {
        if(context.JK.currentUserId) {
          logger.debug("proceeding to redeem complete screen because user has a free jamtrack and is logged in")
          window.location = '/client#/redeemComplete'
        }
        else {
          logger.debug("proceeding to redeem signup screen because user has a free jamtrack and is not logged in")
          window.location = '/client#/redeemSignup'
        }
      }
      else {
        if (!context.JK.currentUserId) {
          logger.debug("proceeding to signin screen because there is no user")
          window.location = '/client#/checkoutSignin';
        }
        else {
          var user = app.currentUser();

          if(user.has_recurly_account && user.reuse_card) {
            logger.debug("proceeding to checkout order screen because we have card info already")
            window.location = '/client#/checkoutOrder';
          }
          else {
            logger.debug("proceeding to checkout payment screen because we do not have card info")
            window.location = '/client#/checkoutPayment';
          }
        }
      }

    }

    function removeCart(e) {
      e.preventDefault();

      var options = {};
      options.id = $(e.target).attr("cart-id");

      rest.removeShoppingCart(options)
        .done(loadShoppingCarts)
        .fail(app.ajaxError);
    }


    function clearContent() {
      $content.empty();
    }

    function loadShoppingCarts() {
      clearContent();

      rest.getShoppingCarts()
        .done(renderShoppingCarts)
        .fail(app.ajaxError);
    }

    function renderShoppingCarts(carts) {
      var data = {};

      if(carts.length > 0) {
        var latest_cart = carts[0];
      }

      var $latestCartHtml = "";

      var any_in_us = false
      context._.each(carts, function(cart) {
        if(cart.product_info.sales_region == 'United States') {
          any_in_us = true
        }
      })

      if (latest_cart) {

        latest_cart.any_in_us = any_in_us

        $latestCartHtml = $(
          context._.template(
            $('#template-shopping-cart-header').html(),
            latest_cart,
            {variable: 'data'}
          )
        );
      }

      var sub_total = 0;
      $.each(carts, function(index, cart) {
        sub_total += parseFloat(cart.product_info.real_price);
      });
      data.sub_total = sub_total;

      totalCost = data.sub_total;

      data.carts = carts;
      var $cartsHtml = $(
        context._.template(
          $('#template-shopping-cart-body').html(),
          data,
          {variable: 'data'}
        )
      );

      $content.append($latestCartHtml).append($cartsHtml);

      events();
    }

    function initialize() {
      var screenBindings = {
        'beforeShow': beforeShow,
        'afterShow': afterShow,
        'afterHide' : afterHide
      };
      app.bindScreen('shoppingCart', screenBindings);

      $screen           = $("#shoppingCartScreen");
      $content          = $screen.find(".shopping-cart-content");

      if($screen.length == 0) throw "$screen must be specified";
      if($content.length == 0) throw "$content must be specified";
    }

    this.initialize = initialize;

    return this;
  }
})(window,jQuery);