/*!
 * project
 *
 *
 * @author
 * @version 1.0.0
 * copyright 2020. ISC licensed.
 */
$(document).ready(function(){
    lnbEvt();
    currentPage();
    modalUi();
    fileupload();
    tabUi();
    if ($('select').length){
        $('select').niceSelect();
    }
    if ($('div.teg').length){
        $('input.teg').tagsinput();
    }
    if ($('table.click').length){
        $(this).find('tr').on('click', function () {
            $(this).addClass('on');
            $(this).siblings('tr').removeClass('on');
        });
    }

    $('.video_img ul li a').on('click', function () {
        $(this).parent().addClass('on');
        $(this).parent().siblings('li').removeClass('on');
    });

    // 체크 박스 모두 체크
    $("input:checkbox[name='all']").on('click', function() {
        if(this.checked){
            $("input:checkbox[name='checkbox']").prop("checked", true);
        }
        else {
            $("input:checkbox[name='checkbox']").prop("checked", false);
        }
    });

    // 체크 박스 체크에 따른 '모두 체크' 변경
    checkAllChecked();

    // datepicker type
    $(function () {
        $('.datetimepicker_month').datetimepicker({
            format: 'MM월',
            //locale: 'ko',
        });
        $('.datetimepicker').datetimepicker({
            format: 'YYYY-MM-DD',
            //locale: 'ko',
        });
        $('.datetimepicker_day_sec').datetimepicker({
            format: 'YYYY-MM-DD/HH:mm:ss',
            //locale: 'ko',
        });
        $('.datetimepicker_day_min').datetimepicker({
            format: 'YYYY-MM-DD/HH:mm',
            //locale: 'ko',
        });
        $('.datetimepicker_time_only').datetimepicker({
            format: 'LT',
            //locale: 'ko',
        });
        $('.datetimepicker_day_hour').datetimepicker({
            format: 'YYYY-MM-DD/HH시',
            //locale: 'ko',
        });
        $('.datetimepicker_year').datetimepicker({
            //locale: 'ko',
            format: 'YYYY',
            viewMode: 'years',
        });
        $('.datetimepicker_from').datetimepicker({
            format: 'YYYY-MM-DD',
            //locale: 'ko',
        });
        $('.datetimepicker_to').datetimepicker({
            format: 'YYYY-MM-DD',
            //locale: 'ko',
            useCurrent: false, //Important! See issue #1075
        });

        $('.datetimepicker_time_only_from').datetimepicker({
            format: 'HH:mm',
            //locale: 'ko',
            // disabledHours: true,
            useCurrent: false,
        });
        $('.datetimepicker_time_only_to').datetimepicker({
            format: 'HH:mm',
            //locale: 'ko',
            // enabledHours: true ,
            useCurrent: false, //Important! See issue #1075
        });

        $('.datetimepicker_min_from').datetimepicker({
            format: 'YY-MM-DD/HH:mm',
            //locale: 'ko',
        });
        $('.datetimepicker_min_to').datetimepicker({
            format: 'YY-MM-DD/HH:mm',
            //locale: 'ko',
            useCurrent: false, //Important! See issue #1075
        });


        $(".datetimepicker_min_from").on("dp.change", function (e) {
            $('.datetimepicker_min_to').data("DateTimePicker").minDate(e.date);
        });
        $(".datetimepicker_min_to").on("dp.change", function (e) {
            $('.datetimepicker_min_from').data("DateTimePicker").maxDate(e.date);
        });


        $(".datetimepicker_from").on("dp.change", function (e) {
            $('.datetimepicker_to').data("DateTimePicker").minDate(e.date);
        });
        $(".datetimepicker_to").on("dp.change", function (e) {
            $('.datetimepicker_from').data("DateTimePicker").maxDate(e.date);
        });

        $(".datetimepicker_time_only_from").on("dp.change", function (e) {
            $('.datetimepicker_time_only_to').data("DateTimePicker").minDate(e.date);
        });
        $(".datetimepicker_time_only_to").on("dp.change", function (e) {
            $('.datetimepicker_time_only_from').data("DateTimePicker").maxDate(e.date);
        });

    });
});

function lnbEvt(){
    $('.lnb_menu_menu').on('click', function() {
        $('.lnb_menu_btn_area').toggleClass('open');
        if($('.lnb_menu_btn_area').hasClass('open')){
            $('.lnb_menu_menu p').html("메뉴닫기");
            $('article').removeClass('close');
            $('section').removeClass('wide');
            return false;
        }else {
            $('.lnb_menu_menu p').html("메뉴열기");
            $('article').addClass('close');
            $('section').addClass('wide');
            return false;
        }
    });
    if ($('.lnb > li > ul').hasClass('depth2')) {
        $('.lnb > li > ul').parent().addClass('has_children');
    }
    if ($('.lnb > li > ul > li > ul').hasClass('depth3')) {
        $('.lnb > li > ul > li > ul').parent().addClass('has_children');
    }
    $('.lnb > li.has_children > a').attr('href', '#');
    $('.lnb > li > a').on('click', function(e){
        e.preventDefault();

        $(this).parent().toggleClass('active');
        // $(this).parent().siblings('li').removeClass('active');
        // $(this).parent().addClass('active');
    });
    if (window.matchMedia('(max-width: 1300px)').matches){
        $('.lnb_menu_menu p').html("메뉴열기");
        $('article').addClass('close');
        $('section').addClass('wide');
        $('.lnb_menu_btn_area').removeClass('open');
    }
}

$(window).resize(function() {
    if (window.matchMedia('(max-width: 1300px)').matches){
        $('.lnb_menu_menu p').html("메뉴열기");
        $('article').addClass('close');
        $('section').addClass('wide');
        $('.lnb_menu_btn_area').removeClass('open');
    }
    var layerHeight = $('.modal').height();
    var layerWidth = $('.modal').width();
    if ($('.modal').hasClass('open')){
        $('.modal').css({
            marginLeft : -layerWidth/2,
            marginTop : -layerHeight/2
        });
    }
});

// 현재 선택된 메뉴 style 적용
function currentPage() {
	var locationUrl = $(location).attr('pathname');
	var dom = $('li.has_children').find('a[href="' + locationUrl + '"]');

	$(dom).addClass('on');
	$(dom).parents('li.has_children').addClass('active');
}

function modalUi() {
    $('a.modalLoad').on('click',function(){
        var $self = $(this);
        var $thisrel = $self.attr('rel');
        var $target = $('#'+ $thisrel);

        // open and focusin
        $target.attr('tabindex', '0').fadeIn(250).focus();
        $target.css({ display: 'table' });
        $target.attr('class', 'modal open');
        // create sizing
        var layerHeight = $target.outerHeight();
        var layerWidth = $target.outerWidth();
        $target.css({
            marginLeft : -layerWidth/2,
            marginTop : -layerHeight/2
        });

        // create background
        createDim();

        // keydown focus repeat
        $target.find(".close").on('keydown', function(e){
            if(e.which=='9'){
                $target.attr('tabindex', '0').focus();
            }
        });

        // close and focusout
        $target.find(".close").on('click',function(e){
            e.preventDefault();
            $target.fadeOut(250);
            removeDim();
            $self.focus();
            $(this).off('click');
            $target.attr('class', 'modal');
            var isVisible = $target.is(':visible');
            var modalLength = $('.modal:visible').length;

            if (isVisible) {
                if (modalLength > 1) {
                    $target.fadeOut(250);
                } else {
                    $('.dim').fadeOut(250);
                }
            }
        });

        $target.find(".modalLoad").on('click',function(e){
            e.preventDefault();
            $target.fadeOut(250);
            $self.focus();
            var isVisible = $target.is(':visible');
            var modalLength = $('.modal:visible').length;

            if (isVisible) {
                if (modalLength > 1) {
                    $target.fadeOut(250);
                } else {
                    $('.dim').fadeOut(250);
                }
            }
        });

        $(document).on("keyup", function(e){
            if(e.which=='27'){
                $target.fadeOut(250);
                removeDim();
                $self.focus();
                $target.attr('class', 'modal');
            }
        });
    });
    $('table .modalLoad').on('dblclick',function(){
        var $self = $(this);
        var $thisrel = $self.attr('rel');
        var $target = $('#'+ $thisrel);

        // open and focusin
        $target.attr('tabindex', '0').fadeIn(250).focus();
        $target.css({ display: 'table' });
        $target.attr('class', 'modal open');
        // create sizing
        var layerHeight = $target.outerHeight();
        var layerWidth = $target.outerWidth();
        $target.css({
            marginLeft : -layerWidth/2,
            marginTop : -layerHeight/2
        });

        // create sizing
        // var layerHeight = $target.outerHeight();
        //         // var layerWidth = $target.outerWidth();
        //         // $target.css({
        //         //     marginLeft : -layerWidth/2,
        //         //     marginTop : -layerHeight/2
        //         // });

        // create background
        createDim();

        // keydown focus repeat
        $target.find(".close").on('keydown', function(e){
            if(e.which=='9'){
                $target.attr('tabindex', '0').focus();
            }
        });

        // close and focusout
        $target.find(".close").on('click',function(e){
            e.preventDefault();
            $target.fadeOut(250);
            removeDim();
            $self.focus();
            $(this).off('click');
            $target.attr('class', 'modal');
            var isVisible = $target.is(':visible');
            var modalLength = $('.modal:visible').length;

            if (isVisible) {
                if (modalLength > 1) {
                    $target.fadeOut(250);
                } else {
                    $('.dim').fadeOut(250);
                }
            }
        });

        $target.find(".modalLoad").on('click',function(e){
            e.preventDefault();
            $target.fadeOut(250);
            $self.focus();
            var isVisible = $target.is(':visible');
            var modalLength = $('.modal:visible').length;

            if (isVisible) {
                if (modalLength > 1) {
                    $target.fadeOut(250);
                } else {
                    $('.dim').fadeOut(250);
                }
            }
        });

        $(document).on("keyup", function(e){
            if(e.which=='27'){
                $target.fadeOut(250);
                removeDim();
                $self.focus();
                $target.attr('class', 'modal');
            }
        });
    });
}

function createDim(){
    if (!$('.dim').length) {
        $('body').append('<div class="dim"></div>');
    }
    $('.dim').fadeIn(250);
    $('body').css({
        overflow : 'hidden'
    }).bind('touchmove', function(e) {
        e.preventDefault();
    });
}

function removeDim(){
    $('.dim').fadeOut(250);
    $('body').css({
        overflow : 'inherit'
    }).unbind('touchmove');
}

function fileupload() {
    var fileTarget = $('.file_upload .upload_hidden');
    fileTarget.on('change', function () { // 값이 변경되면
        if(window.FileReader){ // modern browser
            var filename = $(this)[0].files[0].name;
        } else { // old IE
            var filename = $(this).val().split('/').pop().split('\\').pop(); // 파일명만 추출
        }

        // 추출한 파일명 삽입
        $(this).siblings('.upload_name').val(filename);
    });
}

function tabUi(){
    var idx = $('.tab_cont').index();
    $('.tab_cont').not(':eq('+idx+')').hide(); // tab_cont :: all hide

    $('.tab_lst').each(function(){ // tab_lst li first :: on
        var $this = $(this);
        var $first_lst = $(this).children('li').eq(0);
        $first_lst.addClass('on');
    });

    $('.tab_container').each(function () { // tab_cont first :: on
        var $this = $(this);
        var $first_tab = $(this).children('.tab_cont').eq(0);
        $first_tab.show();
    });

    var $btn_tab = $('.tab_lst').find('li');
    $btn_tab.on('click', function(e){
        e.preventDefault();

        var contTop = $('.tab_container').offset();
        $('.newmodal_body').scrollTop(contTop);


        var $this = $(this),
            $thisrel = $this.attr('rel'); // tab_lst li :: rel
        $thisClass = $('.'+ $thisrel); // tab_cont :: class
        target = $thisClass.parent('.tab_container').attr('id'); // tab_container :: id

        $('#' + target).find('.tab_cont').hide();
        $('#' + target + ' .' + $thisrel).fadeIn(150);

        $this.addClass('on').siblings().removeClass('on'); // tab_lst li :: on

    });
}

//오늘 날짜
function getToday() {
	return new Date();
}

// 오늘 기준 특정 일자 구하기
// fromToday : 오늘로부터 구하고자 하는 날짜 (ex> 어제:-1, 7일 후:7)
function getDayFromToday(fromToday) {
	var todayDate = new Date();
	var yesterDay = todayDate.getTime() + (fromToday * 24 * 60 * 60 * 1000);
	var yesterDate = new Date(yesterDay);

	return yesterDate;
}

// 기본 날짜 선택
function defaultDataSet(fromDate, toDate) {
	// datetimepicker format 지정
	// format info -> https://momentjs.com/docs/#/displaying/format/
	$('.datetimepicker_from').datetimepicker().data('DateTimePicker').format('YYYY-MM-DD');
	$('.datetimepicker_to').datetimepicker().data('DateTimePicker').format('YYYY-MM-DD');

	// date Set
	$('.datetimepicker_from').datetimepicker().data('DateTimePicker').date(fromDate);
	$('.datetimepicker_to').datetimepicker().data('DateTimePicker').date(toDate);
}

// datetimepicker 사용
/*
	strSelector : jqeury selector (ex> '.class' / '#id' 등등)
	dateFormat : info -> https://momentjs.com/docs/#/displaying/format/
*/
function setDatetimepicker(strSelector, dateFormat) {
	return $(strSelector).datetimepicker().data('DateTimePicker').format(dateFormat);
}

// datetimepicker 사용, 날짜 지정
/*
	strSelector : jqeury selector (ex> '.class' / '#id' 등등)
	dateFormat : info -> https://momentjs.com/docs/#/displaying/format/
	selectDate : 셋팅 할 date (ex> '2019-05-20')
*/
function setDatetimepickerWithDate(strSelector, dateFormat, selectDate) {
	var obj = setDatetimepicker(strSelector, dateFormat);

	obj.date(selectDate);
}


// 체크 박스 체크에 따른 '모두 체크' 변경
function checkAllChecked() {
   $('input:checkbox[name="checkbox"]').on('click', function() {
		if ($("input:checkbox[name=checkbox]:checked").length == $("input:checkbox[name=checkbox]").length) {
			$("input:checkbox[name='all']").prop("checked", true);
		}
		else {
			$("input:checkbox[name='all']").prop("checked", false);
		}
   });
}
