var upwardsLocked = false
// JQ 功能擴增
$.fn.triggerAll = function(list) {
    return this.each(function() {
        const $this = $(this)
        $.each(list.split(' '), function(key, val) {
            $this.trigger(val)
        })
    })
}
window.alert = function(message, fadeOut = true){
    genePopup({
        cls:'theme-alert theme-narrow',
        content: message
    }, fadeOut)
}
/**
 *
 * @param {object} data
 * @param {string} [data.cls] 額外class
 * @param {string} [data.title] 標題
 * @param {string} [data.content] 內容
 * @param {*} alert
 */
function genePopup(data, fadeOut=false){
    //產生彈窗
    //throw new Error("中斷")
    let popup = $(`
        
    `)
    $("body").append(popup)
    if(fadeOut){
        setTimeout(function(){
            popup.fadeOut(500, function(){
                popup.trigger("popupClose")
                $(this).remove()
            })
        }, 2000)
    }
}
// 裝置判斷
function DeviceIsTouch() {
    const userAgent = navigator.userAgent
    const regexp = /Android|iPhone|SymbianOS|Windows Phone|iPad|iPod|Touch|Mobile|Tablet|BlackBerry/gi
    return !!userAgent.match(regexp)
}
$(window).on('pageshow.check', function(e){
    //更新購物車數量&框
    function checkProduct(){
        if(e.originalEvent.persisted || (performance.getEntriesByType("navigation")[0] && performance.getEntriesByType("navigation")[0].type === "back_forward")){
            let amountBox = $(".quick-product-amount")
            if(amountBox.length){
                $(".common-loading").removeClass("hide")
                window.location.reload()
            }else{
                updateCartTotal()
            }
        }
    }
    //接收非主站alert
    let alertText = sessionStorage.getItem("backAlert")
    let alertTextFadeout = sessionStorage.getItem("backAlertFadeout")
    if(alertText){
        alert(alertText)
        sessionStorage.removeItem("backAlert")
    }
    if(alertTextFadeout){
        alert(alertTextFadeout, true)
        sessionStorage.removeItem("backAlertFadeout")
    }
    if(alertText || alertTextFadeout){
        $(document).one("popupClose", ".popupBox-wrapper.theme-alert", function(){
            checkProduct()
        })
    }else{
        checkProduct()
    }
})
// resize 裝置判斷
;(function($) {
    $(window).on('resize', function(e) {
        if(DeviceIsTouch()) {
            $('body').removeClass('DeviceWithHover')
        } else {
            $('body').addClass('DeviceWithHover')
        }
    })
})($)
//定義css變數 --vh 避免行動裝置vh計算異常(會被瀏覽器address bar影響)
$(function(){
    function setVh(){
        $('html').attr('style', `--vh: ${window.innerHeight * 0.01}px;`)
    }
    setVh()
    $(window).on('resize', setVh)
})
// 天邊跑馬燈設定
;(function($) {
    const marqueeTarget = $(".top-marquee")
    if(marqueeTarget.length && marqueeTarget.children('.marquee-item').length > 1) {
        marqueeTarget.owlCarousel({
            items: 1,
            nav: false,
            dots: false,
            autoplay: true,
            autoplayTimeout: 5000,
            autoplaySpeed: 1000,
            autoplayHoverPause: true,
            animateIn: 'theme-in',
            animateOut: 'theme-out',
            mouseDrag: false,
            loop: true,
        });
    }
    //跑馬燈倒數模式
    if($('.top-marquee .countdown-box').length) {
        $('.top-marquee .countdown-box').each(function(){
            countDown($(this))
        })
    }
    function leadingZero(number) {
        const num = parseInt(number)
        if(!isNaN(num)) {
            if(Math.abs(num) < 10) {
                return "0" + Math.abs(num)
            } else {
                return String(Math.abs(num))
            }
        } else {
            console.error('輸入格式錯誤')
        }
    }
    function countdownBox(number, string = null) {
        const numberStr = leadingZero(number)
        let returnStr = '' + numberStr + '
'
        if(string) {
            return returnStr + '' + string + '
'
        } else {
            return returnStr
        }
    }
    function countDown(target) {
        const leftTime = target.attr('data-second')
        if(leftTime > 0) {
            const leftSec = leftTime % 60
            const leftMin = Math.floor(leftTime / 60) % 60
            const leftHour = Math.floor(leftTime / 60 / 60) % 24
            const leftDate = Math.floor(leftTime / 60 / 60 / 24)
            if(leftDate > 0) {
                target.html(`
                    ${countdownBox(leftDate, _jsLang.天)}
                    ${countdownBox(leftHour, _jsLang.時)}
                    ${countdownBox(leftMin, _jsLang.分)}
                    ${countdownBox(leftSec, _jsLang.秒)}
                `)
            } else {
                target.html(`
                    ${countdownBox(leftHour, _jsLang.時)}
                    ${countdownBox(leftMin, _jsLang.分)}
                    ${countdownBox(leftSec, _jsLang.秒)}
                `)
            }
            target.attr('data-second', leftTime - 1)
            setTimeout(countDown, 1000, target)
        }
        else
        {
            $(".top-marquee").hide();
            $("body").addClass("no-marquee")
        }
    }
})($)
// 螢幕滾動
;(function($) {
    let lastScrolltop = 0
    $(window).on('scroll', function(e) {
        let currentScrolltop = $(this).scrollTop()
        //console.log(currentScrolltop)
        if(currentScrolltop > 0){
            $('.gotop').fadeIn(400)
            $("body").addClass('is-sticky');
        }else{
            $('.gotop').fadeOut(400)
            $("body").removeClass('is-sticky');
        }
        if(currentScrolltop > lastScrolltop){
            $("body").removeClass('is-upwards');
        }else{
            $("body").addClass('is-upwards');
        }
        lastScrolltop = currentScrolltop
    })
})($)
// 主選單
;(function($) {
    let navbarStep =  ''
    //避免在中間重新整理時menu高度異常
    $(window).on('resize', function(e) {
        if($(this).width() >= 1200 && navbarStep !== "desktop") {
            navbarStep = "desktop"
            $('body').removeClass('menu-open overflow-hidden');
            $('body').off('click', '.navbar-toggle')
            $('.navbar-main').off('click', '.main-menu .navbar-arrow')
                             .find('.with-children').removeClass('in-active')
            $('.navbar-wrapper').off('click.closemenu')
        } else if($(this).width() < 1200 && navbarStep !== "mobile") {
            navbarStep = "mobile"
            $('body').on('click', '.navbar-toggle', function(e) {
                e.preventDefault()
                $('body').toggleClass('menu-open overflow-hidden');
                $('.aside-panel, .function-item').removeClass('in-active');
            })
            $('.navbar-main').on('click', '.main-menu .navbar-arrow', function(e) {
                $(this).closest('.with-children').toggleClass('in-active')
                       .siblings('.with-children').removeClass('in-active')
            })
            $('.navbar-wrapper').on('click.closemenu', function(e){
                if($(e.target).hasClass("navbar-wrapper")){
                    $('body').removeClass('menu-open overflow-hidden');
                    $('.aside-panel, .function-item').removeClass('in-active');
                }
            })
        }
    })
})($)
// gotop
;(function($) {
    $('.gotop').on('click', function(e){
        e.preventDefault()
        $("html, body").animate({scrollTop: 0},800);
    });
})($)
// ==========================================================
//  owl carousel 樣式校正
// ==========================================================
;(function($) {
    function dotsCheck(jqElement) {
        const thisTarget = jqElement
        const checkTarget = thisTarget.find('.owl-dots')
        if(!checkTarget.hasClass('disabled')) {
            thisTarget.addClass('with-dots')
        } else {
            thisTarget.removeClass('with-dots')
        }
    }
    $('body').on('refreshed.owl.carousel', '.owl-carousel.with-dots', function(e) {
        dotsCheck($(this))
    })
})($)
// ==========================================================
//  footer menu toggle
// ==========================================================
;(function($, jQuery, window, document) {
    let footerMenuStep = '';
    $(window).on('resize', function(e) {
        if($(this).width() >= 1200 && footerMenuStep !== 'desktop') {
            footerMenuStep = 'desktop'
            $('.footer-menu').off('click', '.menu-title').find('.menu-item').removeClass('in-active')
        } else if($(this).width() < 1200 && footerMenuStep !== 'mobile') {
            footerMenuStep = 'mobile'
            $('.footer-menu').on('click', '.menu-title', function(e) {
                e.preventDefault()
                $(this).parent('.menu-item').toggleClass('in-active')
                       .siblings('.menu-item').removeClass('in-active')
            })
        }
    })
})($, jQuery, window, document)
// ==========================================================
//  通用跳窗功能
// ==========================================================
;(function($) {
    $(document).on("click", ".popup-trigger", function(){
        let _this = $(this)
        let target = _this.data("target")
        $(".popupBox-wrapper[data-index=" + target + "]").removeClass("hide")
    })
    $('body').on('click', '.popupBox-wrapper:not(.close-disabled)', function(e) {
        let popup = $(this)
        if(e.currentTarget === e.target || $(e.target).hasClass('closer') || $(e.target).parent().hasClass('closer') || $(e.target).hasClass('js-popupBox-closer')) {
            e.preventDefault()
            popup.trigger("popupClose")
            if($(e.target).closest(".popupBox-wrapper").hasClass("popupBox-constant")){
                $(e.target).closest(".popupBox-wrapper").addClass("hide")
            }else{
                PopupCloseAnimate($(e.currentTarget))
            }
        }
    })
})($)
// ==========================================================
//  再買一次
// ==========================================================
;(function($) {
    //再買一次
    $(document).on("click",".Order_Again",function(){
        const order_num = $(this).data("order");
        $.ajax({
            url:Project_Country+"member/ajax/ajax_order_again.php",
            type:"POST",
            data:{order_num:order_num,},
            dataType:'json',
            error:function(d){
                alert('網路連線過慢,網頁請重新整理');
            },
            success:function(d)
            {
                if(d.status != 'ok')
                {
                    alert(d.msg);
                }
                else
                {
                    alert(d.msg);
                    if(d.dataLayer)eval(d.dataLayer);
                    window.location.href = d.url;
                }
            }
        });
    });
})($)
// 列表更多資訊開關
;(function($) {
    $('main').on('click', '.toggle-expand', function(e) {
        //e.preventDefault();
        if(!$(e.target).closest(".toggle-pass").length > 0){
            let parent = $(this).closest('.table-row')
            if(parent.hasClass("in-expand")){
                $(".table-row").removeClass('in-expand')
            }else{
                $(".table-row").removeClass('in-expand')
                parent.addClass('in-expand')
                parent.prev(".table-row-normal").addClass('in-expand')
                parent.next(".table-notebook").addClass('in-expand')
            }
        }
    })
})($)
// ==========================================================
//  側欄選單開關
// ==========================================================
;(function($) {
    /*$('.aside-panel').on('click', 'a', function(e) {
        if($(this).parent().hasClass('with-children')) {
            e.preventDefault()
            $(this).parent('.with-children').toggleClass('in-active')
                   .siblings('.with-children').removeClass('in-active')
        }
    })*/
    $(document).on("click", ".panel-head:not(.no-toggle)", function(){
        $(this).toggleClass("in-collapse")
    })
    $(document).on("click", ".fixed-aside", function(e){
        let _this = $(this)
        if($(e.target).hasClass("fixed-aside")){
            _this.find(".close").click()
        }
    })
    $('.menu-switch').on('click', function(e){
        e.preventDefault()
        $(this).parents('.with-children').eq(0).toggleClass('in-active')
               .siblings('.with-children').removeClass('in-active')
    })
    $('.aside-panel').on('click', '.collapse-title', function(e) {
        e.preventDefault()
        $(this).parent('.item').toggleClass('in-active')
               //.siblings('.item').removeClass('in-active')
    })
})($)
// ==========================================================
//  header功能開關
// ==========================================================
;(function($) {
    $(document).on("click", ".func-link", function(e){
        let _this = $(this)
        let item = _this.closest(".func-item")
        if(item.length > 0){
            if(item.hasClass("in-open")){
                item.removeClass("in-open")
                $(document).off("click.closeFunc")
            }else{
                $(".func-item").removeClass("in-open")
                item.addClass("in-open")
                $(".header-wrapper").addClass("in-func-open")
                $(document).on("click.closeFunc", function(e){
                    if(!$(e.target).closest(".func-item").length){
                        $(".func-item").removeClass("in-open")
                        $(".header-wrapper").removeClass("in-func-open")
                        $(document).off("click.closeFunc")
                    }
                })
            }
        }
    })
})($)
// ==========================================================
//  footer 訂閱電子報功能
// ==========================================================
;(function($) {
    if($('#EpaperForm').length) {
        $("body").on('submit', '#EpaperForm', function(e){
            e.preventDefault()
            const enter_str = check_tools.checkEmailNull($("#Epaper_Email"));
            if( enter_str == "NULL" ){
                alert(_jsLang.請輸入Email);
                return false;
            }else if( enter_str == "ERROR" ){
                alert(_jsLang.您輸入的Email格式錯誤);
                return false;
            }else if( enter_str == "PASS" ){
                $.ajax({
                    url: Project_Country + 'include/ajax/ajax_epaper-p.php',
                    type: 'POST',
                    dataType: 'JSON',
                    data: {
                        Epaper_Email: $("#Epaper_Email").val()
                    },
                })
                .done(function(res) {
                    const status = res.status
                    if(status === "ORDER") {
                        alert(_jsLang.訂閱電子報成功);
                    } else if (status === "CANCEL") {
                        alert(_jsLang.取消訂閱電子報成功);
                    } else if (status === "Usable") {
                        alert(_jsLang.訂閱電子報成功優惠券序號已寄送至您的信箱);
                    } else if(status === "ERROR") {
                        alert(_jsLang.取消訂閱電子報失敗);
                    }
                })
                .fail(function(x, y, z) {
                    console.log(x);
                })
                .always(function() {
                    $("#Epaper_Email").val('');
                });
            }
        });
    }
})($)
// ==========================================================
//  購物車簡易浮動跳窗
// ==========================================================
function FloatShopcart(res) {
    const returnDOM = `
        
            ${res}
        
    `
    return returnDOM
}
;(function($) {
    const shopcartTarget = $('#Shop_Cart_Total')
    let CanShowShopcart = true
    function getTopCart(type = '1'){
        if(CanShowShopcart) {
            CanShowShopcart = false
            $.ajax({
                url: Project_Country + "ajax/ajax_get_cart.php",
                data:{
                    Cart_Type : type
                },
                type: 'POST',
                dataType: 'HTML',
            })
            .done(function(res) {
                if(res){
                    if(shopcartTarget.find(".float-shopcart").length > 0){
                        shopcartTarget.find(".float-shopcart").empty().html(res)
                    }else{
                        shopcartTarget.append(FloatShopcart(res))
                    }
                }else{
                    shopcartTarget.children('.float-shopcart').remove()
                }
            })
            .fail(function(x, y, z) {
                console.log(x);
            })
            .always(function() {
                CanShowShopcart = true
            });
        }
    }
    let enterFlag = false
    shopcartTarget.on('mouseenter', function(e) {
        if(!enterFlag){
            enterFlag = true
            getTopCart()
        }
    }).on('mouseleave', function(e) {
        //shopcartTarget.children('.float-shopcart').remove()
        enterFlag = false
    })
    $(document).on("click", ".float-shopcart .switch-btn", function(){
        getTopCart($(this).data("type"))
    })
    // 浮動窗中商品刪除
    $('body').on('click', '.Left_Top_Del', function(e) {
        e.preventDefault()
        // if(confirm(_jsLang.確定刪除嗎+"?")){
            $.ajax({
                url: Project_Country + "shopcart/ajax/ajax_cart_del.php",
                type:"POST",
                cache:false,
                dataType:'json',
                data:{ID:$(this).attr("sid"),Type:$(this).data("type"),GroupID: $(this).data("group_id")},
            }).done(function(d){
                if(d.Status == 'RET_SUCCESS'){
                    // alert(_jsLang.刪除成功);
                    //window.location.reload();
                    getTopCart($(".switch-btn.in-active").data("type"))
                    if (d.DataLayer) { eval(d.DataLayer) }
                    //更新列表數量
                    for(var sid in d.totals)
                    {
                        //列表
                        let box = $(".quick-product-amount[cartUpdateSid='"+sid+"']");
                        let amount = d.totals[sid];
                        updateAmountBox(box, d.totals[sid]);
                        box.find(".quick-input").val(amount).data("before-change", amount);
                        box.find(".quick-current").html(amount);
                        //詳細
                        $(".amountBox[cartUpdateSid='"+sid+"']").val(amount);
                        $(".amountBox[cartUpdateSid='"+sid+"']").data("before-change", amount);
                    }
                    if(typeof updatePage === 'function'){
                        updatePage();
                    }else if(typeof updateCartTotal === 'function'){
                        updateCartTotal();
                    }
                }else{
                    alert(_jsLang.資料庫忙線中);
                }
            }).fail(function(d){
                alert('網路連線過慢,網頁請重新整理');
            })
        // }
    })
    //活動摺疊
    $(document).on("click", ".float-shopcart .view-all-btn", function(){
        $(".float-shopcart .total-sale-wrapper").toggleClass("in-collapse")
    })
    $(document).on("click", ".common-amount-btn", function(){
        let _this = $(this)
        let box = _this.parents(".common-amount-box")
        let input = box.find(".common-amount-input")
        let plus = box.find(".common-amount-plus")
        let minus = box.find(".common-amount-minus")
        let min = parseInt(input.attr("min"))
        let max = parseInt(input.attr("max"))
        let val = parseInt(input.val())
        if(_this.hasClass("common-amount-plus")){
            if(val < max){
                input.val(val + 1)
                input.trigger("change")
            }
        }else{
            if(val > min){
                input.val(val - 1)
                input.trigger("change")
            }
        }
        if(parseInt(input.val()) == min){
            minus.addClass("in-disabled")
        }else{
            minus.removeClass("in-disabled")
        }
        if(parseInt(input.val()) == max){
            plus.addClass("in-disabled")
        }else{
            plus.removeClass("in-disabled")
        }
    })
    $(document).on("change", ".common-amount-input", function(){
        let input = $(this)
        let box = input.parents(".common-amount-box")
        let plus = box.find(".common-amount-plus")
        let minus = box.find(".common-amount-minus")
        let min = parseInt(input.attr("min"))
        let max = parseInt(input.attr("max"))
        let val = parseInt(input.val())
        input.addClass("in-forzen")
        input.siblings("button").addClass("in-forzen")
        if(!val){
            input.val(min)
        }
        if(val > max){
            input.val(max)
            alert((_jsLang['最多可購買數量'] ??'最多可購買數量') + max)
        }
        if(val < min){
            input.val(min)
        }
        if(parseInt(input.val()) == min){
            minus.addClass("in-disabled")
        }else{
            minus.removeClass("in-disabled")
        }
        if(parseInt(input.val()) == max){
            plus.addClass("in-disabled")
        }else{
            plus.removeClass("in-disabled")
        }
        box.trigger("amountChange")
    })
    let updateTimerFloat = null
    $(document).on("amountChange", ".float-shopcart .cart-amount-box", function(){
        clearTimeout(updateTimerFloat)
        let input = $(this).find(".common-amount-input")
        updateTimerFloat = setTimeout(function(){
            updateCartAmount(input, $.extend({}, $(this).data(), {
                sid:input.attr("sid"),
                prodType:input.attr("prodType"),
                type:input.attr("addType") || 'normal',
                value: input.val(),
            }), function(){
                getTopCart($(".switch-btn.in-active").data("type"))
            })
        },500)
    })
    $(document).on("input", ".quick-input", function(){
        let val = this.value.replace(/\D/g,'')
        this.value = val //? parseInt(val, 10) : (parseInt(originVal) ?? 0)
        //console.log($(this).val())
        //console.log($(this).data("before-change"))
    })
    //快速數量加減(連動購物車)
    $(document).on("click", ".quick-product-amount .quick-btn", function(){
        let _this = $(this)
        let box = _this.parents(".quick-product-amount")
        let input = box.find(".quick-input")
        let plus = box.find(".quick-plus")
        let minus = box.find(".quick-minus")
        let min = parseInt(input.attr("min"))
        let max = parseInt(input.attr("max"))
        let val = parseInt(input.val())
        if(_this.hasClass("quick-plus")){
            if(val < max){
                input.val(val + 1)
                input.trigger("change")
            }else{
                let msg = (_jsLang['最多可購買數量'] ??'最多可購買數量') + max;
                if(input.data("one-page-msg"))
                {
                    msg = input.data("one-page-msg");
                }
                alert(msg)
            }
        }else{
            if(val > min){
                input.val(val - 1)
                input.trigger("change")
            }
        }
        // if(parseInt(input.val()) == 0){
        //     //連動後會移除商品
        //     input.trigger("change")
        // }
        if(parseInt(input.val()) == max){
            plus.addClass("in-disabled")
        }else{
            plus.removeClass("in-disabled")
        }
    })
    $(document).on("change", ".quick-input", function(e){
        let input = $(this)
        let box = input.parents(".quick-product-amount")
        let plus = box.find(".quick-plus")
        let minus = box.find(".quick-minus")
        let min = parseInt(input.attr("min"))
        let max = parseInt(input.attr("max"))
        let val = parseInt(input.val())
        if(!val && val !== 0){
            input.val(min)
        }
        if(val > max){
            let msg = (_jsLang['最多可購買數量'] ??'最多可購買數量') + max;
            if(input.data("one-page-msg"))
            {
                msg = input.data("one-page-msg");
            }
            input.val(max)
            alert(msg);
        }
        if(val < min){
            input.val(min)
        }
        if(parseInt(input.val()) == max){
            plus.addClass("in-disabled")
        }else{
            plus.removeClass("in-disabled")
        }
        box.find(".quick-current").text(input.val())
        box.trigger("amountChange")
    })
    $(document).on("amountChange", ".quick-product-amount:not(.js-modified)", function(e, delta){
        //js-modified用於非通用處理
        let box = $(this)
        if(box.data("timeout")){
            clearTimeout(box.data("timeout"))
        }
        //避免連點+-
        let updateTimer = setTimeout(function(){
            let input = box.find(".quick-input")
            let val = parseInt(input.val())
            if(!val && val !== 0){
                val = input.data("before-change") || 0
            }
            updateCartAmount(input,$.extend({}, box.data(), {
                sid:input.attr("sid"),
                prodType:input.attr("prodType"),
                type:input.attr("addType") || 'normal',
                value: input.val(),
                delta: delta
            }), function(){
                if(box.hasClass("shopcart-extra-amount"))
                {
                    updatePage();
                }
                else
                {
                    updateAmountBox(box, val);
                }
            })
        }, 250)
        box.data("timeout", updateTimer)
    })
    $(document).on("click", ".quick-product-amount.theme-round", function(e){
        let _this = $(this)
        let input = _this.find(".quick-input")
        let inDisabled = (_this.find(".quick-plus.in-disabled").length && input.val() <= 0) ? true : false
        //先關閉其他打開的
        $(document).trigger("click.quick_amount")
        if($(e.target).closest(".popup-trigger").length){
            //貨到通知
            return false
        }
        if(!_this.hasClass("theme-link") && !inDisabled){
            _this.removeClass("theme-round")
        }
        if(inDisabled){
            let alertText = _this.data("disabled-alert")
            if(alertText){
                alert(alertText)
            }
            return false
        }
        if(input.val() <= 0){
            //預設+1
            _this.find(".quick-plus").trigger("click")
        }
        $(document).on("click.quick_amount", function(e){
            if($(e.target).closest(".quick-product-amount").length <= 0){
                _this.addClass("theme-round")
                if(_this.find(".quick-input").val() > 0){
                    _this.addClass("theme-amount")
                }else{
                    _this.removeClass("theme-amount")
                }
                $(document).off("click.quick_amount")
            }
        })
    })
})($)
function FloatCartPopup(dataObj) {
    const shopcartTarget = $('#Shop_Cart_Total')
    $.ajax({
        url     : Project_Country + "ajax/ajax_get_cart.php",
        type    : "POST",
        async   : true,
        cache   : false,
        data    : dataObj,
    }).done(function(res) {
        shopcartTarget.append(FloatShopcart(res))
        setTimeout(function(){
            shopcartTarget.children('.float-shopcart').remove()
        },3000);
    }).fail(function(x, y, z) {
        console.log(x)
    })
}
//單獨更新購物車紅點
function updateCartTotal(){
    $.ajax({
        url: Project_Country + "shopcart/ajax/ajax_update_cart_total.php",
        type:"POST",
        cache:false,
        dataType:'json',
    }).done(function(res){
        if(res.TotalNum >= 0){
            $(".cart-total").text(res.TotalNum)
        }
    }).fail(function(d){
        alert('網路連線過慢,網頁請重新整理');
    })
}
//通用數量加減
function updateCartAmount(amountInput, data, callback = null){
    amountInput.addClass("in-forzen")
    amountInput.siblings("button").addClass("in-forzen")
    $.ajax({
        url: Project_Country + "shopcart/ajax/ajax_update_num.php",
        type:"POST",
        cache:false,
        dataType:'json',
        data:$.extend({}, data, {
            delta: parseInt(amountInput.val()) - parseInt(amountInput.data("beforeChange"))
        })
    }).done(function(d){
        if(d.Status && d.Status.includes('RET_SUCCESS')){
            if(d.TotalNum >=0){
                $(".cart-total").text(d.TotalNum)
                shopcartUpdatePopup(amountInput)
                //a5
                if(amountInput.parents(".quick-product-amount").data("act") == "5"){
                    let sum = 0
                    $("#purchaseBox .quick-input").each(function(){
                        let val = parseInt($(this).val())
                        if(!isNaN(val)){
                            sum += val
                        }
                    })
                    $(".addpurchase-num-slot").text(sum)
                }
            }
            if(d.Status == 'RET_SUCCESS'){
                $(window).trigger("updateCartAmountSuccess")
            }
            //更新列表數量
            for(var sid in d.totals)
            {
                //列表
                let box = $(".quick-product-amount[cartUpdateSid='"+sid+"']");
                let amount = d.totals[sid];
                updateAmountBox(box, d.totals[sid]);
                box.find(".quick-input").val(amount).data("before-change", amount);
                box.find(".quick-current").html(amount);
                //詳細
                $(".amountBox[cartUpdateSid='"+sid+"']").val(amount);
                $(".amountBox[cartUpdateSid='"+sid+"']").data("before-change", amount);
            }
            if(d.Alert){
                alert(d.Alert);
            }
            if(d.DataLayer)eval(d.DataLayer);
            if(callback && typeof callback == 'function'){
                callback(d)
            }
        }else{
            if(amountInput.data("before-change")){
                if(d.Status != 'RET_SUCCESS_OVER_ACT9'){
                    amountInput.val(amountInput.data("before-change"))
                }
            }else{
                amountInput.val(0)
            }
            if(d.Alert){
                alert(d.Alert);
            }else{
                alert("發生錯誤");
            }
        }
    }).fail(function(d){
        if(amountInput.data("before-change")){
            amountInput.val(amountInput.data("before-change"))
        }else{
            amountInput.val(0)
        }
        alert('網路連線過慢,網頁請重新整理');
    }).always(function(){
        //成功後更新初始值
        amountInput.data("before-change", amountInput.val())
        if(!amountInput.parents(".float-shopcart").length){
            amountInput.removeClass("in-forzen")
            amountInput.siblings("button").removeClass("in-forzen")
        }
        //右上快捷購物會覆蓋所以不移除 避免數字回退
        //amountInput.parents(".quick-product-amount").find(".in-loading").removeClass("in-loading")
    })
}
function shopcartUpdatePopup(amountInput){
    let before = parseInt(amountInput.data("before-change"))
    let val = parseInt(amountInput.val())
    if(val > 0){
        if(before == 0){
            AlertPop({
                icon: '',
                string:_jsLang.加入購物車成功,
                theme:'primary'
            })
        }else{
            AlertPop({
                icon: '',
                string:'商品數量已更新',
                theme:'primary'
            })
        }
    }else{
        AlertPop({
            icon: '',
            string:'已移除商品',
            theme:'danger'
        })
    }
}
function updateAmountBox(box, val){
    let minusIcon = box.find(".icon-minus")
    let trashIcon = box.find(".icon-trash")
    if(val > 1){
        minusIcon.removeClass("hide")
        trashIcon.addClass("hide")
    }else{
        minusIcon.addClass("hide")
        trashIcon.removeClass("hide")
    }
    if(!val || val <= 0){
        box.addClass("theme-round")
        box.removeClass("theme-amount")
    }
    let praentBox = box.parents(".product-item-act")
    if(praentBox.length){
        //活動商品
        if(val > 0){
            praentBox.addClass("theme-picked")
        }else{
            praentBox.removeClass("theme-picked")
        }
    }
}
// ==========================================================
//  影片預設圖 to iframe 撥放器
// ==========================================================
;(function($) {
    $(document).on('click', '.StaticVideo', function(e) {
        e.preventDefault()
        const targetVID = $(this).attr('data-vid')
        const targetType = $(this).attr('data-type')
        let videoChild = ''
        switch(targetType) {
            case 'youtube':
            default:
                videoChild = ``
                break;
            case 'facebook':
                videoChild = ``
                break;
        }
        $(this).parents('.responsive-embed').html(videoChild)
    })
})($)
// 商品大小格切換
;(function($) {
    if($('.switch-group').length) {
        const themeAry = []
        $('.switch-group').find('.switch-item').each(function(i, ele) {
                const themeItem = $(ele).attr('data-target')
                themeAry.push(themeItem)
        })
        $('.switch-group').on('click', '.switch-item', function(e) {
            const targetClass = $(this).data('target')
            $(this).addClass('now')
                   .siblings('.switch-item').removeClass('now')
            $(this).parents('main').find('.items-list').removeClass(themeAry.join(' ')).addClass(targetClass)
        })
    }
})($)
// ==========================================================
//  商品規格評論區塊腳本
// ==========================================================
;(function($) {
    // 輪播功能
    let productReviewStep = ''
    $(window).on('resize commentUpdate', function(e) {
        if($(window).width() >= 1200) {
            productReviewStep = 'desktop'
            $('.content-pics').each(function(i, ele) {
                if($(ele).children().length > 0) {
                    $(ele).owlCarousel({
                        margin: 16,
                        nav: true,
                        dots: false,
                        navText: ['', ''],
                        responsive: {
                            0: {
                                items: 3
                            },
                        }
                    })
                }
            });
        } else if($(window).width() < 1200) {
            productReviewStep = 'mobile'
            $('.content-pics').each(function(i, ele) {
                if($(ele).data('owl.carousel')) {
                    $(ele).data('owl.carousel').destroy()
                }
            });
        }
    })
    // 放大圖
    $(document).on('click', '.content-pics .OpenSlide', function(e) {
        e.preventDefault()
        $('body').addClass('overflow-hidden')
        const targetPic = $(this).attr('href');
        const targetGroup = $(this).attr('group')
        const targetStep = $(this).attr('data-step')
        const groupAry = $(this).parents('.content-pics').find('[group=' + targetGroup + ']')
        const slideAry = []
        groupAry.each(function(i, ele) {
            const pushString = $(ele).attr('href')
            slideAry.push(pushString)
        });
        // console.log(slideAry)
        const appendSlides = slideAry.reduce(function(prev, ele, i) {
            const thisStr = `
                
            `
            return prev + thisStr
        }, '')
        const appendChild = `
        
        `
        $('body').append(appendChild)
    })
    // 滑動到評價區塊
    $(document).on('click', '#Go_Comment', function(e) {
        e.preventDefault()
        const clickTarget = $(this).attr('data-target')
        if($(clickTarget).length) {
            const scrollTop = $(clickTarget).offset().top - $('.header-wrapper').height()
            $(clickTarget).trigger('click')
            $('html, body').animate({
                scrollTop
            }, 750)
        }
    })
    updateAsideProductNum()
})($)
// ==========================================================
//  桌機版商品放大功能
// ==========================================================
;(function($) {
    /*if(!DeviceIsTouch()) {
        $(document).on('click', '.zoom-link', function(e) {
            e.preventDefault()
        }).on('mouseenter', '.zoom-link', function(e) {
            e.preventDefault()
            const thisPic = $(this).attr('href')
            $(this).before(`
                 
                 `)
        }).on('mousemove', '.zoom-link', function(e) {
            e.preventDefault()
            const targetImg = $(this).siblings('.zoomin-picture')
            const targetCursor = $(this).siblings('.zoomin-cursor')
            const imgHeight = $(targetImg).height()
            const imgWidth = $(targetImg).width()
            $(targetImg).css({
                top: (e.offsetY / $(this).height() * imgHeight * -1 + e.offsetY),
                left: (e.offsetX / $(this).width() * imgWidth * -1 + e.offsetX)
            })
            $(targetCursor).css({
                top: e.offsetY,
                left: e.offsetX
            })
        }).on('mouseleave', '.zoom-link', function(e) {
            e.preventDefault()
            $(this).siblings('.zoomin-picture, .zoomin-cursor').remove()
        })
    }*/
})($)
// ==========================================================
//  摺疊table開關功能
// ==========================================================
;(function($) {
    $(document).on('click', '.CollapseToggle', function(e) {
        e.preventDefault()
        const $targetBox = $(this).parents('.table-row')
        if($targetBox.hasClass('table-controls')) {
            $targetBox.toggleClass('in-expand');
        } else {
            $targetBox.prev('.table-controls').toggleClass('in-expand');
        }
    })
})($)
// ==========================================================
//  通用型滑動到指定位置
// ==========================================================
;(function($) {
    $(document).on('click', '.ScrollToTarget', function(e) {
        e.preventDefault()
        const scrollTarget = $(this).attr('data-target')
        if($(scrollTarget).length) {
            const scrollTop = $(scrollTarget).offset().top - $('.header-wrapper').height()
            $('html, body').animate({
                scrollTop
            }, 750)
        }
    })
})($)
// ==========================================================
//  商品詳細區塊切換頁籤
// ==========================================================
;(function($) {
    $(document).on("click", ".detail-tabs .tab-btn", function(){
        let _this = $(this)
        let target = _this.data("target")
        if(!_this.hasClass("in-active")){
            $(".tab-btn, .tab-content").removeClass("in-active")
            _this.addClass("in-active")
            $(".tab-content[data-type='" + target + "']").addClass("in-active")
        }
    })
})($)
// ==========================================================
//  密碼顯示切換
// ==========================================================
;(function($) {
    $(document).on('click', '.password-toggle', function(e) {
        e.preventDefault()
        const target = $(this).siblings('input')
        const targetType = target.attr('type')
        $(this).find('.icon').toggleClass('icon-eye').toggleClass('icon-eye-slash')
        if(targetType === 'password') {
            target.attr('type', 'text')
        } else if(targetType === 'text') {
            target.attr('type', 'password')
        }
    })
})($)
/*影片效果*/
function videoBox(){
    //影片控制
    $(document).on('click','.videoControl',function(e){
        e.preventDefault()
        const targetVideo = $($(this).attr('data-target'))[0]
        if(targetVideo.paused){
            $(this).find('.fa').addClass('fa-pause').removeClass('fa-play');
            targetVideo.play();
        } else {
            $(this).find('.fa').addClass('fa-play').removeClass('fa-pause');
            targetVideo.pause();
        }
    });
    // //影片預覽圖
    // if(document.getElementById("Video")){
    //     document.getElementById("Video").oncanplay=function(){
    //         var video = $("#Video").get(0);
    //         var canvas = document.getElementById("video_review");
    //                 canvas.getContext('2d').drawImage(video, 0, 0, 66, 92);
    //     };
    // }
}
function LeadingZero(input, strLength = 2) {
    let str = String(input)
    if(str.length < strLength) {
        str = '0' + str
        // console.log(str)
        return LeadingZero(str, strLength)
    } else {
        return str
    }
}
function CountdownTimer(limitTime, runFunc = () => false) {
    const now = Date.now()
    if(limitTime > now) {
        const leftTimes     = limitTime - now
        const leftSec       = Math.floor(leftTimes / 1000) % 60
        const leftMin       = Math.floor(leftTimes / 1000 / 60) % 60
        const leftHour      = Math.floor(leftTimes / 1000 / 60 / 60)
        runFunc(`
            ${_jsLang.倒數}
            ${LeadingZero(leftHour)}:${LeadingZero(leftMin)}:${LeadingZero(leftSec)}
        `)
        setTimeout(CountdownTimer, 1000, limitTime, runFunc)
    } else {
        runFunc(`${_jsLang.活動結束}`)
    }
}
function CountDown(secondsTarget, runFunc = () => false) {
    const seconds = secondsTarget.attr('second')
    if(seconds > 0) {
        const leftSec       = Math.floor(seconds / 1) % 60
        const leftMin       = Math.floor(seconds / 1 / 60) % 60
        const leftHour      = Math.floor(seconds / 1 / 60 / 60)
        runFunc(`
            ${_jsLang.倒數}
            ${LeadingZero(leftHour)}:${LeadingZero(leftMin)}:${LeadingZero(leftSec)}
        `)
        secondsTarget.attr('second', seconds - 1)
        setTimeout(CountDown, 1000, secondsTarget, runFunc)
    } else {
        runFunc(`${_jsLang.活動結束}`)
    }
}
// 關閉跳窗特效
function PopupCloseAnimate(jqElement) {
    if(jqElement.hasClass("popupBox-constant")){
        jqElement.addClass("hide")
    }else{
        jqElement.remove()
    }
    $('body').removeClass('overflow-hidden')
}
//  客製化 alert popup
function AlertPop(obj) {
    const setting = {
        icon: '',
        string: '',
        theme: ''
    }
    if(obj) {
        Object.assign(setting, obj)
    }
    const alertElement = $(`
        
    `)
    $('body').append(alertElement)
    setTimeout(function(){
        alertElement.fadeOut(500, function(){
            $(this).remove()
        })
    },3000)
}
//  自定義 confirm popup
function ConfirmPop(obj) {
    const setting = {
        titleName: '',
        titleColor: '',
        string: '',
        trueFunction: () => false,
        falseFunction: () => false,
        extraClass: '',
    }
    if(obj) {
        Object.assign(setting, obj)
    }
    const titleStyle = (setting.titleColor)? `class="confirm-title" style="color: ${setting.titleColor};"`: `class="confirm-title font-primary"`
    const confirmTitle = (setting.titleName)? `
            `)
        }).on('mousemove', '.zoom-link', function(e) {
            e.preventDefault()
            const targetImg = $(this).siblings('.zoomin-picture')
            const targetCursor = $(this).siblings('.zoomin-cursor')
            const imgHeight = $(targetImg).height()
            const imgWidth = $(targetImg).width()
            $(targetImg).css({
                top: (e.offsetY / $(this).height() * imgHeight * -1 + e.offsetY),
                left: (e.offsetX / $(this).width() * imgWidth * -1 + e.offsetX)
            })
            $(targetCursor).css({
                top: e.offsetY,
                left: e.offsetX
            })
        }).on('mouseleave', '.zoom-link', function(e) {
            e.preventDefault()
            $(this).siblings('.zoomin-picture, .zoomin-cursor').remove()
        })
    }*/
})($)
// ==========================================================
//  摺疊table開關功能
// ==========================================================
;(function($) {
    $(document).on('click', '.CollapseToggle', function(e) {
        e.preventDefault()
        const $targetBox = $(this).parents('.table-row')
        if($targetBox.hasClass('table-controls')) {
            $targetBox.toggleClass('in-expand');
        } else {
            $targetBox.prev('.table-controls').toggleClass('in-expand');
        }
    })
})($)
// ==========================================================
//  通用型滑動到指定位置
// ==========================================================
;(function($) {
    $(document).on('click', '.ScrollToTarget', function(e) {
        e.preventDefault()
        const scrollTarget = $(this).attr('data-target')
        if($(scrollTarget).length) {
            const scrollTop = $(scrollTarget).offset().top - $('.header-wrapper').height()
            $('html, body').animate({
                scrollTop
            }, 750)
        }
    })
})($)
// ==========================================================
//  商品詳細區塊切換頁籤
// ==========================================================
;(function($) {
    $(document).on("click", ".detail-tabs .tab-btn", function(){
        let _this = $(this)
        let target = _this.data("target")
        if(!_this.hasClass("in-active")){
            $(".tab-btn, .tab-content").removeClass("in-active")
            _this.addClass("in-active")
            $(".tab-content[data-type='" + target + "']").addClass("in-active")
        }
    })
})($)
// ==========================================================
//  密碼顯示切換
// ==========================================================
;(function($) {
    $(document).on('click', '.password-toggle', function(e) {
        e.preventDefault()
        const target = $(this).siblings('input')
        const targetType = target.attr('type')
        $(this).find('.icon').toggleClass('icon-eye').toggleClass('icon-eye-slash')
        if(targetType === 'password') {
            target.attr('type', 'text')
        } else if(targetType === 'text') {
            target.attr('type', 'password')
        }
    })
})($)
/*影片效果*/
function videoBox(){
    //影片控制
    $(document).on('click','.videoControl',function(e){
        e.preventDefault()
        const targetVideo = $($(this).attr('data-target'))[0]
        if(targetVideo.paused){
            $(this).find('.fa').addClass('fa-pause').removeClass('fa-play');
            targetVideo.play();
        } else {
            $(this).find('.fa').addClass('fa-play').removeClass('fa-pause');
            targetVideo.pause();
        }
    });
    // //影片預覽圖
    // if(document.getElementById("Video")){
    //     document.getElementById("Video").oncanplay=function(){
    //         var video = $("#Video").get(0);
    //         var canvas = document.getElementById("video_review");
    //                 canvas.getContext('2d').drawImage(video, 0, 0, 66, 92);
    //     };
    // }
}
function LeadingZero(input, strLength = 2) {
    let str = String(input)
    if(str.length < strLength) {
        str = '0' + str
        // console.log(str)
        return LeadingZero(str, strLength)
    } else {
        return str
    }
}
function CountdownTimer(limitTime, runFunc = () => false) {
    const now = Date.now()
    if(limitTime > now) {
        const leftTimes     = limitTime - now
        const leftSec       = Math.floor(leftTimes / 1000) % 60
        const leftMin       = Math.floor(leftTimes / 1000 / 60) % 60
        const leftHour      = Math.floor(leftTimes / 1000 / 60 / 60)
        runFunc(`
            ${_jsLang.倒數}
            ${LeadingZero(leftHour)}:${LeadingZero(leftMin)}:${LeadingZero(leftSec)}
        `)
        setTimeout(CountdownTimer, 1000, limitTime, runFunc)
    } else {
        runFunc(`${_jsLang.活動結束}`)
    }
}
function CountDown(secondsTarget, runFunc = () => false) {
    const seconds = secondsTarget.attr('second')
    if(seconds > 0) {
        const leftSec       = Math.floor(seconds / 1) % 60
        const leftMin       = Math.floor(seconds / 1 / 60) % 60
        const leftHour      = Math.floor(seconds / 1 / 60 / 60)
        runFunc(`
            ${_jsLang.倒數}
            ${LeadingZero(leftHour)}:${LeadingZero(leftMin)}:${LeadingZero(leftSec)}
        `)
        secondsTarget.attr('second', seconds - 1)
        setTimeout(CountDown, 1000, secondsTarget, runFunc)
    } else {
        runFunc(`${_jsLang.活動結束}`)
    }
}
// 關閉跳窗特效
function PopupCloseAnimate(jqElement) {
    if(jqElement.hasClass("popupBox-constant")){
        jqElement.addClass("hide")
    }else{
        jqElement.remove()
    }
    $('body').removeClass('overflow-hidden')
}
//  客製化 alert popup
function AlertPop(obj) {
    const setting = {
        icon: '',
        string: '',
        theme: ''
    }
    if(obj) {
        Object.assign(setting, obj)
    }
    const alertElement = $(`
        
    `)
    $('body').append(alertElement)
    setTimeout(function(){
        alertElement.fadeOut(500, function(){
            $(this).remove()
        })
    },3000)
}
//  自定義 confirm popup
function ConfirmPop(obj) {
    const setting = {
        titleName: '',
        titleColor: '',
        string: '',
        trueFunction: () => false,
        falseFunction: () => false,
        extraClass: '',
    }
    if(obj) {
        Object.assign(setting, obj)
    }
    const titleStyle = (setting.titleColor)? `class="confirm-title" style="color: ${setting.titleColor};"`: `class="confirm-title font-primary"`
    const confirmTitle = (setting.titleName)? `${setting.titleName}
`: ''
    const confirmElement = `
        
    `
    $('body').addClass('overflow-hidden').append(confirmElement)
    $('.confirm-popup').on('click', '.btn', function(e) {
        e.preventDefault()
        let returnValue = false
        const targetWrap = $(this).parents('.confirm-popup')
        PopupCloseAnimate(targetWrap)
        if($(this).attr('data-value') === 'true') {
            returnValue = true
        } else {
            returnValue = false
        }
        return (returnValue)? setting.trueFunction(): setting.falseFunction()
    })
}
// ==========================================================
//  複製連結
// ==========================================================
$(function(){
	$(document).on("click", ".copy-btn", function(e){
		window.navigator.clipboard.writeText($(this).data("link"))
		alert("複製連結成功")
	})
})
$(function(){
	$(".HITS_BT").on("click",function(e){
        e.preventDefault();
        if( $.isNumeric($(this).attr('hid')) && $.isNumeric($(this).attr('hdid')) ){
            var hid = $(this).attr('hid');
            var hdid = $(this).attr('hdid');
            var url = $(this).attr('href');
            var target = $(this).attr('target');
            $.ajax({
                url:Project_Country+"ajax/ajax_add_ad_hits-p.php",
                type:"POST",
                cache:false,
                async:false,
                data:{Hid: hid , Hdid : hdid},
                error:function(d){
                    alert('網路連線過慢,網頁請重新整理');
                },
                success:function(d){
                    if(url){
                        if(target == '_blank'){
                            window.open(url);
                        }else if( ( typeof target === 'undefined' ) || (target == '') ){
                            window.location = url;
                        }else{
                        }
                    }
                }
            });
        }else{
            alert(_jsLang.這是錯誤的連結);
        }
    });
})
// ==========================================================
//  滾動事件節流
// ==========================================================
function throttleScroll(func, time, scrollBox = $(window)){
    let throttleFlag = false
    function throttle(method ,currentScroll){
        if(throttleFlag){
            return false
        }
        throttleFlag = true
        setTimeout(function(){
            //currentScroll為當前滾動的容器
            method(currentScroll)
            throttleFlag = false
        }, time)
    }
    let tempFunc = function(){
        throttle(func, $(this))
    }
    return {
        init: function(){
            scrollBox.on('scroll', tempFunc)
        },
        destroy: function(){
            scrollBox.off('scroll', tempFunc)
        }
    }
}
//單行商品
function simpleProductList(list){
    if($(window).width() > 1199 && list.find(".item").length > 0){
        list.owlCarousel({
            nav: true,
            loop: false,
            margin: 20,
            dots: false,
            mouseDrag: false,
            animateIn: 'fadeIn',
            animateOut: 'fadeOut',
            items: 4,
            navText: ['', ''],
        })
    }else{
        list.trigger("destroy.owl.carousel")
    }
}
function simpleProductListSide(list){
    if($(window).width() > 1199 && list.find(".item").length > 0){
        list.owlCarousel({
            nav: true,
            loop: false,
            margin: 20,
            dots: false,
            mouseDrag: false,
            animateIn: 'fadeIn',
            animateOut: 'fadeOut',
            items: 3,
            navText: ['', ''],
        })
    }else{
        list.trigger("destroy.owl.carousel")
    }
}
// ==========================================================
//  橫向滾動
// ==========================================================
;(function($) {
    //避免全局綁定
    $(".horizontal-wheel").on("wheel", function(e){
        let _this = $(this)
        // let scrollLeft = _this.scrollLeft()
        let scrollWidth = this.scrollWidth
        let clientWidth = this.clientWidth
        if(scrollWidth > clientWidth){
            e.preventDefault()
            this.scrollLeft += e.originalEvent.deltaY
        }
    })
})($)
// ==========================================================
//  更新側欄總商品數量
// ==========================================================
function updateAsideProductNum(){
    let num = $("#Ajax_Total").val()
    if((num || num === '0') && $(".products-filter-num").length){
        $(".products-filter-num").text(`(篩選出: ${num})`)
    }
}
// ==========================================================
// 	商品展示區塊輪播、商品圖預覽功能、手機版放大功能、購物跳窗
// ==========================================================
;(function($) {
	let previewStep = ''
	videoBox()
	$(document).on('click', '.moreview .picitem', function(e) {
		e.preventDefault()
        let _this = $(this)
		const hoverTarget =_this.attr('data-target')
		const funcWrap = _this.parents('.preview-side')
		_this.parents('.moreview')
			   .find('.picitem').removeClass('now')
               _this.addClass('now')
		funcWrap.find('.item-box').removeClass('now keep-now')
		funcWrap.find(hoverTarget).addClass('keep-now')
        //手機時滾動到螢幕中間
        if($(window).width() < 1200){
            _this[0].scrollIntoView({
                behavior:"smooth",
                block:"nearest",
                inline: "center"
            })
        }
	})
	$(window).on('resize', function(e) {
		if($(this).width() >= 1200 && previewStep !== 'desktop') {
			previewStep = 'desktop'
			// 輪播
			if($('.preview-side .productImg').data('owl.carousel')) {
				$('.preview-side .productImg').data('owl.carousel').destroy()
			}
			// 預覽圖 hover 事件
			$(document).on('mouseenter', '.moreview .picitem', function(e) {
				e.preventDefault()
				const hoverTarget = $(this).attr('data-target')
				const funcWrap = $(this).parents('.preview-side')
                const item = funcWrap.find(hoverTarget)
				item.addClass('in-hover')
                item.siblings('.now').addClass("keep-now")
                item.siblings('.item-box').removeClass('in-hover now')
			}).on('mouseleave', '.moreview', function(e) {
				e.preventDefault()
				const funcWrap = $(this).parents('.preview-side')
				funcWrap.find('.keep-now').addClass('now').removeClass('keep-now')
				funcWrap.find('.item-box').removeClass('in-hover')
			})
			$(document).off("click.mobileNav", ".picitem")
		} else if($(this).width() < 1200 && previewStep !== 'mobile') {
			previewStep = 'mobile'
			// 輪播
			if($('.preview-side .productImg').children().length > 0) {
				$('.preview-side .productImg').addClass('with-dots').owlCarousel({
					items: 1,
					dots: true,
					nav: false,
					//navText: ['', ''],
					loop: false,
                    margin:10
				})
			}
			// 預覽圖 hover 事件
			$(document).off('mouseenter', '.moreview .picitem')
					   .off('mouseleave', '.moreview')
			// 預覽圖 click 事件
			$(document).off('click.mobileNav', '.picitem')
			$(document).on("click.mobileNav", ".picitem", function(){
				let _this = $(this)
                let index = _this.parents(".swiper-slide").index()
				$('.preview-side .productImg').trigger("to.owl.carousel", [index,100])
			})
		}
	})
    //$(window).trigger("resize")
    // moreview 輪播
    function moreviewSwiper(){
        $(".product-detail").each(function(){
            let swiperItem
            let _this = $(this)
            let moreview = _this.find('.moreview').eq(0)
            if(moreview.find(".swiper").length){
                swiperItem = moreview.find(".swiper")[0].swiper
            }
            if($(window).width() >= 1200 || _this.parents(".quickShop-box").length){
                if(!swiperItem){
                    moreview.wrapInner('')
                            .find('.picitem').wrap('')
                    // moreview.append(`
                    //     
                    //     
                    // `)
                    const swiper = new Swiper('.moreview .swiper', {
                        // navigation: {
                        //     nextEl: '.swiper-button-next',
                        //     prevEl: '.swiper-button-prev',
                        // },
                        breakpoints: {
                            0: {
                                slidesPerView: 4.5,
                                spaceBetween: 12,
                            },
                            1400: {
                                slidesPerView: 5.5,
                                spaceBetween: 16,
                            },
                        },
                        on: {
                            click: function(swiper, event){
                                const clickedIndex = swiper.clickedIndex
                                const visibleSlides = swiper.slidesPerViewDynamic()
                                const firstVisibleIndex = swiper.activeIndex
                                const lastVisibleIndex = firstVisibleIndex + Math.floor(visibleSlides) - 1 //倒數第二個完整item
                                if((clickedIndex <= firstVisibleIndex) || (clickedIndex >= lastVisibleIndex)){
                                    swiper.slideTo(clickedIndex - (Math.floor(visibleSlides) / 2 - 1))
                                }
                            }
                        }
                    })
                }
            }else{
                if(swiperItem){
                    swiperItem.destroy(true, true)
                    let items = moreview.find(".picitem").detach()
                    moreview.empty()
                    moreview.append(items)
                }
            }
        })
    }
    moreviewSwiper()
    $(window).on("resize", function(){
        moreviewSwiper()
    })
    $(document).on("moreviewUpdate", ".moreview", function(){
        moreviewSwiper()
    })
    $(window).on("productPopup", function(){
        moreviewSwiper()
    })
    //分享
    $(".share-group").on("click", ".share-toggle", function(){
        $(".share-group").toggleClass("in-open")
    })
    //  快速購物跳窗
    let commonShopcartStep = false
    $('body').on('click', '.QuickShop', function(e) {
        e.preventDefault()
        if(!commonShopcartStep) {
            commonShopcartStep = true
            jQuery.ajax({
                url:  Project_Country + 'ajax/ajax_popup_shopbox.php',
                type: 'POST',
                dataType: 'html',
                data: {
                    SID: $(this).attr('SID'),
                    Serial: $(this).attr('serial'),
                    Amount: $(this).parent().find('.amountBox').val(),
                    pageShopId: $(this).attr('pageShopId'),
                },
            }).done(function(res){
                if(res.indexOf('window.location.href=') == 0)
                {
                    eval(res);
                }
                else
                {
                    $('body').addClass('overflow-hidden').append(res)
                    if($('.quickShop-box .preview-side .productImg').children().length > 0) {
                        $('.quickShop-box .preview-side .productImg').addClass('with-dots').owlCarousel({
                            items: 1,
                            dots: true,
                            nav: false,
                            //navText: ['', ''],
                            loop: false,
                            margin:10
                        })
                    }
                    $(".quickShop-box .picitem").off('click.mobileNav')
                    $(".quickShop-box .picitem").on("click.mobileNav", function(){
                        let _this = $(this)
                        let index = _this.parents(".swiper-slide").index()
                        $('.quickShop-box .preview-side .productImg').trigger("to.owl.carousel", [index,100])
                    })
                }
            }).fail(function(x, y, z) {
                console.log(x)
            }).always(function() {
                commonShopcartStep = false
            })
        }
    })
})($)
// ==========================================================
// 	購物車摺疊區塊
// ==========================================================
;(function($) {
    //$(".shopcart-group").addClass("in-collapse")
    $(document).on('click', '.group-header', function(){
        let group = $(this).parents('.shopcart-group')
        if(group.hasClass('in-collapse')){
            group.removeClass('in-collapse')
        }else{
            group.addClass('in-collapse')
        }
    })
})($)
// ==========================================================
// 	購物類radio區塊
// ==========================================================
;(function($) {
    function updateRadioWrapper(){
        if($(".shopcart-radio-wrapper").length > 0){
            $(".shopcart-radio-wrapper").each(function(){
                $(this).find(".radio-input:checked").parents(".radio-group").addClass("in-checked").siblings().removeClass("in-checked")
            })
        }
    }
    updateRadioWrapper()
    $(window).on("pageshow", function(){
        updateRadioWrapper()
    })
    $(".invoice-radio-wrapper").each(function(){
        updateInvoiceFunc($(this))
    })
    $(window).on("resize", function(){
        $(".invoice-radio-wrapper").each(function(){
            updateInvoiceFunc($(this))
        })
    })
    $(window).on("updateInvoice", function(){
        updateRadioWrapper()
        $(".invoice-radio-wrapper").each(function(){
            updateInvoiceFunc($(this))
        })
    })
    //更改發票類型
    $(document).on("change", ".shopcart-radio-wrapper .radio-input", function(){
        let _this = $(this)
        let wrapper = _this.parents(".shopcart-radio-wrapper")
        wrapper.find(".radio-input:checked").parents(".radio-group").addClass("in-checked").siblings().removeClass("in-checked")
        //發票
        if(wrapper.hasClass("invoice-radio-wrapper")){
            updateInvoiceFunc(wrapper)
        }
    })
    function updateInvoiceFunc(wrapper){
        let invoType = wrapper.find(".radio-input:checked").val()
        wrapper.find(".invoice-group").addClass("hide")
        wrapper.find(".invoice-group[data-target=" + wrapper.find(".radio-input:checked").val() + "]").removeClass("hide")
        //手機切換時將細項轉移位置
        if(wrapper.find(".radio-input:checked").length){
            if($(window)[0].innerWidth < 1200){
                let invoContainer = wrapper.find(".invoice-container").detach()
                wrapper.find(".radio-input:checked").parents(".radio-group").after(invoContainer)
            }else{
                let invoContainer = wrapper.find(".invoice-container").detach()
                wrapper.find(".radio-box").after(invoContainer)
            }
        }
        if(invoType){
            //必填欄位更新
            let invoGroup = wrapper.find(".invoice-group[data-target=" + invoType + "]")
            wrapper.find("forms_show").text("")
            wrapper.find("[fun]").each(function(){
                $(this).attr("fun", "")
            })
            invoGroup.find("input, select").each(function(){
                let col = $(this)
                if(!col.parents(".invoice-checked-group").length){
                    if(col.attr("type") == "radio" || col.attr("type") == "checkbox"){
                        col.attr("fun", "checkItems")
                    }else{
                        col.attr("fun", "checkNull")
                    }
                }
            })
            updateOnlineInvoice(invoType)
        }
    }
    //更改雲端發票種類
    $(document).on("change", ".invoice-radio", function(){
        let wrapper = $(".invoice-radio-wrapper")
        let invoType = wrapper.find(".radio-input:checked").val()
        updateOnlineInvoice(invoType)
    })
    function updateOnlineInvoice(id){
        $(".invoice-group[data-target="+id+"] .invoice-checked-group").find("[fun]").each(function(){
            $(this).attr("fun", "")
        })
        $(".invoice-group[data-target="+id+"]").find(".forms_show").text("")
        $(".invoice-group[data-target="+id+"] .invoice-radio:checked").parents(".invoice-item").find(".invoice-checked-group input").each(function(){
            let fun = $(this).data("funname") || 'checkNull';
            $(this).attr("fun", fun);
        })
    }
})($)
//分類頁切換
;(function($) {
    $(".page-nav").on("click", ".nav-item", function(){
        let _this = $(this)
        let target =_this.data("for")
        $(".page-nav .nav-item").removeClass("in-active")
        $(".page-group").removeClass("in-active")
        _this.addClass("in-active")
        $(".page-group[data-id='" + target + "']").addClass("in-active")
    })
    if($(".page-nav .nav-item.in-active").length){
        $(".page-nav .nav-item.in-active")[0].scrollIntoView({
            block: 'center',
            inline: 'center'
        })
    }
})($)
//檢查帳號格式
;(function($) {
    $(document).on("input", ".login-account-check input", function(){
        let val = $(this).val()
        let codeSelect = $(".login-account-check select")
        let isValid = /^\d+$/.test(val) && val.length >=3
        if(isValid){
            codeSelect.removeClass("hide")
        }else{
            codeSelect.addClass("hide")
        }
    })
})($)
// trigger function
;(function($) {
    $(window).triggerAll('resize scroll')
})($)
;(function($) {
    //領取抵用券
    $(".coupon-data").on('click','.coupon-btn',function(){
        var coupon_id = $(this).attr("coupon_id");
        if(coupon_id){
            $.ajax({
                url:Project_Country+'ajax/ajax_get_coupon.php',
                type:"POST",
                cache:false,
                async:true,
                data:{coupon_id:coupon_id},
                error:function(d){
                    alert('網路連線過慢,網頁請重新整理');
                },
                success:function(d){
                    switch(d){
                        case "COUPON_OK":
                            alert('領取優惠券成功');
                            window.location.reload();
                            break;
                        case "NO_COUPON":
                            alert('已無可領取優惠券');
                            window.location.reload();
                            break;
                        case "COUPON_GOT":
                            alert('已取得優惠券');
                            window.location.reload();
                            break;
                        case "COUPON_ERROR":
                            alert('領取錯誤,請重整');
                            window.location.reload();
                            break;
                        case "LOGIN_ERROR":
                            alert('請先登入會員後再領取');
                            window.location.href = '/member-login/';
                            break;
                        default:
                            alert(_jsLang.資料庫忙線中);
                            break;
                    };
                }
            });
        }
    });
    //優惠券詳細
    $(document).on('click', '.coupon-trigger', function(){
        let content = $(this).parents(".coupon-item").find('.coupon-content').html()
        $('body').addClass('overflow-hidden')
        const appendChild = `
        
        `
        $('body').append(appendChild)
    })
})($)
//簡易驗證表單
;(function($) {
    //輸入完後檢驗
    $(".check-pass-form").on("change", "input, textarea, select", function(){
        let _this = $(this)
        let name = _this.attr("name")
        let funItem = $("[name='"+name+"'][fun!='']")
        let fun = ""
        //判斷是否有必填 排除手機/email驗證
        if(!_this.parents(".sms-row").length){
            if(funItem.length){
                fun = funItem.eq(0).attr("fun")
            }else{
                if($("[name='"+name+"'][data-fun]").length){
                    fun = $("[name='"+name+"'][data-fun!='']").eq(0).data("fun")
                }else{
                    fun = 'checkNull'
                }
            }
            let ret = ''
            if(fun && _this.length){
                ret = check_tools[fun](_this, $("#Main_Form"))
            }
            if(ret == 'PASS'){
                if(_this.hasClass("address-input") || _this.hasClass("address-select")){
                    //地址區塊另外處理
                    let addressFlag = true
                    _this.parents(".table-row").find(".address-select, .address-input").each(function(){
                        let addCol = $(this)
                        if(!addCol.val()){
                            if(addCol.is(":visible")){
                                addressFlag = false
                                return false
                            }
                        }else if(addCol.hasClass("address-input")){
                            console.log(check_tools['checkNullAddress'](addCol, $("#Main_Form")))
                            if(check_tools['checkNullAddress'](addCol, $("#Main_Form")) !== 'PASS'){
                                addressFlag = false
                                return false
                            }
                        }
                    })
                    if(addressFlag){
                        _this.parents(".table-row").addClass("theme-pass")
                    }else{
                        _this.parents(".table-row").removeClass("theme-pass")
                    }
                }else{
                    _this.parents(".table-row").addClass("theme-pass")
                }
            }else{
                _this.parents(".table-row").removeClass("theme-pass")
            }
        }
    })
})($)