$(document).ready(function () {
    gnbMenu();
    selectTab("#tab01");  //¼±»ý´Ô ¸ÞÀÎ1
    selectTab("#tab02");  //¼±»ý´Ô ¸ÞÀÎ2
    selectTab("#tab04");  //¼öÇèÁ¤º¸ sub01
    selectTab("#tab05");  //¼öÇèÁ¤º¸ sub02
    selectTab("#tab07"); //ÀÚÁÖ¹¯´ÂÁú¹® tab
    selectTab("#tab08"); //ÀÎÅÍ³Ý¼­Á¡

    try {
        minHeight();
    } catch (e) { }

    /*°øÅë header ¿ÞÂÊ ¹è³Ê*/
    if ($('#headerB .swiper-slide').length > 1) {
        var swiper = new Swiper('#headerB', {
            direction: 'vertical',
            autoplay: {
                delay: 2500,
                disableOnInteraction: false,
            },
            loop: true,
            pagination: {
                el: '#headerB .swiper-pagination',
                clickable: true,
            },
        });
    }

    /* GNB °íÁ¤ Test */
    (function () {
        var root = $('.hd_utility');
        var hdLogo = $('.hd_logo');
        $(window).scroll(function () {
            $.fn.gnbFixed = function () {
                if ($(window).scrollTop() > hdLogo.offset().top + hdLogo.innerHeight()) {
                    root.addClass('fixed');
                    $('.hd_bottom').addClass('fixed');
                    hdLogo.addClass('fixed');
                    $('.scr_header').css({ top: '62px' });
                } else {
                    root.removeClass('fixed');
                    $('.hd_bottom').removeClass('fixed');
                    hdLogo.removeClass('fixed');
                };
            };
            //			$(document).gnbFixed();
        });
    })();



    /* ---Çì´õ ¸µÅ© ¸®½ºÆ® .homep_link --- */
    $('.hd_top .homep_link .road1').click(function () {
        //console.log($(this).hasClass('on'));
        if ($(this).hasClass('on')) {
            $(this).removeClass('on');
        } else {
            $('.hd_top .homep_link .road1').removeClass('on');
            $(this).addClass('on');
        }
    });

    /* ---// Çì´õ ¸µÅ© ¸®½ºÆ® .homep_link --- */


    /* --- Çì´õ '°ø¹«¿ø°­ÁÂ' 9/7±Þ ¼¿·ºÆ® --- */


    var dthidx;

    $("#headertop .hd_utility .mnu_list.off .depview").hover(function () {
        dthidx = $(this).index();

        $("#headertop .hd_utility .mnu_list.off  > li").each(function (i) {
            if (dthidx == i) {
                //over
                $(this).addClass("on");
                $(this).find(".depth_hover").show();
            } else {
                //out
                $(this).removeClass("on");
                $(this).find(".depth_hover").hide();
            };
        });

    }, function () {

        dthidx = $("#headertop .hd_utility .mnu_list.off  > li").length;


        $("#headertop .hd_utility .mnu_list.off  > li").each(function (i) {
            if (dthidx == i) {
                //over
                $(this).addClass("on");
                $(this).find(".depth_hover").show();
            } else {
                //out
                $(this).removeClass("on");
                $(this).find(".depth_hover").hide();
            };
        });
    });




    /* --- // Çì´õ '°ø¹«¿ø°­ÁÂ' 9/7±Þ ¼¿·ºÆ® --- */



    /* ---¿Â¶óÀÎ ÇÐ¿ø ¸µÅ© ¸®½ºÆ® .hd_utility.right_btn --- */

    // depth2
    $('.hd_utility .right_btn.online > a').click(function () {
        if ($(this).hasClass('on')) {
            $(this).removeClass('on');
        } else {
            $('.hd_utility .right_btn.online > a').removeClass('on');
            $(this).addClass('on');

        }
    });

    // depth3
    $('.hd_utility .right_btn.online a.road2').click(function () {
        if ($(this).hasClass('on')) {
            $(this).removeClass('on');
        } else {
            $(this).addClass('on');
        }
    });

    /* ---// ¿Â¶óÀÎ ÇÐ¿ø ¸µÅ© ¸®½ºÆ® homep_link --- */

    if ($('.mg_popup_wrap').length) {
        initMegaPopup();
    }
});

function gnbMenu() {
    $('.lnb li').bind('click', function () {
        var target = $(this);
        if (!$(this).hasClass("on")) {
            $(this).parents().find('.lnb li').removeClass("on");
            $(this).addClass("on");
        } else {
            $(this).removeClass('on');
        }
    });
}

function minHeight() {
    try {
        var footerH = document.getElementById('mFooter').offsetHeight,
            headerH = document.getElementById('mheader').offsetHeight,
            sectionH = (window.innerHeight) - footerH - headerH;
        document.getElementById('mContainer').style.minHeight = sectionH + 'px';
    } catch (e) {
        var footerH = document.getElementById('footer').offsetHeight,
            headerH = document.getElementById('headertop').offsetHeight,
            sectionH = (window.innerHeight) - footerH - headerH;
        document.getElementById('mContainer').style.minHeight = sectionH + 'px';
    }
}

/*common tab*/
function selectTab(selector) {
    var selectedTab = null;
    var Tabs = $(selector).find("li");
    Tabs.click(function () {
        selectedTab = $(this);
        if (selectedTab != null) {
            selectedTab.parent().find("li").removeClass("on");
            selectedTab.addClass("on");
            selectedTab.parent().siblings().find($(".tab_content")).css('display', 'none');
            var activeTab = selectedTab.attr("rel");
            $("#" + activeTab).fadeIn()
        }
    });
}


//°ø¿ë·¹ÀÌ¾î Ã³¸®////////////////////////////////////////////////////////
function fncLayerShow(i, a, s) {

    //ÆË¾÷°³Ã¼
    var e = $('#' + i);

    //È­¸éÀÇ ³ôÀÌ¿Í ³Êºñ¸¦ ±¸ÇÑ´Ù.
    var maskWidth = $(document).width();
    var maskHeight = $(document).height();

    var popWidth = e.width();

    var popHeight = e.height();

    $("body").append("<div class='darkmask'></div>");
    var t = $(".darkmask");
    //¸¶½ºÅ©ÀÇ ³ôÀÌ¿Í ³Êºñ¸¦ È­¸é °ÍÀ¸·Î ¸¸µé¾î ÀüÃ¼ È­¸éÀ» Ã¤¿î´Ù.
    t.css({ 'width': '100%', 'height': maskHeight });

    //¾Ö´Ï¸ÞÀÌ¼Ç È¿°ú - ÀÏ´Ü 1ÃÊµ¿¾È ±î¸Ä°Ô µÆ´Ù°¡ 80% ºÒÅõ¸íµµ·Î °£´Ù.
    t.fadeIn(1);
    $('html,body').css('overflow', 'hidden');
    t.fadeTo("slow", 0.8);

    var ph = $(window).height() - popHeight;
    if (ph < 0) { ph = 0; }
    e.css({ 'left': ($(window).width() - popWidth) / 2, 'top': (ph) / 2 });

    eval("e." + a + "('" + s + "')");
}

function fncLayerHide(i, a, s) {
    var t = $(".darkmask");

    t.fadeOut('fast');
    $('.darkmask').remove();
    $('html,body').css('overflow', 'visible');
    var e = $('#' + i);
    eval("e." + a + "('" + s + "')");
}
//°ø¿ë·¹ÀÌ¾î Ã³¸®////////////////////////////////////////////////////////

// ½½¸¯ ·£´ýÃ³¸®½Ã »ç¿ë , ex : $(".elem").randomize().slick();
$.fn.randomize = function (selector) {
    var $elems = selector ? $(this).find(selector) : $(this).children(),
        $parents = $elems.parent();

    $parents.each(function () {
        $(this).children(selector).sort(function (childA, childB) {
            // * Prevent last slide from being reordered
            if ($(childB).index() !== $(this).children(selector).length - 1) {
                return Math.round(Math.random()) - 0.5;
            }
        }.bind(this)).detach().appendTo(this);
    });

    return this;
};

function initMegaPopup() {
    $('.mg_popup_wrap').each(function () {
        if ($(this).data('width')) {
            $(this).css('max-width', $(this).data('width'));
        }
    });

    $('.cmg_popup_wrap').each(function () {
        if ($(this).data('width')) {
            $(this).css('max-width', $(this).data('width'));
        }
    });

    $('.zoom-gallery').magnificPopup({
        delegate: 'a',
        type: 'image',
        closeOnContentClick: false,
        closeBtnInside: false,
        mainClass: 'mfp-with-zoom mfp-img-mobile',
        image: {
            verticalFit: true,
            titleSrc: function (item) {
                return item.el.attr('title') + ' &middot; <a class="image-source-link" href="' + item.el.attr('data-source') + '" target="_blank">¹Ù·Î°¡±â</a>';
            }
        },
        gallery: {
            enabled: true
        },
        zoom: {
            enabled: true,
            duration: 300, // don't foget to change the duration also in CSS
            opener: function (element) {
                return element.find('img');
            }
        }
    });
}

// https://dimsemenov.com/plugins/magnific-popup/documentation.html
function openMegaPopup(popupId, type, closeOnBgClick, fixedContentPos, openCallback, closeCallback) {
    var posY = null;
    var magnificPopupConfiguration = function () {
        return {
            beforeOpen: function () {
                posY = window.pageYOffset;
                $('html').css('overflow', 'hidden');
                $('body').css({ 'position': 'fixed', 'top': -posY });
            },
            resize: function () { },
            open: function () { },
            beforeClose: function () {
                $('html').css('overflow', '');
                $('body').css({ 'position': '', 'top': '' });
                window.scrollTo(0, posY);
            }
        }
    }
    var magnificPopupDimmConfiguration = function (dimmClass) {
        return {
            open: function () {
                $('.mfp-content').prepend('<div class="' + dimmClass + '"></div>');
                if (typeof openCallback === 'function') {
                    openCallback();
                }
            },
            beforeClose: function () {
                $('.mfp-content .' + dimmClass).remove();

            },
            close: function () {
                if (typeof closeCallback === 'function') {
                    closeCallback();
                }
            }
        }
    }
    var defaultOption = {
        items: {
            src: '#' + popupId,
            type: 'inline',
        },
        fixedBgPos: true,
        overflowY: 'auto',
        closeBtnInside: true,
        preloader: false,
        midClick: true,
        removalDelay: 300,
        showCloseBtn: closeOnBgClick === false ? false : true,
        closeOnBgClick: closeOnBgClick === false ? false : true,
        enableEscapeKey: false,
    };

    if (type === 1 || type === undefined) {
        customOption = {
            fixedContentPos: fixedContentPos === false ? false : true,
            removalDelay: 300,
            mainClass: 'mfp-zin',
        }
    } else if (type === 2) {
        customOption = {
            fixedContentPos: fixedContentPos === false ? false : true,
            removalDelay: 300,
            mainClass: 'fade-slideup fix-bottom',
            callbacks: magnificPopupConfiguration(),
        }
    } else if (type === 3) {
        customOption = {
            fixedContentPos: fixedContentPos === false ? false : true,
            removalDelay: 300,
            mainClass: 'fade-slidedown fix-top',
            callbacks: magnificPopupConfiguration(),
        }
    } else if (type === 4 || type === 5 || type === 6) {
        var dimClass = '';
        if (type === 4) {
            dimClass = 'mg_popup_dimm';
        } else if (type === 5) {
            dimClass = 'mg_popup_dimm2';
        } else if (type === 6) {
            dimClass = 'mg_popup_dimm3';
        }
        customOption = {
            fixedContentPos: fixedContentPos === false ? false : true,
            removalDelay: 300,
            mainClass: 'mfp-zin',
            callbacks: magnificPopupDimmConfiguration(dimClass),
        }
    }
    var getOption = Object.assign(defaultOption, customOption);
    $.magnificPopup.open(getOption);
}

function illegalFile(gubn) {
    fncMegaDownload("/userdown/illegal/Àç¹ß¹æÁöÈ®¾à¼­_¸Þ°¡°ø¹«¿ø.pdf", "");
    return false;
}

function illegalSuperPopup(ill) {
    var idV = "illegalSpop";
    var rtn = false;
    try {
        $('#' + idV).remove();
        $.ajax({
            type: "POST",
            async: false,
            url: "/common/popup/illegal.asp?ill=" + ill
        }).done(function (data) {
            if (data != "") {
                $('body').append(data);

                initSuperPopup(idV);
                openSuperPopup(idV);
                rtn = true;
            }
        });
    } catch (error) {
        rtn = false;
    } finally {
        return rtn;
    }
}

function initSuperPopup(popupId) {
    var $target = $('#' + popupId);
    $target.find('.smg_popup_inner').css('max-width', $target.data('width'));
    $('#Wrap').after($target);
}

function openSuperPopup(popupId) {
    $('#' + popupId).show();
}

function closeSuperPopup(popupId) {
    $('#' + popupId).hide();
}

function closeSuperPopupToday(popupId, todayId) {
    setCookiePopupToday(todayId, 'close', 1);
    closeSuperPopup(popupId);
}

function openCmegaPopup(popupId, dimm) {
    if (dimm) {
        $('#' + popupId).before(`<div class="cmg_dimm" id="${popupId}_dimm"></div>`);
        if ($('#' + popupId).hasClass('super')) {
            $('#' + popupId + '_dimm').addClass('super');
        }
    }
    $('#' + popupId).show();
}

function closeCmegaPopup(popupId, remove) {
    if ($('#' + popupId + '_dimm').length) {
        $('#' + popupId + '_dimm').remove();
    }
    if (remove) {
        $('#' + popupId).remove();
    } else {
        $('#' + popupId).hide();
    }
}

$(document).on('click', '.cmg_dimm', function () {
    $(this).next('.cmg_popup_wrap').hide();
    $(this).remove();
});

function setCookiePopupToday(name, value, expiredays) {
    var todayDate = new Date();
    todayDate = new Date(parseInt(todayDate.getTime() / 86400000) * 86400000 + 54000000);
    if (todayDate > new Date()) {
        expiredays = expiredays - 1;
    }
    todayDate.setDate(todayDate.getDate() + expiredays);
    document.cookie = name + "=" + escape(value) + "; path=/; expires=" + todayDate.toGMTString() + ";"
}

function customScrollbar(selector) {
    var isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ? true : false;
    if (!isMobile) {
        $(selector).mCustomScrollbar({
            theme: "minimal-dark",
        });
    } else {
        $(selector).addClass('mo')
    }
}

var globalCookiePopup = {
    cookie_arr: null,
    set: function (name, value, options) {
        options = options || {};
        this.cookie_arr = [escape(name) + '=' + escape(value)];
        //-- expires
        if (options.expires) {
            if (typeof options.expires === 'object' && options.expires instanceof Date) {
                var date = options.expires;
                var expires = "expires=" + date.toUTCString();
                this.cookie_arr.push(expires);
            }
        } else if (options.expires_day) {
            this.set_expires_date(options.expires_day, 24 * 60 * 60);
        } else if (options.expires_hour) {
            this.set_expires_date(options.expires_hour, 60 * 60);
        }
        //-- domain
        if (options.domain) {
            var domain = "domain=" + options.domain;
            this.cookie_arr.push(domain);
        }
        //-- path
        if (options.path) {
            var path = 'path=' + options.path;
            this.cookie_arr.push(path);
        }
        //-- secure
        if (options.secure === true) {
            var secure = 'secure';
            this.cookie_arr.push(secure);
        }
        document.cookie = this.cookie_arr.join('; ');
    },
    get: function (name) {
        var nameEQ = escape(name) + "=";
        var ca = document.cookie.split(';');

        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == ' ') c = c.substring(1, c.length);
            if (c.indexOf(nameEQ) == 0) return unescape(c.substring(nameEQ.length, c.length));
        }
        return null;
    },
    del: function (name, options) {
        options = options || {};
        options.expires_day = -1;
        this.set(name, '', options);
    },
    set_expires_date: function (expires, time) {
        var date = new Date();
        date.setTime(date.getTime() + (expires * time * 1000));
        var expires = "expires=" + date.toUTCString();
        this.cookie_arr.push(expires);
    }
}

var mgFrontHolidays = ["3-1", "5-5", "6-6", "8-15", "2023-9-28", "2023-9-29", "10-3", "10-9", "12-25"]; // ´Þ·Â¿¡¼­ ¼±ÅÃµÇ¸é ¾ÈµÇ´Â °øÈÞÀÏ
var mgCustomFrontHolidays = null;//ÁöÁ¤°øÈÞÀÏ
var mgCustomHolidays = function () {
    var year = new Date().getFullYear();
    mgCustomFrontHolidays = mgFrontHolidays.map(function (holiday, index) {
        if (holiday.length <= 5) {
            return holiday = year + '-' + holiday
        } else {
            return holiday
        }
    });
}
mgCustomHolidays();

// ¸Þ°¡°ø¹«¿ø ÇÁ·ÐÆ® ½ºÅ©¸³Æ®(UI °³¹ß ¸Þ¼­µå ¸ðÀ½)
var mgFrontScript = window.mgFrontScript || (function () {
    return {
        isDay: function (number) {
            /* ¼³¸í : ¿À´Ã ³¯Â¥ Çü½Ä ex) 2023-02-03
               »ç¿ëÃ³ : °øÅë ´Þ·Â ÀÎÇ² */
            var date = new Date(),
                year = date.getFullYear(),
                today = number ? date.getDate() + Number(number) : date.getDate(),
                month = new String(date.getMonth() + 1) < 10 ? '0' + new String(date.getMonth() + 1) : new String(date.getMonth() + 1),
                day = new String(today) < 10 ? '0' + new String(today) : new String(today),
                txt = year + '-' + month + '-' + day;
            return txt;
        },
        onSelectPickerDay: function ($this, dateText, inst) {
            /*  ¼³¸í : ´Þ·Â ¼±ÅÃµÈ ³¯Â¥ Çü½Ä ex) 2023-02-03
                »ç¿ëÃ³ : °øÅë ´Þ·Â jQuery UI datepicker : onSelect ³»ºÎ */
            var date = $.datepicker.parseDate($this.datepicker('option', 'dateFormat'), dateText),
                year = date.getFullYear(),
                month = (date.getMonth() + 1) < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1,
                day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate(),
                txt = year + '-' + month + '-' + day;
            return txt;
        },
        noWeekendsOnly: function (date) {
            /*  ¼³¸í : ´Þ·Â Åä¿äÀÏ, ÀÏ¿äÀÏ ºñÈ°¼ºÈ­
                »ç¿ëÃ³ : °øÅë ´Þ·Â jQuery UI datepicker : beforeShowDay ³»ºÎ */
            var noWeekend = $.datepicker.noWeekends(date);
            return noWeekend[0] ? [true] : noWeekend;
        },

        noWeekendsWithHolidays: function (date) {
            /*  ¼³¸í : ´Þ·Â Åä¿äÀÏ, ÀÏ¿äÀÏ, °øÈÞÀÏ ºñÈ°¼ºÈ­
                »ç¿ëÃ³ : °øÅë ´Þ·Â jQuery UI datepicker : beforeShowDay ³»ºÎ */
            var noWeekend = $.datepicker.noWeekends(date);
            var m = date.getMonth(), d = date.getDate(), y = date.getFullYear();
            for (i = 0; i < mgCustomFrontHolidays.length; i++) {
                if ($.inArray(y + '-' + (m + 1) + '-' + d, mgCustomFrontHolidays) != -1) {
                    return [false];
                }
            }
            if (noWeekend[0]) {
                return [true];
            } else {
                return noWeekend;
            }


        }
    }
}());

//¸Þ°¡ÆÐ½º ÇÒÀÎ °¡°Ý Àû¿ë passTab
function numberWithCommas(number) {
    return Math.ceil(number).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
};

$('.passTab .tab_cont .sale_box').each(function () {
    let origin = +($(this).find('.price .origin_price b').text().split(',').join(""));
    let sale_per = (100 - $(this).find('.price .discount_price .sale_per').text()) / 100;
    $(this).find('.price .discount_price b').text(numberWithCommas(origin * sale_per));
});


// GA·Î º¯°æµÇ´Â URLÀ» ¿ø·¡ URL·Î º¯°æ
function changeGAUrl(url) {
    var currentUrl = url;

    // Á¦°ÅÇÒ ¸Å°³º¯¼öµé
    var parametersToRemove = ["_ga", "_gl"];

    // URL¿¡¼­ ¸Å°³º¯¼ö Á¦°Å
    parametersToRemove.forEach(function (param) {
        var regex = new RegExp(param + "=[^&]*[&]?", "gi");
        currentUrl = currentUrl.replace(regex, "");
    });

    // ¸¸¾à ¸Ç ³¡¿¡ '&' ¹®ÀÚ°¡ ³²¾ÆÀÖ´Ù¸é Á¦°Å
    currentUrl = currentUrl.replace(/&$/, "");

    // º¯°æµÈ URL·Î ÆäÀÌÁö ÀÌµ¿ (URLÀ» º¯°æÇÏ°í ½ÍÁö ¾Ê´Ù¸é ÀÌ ºÎºÐÀ» »ý·«ÇÒ ¼ö ÀÖ½À´Ï´Ù.)
    window.location.href = currentUrl;
}

// ajax È£Ãâ ½Ã »ç¿ëÇÏ´Â ·Îµù È­¸é
function loadingUI(type, hcode) {
    $('body').append('<div id="loading_ui" class="' + hcode + '"><div class="spinner_wrap"><div class="spinner"></div></div></div>');

    $('#loading_ui').show();
    const checkElement = setInterval(function() { // length°¡ 0ÀÌ ¾Æ´Ò ¶§±îÁö ¹Ýº¹
        if (type == 'lecture') {
            if ($('.lectlist .lect_item .listTitle .subject a').text().trim().length > 0) { //°­ÁÂ¸®½ºÆ® ÅØ½ºÆ® À¯¹«
                $('#loading_ui').fadeOut(100);
                clearInterval(checkElement);
            }
        }
    }, 300); // 300ms¸¶´Ù È®ÀÎ

    setTimeout(function(){
        if ($('#loading_ui').css('display') == 'block') {
            $('#loading_ui').fadeOut(100);
            clearInterval(checkElement);
        }
    }, 10 * 1000); // ³×Æ®¿öÅ© ºÒ¾ÈÇÑ »óÈ²¿¡¼­ 10ÃÊ ÀÌÈÄ¿¡ Á¦°Å
}