(function ($, Drupal, window, document, undefined) {

  Drupal.behaviors.catalog_pubs = {
    attach: function (context) {

      function clearShoppingCart() {
        $("#publication-shopping-cart").html("");
        localStorage.removeItem("publication-shopping-cart");
        localStorage.removeItem("publication-shopping-cart-token");
      }


      function updateCart(sku, count) {
        if (count == null) {
          count = 0;
        }
        var publication_items = localStorage.getItem("publication-shopping-cart");
        if (publication_items == null) {
          publication_items = {};

        }
        else {
          publication_items = JSON.parse(publication_items);
        }

        var imge_src = $('#publication-add-to-cart-' + sku).parents('article.node--type-nhlbi-publication').find('.field--name-field-hero-image > a > .image-style-freeform-crop').attr('src');
        var title = $('#publication-add-to-cart-' + sku).parents('article.node--type-nhlbi-publication').attr('data-title');
        if(title === undefined) {
          title = $('#publication-add-to-cart-' + sku).parents('article.node--type-nhlbi-publication').find('.publicationTitle a').attr('data-title');
        }
        var total_count = $("#publication-select-count-" + sku + " option").length;
        var prev_count = 0
        if (typeof publication_items[sku] !== "undefined") {
          prev_count = publication_items[sku].count;
        }

        publication_items[sku] = {}

        publication_items[sku].src = imge_src;
        publication_items[sku].sku = sku;
        publication_items[sku].title = title;
        publication_items[sku].total_count = total_count;
        var new_count = parseInt(prev_count) + parseInt(count);
        if (new_count > parseInt(total_count)) {
          new_count = parseInt(total_count);
        }
        publication_items[sku].count = new_count;

        localStorage.setItem("publication-shopping-cart", JSON.stringify(publication_items));
        showNavBarCart(sku);
      }


      function showNavBarCart(current_pub_sku = null) {
        var publication_items = localStorage.getItem("publication-shopping-cart");
        if (publication_items != null) {
          publication_items = JSON.parse(publication_items);

          var publength = Object.keys(publication_items).length;

          if (publength > 0) {
            var cart_display_total_count = 0;

            $.each(publication_items, function (key, val) {
              cart_display_total_count = parseInt(cart_display_total_count) + parseInt(publication_items[key].count);
            });

            $("#publication-shopping-cart").html('<div id="nav-bar-cart"><p>View Shopping Cart</p><div class="items-count"><span>'
              + cart_display_total_count + '</span></div></div>');


            // Update selected item on cart.
            if (current_pub_sku != null) {
              if (publication_items[current_pub_sku] != null) {
                // reverted code to not default count to added cart.
                $('#publication-select-count-' + current_pub_sku).val(1);


                var index_disable = publication_items[current_pub_sku].total_count - publication_items[current_pub_sku].count
                var i;
                for (i = 0; i <= publication_items[current_pub_sku].total_count; i++) {
                  if (i > index_disable) {
                    $('#publication-select-count-' + current_pub_sku + ' option[value="' + i + '"]').attr('disabled', 'disabled');
                  }
                }
              }

            }
          }
          else {
            $("#publication-shopping-cart").html("");
            //$('#publication-select-count option').removeAttribute('disabled');
          }


        }
        else {
          $("#publication-shopping-cart").html("");
          // $('#publication-select-count option').removeAttribute('disabled');
        }


      }

      function showOnboardingMessage() {
        var onboarding_clicked = localStorage.getItem("publication-onboarding-clicked");
        if (onboarding_clicked != "1" || onboarding_clicked == null) {
          $("#landing-page-onboarding-text").appendTo(".views-element-container .nhlbi-searchbar");
          $("#landing-page-onboarding-text").show();
        }

      }


      function createCartModal(event) {
        event.preventDefault();
        $('#cart-container-wrapper-lightbox').html("");
        var cart_modal_string = '<div id="cart-dialog-container">';
        cart_modal_string += createCartDialogHTML();
        cart_modal_string += '</div>';

        $('#cart-container-wrapper-lightbox').html(cart_modal_string);
        $('#cart-container-wrapper-lightbox').show();
      }


      function createCartDialogHTML(count) {
        var publication_items = localStorage.getItem("publication-shopping-cart");
        var cart_html = '<div class="cart-dialog">';
        $('body').addClass('mobile-dialog-active');
        cart_html += '<h1>Publications Cart<span class="cart-dialog-close-button">x</span></h1><h1 id="publication-cart-mobile">Cart Summary:<span class="cart-dialog-close-button">x</span></h1>';


        publication_items = JSON.parse(publication_items);
        var pubs_empty = true;
        var tt_count = $("#nav-bar-cart div span").text();
        for (publication in publication_items) {
          var item_select_html = createPubsSelectList(publication_items[publication].sku,
            publication_items[publication].count,
            publication_items[publication].total_count);

          cart_html += '<div class="dialog-cart-item">';
          cart_html += '<div class="dialog-image-wrapper"><img alt="' + publication_items[publication].title + '" src="' + publication_items[publication].src + '"></div>';
          cart_html += '<div class="title-select"><div class="dialog-item-title">' + publication_items[publication].title + '</div>';
          cart_html += '<div class="dialog-item-total">Copy limit:' + publication_items[publication].total_count + '</div>';
          cart_html += '<div class="dialog-item-select">' + item_select_html + '<a class="delete-item" data-sku-id="' + publication_items[publication].sku + '">Remove</a>' +
            '<div class="confirm-dialog">Are you sure?<a data-sku-id="' + publication_items[publication].sku + '" class="confirm-delete">Yes </a> /' +
            '<a class="cancel-delete">No</a></div></div></div>';
          cart_html += '</div>';

          pubs_empty = false;
        }
        if (pubs_empty) {
          cart_html += '<div class="cart-empty-message"><i>Your cart is empty.</i></div>';
        }
        cart_html += '<div class="cart-dialog-actions">';

        if (!pubs_empty) {

          cart_html += '<div class="total-cart-items"><span>Total Items: ' + tt_count + '</span></div><div class="dialog-action-wrapper"><div id="cart-proceed-to-checkout" data-action="Proceed to checkout">Proceed to checkout</div>';

        }
        cart_html += '<div id="cart-keep-browsing" data-action="Keep browsing">Continue Browsing</div></div></div>';
        cart_html += '</div>';
        return cart_html;
      }

      function createPubsSelectList(sku, count, total_count) {

        var index = 1;
        var qty_text = "Qty: "
        var select_html = '<select id="cart-dialog-select-' + sku + '" class="cart-dialog-select" data-sku-id="' + sku + '">';
        while (index <= total_count) {
          if (index == count) {
            select_html += '<option value="' + index + '" selected>' + qty_text + ' ' + index + '</option>';
          }
          else {
            select_html += '<option value="' + index + '">' + qty_text + ' ' + index + '</option>';
          }
          index = index + 1;
        }
        select_html += '</select>';
        return select_html;
      }

      function submitForm(action, method, values) {
        var form = $('<form/>', {
          action: action,
          method: method
        });
        $.each(values, function () {
          form.append($('<input/>', {
            type: 'hidden',
            name: this.name,
            value: this.value
          }));
        });
        form.append($('<input/>', {
          type: 'submit',
          value: 'Checkout'
        }));
        form.appendTo('body').submit();
      }

      function getParameters() {
        var searchString = window.location.search.substring(1),
          params = searchString.split("&"),
          hash = {};

        if (searchString == "") {
          return {};
        }
        for (var i = 0; i < params.length; i++) {
          var val = params[i].split("=");
          hash[unescape(val[0])] = unescape(val[1]);
        }

        return hash;
      }

      $(document).on('click', '#nav-bar-cart', function (event) {
        event.preventDefault();

        createCartModal(event);
      });

      $(document).on('click', '.cart-dialog-close-button, #cart-keep-browsing', function (event) {

        var publication_items = localStorage.getItem("publication-shopping-cart");
        publication_items = JSON.parse(publication_items);
        $('body').removeClass('mobile-dialog-active');

        var index = 0;
        $(".dialog-item-select").each(function (index) {
          var count = $(this).find("select").val();
          var sku = $(this).find("a").data("sku-id");
          publication_items[sku].count = count;

          index = index + 1;
        });

        localStorage.setItem("publication-shopping-cart", JSON.stringify(publication_items));

        $('#cart-container-wrapper-lightbox').hide();
        $('#cart-container-wrapper-lightbox').html("");
        showNavBarCart();

        // update page cart..
      });

      $(document).on('click', '.dialog-item-select a.delete-item', function (event) {

        $(this).parent().find(".confirm-dialog").show();
        $(this).parent().find(".confirm-dialog").css('display', 'inline-block');
        $(this).hide();

      });

      $(document).on('click', '.dialog-item-select a.confirm-delete', function (event) {

        var publication_items = localStorage.getItem("publication-shopping-cart");
        publication_items = JSON.parse(publication_items);
        var current_pub_sku = $(this).data("sku-id");
        var removed_count = parseInt(publication_items[$(this).data("sku-id")].count);
        var old_count = parseInt($("#nav-bar-cart div span").text());
        var new_count = old_count - removed_count;

        delete publication_items[$(this).data("sku-id")];
        localStorage.setItem("publication-shopping-cart", JSON.stringify(publication_items));
        if (Object.keys(publication_items).length > 0) {
          $(this).closest(".dialog-cart-item").html('<div class="item-delete-message"><i>Item Successfully Deleted.</i></div>');
          $('.total-cart-items > span').text('Total Items: ' + new_count);
          $("#nav-bar-cart div span").text(new_count);
        }
        else {
          createCartModal(event);
        }
        showNavBarCart();

        if (current_pub_sku != null) {
          if (publication_items[current_pub_sku] == null) {
            $('#publication-select-count-' + current_pub_sku + ' option').removeAttr('disabled');
            $('#publication-select-count-' + current_pub_sku + ' option').removeAttr("selected");
          }
        }

      });

      $(document).on('click', '.dialog-item-select a.cancel-delete', function (event){
        createCartModal(event);
        showNavBarCart();
      });
        // $(document).once('cart-qty-change').on('change', '.cart-dialog-select', function (event) {
      $(once('cart-qty-change', 'body', context)).each(function () {
        $(this).on('change', '.cart-dialog-select', function (event) {
          var current_pub_sku = $(this).data("sku-id");
          var publication_items = localStorage.getItem("publication-shopping-cart");
          publication_items = JSON.parse(publication_items);
          publication_items[current_pub_sku].count = $(this).val();

          var cart_display_total_count = 0;
          $.each(publication_items, function (key, val) {
            cart_display_total_count = cart_display_total_count + parseInt(publication_items[key].count);
          });
          localStorage.setItem("publication-shopping-cart", JSON.stringify(publication_items));
          $('.total-cart-items > span').text('Total Items: ' + cart_display_total_count);
          $("#nav-bar-cart div span").text(cart_display_total_count);
        });
      });

      $(once('nhlbi-auto-submit', 'body', context)).each(function (context) {
        $(this).on('click', "[data-action='Add to cart']", function (e) {
          var sku = $(this).data("sku-id");
          var count = $("#publication-select-count-" + sku).val();
          updateCart(sku, count);

          createCartModal(e);
          e.preventDefault();
        });
      });


      $("#need-more-copies").click(function (event) {
        $(".order-more-dialog-wrapper").show();
      });

      $(document).on('click', '.order-more-got-it, .order-dialog-close-button', function (event) {
        $('.order-more-dialog-wrapper').hide();
      });


      $(document).on("click", ".dismiss-button a", function (e) {
        localStorage.setItem("publication-onboarding-clicked", 1);
        $("#landing-page-onboarding-text").hide();

      });


      $(document).on("click", "#cart-proceed-to-checkout", function (e) {


        var publication_items_post = [{}];
        var publication_items = localStorage.getItem("publication-shopping-cart");
        publication_items = JSON.parse(publication_items);

        var index = 0;
        $(".dialog-item-select").each(function (index) {
          //update_json_string = update_json_string +
          var count = $(this).find("select").val();
          var sku = $(this).find("a").data("sku-id");
          publication_items_post[index] = {
            'sku': sku,
            'quantity': count
          };
          publication_items[sku].count = count;

          index = index + 1;
        });

        localStorage.setItem("publication-shopping-cart", JSON.stringify(publication_items));


        $.get("/nhlbi_catalog_pubs/checkout?" + Math.random(), function (data) {

          var token = data[0];
          localStorage.setItem("publication-shopping-cart-token", token);
          $("#publication-checkout input[name='orderId']").val(Math.random());
          // Create the token input if it doesn't exist.
          if ($("#publication-checkout input[name='token']").length == 0) {
            $('#publication-checkout').prepend('<input type="hidden" name="token" value="">');
          }
          $("#publication-checkout input[name='token']").val(data[0]);
          $("#publication-checkout input[name='payload']").val(JSON.stringify(publication_items_post));
          $("#publication-checkout").submit();


        });


        e.preventDefault();
      });

      var token = localStorage.getItem("publication-shopping-cart-token");

      //
      if (token != null) {

        $.get("/api/publications/order_expired?token=" + token + "&" + Math.random(), function (data) {

          var order_expired = data;

          if (order_expired) {
            clearShoppingCart();
          }
          else {
            showNavBarCart();
          }

        });


      }
      else {
        showNavBarCart();
      }


      showOnboardingMessage();
    }
  }

})(jQuery, Drupal, this, this.document);