$(document).ready(function(){
    setTimeout(function() {
        $('#fix_inquiry_btn').removeClass('active');
        $('#fix_inquiry_btn').addClass('inactive');
    }, 3000);

    tnbMenuToggle(); // tnb 언어변경
    tnbTooltip(); // tnb left menu tooltip
    tnbSticky(); // 스크롤 tnb
    gnbDd(); // gnb 드롭다운
    gnbTab();

    quickSearchToggle(); // quick search

    totop();

    ask_fn();

    popupCls();

    // listImgResize();

    //gnb swiper
    var swiperBanner = new Swiper(".gnb_banner_sw", {
        pagination: {
            el: ".swiper-pagination",
            clickable: true,
        },
    });

    // breadcrumb 첫번째 글자 강제 대문자
    // $(".breadcrumb .txt").each(function () {
    //     let txt = $(this).text().toLowerCase();
    //     let new_txt = txt.replace(/^[a-z]/, char => char.toUpperCase());
    //     $(this).text(new_txt);
    // });

    //  클립 여부 확인
    onClickFn();

    //  클립 여부 확인 (bigin)
    // $('.clip_bigin_check').on('click', function() {
    //     let clip_tag    = $(this);
    //     let product_num = clip_tag.data('product');
    //     let language    = clip_tag.data('language');
    //
    //     clipProduct_bigin(product_num, language, clip_tag);
    // });

    //  클립 여부 확인 (pdp)
    $('.clip_pdp_check').on('click', function() {
        let clip_tag    = $(this);
        let product_num = clip_tag.data('product');
        let language    = clip_tag.data('language');
        if ($(this).hasClass('clipped')) {
            unclipProduct_pdp(clip_tag, product_num);
        } else {
            clipProduct_pdp(clip_tag, product_num);
        }
    });

    // header_dimmed click 시 q_search 닫기
    $(".header_dimmed").on("click", function () {
        quickSearchClose();
    });

    if($(".wrap").hasClass("ko")) {
        $.datepicker.setDefaults({
            dateFormat: 'yymmdd',
            prevText: '이전 달',
            nextText: '다음 달',
            monthNames: ['1월', '2월', '3월', '4월', '5월', '6월', '7월', '8월', '9월', '10월', '11월', '12월'],
            monthNamesShort: ['1월', '2월', '3월', '4월', '5월', '6월', '7월', '8월', '9월', '10월', '11월', '12월'],
            dayNames: ['일', '월', '화', '수', '목', '금', '토'],
            dayNamesShort: ['일', '월', '화', '수', '목', '금', '토'],
            dayNamesMin: ['일', '월', '화', '수', '목', '금', '토'],
            showMonthAfterYear: true,
            yearSuffix: '년'
        });
    }

    // date-picker
    $(".datepicker").each(function(){
        if($(this).attr("name") == "end_date") {
            $(this).datepicker({
                dateFormat: "yy-mm-dd",
                changeMonth: true,
                changeYear: true,
                maxDate: 0
            });
        } else {
            $(this).datepicker({
                dateFormat: "yy-mm-dd",
                changeMonth: true,
                changeYear: true
            });
        }
        $(this).attr("readonly", true);
    });

    // date-picker expected-delivery in inquiry_v2.blade
    $(".datepicker_expected").each(function(){
        $(this).datepicker({
            dateFormat: "yy-mm-dd",
            changeMonth: true,
            changeYear: true,
            minDate: 0
        });
        $(this).attr("readonly", true);
    });

    skeletonUi();

    tnbActive();

    statusPosition(); //프로젝트 리스트 status bar 텍스트 css

    tooltipComm();

    footerInfo();
});

$(window).scroll(function () {
    ipadScrollFocusFn();        // ipad - 스크롤 시 포커즈 아웃
    tnbSticky(); // 스크롤 tnb
});
$(window).resize(function () {
    // listImgResize();
    statusPosition(); // 임시 pd list 이미지 사이즈 조정
    tooltipPosition();
});

// ipad - 스크롤 시 포커즈 아웃
function ipadScrollFocusFn() {
    if (isIpadOS()) {
        $('#q_search_input_1').blur();
        $('#q_search_input_2').blur();
    }
}

// tnb 언어변경
function changeLanguage(lang) {
    let current_path = location.pathname;
    const path_array = current_path.split("/");
    path_array.shift();
    path_array.shift();
    let params = location.search;
    let new_path = "/"+lang+"/"+path_array.join("/");
    if (params) {
        new_path = new_path+params;
    }
    location.href = new_path;
}

// business info 확장
function footerInfo() {
    $(".bi_ex_btn").click(function(e) {
        e.preventDefault();
        if($("footer .info_ex").css("display") == "none") {
            $("footer .info_ex").slideDown(400);
            $(".bi_ex_btn").addClass("open");
        } else {
            $("footer .info_ex").slideUp(400);
            $(".bi_ex_btn").removeClass("open");
        }
    });
}

// tnb 드롭다운
function tnbMenuToggle() {
    $(".tnb_dd_btn").click(function(e) {
        e.preventDefault();
        e.stopPropagation();
        // dd position
        let el = $(this).next(".user_dd");
        let elW = el.width();
        el.css("margin-left", "-" + elW / 2 + "px")
        if($(this).parents(".tnb_dd_w").hasClass('open')) {
            $(this).parents(".tnb_dd_w").removeClass("open");
        } else {
            $(".tnb_dd_w").removeClass("open");
            $(this).parents(".tnb_dd_w").addClass("open");
        }
    });
    $(".tnb_dd_btn").mouseenter(function(e) {
        e.preventDefault();
        e.stopPropagation();
        // dd position
        let el = $(this).next(".user_dd");
        let elW = el.width();
        el.css("margin-left", "-" + elW / 2 + "px")
        $(this).parents(".tnb_dd_w").addClass("open");
    });
    $(".tnb_dd_w").mouseleave(function(e) {
        if($(this).hasClass('open')) {
            $(this).removeClass("open");
        }
    });

    $(document).on('click', function(e){
        $('.tnb_dd_w').removeClass('open');
    });
}

// tnb left menu tooltip
function tnbTooltip() {
    // tooltip 가운데정렬

    $(".tnb_w .l_menu li a").mouseover(function(){
        let el = $(this).next(".tnb_tooltip");
        let w = el.width();
        el.css("margin-left", "-" + w / 2 + "px");
        el.css("display", "block");
    });
    $(".tnb_w .l_menu li a").mouseout(function(){
        $(this).next(".tnb_tooltip").css("display", "none");
    });
}

// 스크롤 tnb
function tnbSticky() {
    if($(window).scrollTop() >= 100) {
        $(".wrap").addClass('sticky');
    } else {
        $(".wrap").removeClass('sticky');
    }
}


// tnb active 효과 추가
function tnbActive () {
    let url = window.location.pathname;
    let i = "";

    //
    //
    // header1
    $(".gnb_dd_w .gnb_dd_item .gnb_item a").each(function() {
        if ($(this).attr("href") == url) {
            i = $(this).parents(".gnb_dd_item").index();
        }
    });
    if (i != "") {
        $(".default .gnb_w li").eq(i).find("a").addClass("hover");
        $(".sticky_menu .gnb_w li").eq(i).find("a").addClass("hover");
    }
    $(".gnb_w li").each(function() {
        let g_url = $(this).find("a").attr("href");

        if (g_url == url) {
            $(this).find("a").addClass("hover");
        }
    });

    //
    //
    // header2
    $(".gnb_dd_w .gnb_dd_item .gnb_item a").each(function() {
        if ($(this).attr("href") == url) {
            i = $(this).parents(".gnb_dd_item").data('num');
        }
    });
    if (i != "") {
        $(`.gnb_w li[data-num=${i}]`).find("a").addClass("hover");
    }
    $(".gnb_w li").each(function() {
        let g_url = $(this).find("a").attr("href");

        if (g_url == url) {
            $(this).find("a").addClass("hover");
        }
    });

}
// gnb max-height 계산
// function gnbMh () {
//     $('.header2 .gnb_dd_w .gnb_dd_item .gnb_list').each(function() {
//         if ($(this).parents('.gnb_dd_item').hasClass('not_mh') == false) {
//             let h = 0;
//             $(this).find('.gnb_item.depth2').each(function () {
//                 let tmp = $(this).height();
//                 if (h < tmp) {
//                     h = tmp;
//                 }
//             });
//             if (h != 0) {
//                 $(this).css('max-height', h + 'px');
//             }
//         }
//     });
// }
// gnb 드롭다운 메뉴
function gnbDd() {
    $(".header .gnb_w ul li .depth1_link").on("mouseover", function(){
        $(".gnb_w li").each(function() {
            $(this).find("a").removeClass("hover");
        });
    });
    $(".header .gnb_w ul li .depth1_link").on("mouseout", function(){
        tnbActive();
    });
    $(".header .gnb_w ul li.has_2depth .depth1_link").on("mouseover", function(){
        $(".gnb_w li").each(function() {
            $(this).find("a").removeClass("hover");
        });
        $(".gnb_dd_w .gnb_dd_item").each(function(){
            $(this).css("display", "none");
        });
        let i = $(this).parent("li.depth1").index();
        $(".gnb_dd_w .gnb_dd_item").eq(i).css("display", "block");

        $(".header_dimmed").css("display", "block");
    });

    $(".header .gnb_w ul li.has_2depth .depth1_link").click(function (e){
        $(".gnb_w li").each(function() {
            $(this).find("a").removeClass("hover");
        });
        e.preventDefault();
        let i = $(this).parent("li.depth1").index();
        if($(".gnb_dd_w .gnb_dd_item").eq(i).css("display") == "block") {
            let link = $(this).attr("href");
            location.href = link;
        }
    });

    $(".gnb_dd_w .gnb_dd_item").on("mouseover", function(){
        $(".header .gnb_w ul li.has_2depth .depth1_link").each(function(){
            $(this).removeClass("hover");
        });
        $(".header .sticky_menu .gnb_w ul li.depth1 .depth1_link").each(function(){
            $(this).removeClass("hover");
        });
        let i = $(this).index();
        $(".header .gnb_w ul li.depth1 .depth1_link").each(function(j){
            if (i == j) {
                $(this).addClass("hover");
            }
        });
        $(".header .sticky_menu .gnb_w ul li.depth1 .depth1_link").each(function(j){
            if (i == j) {
                $(this).addClass("hover");
            }
        });
        $(this).css("display", "block");
        $(".header_dimmed").css("display", "block");
    });

    $(".header .gnb_w ul li.has_2depth .depth1_link").on("mouseout", function(){
        $(".gnb_dd_w .gnb_dd_item").each(function(){
            $(this).css("display", "none");
        });
        $(".header_dimmed").css("display", "none");
        tnbActive();
    });

    $(".gnb_dd_w .gnb_dd_item").on("mouseout", function(){
        $(".header .gnb_w ul li.has_2depth .depth1_link").each(function(){
            $(this).removeClass("hover");
        });
        $(this).css("display", "none");
        $(".header_dimmed").css("display", "none");
        tnbActive();
    });

    // header2
    $(".header2 .gnb_w ul li .depth1_link").on("mouseover", function(){
        $(".gnb_w li").each(function() {
            $(this).find("a").removeClass("hover");
        });
        $(".gnb_dd_w .gnb_dd_item").each(function(){
            $(this).css("display", "none");
        });
        if ($(this).parents('li').hasClass('has_2depth')) {
            let i = $(this).parent("li.depth1").data('num');
            $(`.gnb_dd_w .gnb_dd_item[data-num=${i}]`).css("display", "block");
            // gnbMh();
            gnbScrollReset();
            $(".header_dimmed").css("display", "block");
        }
    });
    $(".header2 .gnb_w ul li .depth1_link").on("mouseout", function(){
        $(".gnb_dd_w .gnb_dd_item").each(function(){
            $(this).css("display", "none");
        });
        $(".header_dimmed").css("display", "none");
        tnbActive();
    });


    $(".header2 .gnb_w ul li.has_2depth .depth1_link").click(function (e){
        e.preventDefault();
        let i = $(this).parent("li.depth1").data('num');
        if($(`.gnb_dd_w .gnb_dd_item[data-num=${i}]`).css("display") == "block") {
            let link = $(this).attr("href");
            location.href = link;
        }
    });

    $(".gnb_dd_w .gnb_dd_item").on("mouseover", function(){
        $(".header2 .gnb_w ul li.has_2depth .depth1_link").each(function(){
            $(this).removeClass("hover");
        });
        let i = $(this).data('num');
        $(`.header2 .gnb_w ul li[data-num=${i}]`).find('.depth1_link').addClass("hover");
        $(this).css("display", "block");
        // gnbMh();
        $(".header_dimmed").css("display", "block");
    });
    $(".gnb_dd_w .gnb_dd_item").on("mouseout", function(){
        $(".header2 .gnb_w ul li .depth1_link").each(function(){
            $(this).removeClass("hover");
        });
        $(this).css("display", "none");
        $(".header_dimmed").css("display", "none");
        tnbActive();
    });

}
// gnb all menu tab
function gnbTab() {
    $('.gnb_dd_w .gnb_dd_item.all_menu .l_tab_menu li').eq(0).addClass('active');
    $('.gnb_dd_w .gnb_dd_item.all_menu .r_tab_cont .tab_cont_w').eq(0).addClass('active');

    $('.gnb_dd_w .gnb_dd_item.all_menu .l_tab_menu li a').click(function(e) {
        e.preventDefault();
        gnbScrollReset();
        $('.gnb_dd_w .gnb_dd_item.all_menu .l_tab_menu li').each(function() {
            $(this).removeClass('active');
        });
        $('.gnb_dd_w .gnb_dd_item.all_menu .r_tab_cont .tab_cont_w').each(function() {
            $(this).removeClass('active');
        });
        $(this).parents('li').addClass('active');
        $(`.gnb_dd_w .gnb_dd_item.all_menu .r_tab_cont .tab_cont_w[data-num=${$(this).data('num')}]`).addClass('active');
    });

    // dd css control
    $('.gnb_dd_w .gnb_dd_item.all_menu .r_tab_cont .tab_cont_w .tab_cont.right').each(function() {
        if ($(this).find('.tab_cont_item').length == 0) {
            $(this).css('display', 'none');
        }
    });
}
// gnb scroll reset
function gnbScrollReset() {
    $('.header2 .gnb_dd_w .gnb_dd_item .dd_align.left').scrollTop(0);
    $('.header2 .gnb_dd_w .gnb_dd_item.all_menu .r_tab_cont .tab_cont_w .tab_cont .tab_cont_in').scrollTop(0);
}

// quick search
function quickSearchToggle() {
    $(".q_search_btn").click(function(e){
        e.preventDefault();
        if($(".q_search_w").css("display") == "none") {
            quickSearchOpen();
        } else {
            quickSearchClose();
        }
    });
    $(".q_search_w .cls_btn").click(function(e){
        e.preventDefault();
        quickSearchClose();
    });
    $(".search_w").click(function (e){
        e.preventDefault();
        quickSearchOpen();
    });
    $("#q_search_input_1").on('focus', function(e) {
        e.preventDefault();
        quickSearchOpen();
    });
}



function quickSearchOpen() {
    console.log('ddd');
    $(".header_dimmed").css("display", "block");
    $(".q_search_w").css("display", "block");
    if ($('.wrap').hasClass('sticky')) {
        $(".q_search_input").focus();
    }
    // listImgResize();
}
function quickSearchClose() {
    $(".header_dimmed").css("display", "none");
    $(".q_search_w").css("display", "none");
}

// to top button
let activeAc = false;
let lastScroll = 0;
function totop() {

    $('.totop').click(function(e) {
        e.preventDefault();
        $('html, body').animate({ scrollTop : 0 }, 400);
        return false;
    });

};
$(window).scroll(function(){

    let scrollTop = $(this).scrollTop();
    let innerHeight = $(this).innerHeight();
    let scrollHeight = $('.wrap').prop('scrollHeight');
    if (scrollTop + innerHeight >= scrollHeight - 10) {
        activeAc = true;
    }


    if (scrollTop > lastScroll){
        if (($('#fix_inquiry_btn').hasClass('active')))     { $('#fix_inquiry_btn').removeClass('active');   }
        if (!($('#fix_inquiry_btn').hasClass('inactive')))  { $('#fix_inquiry_btn').addClass('inactive');    }
    } else {
        if (($('#fix_inquiry_btn').hasClass('inactive')))   { $('#fix_inquiry_btn').removeClass('inactive'); }
        if (!($('#fix_inquiry_btn').hasClass('active')))    { $('#fix_inquiry_btn').addClass('active');      }
    }

    lastScroll = scrollTop;

    // 푸터 위치에서 INQUIRY 숨김
    if (scrollTop + innerHeight >= scrollHeight - 100) {
        $("#fix_inquiry_btn").fadeOut();
    } else {
        $("#fix_inquiry_btn").fadeIn();
    }
});

//  스크롤 현재 상태
let isScrolling;

window.addEventListener('scroll', function ( event ) {
    // Clear our timeout throughout the scroll
    window.clearTimeout( isScrolling );

    // 스크롤이 멈출 경우 이벤트
    isScrolling = setTimeout(function() {
        if (($('#fix_inquiry_btn').hasClass('active')))     { $('#fix_inquiry_btn').removeClass('active');  }
        if (!($('#fix_inquiry_btn').hasClass('inactive')))  { $('#fix_inquiry_btn').addClass('inactive');   }
    }, 3000);

}, false);

// popup
//팝업 열기
function openPopup(popupName) {
    $('.' + popupName).fadeIn(300);
    $(".dimmed").fadeIn(300);
    $("body").css("overflow", "hidden");
};
//팝업 안에서 기존 팝업 닫고 새로 열기
function openPopupIn(popupName) {
    $('.popup_comm').css('display','none');
    $('.' + popupName).css('display','block');
};
//팝업 안에서 기존 팝업 위에 팝업 열기
function openPopupIn2(popupName) {
    $('.' + popupName).fadeIn(300);
    $('.' + popupName).css("z-index", "10003");
    $(".dimmed2").fadeIn(300);
};
function popupCls(){
    // 팝업 닫기
    $('.popup_close').click(function(e) {
        e.preventDefault();
        e.stopPropagation();
        $('.popup_comm').fadeOut(300);
        $(".dimmed").fadeOut(300);
        $(".dimmed2").css('display','none');
        $("body").css("overflow", "");
        $("body").css("overflow-y", "auto");
    });
    // 팝업 안에서 2차 팝업만 닫기
    $('.popup_close2').click(function(e) {
        e.preventDefault();
        e.stopPropagation();
        $(".dimmed2").fadeOut(300);
        $(this).parents('.popup_comm').fadeOut(300);
        $(this).parents('.popup_comm').css("z-index", "10001");
    });

}

// 열린 팝업 닫기
function popupClsFn(){
    $('.popup_comm').fadeOut(300);
    $(".dimmed").fadeOut(300);
    $(".dimmed2").css('display','none');
    $("body").css("overflow", "");
    $("body").css("overflow-y", "auto");
}
// 열린 팝업 안에서 팝업 닫기
function popupClsFn2(){
    $(".dimmed2").fadeOut(300);
    $('.popup_comm').fadeOut(300);
    $('.popup_comm').css("z-index", "10001");
}
// alert 팝업 공통처리
function alertPopup(mode, ok, tit, desc) {
    /** mode 는 'd', 'in', 'in2'
     * 'd' == '일반 팝업 오픈';
     * 'in' == '팝업 안에서 기존 팝업 닫고 새로 열기';
     * 'in2' == '팝업 안에서 기존 팝업 위에 팝업 열기';
     ** ok는 확인 버튼 텍스트
     ** tit는 타이틀 텍스트
     ** desc는 desc 텍스트 (없으면 안보냄)
     * */
    let el = '';
    if (mode == 'd') {
        el = 'alert_common_popup1';
    } else if (mode == 'in') {
        el = 'alert_common_popup1';
    } else if (mode == 'in2') {
        el = 'alert_common_popup2';
    }
    $(`.${el} .txt .tit`).html(tit);
    $(`.${el} .btn a`).html(ok);
    if (desc) {
        $(`.${el} .txt .desc`).css('display', 'block');
        $(`.${el} .txt .desc`).html(desc);
    } else {
        $(`.${el} .txt .desc`).css('display', 'none');
    }
    if (mode == 'd') {
        openPopup(el);
    } else if (mode == 'in') {
        openPopupIn(el);
    } else if (mode == 'in2') {
        openPopupIn2(el);
    }
}

//ask

function ask_fn() {
    $('.askus_popup .form_item .others input').change(function(){
        var parent = $(this).parents('.step');
        var cont = parent.find('.other_op');

        if($(this).is(':checked')) {
            cont.css('display', 'block');
        } else {
            cont.css('display', 'none');
        }
    });

    // $('#ask_popup_open').click(function(e){
    //     e.preventDefault();
    //     ask_popup_open();
    // });
}

function ask_popup_open() {
    var i = 0;
    ask_n(i);
    openPopup('askus_popup');
}


function ask_n(i) {
    if(i == 0) {
        $('.askus_popup .step').css('display', 'none');
        $('.askus_popup .step.step1').css('display','block');
        $('.askus_popup .progress_w .bar').css('width', '20%');
        $('.askus_popup .progress_w .bar').text('20%');
        $('.askus_popup .progress_w .txt').text('1/5');
    }

    if(i == 1) {
        $('.askus_popup .step').css('display', 'none');
        $('.askus_popup .step.step2').css('display','block');
        $('.askus_popup .progress_w .bar').css('width', '40%');
        $('.askus_popup .progress_w .bar').text('40%');
        $('.askus_popup .progress_w .txt').text('2/5');
    }
    if(i == 2) {
        $('.askus_popup .step').css('display', 'none');
        $('.askus_popup .step.step3').css('display','block');
        $('.askus_popup .progress_w .bar').css('width', '60%');
        $('.askus_popup .progress_w .bar').text('60%');
        $('.askus_popup .progress_w .txt').text('3/5');
    }
    if(i == 3) {
        $('.askus_popup .step').css('display', 'none');
        $('.askus_popup .step.step4').css('display','block');
        $('.askus_popup .progress_w .bar').css('width', '80%');
        $('.askus_popup .progress_w .bar').text('80%');
        $('.askus_popup .progress_w .txt').text('4/5');
    }
    if(i == 4) {
        $('.askus_popup .step').css('display', 'none');
        $('.askus_popup .step.step5').css('display','block');
        $('.askus_popup .progress_w .bar').css('width', '100%');
        $('.askus_popup .progress_w .bar').text('100%');
        $('.askus_popup .progress_w .txt').text('5/5');
    }
}


function expandFn(obj) {
    if($(obj).next(".expand_cont").css("display") == "block") {
        $(obj).parents(".expand_item").removeClass("open");
        $(obj).next(".expand_cont").slideUp();
    } else {
        $(obj).parents(".expand_item").addClass("open");
        $(obj).next(".expand_cont").slideDown();
    }
}

// function listImgResize() {
//     $(".pd_list_comm .pd_item").each(function(){
//         let el = $(this).find(".pd_img");
//         let img = el.find("img").attr("src");
//         let w = el.width();
//         el.css("height", w + "px").css("background-image", "url('" + img + "')");
//     });
// }
function onClickFn() {
    //  클립 여부 확인
    $('.clip_check').on('click', function() {
        let clip_tag    = $(this);
        let product_num = clip_tag.data('product');
        if ($(this).hasClass('clipped')) {
            unclipProduct(clip_tag, product_num);

        } else {
            clipProduct(clip_tag, product_num);
        }
    })
}
function onClickFn2() {
    //  클립 여부 확인
    $('.clip_check2').on('click', function() {
        let clip_tag    = $(this);
        let product_num = clip_tag.data('product');
        if ($(this).hasClass('clipped')) {
            unclipProduct(clip_tag, product_num);

        } else {
            clipProduct(clip_tag, product_num);
        }
    })
}
function clipProduct(clip_tag, product_num) {
    $.ajax({
        header: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        async: false,
        url: '/ajax/clip_product',
        type: 'POST',
        data: {
            product_num: product_num,
            _token: $('meta[name="csrf-token"]').attr('content')
        },
        dataType: 'json',
        success: function(res) {
            if (res.result === 'success') {
                clip_tag.addClass('clipped');
                openPopup('clip_add_success_popup');
            } else {
                console.log(res.msg);
            }
        },
        error: function (request, status, error) {
            let msg = "ERROR : " + request.status + "<br>";
            msg += +"Content : " + request.responseText + "<br>" + error;
            console.log(msg);
        }
    });
}

function clipProduct_pdp(clip_tag, product_num) {
    $.ajax({
        header: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        async: false,
        url: '/ajax/clip_product',
        type: 'POST',
        data: {
            product_num: product_num,
            _token: $('meta[name="csrf-token"]').attr('content')
        },
        dataType: 'json',
        success: function(res) {
            if (res.result === 'success') {
                clip_tag.addClass('clipped');
                clip_tag.parent().addClass('clipped');
                openPopup('clip_add_success_popup');
            } else {
                console.log(res.msg);
            }
        },
        error: function (request, status, error) {
            let msg = "ERROR : " + request.status + "<br>";
            msg += +"Content : " + request.responseText + "<br>" + error;
            console.log(msg);
        }
    });
}


function unclipProduct(clip_tag, product_num) {
    $.ajax({
        header: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        async: false,
        url: '/ajax/delete_clip',
        type: 'POST',
        data: {
            product_num: product_num,
            _token: $('meta[name="csrf-token"]').attr('content')
        },
        dataType: 'json',
        success: function(res) {
            if (res.result === 'success') {
                clip_tag.removeClass('clipped');
                openPopup('clip_delete_success_popup');
            } else {
                console.log(res.msg);
            }
        },
        error: function (request, status, error) {
            let msg = "ERROR : " + request.status + "<br>";
            msg += +"Content : " + request.responseText + "<br>" + error;
            console.log(msg);
        }
    });
}

function unclipProduct_pdp(clip_tag, product_num) {
    $.ajax({
        header: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        async: false,
        url: '/ajax/delete_clip',
        type: 'POST',
        data: {
            product_num: product_num,
            _token: $('meta[name="csrf-token"]').attr('content')
        },
        dataType: 'json',
        success: function(res) {
            if (res.result === 'success') {
                clip_tag.removeClass('clipped');
                clip_tag.parent().removeClass('clipped');
                openPopup('clip_delete_success_popup');
            } else {
                console.log(res.msg);
            }
        },
        error: function (request, status, error) {
            let msg = "ERROR : " + request.status + "<br>";
            msg += +"Content : " + request.responseText + "<br>" + error;
            console.log(msg);
        }
    });
}


// 팝업창 쿠키
function getCookie(name) {
    let cookie = document.cookie;
    if (document.cookie != "") {
        var cookie_array = cookie.split("; ");
        for ( var index in cookie_array) {
            var cookie_name = cookie_array[index].split("=");
            if (cookie_name[0] == "popupYN") {
                return cookie_name[1];
            }
        }
    } return;
}
function setCookie(name, value, expiredays) {
    let date = new Date();
    date.setDate(date.getDate() + expiredays);
    document.cookie = escape(name) + "=" + escape(value) + "; expires=" + date.toUTCString();
}
function openCookiePopup() {
    let cookieCheck = getCookie("popupYN");
    if (cookieCheck != "N") {
        $('.main_img_popup').fadeIn(300);
        $("body").css("overflow", "hidden");
    }
}
function closeCookiePopup() {
    setCookie("popupYN", "N", 1);
    $('.main_img_popup').fadeOut(300);
    $("body").css("overflow", "");
    $("body").css("overflow-y", "auto");
}
function minicartRefresh(user_num, locale) {
    $.ajax({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        async: false,
        url:'/minicart_list',
        type: 'GET',
        data: {
            user_num: user_num,
        },
        dataType: 'json',
        success:function(result) {
            if (result.result=="success") {

                let cart_list = result.cart_list;
                let total_count = result.cart.items_count;
                let total_amount = result.cart.items_amount;
                let total_amount_plus = "";
                let html = "";

                if(total_amount > 100) {
                    total_amount_plus = "99+";
                } else {
                    total_amount_plus = total_amount;
                }

                for (let i = 0; i < total_count; i++) {
                    let pd_type = "";
                    if (cart_list[i]['type'] == 1) {
                        pd_type = "FORMULA";
                    } else if (cart_list[i]['type'] == 2) {
                        pd_type = "PACKAGING";
                    };

                    let cont = `
                        <li class="samplebag_item">
                            <a href="/${locale}/pdp/${cart_list[i]['ctk_code']}">
                                <div class="samplebag_item_in">
                                    <div class="item_img">
                                        <img src="${cart_list[i]['main_image']}" alt="${cart_list[i]['text']}'s image">
                                    </div>
                                    <div class="item_info">
                                        <div class="pd_tit">${cart_list[i]['text']}</div>
                                        <div class="pd_bot">
                                            <div class="pd_type">
                                                ${pd_type}
                                            </div>
                                            <div class="pd_qty">Qty:${cart_list[i]['amount']}</div>
                                        </div>
                                    </div>
                                </div>
                            </a>
                        </li>
                    `;
                    html += cont;
                }
                if (total_count > 0) {
                    $("#tnb_sample_count").css("display", "block");
                    $("#tnb_sample_count1").css("display", "block");
                    $("#tnb_sample_count2").css("display", "block");
                }

                $("#tnb_sample_count").text(total_amount_plus); // new
                $("#tnb_sample_count1").text(total_amount_plus); // default
                $("#tnb_sample_count2").text(total_amount_plus); // sticky
                $("#tnb_list_count").text(total_amount); // new
                $("#tnb_list_count1").text(total_amount); // default
                $("#tnb_list_count2").text(total_amount); // sticky
                $("#tnb_samplebag_list").html(html); // new
                $("#tnb_samplebag_list1").html(html); // default
                $("#tnb_samplebag_list2").html(html); // sticky

                window.dataLayer.push({
                    event: 'load_cartlist'
                });
            } else {
                alert(result.msg);
            }
        },
        error: function (request, status, error){
            let msg = "ERROR : " + request.status + "<br>";
            msg +=  + "Content : " + request.responseText + "<br>" + error;
            console.log(msg);
            console.log(request);
        }
    });
}

function validateEmailComm(sEmail) {
    let filter = /^(([^<>()[\]\.,;:\s@\"]+(\.[^<>()[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;
    if (filter.test(sEmail)) {
        return false;
    }
    else {
        return true;
    }
}

function changeTrackLink () {
    // track order -> track item
    let page_lang = $("#active_lang").data("lang");
    $("#tnb_order_link1").attr("href", "/"+page_lang+"/track/item");
    $("#tnb_order_link2").attr("href", "/"+page_lang+"/track/item");
}

function skeletonUi() {
    // 스켈레톤 ui
    $('img').each(function(){
        let img = new Image();
        let el = $(this).parents('.skeleton_w');
        img.onload = function() {
            // console.log($(this).attr('src') + ' - done!');
            el.removeClass('skeleton_w');
        }
        img.src = $(this).attr('src');
    });
}

// smooth scroll focus
function smoothFocus(el) {
    let target = $(el);
    $('html,body').animate({
        scrollTop: target.offset().top - 120
    }, 500, function(){
        target.focus();
    });
}
function smoothFocusVal(n) {
    let pos = Number(n);
    $('html,body').animate({
        scrollTop: pos - 120
    }, 500);
}

//프로젝트 리스트 status bar 텍스트 css(언어별 width값 다름 이슈)
function statusPosition() {
    $(".moq_status_w .status_item .status_txt").each(function() {
        var itemWidth = $(this).width();
        var itemLeft = itemWidth / 2;
        $(this).css("margin-left", "-" + itemLeft + "px");
    });
};


// tooltip 기능 공통
function tooltipComm() {
    tooltipPosition();
    // tooltip open
    $(".use_tooltip_comm").mouseenter(function(){
        $(this).addClass("open");
    });

    // tooltip close
    $(".use_tooltip_comm").mouseleave(function(){
        $(this).removeClass("open");
    });

    $(".tooltip_close").on("click", function(e){
        e.preventDefault();
        $(this).parents(".use_tooltip_comm").removeClass("open");
    });
};
function tooltipPosition() {
    $(".use_tooltip_comm").each(function(){
        if (!$(this).hasClass('center')) {
            let left = $(this).outerWidth() / 2;
            $(this).find('.tooltip_in .after').css('left', left);
        }
    });
}

// IOS check
function isIOS() {
    if (/iPad|iPhone|iPod/.test(navigator.platform)) {
        return true;
    } else {
        return navigator.maxTouchPoints &&
            navigator.maxTouchPoints > 2 &&
            /MacIntel/.test(navigator.platform);
    }
}
// ipad Check
function isIpadOS() {
    return navigator.maxTouchPoints &&
        navigator.maxTouchPoints > 2 &&
        /MacIntel/.test(navigator.platform);
}

/** SLACK 발송  */
/* payload 예시
    1.
    let payload = {'text': 'AJAX 진입 전'};

    2.
    let payload = {
        "text": "Javascript :: 재문의",
        "blocks": [
            {
                "type": "section",
                "text": {
                    "type": "mrkdwn",
                    "text": 'Javascript :: 모바일 재문의('+ '{{ !empty($basic_info['ui_num']) ? $basic_info['ui_num'] : '' }}' +') 발송 전'
                }
            },
            {
                "type": "section",
                "block_id": "section123",
                "fields": [
                    {
                        "type": "mrkdwn",
                        "text": "" +
                            "*1. UserNum* "+ '{{ !empty($basic_info['user_num']) ? $basic_info['user_num'] : '' }}' +"\n\n" +
                            "*2. Language Code* "+ '{{ !empty($basic_info['language_code']) ? $basic_info['language_code'] : 'en' }}' +"\n\n" +
                    }
                ]
            }
        ]
    };
*/
function sendSlack(payload) {
    let xhr = new XMLHttpRequest();
    xhr.open("POST", 'https://hooks.slack.com/services/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', true);

    //Send the proper header information along with the request
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    xhr.onreadystatechange = function() { // Call a function when the state changes.
        if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
            // Request finished. Do processing here.
        }
    }

    xhr.send(JSON.stringify(payload));
}

// 검색용 텍스트 히든 처리
function searchTxtHidden() {
    $('.row.description .item_desc p').each(function() {
        let replace_str = $(this).html().replace('<*****', '<span style="display:none;">')
            .replace('*****>', '</span>')
            .replace('&lt;*****', '<span style="display:none;">')
            .replace('*****&gt;', '</span>');
        $(this).html(replace_str);
    });
}