(function($) {
  $.fn.extend({
    addCart : function(shopCode, commodityCode, skuCode, headerCommercialType) {
      if (skuCode === "") {
        window.alert(i18next.t('commodity:text.サイズを選択してください。'));
        return;
      }
      var form = $("form#add_cart");
      form.find("[name=shopCode]").val(shopCode);
      form.find("[name=commodityCode]").val(commodityCode);
      form.find("[name=skuCode]").val(skuCode);
      form.find("[name=headerCommercialType]").val(headerCommercialType);
      form.submit();
    },
    addFavorite : function(skuCode) {
      if (skuCode === "") {
        window.alert(i18next.t('commodity:text.サイズを選択してください。'));
        return;
      }

      var trigger = this;
      var sizeLabel = $(trigger).attr('data-size-label');
      var janCode = $(trigger).attr('data-jan-code');
      // 二度押し防止
      $(trigger).prop('disabled', true);
      var baseUrl = window.location.href.replace(
          /\/commodity\/.*$/, "/");
      $.ajax(
          {
            url : baseUrl.replace("http:", "https:")
                + "commodity/add-favorite-json",
            dataType : "jsonp",
            data : {
              "skuCode" : skuCode
            },
            timeout : 5000
          })
          .done(
              function(data) {
                $(".fav_result_success").hide();
                $(".fav_result_already").hide();
                $(".fav_result_notlogin").hide();
                $(".fav_result_reload").hide();

                if (data.message === "done") {
                  $(".fav_result_success").fadeIn("fast");
                  $(".sku_" + skuCode + " > .fav > a > *").remove();
                  $(".sku_" + skuCode + " > .fav > a").append($("<span />").attr("class", "fav_already icon-A06-heart").text("お気に入りに登録されています"));
                  $(".sku_" + skuCode + " > .fav > button").removeClass('-not-already').addClass('-already').text(i18next.t('commodity:text.お気に入りに登録されています'));
                  if(typeof clickEvent !== 'undefined') clickEvent.addToWishlist(skuCode, 'view_item', sizeLabel, janCode);
                } else if (data.message === "already") {
                  $(".fav_result_already").fadeIn("fast");
                  $(".sku_" + skuCode + " > .fav > a > *").remove();
                  $(".sku_" + skuCode + " > .fav > a").append($("<span />").attr("class", "fav_regist icon-A07-hert-outline").text("お気に入りに登録する"));
                  $(".sku_" + skuCode + " > .fav > button").removeClass('-already').addClass('-not-already').text(i18next.t('commodity:text.お気に入りに登録する'));
                } else if (data.message === "notlogin") {
                  $(".fav_result_notlogin").find("a").attr("href",
                      baseUrl + "commodity/add-favorite/" + skuCode);
                  $(".fav_result_notlogin").fadeIn("fast");
                } else {
                  $(".fav_result_reload").fadeIn("fast");
                }
              }).fail(
              function() {
                $(".fav_result_reload").fadeIn("fast");
                location.href = baseUrl.replace("http:", "https:")
                    + "commodity/add-favorite/" + skuCode;
              }).always(function() {
                // 二度押し防止解除
                setTimeout(function() {
                  $(trigger).prop('disabled', false);
              }, 1000);
          });
      return false;
    },
    feedback : function(reviewPostId) {
      $(this).attr('disabled', 'disabled');
      $(this).next('span').removeClass('befor_feedback');
      var num = $('#feedback_num_' + reviewPostId).text();
      if (/[0-9]+/.test(num)) $('#feedback_num_' + reviewPostId).text(Number(num) + 1);
      var baseUrl = window.location.href.replace(/\/commodity\/.*$/, "/");
      $.ajax(
          {
            url : baseUrl.replace("http:", "https:") + "commodity/feedback-json",
            dataType : "jsonp",
            data : {
              "reviewPostId" : reviewPostId
            },
            timeout : 5000
          }
      ).done(
          function(data) {
            if (data.message === "done") {
              console.log("numRefs: " + data.numRefs);
            }
          }
      ).fail(
          function() {
            console.log("failed to update numRefs.");
          });
      return false;
    }
  });
})(jQuery);

$(function() {
  $.ajaxSetup({
    cache : false,
    beforeSend : function(xhr) {
      xhr
          .setRequestHeader('If-Modified-Since',
              'Thu, 01 Jun 1970 00:00:00 GMT');
    }
  });

  // Tab Change UI
  $(function tabChangeUI() {
    var $target = $('.list_tab');

    var index = 0;
    var $trigger = $target.find('li');
    var $tabCont = $('.jsTabCont');
    var current = 'current';

    $trigger.eq(0).addClass(current);
    $tabCont.eq(0).addClass(current);

    $trigger.click(function() {
      if (index != $trigger.index(this)) {
          index = $trigger.index(this);

          $trigger.removeClass(current).eq(index).addClass(current);
          $tabCont.removeClass(current).eq(index).addClass(current);

        // Tab Size Select
        if ($tabCont.eq(index).hasClass('tab_area_size')){
          // First Click Only
          var click = $(this).data("click");
          if(!click){
            $(this).data("click", true);
            tableScroll();
          }
        }
      }
      return false;
    });

    // Overflow Table
    var tableScroll = function() {
      var $sizeBlock = $('.block_tbl_size');

      if($sizeBlock.length < 1) {
        return this;
      }

      $sizeBlock.each(function() {
        $tblHead = $(this).find('.unit_tbl_head');
        $tblInner = $(this).find('.unit_tbl_body .inner');
        $tblInnerTable = $tblInner.find('.tbl_detail_01');

        var _width_body = $tblInner.outerWidth();
        var _width_innerTable = $tblInnerTable.outerWidth();
        var _width_scrollMax = _width_innerTable - _width_body;

        // Buyed Item List
        $buyedItemHead = $(this).find('.buyed_items_head');
        $buyedItemBody = $(this).find('.buyed_items_thumb');
        $buyedItemSup = $(this).find('.buyed_items_supplement');

        // Heading Height Set
        var _height_buyedHead = $buyedItemHead.find('th:first-child').outerHeight();
        $buyedItemHead.find('th:first-child').css('height', _height_buyedHead);

        // Supplement Information Cell Height Set
        var $buyedItem = $(this).find('.jsBuyedItem');

        $buyedItem.each(function() {
          if ($(this).hasClass('buyed_items_supplement')) {
            $(this).prev('tr').find('td:first-child').css('height', '55px'); // min-height set
          }
        });

        // Cell Default Height
        $setHeightCell = $tblHead.find('tbody tr:last-child th');
        var _height_tr = $setHeightCell.outerHeight();

        // Overflow On
        if (_width_innerTable > _width_body ) {
          $tblInner.css('overflow-x', 'scroll');
          $tblInner.parent().addClass('isShadow');

          // Set Scroll Bar Height
          var _height_outer = $tblInner.outerHeight();
          var _height_inner = $tblInnerTable.outerHeight();
          var _height_scrollBar = _height_outer - _height_inner;

          if(_height_tr == _height_tr) {
            $setHeightCell.css('height', _height_tr + _height_scrollBar);
          }

          // Scrolling Add Shadow
          $tblInner.bind("scroll", function() {
            $(this).parent().prev().removeClass('isShadow');
            $(this).parent().removeClass('isShadow');

            if ($(this).scrollLeft() > 0) {
              $(this).parent().prev().addClass('isShadow');
            }

            if ($(this).scrollLeft() < _width_scrollMax - 3) {
              $(this).parent().addClass('isShadow');
            }
          });

        // Overflow Off
        } else {
          $tblInner.css('overflow-x', 'hidden');
        }
      });
    };

  });
});
