var normalSearchBox;
var stickySearchBoxVerPc;
var stickySearchBoxVerSp;
var currentSearchBox;
var ymallCartEnabled = false;

const cartDataUrl = '/shop/js/cart.aspx?fmt=data';
const cartDataUrlApp = '/smrt/js/cart.aspx?fmt=data';
const ymallUrl = 'https://ymall.jp/';
const ymallCartUrl = ymallUrl + 'shop/customer/gateway.aspx?ret=L3Nob3AvY2FydC9jYXJ0LmFzcHg%253d&service=sessionl';
const ymallCartUrlApp = ymallUrl + 'smrt/cart/cart.aspx';
const isApp = false;

function getCartDataUrl() {
    return isApp ? cartDataUrlApp : cartDataUrl;
}

function move_mypage() {
    window.location.href = customerMenuUrl;
}

function move_cart() {
    var url = cartUrl;
    if (ymallCartEnabled) {
        url = ymallCartUrl;
        if (isApp) {
            url = ymallCartUrlApp;
        }
    }
    window.location.href = url;
}

function updateFavoriteButtonActive(sku) {
    $('.js-favorite').each(function () {
        if ($(this).attr('data-sku') === sku) {
            if ($(this).hasClass('js-favorite-type-text')) {
                $(this).closest('.overlay-delete').removeClass('is-active');
            } else if ($(this).hasClass('js-favorite-type-icon')) {
                $(this).addClass('is-checked');
                let label = 'お気に入りから削除';
                if ($(this).attr('data-product-detail')) {
                    label = 'お気に入り<br>削除';
                }
                $(this).children('.button-like__label').html(label);
            }
        }
    });
}

function updateFavoriteButtonInactive(sku) {
    $('.js-favorite').each(function () {
        if ($(this).attr('data-sku') === sku) {
            if ($(this).hasClass('js-favorite-type-text')) {
                $(this).closest('.overlay-delete').addClass('is-active');
            } else if ($(this).hasClass('js-favorite-type-icon')) {
                $(this).removeClass('is-checked');
                let label = 'お気に入りに追加';
                if ($(this).attr('data-product-detail')) {
                    label = 'お気に入り<br>追加';
                }
                $(this).children('.button-like__label').html(label);
            }
        }
    });
}

function clickFavoriteText() {
    const sku = $(this).attr('data-sku');
    if ($(this).closest('.overlay-delete').hasClass('is-active')) {
        updateFavoriteButtonActive(sku);
        if ($(this).hasClass('after-reload')) {
            addFavorite(sku, function () {
                setTimeout("window.location.reload()", 500);
            });
        } else if ($(this).hasClass('header-not-reload')) {
            addFavorite(sku, function () {
            });
        } else {
            addFavorite(sku, function () {
                loadHeaderFavorite();
            });
        }
    } else {
        updateFavoriteButtonInactive(sku);
        if ($(this).hasClass('header-not-reload')) {
            removeFavorite(sku, function () {
            });
        } else {
            removeFavorite(sku, function () {
                loadHeaderFavorite();
            });
        }
    }
}

function clickFavoriteIcon() {
    const sku = $(this).attr('data-sku');
    if ($(this).hasClass('is-checked')) {
        updateFavoriteButtonInactive(sku);
        removeFavorite(sku, function () {
            loadHeaderFavorite();
        });
    } else {
        updateFavoriteButtonActive(sku);
        addFavorite(sku, function () {
            loadHeaderFavorite();
        });
    }
}

function addFavorite(sku, callback) {
    if ($(".js-login-user").length == 0) {
        window.location.href = '/ylogin';
    }
    let params = {sku: sku};
    $.ajax({
        type: 'POST',
        url: '/kaden/changewishlist/',
        dataType: 'json',
        data: params
    }).done(function (response) {
        callback();
    });
}

function removeFavorite(sku, callback) {
    let params = {sku: sku, remove: 'remove'};
    $.ajax({
        type: 'POST',
        url: '/kaden/changewishlist/',
        dataType: 'json',
        data: params
    }).done(function (response) {
        callback();
    });
}

function getVisibleSearchBox() {
    const stickyHeader = $('.l-header-sticky').eq(0);
    const spStickyHeader = $('#search-area-sticky-sp');

    if ((stickyHeader.hasClass('is-active'))) {
        if (spStickyHeader.css('display') === 'none') {
            return stickySearchBoxVerPc;
        } else if (spStickyHeader.css('display') !== 'none') {
            return stickySearchBoxVerSp;
        }
    }

    return normalSearchBox;
}

function handleSwitchSearchBoxEvent(e) {
    setTimeout(function () {
        const detectedSearchBox = getVisibleSearchBox();

        if (currentSearchBox !== detectedSearchBox) {
            detectedSearchBox.setSearchWord(currentSearchBox.getSearchWord());
            detectedSearchBox.setCategory(currentSearchBox.getCategory());

            if (detectedSearchBox === normalSearchBox) {
                currentSearchBox.hideSuggestArea();
            }

            currentSearchBox = detectedSearchBox;
        }
    }, 350);
}

function updateMemberPoint() {
    var formatter = new Intl.NumberFormat('ja-JP');
    $.get('/ajax/memberpoint/', function(data) {
        if (data.status == 'ok') {
            $(".total_point").html(formatter.format(data.values.total_point));
            $(".limited_point").html(formatter.format(data.values.limited_point));
        }
    });
}

function loadHeaderFavorite() {
    $("#ajax-header-favorite").load('/ajax/headerwish/', function() {
        $(this).attr('data-loaded', '1');
        $("#ajax-header-favorite-sticky").html($(this).html());
        initItems();
        $('.ajax-header-favorite .js-favorite-type-text').click(clickFavoriteText);
        $(".ajax-header-favorite .js-favorite-type-icon").click(clickFavoriteIcon);
        $(".ajax-header-favorite .js-select-recommend-product").click(sendSelectRecommendProductLog);
    });
}

function loadHeaderFavoriteOnce() {
    if ($("#ajax-header-favorite").attr('data-loaded') == '0') {
        loadHeaderFavorite();
    }
}

function loadHeaderOrderHistory() {
    $("#ajax-header-order-history").load('/ajax/headerorderhistory/', function () {
        $(this).attr('data-loaded', '1');
        $("#ajax-header-order-history-sticky").html($(this).html());
        initItems();
    });
}

function loadHeaderOrderHistoryOnce() {
    if ($("#ajax-header-order-history").attr('data-loaded') == '0') {
        loadHeaderOrderHistory();
    }
}

function loadHeaderCartGoods() {
    $.get(cartgoodsUrl, function(data) {
        var webcomCount = 0;
        var totalCount = 0;
        if (data && data.count) {
            webcomCount = data.count;
        }
        if (typeof ymCartData !== 'undefined' && ymCartData.cnt) {
            totalCount = ymCartData.cnt;
        }

        $(".item-count-in-cart").html(totalCount);

        var ajaxHeaderCartGoods = $("#ajax-header-cart-goods");
        ajaxHeaderCartGoods.find(".spinner-loading").remove();
        if (webcomCount > 0) {
            ajaxHeaderCartGoods.find(".js-product-link").attr('href', '/' + data.sku + '/');
            ajaxHeaderCartGoods.find(".js-product-name").html(data.name);
            ajaxHeaderCartGoods.find(".js-product-img").attr('src', data.img);
            ajaxHeaderCartGoods.find(".js-product-img").attr('alt', data.name);
            if (totalCount > 1) {
                ajaxHeaderCartGoods.find(".js-other-cart-product-count").html(totalCount - 1);
                ajaxHeaderCartGoods.find(".js-other-cart-product").show();
            }
            ajaxHeaderCartGoods.find(".js-header-cart-disable").remove();
            ajaxHeaderCartGoods.find(".js-header-cart-ymall").remove();
            ajaxHeaderCartGoods.find(".js-header-cart-enable").show();
        } else if (totalCount > 0) {
            ajaxHeaderCartGoods.find(".js-header-cart-enable").remove();
            ajaxHeaderCartGoods.find(".js-header-cart-disable").remove();
            ajaxHeaderCartGoods.find(".js-header-cart-ymall").show();
            ymallCartEnabled = true;
        } else {
            ajaxHeaderCartGoods.find(".js-header-cart-enable").remove();
            ajaxHeaderCartGoods.find(".js-header-cart-ymall").remove();
            ajaxHeaderCartGoods.find(".js-header-cart-disable").show();
        }
        $("#ajax-header-cart-goods-sticky").html(ajaxHeaderCartGoods.html());

        initItems();
        $('.js-continue-shopping').on('click', function (e) {
            const element = $(this).closest('.header-info-nav__item');
            element.find('.l-header-overlay').trigger('click');
        });
    });
}

function initItems() {
    YApp.SalesEnd.init();
    YApp.RatingLink.checkCount();
    YApp.LineClamp.init();
    YApp.Swiper.init();
}

function setProductDisplayByStock() {
    if ($('.show_only_stock').prop('checked')) {
        $('.nostock').hide();
    } else {
        $('.nostock').show();
    }
}

$(function () {
    $('.replace-element').each(function () {
        const dupElm = $($(this).attr('data-source-element')).clone(true);
        const replaceId = $(this).attr('data-replace-id');

        if (replaceId) {
            dupElm.attr('id', replaceId);
        }

        $(this).replaceWith(dupElm);
    });

    normalSearchBox = new SearchBox('#search-area');
    stickySearchBoxVerPc = new SearchBox('#search-area-sticky');
    stickySearchBoxVerSp = new SearchBox('#search-area-sticky-sp');
    currentSearchBox = getVisibleSearchBox();

    $(document).on('scroll', handleSwitchSearchBoxEvent);
    $(window).on('resize orientationchange', handleSwitchSearchBoxEvent);

    $('.js-favorite-type-text').click(clickFavoriteText);
    $('.js-favorite-type-icon').click(clickFavoriteIcon);

    $('.show_only_stock').change(function() {
        $('.show_only_stock').prop('checked', $(this).prop('checked'));
        setProductDisplayByStock();
    });
    setProductDisplayByStock();

    $(document).on('click', '.js-add-to-cart', function (e) {
        const sku = $(this).attr('data-sku').trim();
        $("#list_item_cart_form input[name=goods]").val(sku);
        if ($(this).attr('data-quantity')) {
            const quantity = $(this).attr('data-quantity').trim();
            $("#list_item_cart_form input[name=qty]").val(quantity);
        }
        $("#list_item_cart_form").submit();
    });

    $(document).on('click', '.js-product-detail,.js-product-detail--newtab', function (e) {
        const sku = $(this).attr('data-sku').trim();
        const word = $(this).attr('data-word').trim();
        const qtyInput = $(this).parent().find('.qty-input');
        let url = '/' + sku + '/';
        if (qtyInput.length) {
            url += '?qty=' + qtyInput.val();
            if (word !== '') {
                url += '&q=' + encodeURIComponent(word);
            }
        } else {
            if (word !== '') {
                url += '?q=' + encodeURIComponent(word);
            }
        }

        if ($(this).hasClass('js-product-detail--newtab')) {
            window.open(url, '_blank');
        } else {
            location.href = url;
        }
    });

    const bigCategories = $('.js-header-category-nav__source').eq(0).find('.header-category-nav__first-lv-item');
    const spCategoryTemplate = $('nav.header-category-nav-sp .header-category-nav-sp__template').children().eq(0);

    bigCategories.each(function () {
        const bigCategoryName = $(this).find('.header-category-nav__title > a').text();
        const bigCategoryHref = $(this).find('.header-category-nav__title > a').attr('href');
        const middleCategories = $(this).find('.header-category-nav__second-lv-item');
        const category = spCategoryTemplate.clone(true)

        category.find('.js-header-category-nav-sp__big-category').text(bigCategoryName);
        category.find('.js-header-category-nav-sp__big-category-title > a').text(bigCategoryName).attr('href', bigCategoryHref);

        middleCategories.each(function () {

            const middleCategoryName = $(this).find('a').text();
            const middleCategoryUrl = $(this).find('a').attr('href');
            const middleCategoryLink = $('<a></a>').attr('href', middleCategoryUrl).text(middleCategoryName);
            const middleCategory = $('<div></div>').addClass('header-category-nav-sp__item').append(middleCategoryLink)

            category.find('.header-category-nav-sp__list').append(middleCategory);
        });

        $('nav.header-category-nav-sp .js-header-category-nav-sp__deploy-area').append(category);
    });

    Drilldown.spNavInit();

    $(".ajax-header-favorite-button").click(loadHeaderFavoriteOnce);
    $(".ajax-header-order-history-button").click(loadHeaderOrderHistoryOnce);

    updateMemberPoint();
    $.getScript(getCartDataUrl())
        .always(function() {
            loadHeaderCartGoods();
        });
});
