var fileUpdateCnt = 0; 
var loadFile = 0;
var closeProductNumber = 0;
var $thisUploadCheck = '', taxUse = '', CANCEL = false, ABORT = false;
var uadmin = '';
(function (jQuery) {
    jQuery.modalON = function (text,bgcolor) {
        var checkSetBgcolor = (typeof bgcolor != 'undefined' && bgcolor) ? true : false;

        bgcolor = (checkSetBgcolor) ? bgcolor : '#fff';
        var msg = (text) ? text : '';
        
        if ($('.ModalPlugin').length < 1) {
            $('body').prepend('<div class="ModalPlugin"><svg version="1.1" xmlns="http://www.w3.org/svg/2000" viewBox="0 0 30 30" width="60"><circle cy="15" cx="15" r="14" /></svg><p>' + msg + '</p></div>');
        }

        $('.ModalPlugin').css({
            "display": "inherit",
            "position": "fixed",
            "z-index": "99999999",
            "top": "0",
            "left": "0",
            "right": "0",
            "bottom": "0",
            "background": bgcolor,
            "width": "100%",
            "text-align": "center",
            "height": "100%"
        });
        if(!checkSetBgcolor) $('.ModalPlugin p').css('color','#3f3f3f');
        $('.ModalPlugin').show();
        $(document)
            .off('click','.ModalPlugin')
            .on ('click','.ModalPlugin', function(e) {
                e.preventDefault();
            });
    }

    jQuery.modalOFF = function () {
        $('.ModalPlugin').remove();
    }

    jQuery.uploadON = function (text) {
        UPLOAD = 0;
        UPLOADED = 0;
        PROGRESS = 0;
        var msg = (text) ? text : 'Uploading images...';
        if ($('.uploadModal').length < 1) {
            $('body').prepend('<div class="uploadModal"></div>');
            $('.uploadModal').append('<button class="cl-mobile-btn upload-close close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16"><polygon points="16 1 15 0 8 7 1 0 0 1 7 8 0 15 1 16 8 9 15 16 16 15 9 8 "></polygon></svg></span></button>');
            $('.uploadModal').append('<div class="upload-wrap"></div>');
            $('.uploadModal .upload-wrap').append('<div class="upload-header"></div>');
            $('.uploadModal .upload-wrap').append('<div class="upload-content"></div>');

            $('.uploadModal .upload-header').append('<h1>' + $.lang[LANG]['editor.upload.title.1'] + '</h1>');
            $('.uploadModal .upload-header').append('<button type="" class="upload-close close"><span><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16"><path d="M8.71 8l7.15-7.15c0.2-0.2 0.2-0.51 0-0.71s-0.51-0.2-0.71 0L8 7.29 0.85 0.15c-0.2-0.2-0.51-0.2-0.71 0s-0.2 0.51 0 0.71L7.29 8l-7.15 7.15c-0.2 0.2-0.2 0.51 0 0.71C0.24 15.95 0.37 16 0.5 16s0.26-0.05 0.35-0.15L8 8.71l7.15 7.15c0.1 0.1 0.23 0.15 0.35 0.15s0.26-0.05 0.35-0.15c0.2-0.2 0.2-0.51 0-0.71L8.71 8z"></path></svg></span></button>');
            $('.uploadModal .upload-content').append('<div class="upload-cancel"><div class="btn btn-default">' + $.lang[LANG]['config.close'] + '</div></div>');
        }
        $('.uploadModal .upload-content').find('.file').remove();

        $progress = $('<div id="file-upload-progress" class="file-upload-progress"></div>');
        $bar = $('<div class="progress-bar"></div>');
        $progress.css({
            'height': '2px',
            'background-color':'#d1d3d5',
            'overflow' : 'hidden',
        });
        $progress.append($bar);
        if($('.uploadModal #file-upload-progress').length==0) {
            $('.uploadModal .upload-header').append($progress);
            $('.uploadModal .upload-header').append('<div class="info1"></div>');
            $('.uploadModal .upload-header').append('<div class="info2"></div>');
        }
        // $('.uploadModal').show();
    }

    jQuery.uploadOFF = function () {
        $('.uploadModal').fadeOut(500, function(){
            $(this).remove();
        });
    }

    jQuery.upload_add = function(e,data,upload_type) {
        $('.uploadModal').show();
        var submit = true, err = '';

        var checkPlan = false,
            checkPlanType = '',
            filesize = data.files[0].size,
            maxsize = 10485760; //10MB == 10485760Byte

        if(typeof PAGE_MODE != 'undefined') {
            if (PAGE_MODE == 'c') {
                checkPlan = VALIDPLAN;
                checkPlanType = VALIDTYPE;
            } else if(typeof property != 'undefined' && property) {
                checkPlan = property.VALIDPLAN;
                checkPlanType = property.VALIDTYPE;
            }
        }
        if(upload_type == 'flink' && checkPlan && $.inArray(checkPlanType,['BN','SM']) > -1) maxsize = 104857600; //100MB == 104857600Byte
        if(upload_type == 'forum_file' && VALIDPLAN && $.inArray(VALIDTYPE,['BN','SM']) > -1) maxsize = 104857600; //100MB == 104857600Byte

        if( filesize > maxsize) {
            filesize = (filesize/1024/1024).toFixed(1);
            if(maxsize == 104857600) err = $.lang[LANG]['editor.upload.max.100'] + $.lang[LANG]['editor.upload.max.2'];
            else err = $.lang[LANG]['editor.upload.max.1'] + $.lang[LANG]['editor.upload.max.2'];
            submit = false;
        }

        var image_types = 'jpg|jpeg|png|bmp|ico|gif|psd|ai|icns|webp',
            text_types = 'txt|hwp|hwpx|hwt|doc|docx|docm|pdf|xls|xlsx|ppt|pps|ppsm|ppsx|pptx|pptm|potx|rtf|csv',
            audio_types = 'mp3|wma|wav|ogg',
            video_types = 'mp4|avi|wmv|mpg|mpeg',
            etc_types = 'zip|7z|rar|ttf|otf',
            allowed_types = '';

        var filename = data.files[0].name;
        var search = /%/g,
            match = filename.match(search);

        if(match===null) {
            var uploadErrors = [];
            if(upload_type == 'flink' || upload_type == 'forum_file') {
                allowed_types = image_types + '|' + text_types + '|' + audio_types + '|' + video_types + '|' + etc_types;
                var validFileAllTypes = allowed_types.split('|'),
                    alltypeAry = data.files[0]['name'].toLowerCase().split('.');
                if (validFileAllTypes.indexOf(alltypeAry[alltypeAry.length - 1]) == -1) {
                    console.log(data.files[0]['name'] + ' => ' + data.files[0]['type']);

                    err = $.lang[LANG]['editor.upload.error.flink'];
                    submit = false;
                }
            } else {
                var validImageTypes = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
                var imgtypeAry = data.files[0]['name'].toLowerCase().split('.');
                if (validImageTypes.indexOf(imgtypeAry[imgtypeAry.length - 1]) == -1) {
                    err = $.lang[LANG]['editor.upload.error.ext'];
                    submit = false;
                }
            }

        } else {
            err = $.lang[LANG]['editor.upload.filename'];
            submit = false;
        }

        var fileSize = (data.files[0].size/1024/1024).toFixed(1) + 'MB';
        var tpl = '<div class="file">\
            <div class="progress"><div class="progress-bar"></div></div>\
            <div class="progress-info"><span class="file-name">' + data.files[0].name + '</span><span class="file-size">' + fileSize + '</span><span class="ing">' + $.lang[LANG]['editor.upload.response'] + '</span></div>\
            <div class="preview"></div>\
            </div>';
        data.context = $(tpl).insertBefore($('.uploadModal .upload-content .upload-cancel'));

        if(upload_type == 'all') {
            data.context.find('.preview').addClass('not_image');
        } else {
            if(data.files[0].type.match('image.*')) {
                if (data.files && data.files[0]) {
                    var reader = new FileReader();
                    reader.onload = function(e) {
                        // data.context.find('.preview').append('<img src="' + e.target.result + '">');
                        if(e.target.result != '') {
                            data.context.find('.preview').css('background-image', 'url(' + e.target.result + ')');
                        }
                        else {
                            data.context.find('.preview').addClass('no_preview');
                        }
                    }
                    reader.readAsDataURL(data.files[0]);
                }
            } else data.context.find('.preview').addClass('not_image');
        }

        return {
            submit : submit,
            err : err
        }
    }

    jQuery.upload_progress = function(e,data) {
        var rate = (data.bitrate/1024).toFixed(1) + 'kbps';
        var progress = parseInt((data.loaded / data.total) * 100, 10);
        if(typeof data.context != 'undefined') {
            data.context.find('.res').text(data.bitrate);
            data.context.find('.progress-bar').css('width',progress + '%');
            data.context.find('.ing').text(progress + '%');
            data.context.find('.rate').text(rate);
            if(progress == 100) {
                data.context.find('.ing').text($.lang[LANG]['editor.upload.response']);
            }
        }
    }

    jQuery.upload_done = function(e,data) {
        data.context.addClass('done');
        data.context.find('i').removeClass("fa-circle-o-notch fa-spin fa-3x fa-fw").addClass("fa-check");
        data.context.find('.ing').text($.lang[LANG]['editor.upload.done']);
        data.context.find('.rate').fadeOut();

        if(typeof data.result.error != 'undefined') {
            data.context.find('.loading').html('<i class="fa fa-times error"></i>');
            data.context.find('.ing').addClass('error').text(data.result.error);
        }
    }

    jQuery.upload_progressall = function(e,data) {
        var total = (data.total/1024/1024).toFixed(1) + 'MB';
        $('.uploadModal .info1').text($.lang[LANG]['editor.upload.size.total'] + total);
        $('.uploadModal .info2').html('<span>' + (UPLOADED+1) + '</span>/' + UPLOAD.toString());
        var progress = parseInt((data.loaded / data.total) * 100, 10);
        $('.file-upload-progress .progress-bar').css('width',progress + '%');
    }

    jQuery.upload_start = function(e,data) {
        $('.uploadModal .upload-header h1').text($.lang[LANG]['editor.upload.title.2']);
        $('.uploadModal .upload-content .upload-cancel .btn-default').text($.lang[LANG]['config.cancel']);
    }

    jQuery.progressON = function(text,sub,delay,cancel_off) {
        CANCEL = false;
        var msg = (typeof text !='undefined') ? text : $.lang[LANG]['editor.delete.title.2'];
        if ($('.progressModal').length < 1) {
            $('body').prepend('<div class="progressModal"></div>');
            if( (typeof text !='undefined' && text == '이미지를 업로드 중입니다.') || (typeof text != 'undefined' && text == 'Uploading...')) {
                $('.progressModal').append("<div class='progress-wrap btn-bottom-wrap-bgcolor'></div>");
            } else {
                $('.progressModal').append("<div class='progress-wrap'></div>");
            }
            $('.progressModal .progress-wrap').append("<div class='progress-header'></div>");
            $('.progressModal .progress-wrap').append("<div class='progress-content'></div>");

            $('.progressModal .progress-header').append('<h1>' + msg + '</h1>');
            // $('.progressModal .progress-header').append('<div class="close"></div>');
            
            if(typeof cancel_off != 'undefined' && cancel_off === true) {
            } else {
                if(typeof delay == 'undefined') {
                    $('.progressModal .progress-content').append('<div class="progress-cancel"><div class="btn btn-default">' + $.lang[LANG]['config.cancel'] + '</div></div>');
                } else {
                    setTimeout(function() {
                        $('.progressModal .progress-content').append('<div class="progress-cancel"><div class="btn btn-default">' + $.lang[LANG]['config.cancel'] + '</div></div>');
                    },delay);
                }
            }
            $progress = $('<div id="file-upload-progress" class="file-upload-progress"></div>');
            $bar = $('<div class="progress-bar progress-bar-success"></div>');
            $progress.css({
                'height': '5px',
                'background-color':'#f5f5f5',
                'overflow' : 'hidden',
            });
            $progress.append($bar);
            $progress = $('<div id="file-upload-progress" class="file-upload-progress"></div>');
            $bar = $('<div class="progress-bar"></div>');
            $progress.css({
                'height': '2px',
                'background-color':'#f5f5f5',
                'overflow' : 'hidden',
            });
            $progress.append($bar);
            if($('.progressModal #file-upload-progress').length==0) {
                $('.progressModal .progress-header').append($progress);
                $('.progressModal .progress-header').append('<div class="info1"></div>');
                $('.progressModal .progress-header').append('<div class="info2"></div>');
                $('.progressModal .progress-header').append('<p>&nbsp;</p>');
            }            
        }
        if(typeof sub != 'undefined') {
            $('.progressModal .progress-header .info1').html('<i class="fa fa-circle-o-notch fa-spin fa-3x fa-fw"></i> ' + sub);
        }

        $('body').addClass('overflow-hidden');

        $(document).on('click','.progress-cancel',function(e) {
            CANCEL = true; ABORT = true;
            $.progressOFF();
        });
        $('.progressModal').show();
    }

    jQuery.progressOFF = function() {
        $('body').removeClass('overflow-hidden');
        $('.progressModal').fadeOut().remove();
    }

    jQuery.processON = function(text,bg) {
        var msg = (text) ? text : '';
        bg = (bg) ? bg : 'rgba(0,0,0,0.75)';
        if ($('.processModal').length < 1) {
            if($('.reorderModal').length) {
                $('.reorderModal').after('<div class="processModal"><svg version="1.1" xmlns="http://www.w3.org/svg/2000" viewBox="0 0 30 30" width="60"><circle cy="15" cx="15" r="14" /></svg><p>' + msg + '</p></div>');
            } else {
                $('body').prepend('<div class="processModal"><svg version="1.1" xmlns="http://www.w3.org/svg/2000" viewBox="0 0 30 30" width="60"><circle cy="15" cx="15" r="14" /></svg><p>' + msg + '</p></div>');
            }
        } else {
            $('.processModal').find('p').html(text);
        }

        $('.processModal').css({
            'display': 'inherit',
            'position': 'fixed',
            'z-index': '9999999999',
            'top': '0',
            'left': '0',
            'width': '100%',
            'text-align': 'center',
            'height': '100%',
            'background-color' : bg
        });
        $('.processModal').fadeIn();
    }

    jQuery.processOFF = function() {
        $('.processModal').fadeOut().remove();
    }

    jQuery.loadingOn = function(selector,txt) {
        if(typeof txt == 'undefined') txt = '';
        selector.prepend('<div class="loadingModal"><svg class="spin_svg" version="1.1" xmlns="http://www.w3.org/svg/2000" viewBox="0 0 30 30" width="60"><circle cy="15" cx="15" r="14" /></svg><p>' + txt + '</p></div>');        $('.loadingModal').css({
            'display': 'inherit',
            'position': 'absolute',
            'z-index': '9999999999',
            'top': '0',
            'left': '0',
            'width': '100%',
            'text-align': 'center',
            'height': '100%',
            'background-color' : ''
        });
        $('.loadingModal').fadeIn();
    }

    jQuery.loadingOFF = function() {
        $('.loadingModal').fadeOut().remove();
    }

    jQuery.guideON = function(step) {
        hideElementListPanel();
        var $guide = $('<div class="guideModal"></div>');

        if ($('.guideModal').length < 1) {
            $('body').prepend($guide);
            $('.guideModal').append('<div class="content"></div>')
            $('.guideModal').css({
                'display': 'inherit',
                'position': 'fixed',
                'z-index': '99999999',
                'top': '0',
                'left': '0',
                'width': '100%',
                'text-align': 'center',
                'background-color' : 'transparent',
                'height': '100%',
            });
            $('.guideModal .content').css({
                'width' : '100%',
                'height' : '100%',
                'background-color' : 'rgba(0,0,0,0.6)',
                'margin-top' : '35px'
            });
            $('.guideModal').fadeIn();
        }

        $('.guideModal').find('.popover').fadeOut().remove();
        $('.menu-config.edit-menu').removeClass('active');
        $('.menu-config.edit-site').removeClass('active');
        $('.el_0_ctrl .config-element').css('z-index','4');
        $('.addElementButton').css('z-index','1');
        $('.config-image-edit').hide();
        $('.config-element').removeClass('disabled');
        $('.add-block').removeClass('disabled');

        switch(step) {
            case 1 : 
                $('.menu-config.edit-menu').addClass('active');
                var str = '\
                <div class="popover bottom">\
                    <div class="arrow"></div>\
                    <div class="popover-content" style="padding:15px 15px 10px;font-weight:600;">\
                        <p>' + $.lang[LANG]["editor.guide.steps.1"] + '</p>\
                    </div>\
                    <h3 style="padding:5px;overflow:auto;" class="popover-title" id="popover-bottom">\
                        <div class="pull-left"><span class="btn btn-default btn-sm" onclick="$.guideON();">' + $.lang[LANG]['config.close'] + '</span></div>\
                        <div class="pull-right"><span style="padding-right:5px;"> <b>1</b> / 7 </span><span class="btn btn-primary btn-sm" onclick="$.guideON(2);">' + $.lang[LANG]['editor.guide.next'] + '</span></div>\
                    </h3>\
                </div>\
                ';
                $step1 = $(str);
                $('.guideModal').find('.content').append($step1);
                $step1.css({
                    'top' : $('.editor-navbar').outerHeight()+2,
                    'left' : '0px'
                });

                $('.dsgn-body').scrollTop(0);
                $step1.fadeIn();
                break;

            case 2 :
                $('.menu-config.edit-site').addClass('active');
                var str = '\
                <div class="popover bottom">\
                    <div class="arrow"></div>\
                    <div class="popover-content" style="padding:15px 15px 10px;font-weight:600;">\
                        <p>' + $.lang[LANG]["editor.guide.steps.2"] + '</p>\
                    </div>\
                    <h3 style="padding:5px;overflow:auto;" class="popover-title" id="popover-bottom">\
                        <div class="pull-left"><button class="btn btn-default btn-sm" onclick="$.guideON()">' + $.lang[LANG]['config.close'] + '</button></div>\
                        <div class="pull-right"><span style="padding-right:5px;"> <b>2</b> / 7 </span><span class="btn btn-primary btn-sm" onclick="$.guideON(3);">' + $.lang[LANG]['editor.guide.next'] + '</span></div>\
                    </h3>\
                </div>\
                ';
                $step2 = $(str);
                $('.guideModal').find('.content').append($step2);
                $step2.css({
                    'top' : $('.editor-navbar').outerHeight()+2,
                    'left' : '268px'
                });
                $step2.fadeIn();
                break;

            case 3:
                $('.menu-config.edit-site').removeClass('active');
                $('.element').removeClass('active');
                if($('.el_0').length<1) {
                    $.guideON(13);
                    return false;
                }
                $('.el_0_ctrl').hide();
                $('.config-element-section').first().show().addClass('active');
                //$('.el_0_ctrl').show();

                var popover_direction = ($('header').hasClass('sidebar')) ? 'right' : 'left',
                    arrow_style = (popover_direction == 'right') ? 'style="left:-8px; margin-top: -8px; border-right: none;"' : '';
                var str = '\
                <div class="popover '+popover_direction+'">\
                    <div class="arrow" '+arrow_style+'></div>\
                    <div class="popover-content" style="padding:15px 15px 10px;font-weight:600;">\
                        <p>' + $.lang[LANG]["editor.guide.steps.3"] + '</p>\
                    </div>\
                    <h3 style="padding:5px;overflow:auto;" class="popover-title" id="popover-bottom">\
                        <div class="pull-left"><button class="btn btn-default btn-sm" onclick="$.guideON()">' + $.lang[LANG]['config.close'] + '</button></div>\
                        <div class="pull-right"><span style="padding-right:5px;"> <b>3</b> / 7 </span><span class="btn btn-primary btn-sm" onclick="$.guideON(4);">' + $.lang[LANG]['editor.guide.next'] + '</span></div>\
                    </h3>\
                </div>\
                ';
                $step3 = $(str);
                $('.guideModal').find('.content').append($step3);
                var right = ($('header').hasClass('sidebar')) ? 'inherit' : '80px',
                    left = ($('header').hasClass('sidebar')) ?  '270px' : 'inherit';
                $step3.css({
                    'left' : left,
                    'top'  : 0,
                    'right' : right
                });
                $step3.fadeIn();
                $('.el-menu_ctrl').show().css('z-index','99999999');
                addElementButtonDisplay('el_0');
                break;

            case 4:
                $('.el-menu_ctrl').hide();
                var winHeight = $('.dsgn-body').height(),
                    elOffsetTop = $('.addel_0').offset().top;

                var arrow = (winHeight>elOffsetTop) ? 'bottom' : 'top';
                $('.addElementButton').css('z-index','99999999');
                $('.add-block').removeClass('disabled').css('z-index','99999999');
                $('.addel_0 li .add-block').show().css('z-index','99999999');

                var str = '\
                <div class="popover ' + arrow + '">\
                    <div class="arrow"></div>\
                    <div class="popover-content" style="padding:15px 15px 10px;font-weight:600;">\
                        <p>' + $.lang[LANG]["editor.guide.steps.4"] + '</p>\
                    </div>\
                    <h3 style="padding:5px;overflow:auto;" class="popover-title" id="popover-bottom">\
                        <div class="pull-left"><button class="btn btn-default btn-sm" onclick="$.guideON()">' + $.lang[LANG]['config.close'] + '</button></div>\
                        <div class="pull-right"><span style="padding-right:5px;"> <b>4</b> / 7 </span><span class="btn btn-primary btn-sm" onclick="$.guideON(5);">' + $.lang[LANG]['editor.guide.next'] + '</span></div>\
                    </h3>\
                </div>\
                ';
                $step4 = $(str);
                $('.guideModal').find('.content').append($step4);

                var left = ($('.dsgn-body').width()/2) - ($step4.width()/2) - 10;
                if($('header').hasClass('sidebar')) left = left + 260;

                if(elOffsetTop>winHeight) {
                    $('.dsgn-body').animate({scrollTop:elOffsetTop-($('.dsgn-body').height()/2)},'500','swing', function() {
                        var top = $('.addel_0').offset().top - 150;
                        $step4.css({
                            'top' : top + 'px',
                            'left' : left + 'px'
                        });
                        $step4.fadeIn();
                    });
                } else {
                    if(winHeight/2 > elOffsetTop) {
                        $step4.removeClass(arrow).addClass('bottom');
                        var top = elOffsetTop + 40;
                        $step4.css({
                            'top' : top + 'px',
                            'left' : left + 'px'
                        });
                        $step4.fadeIn();
                    } else {
                        $step4.removeClass(arrow).addClass('top');
                        var top = elOffsetTop -150;
                        $step4.css({
                            'top' : top + 'px',
                            'left' : left + 'px'
                        });
                        $step4.fadeIn();
                    }
                }
                break;

            case 5: 
                showElList();

                var str = '\
                <div class="popover right">\
                    <div class="arrow" style="left:-8px; margin-top: -8px; border-right: none;"></div>\
                    <div class="popover-content" style="padding:15px 15px 10px;font-weight:600;">\
                        <p>' + $.lang[LANG]["editor.guide.steps.5"] + '</p>\
                    </div>\
                    <h3 style="padding:5px;overflow:auto;" class="popover-title" id="popover-bottom">\
                        <div class="pull-left"><button class="btn btn-default btn-sm" onclick="$.guideON()">' + $.lang[LANG]['config.close'] + '</button></div>\
                        <div class="pull-right"><span style="padding-right:5px;"> <b>5</b> / 7 </span><span class="btn btn-primary btn-sm" onclick="$.guideON(6);">' + $.lang[LANG]['editor.guide.next'] + '</span></div>\
                    </h3>\
                </div>\
                ';
                $step5 = $(str);
                $('.guideModal').find('.content').append($step5);
                var top = ($('.dsgn-body').height()/2) - ($step5.height()/2);
                $step5.css({
                    'top' : top + 'px',
                    'left' : '175px'
                });
                $step5.fadeIn(function() {
                    $('.guideModal .content').css('margin-top','0px');
                    $('.guideModal .content').css('margin-left','170px');
                });
                break;

            case 6:
                $('.guideModal .content').css('margin-top','35px');
                $('.guideModal .content').css('margin-left','0px');
                hideElementListPanel();
                var str = '\
                <div class="popover bottom">\
                    <div class="arrow"></div>\
                    <div class="popover-content" style="padding:15px 15px 10px;font-weight:600;">\
                        <p>' + $.lang[LANG]["editor.guide.steps.6"] + '</p>\
                    </div>\
                    <h3 style="padding:5px;overflow:auto;" class="popover-title" id="popover-bottom">\
                        <div class="pull-left"><button class="btn btn-default btn-sm" onclick="$.guideON();">' + $.lang[LANG]['config.close'] + '</button></div>\
                        <div class="pull-right"><span style="padding-right:5px;"> <b>6</b> / 7 </span><span class="btn btn-primary btn-sm" onclick="$.guideON(7);">' + $.lang[LANG]['editor.guide.next'] + '</span></div>\
                    </h3>\
                </div>\
                ';
                $step6 = $(str);
                $('.guideModal').find('.content').append($step6);
                var left = $('#change-mode').offset().left - ($step6.width()/2) + ($('#change-mode').width()/2);
                $step6.css({
                    'top' : $('.editor-navbar').outerHeight()+2,
                    'left' : left + 'px'
                });
                $step6.fadeIn();

                break;

            case 7:
                $('.guideModal .content').css('margin-left','0px');
                hideElementListPanel();
                var str = '\
                <div class="popover bottom">\
                    <div class="arrow"></div>\
                    <div class="popover-content" style="padding:15px 15px 10px;font-weight:600;">\
                        <p>' + $.lang[LANG]["editor.guide.steps.7"] + '</p>\
                    </div>\
                    <h3 style="padding:5px;text-align:right;" class="popover-title" id="popover-bottom"><span style="padding-right:5px;"> <b>7</b> / 7 </span><span class="btn btn-primary btn-sm" onclick="$.guideON();">' + $.lang[LANG]['editor.guide.start'] + '</span></h3>\
                </div>\
                ';
                $step7 = $(str);
                $('.guideModal').find('.content').append($step7);
                var left = $('#config-publishing').offset().left - ($step7.width()/2) + ($('#config-publishing').width()/2);
                $step7.css({
                    'top' : $('.editor-navbar').outerHeight()+2,
                    'left' : left + 'px'
                });
                $step7.fadeIn();

                break;
            case 13:
                $('.el-menu').addClass('active');
                $('.config-element-section').hide();
                $('.el-menu_ctrl').show();

                var str = '\
                <div class="popover left">\
                    <div class="arrow"></div>\
                    <div class="popover-content" style="padding:15px 15px 10px;font-weight:600;">\
                        <p>메뉴변경, 이미지 업로드, 배경색, 여백 조절 등 블럭의 세부사항을 설정할 수 있습니다.</p>\
                    </div>\
                    <h3 style="padding:5px;overflow:auto;" class="popover-title" id="popover-bottom">\
                        <div class="pull-left"><button class="btn btn-default btn-sm" onclick="$.guideON()">' + $.lang[LANG]['config.close'] + '</button></div>\
                        <div class="pull-right"><span style="padding-right:5px;"> <b>3</b> / 7 </span><span class="btn btn-primary btn-sm" onclick="$.guideON(14);">' + $.lang[LANG]['editor.guide.next'] + '</span></div>\
                    </h3>\
                </div>\
                ';
                $step3 = $(str);
                $('.guideModal').find('.content').append($step3);
                var top = $('.el-menu_ctrl').offset().top - ($step3.height()/2)+27;
                $step3.css({
                    'top' : top + 'px',
                    'left' : 'inherit',
                    'right' : '80px'
                });
                $step3.fadeIn();
                $('.config-element').addClass('disabled');
                $('.el-menu_ctrl .config-element').css('z-index','99999999');
                //addElementButtonDisplay('el_0');

                break;

            case 14:
                $('.el-menu_ctrl .config-element').hide();
                var str = '\
                <div class="popover right">\
                    <div class="arrow"></div>\
                    <div class="popover-content" style="padding:15px 15px 10px;font-weight:600;">\
                        <p>현재 선택된 위치에 블럭을 추가하여 사이트를 만들 수 있습니다.</p>\
                    </div>\
                    <h3 style="padding:5px;overflow:auto;" class="popover-title" id="popover-bottom">\
                        <div class="pull-left"><button class="btn btn-default btn-sm" onclick="$.guideON()">' + $.lang[LANG]['config.close'] + '</button></div>\
                        <div class="pull-right"><span style="padding-right:5px;"> <b>4</b> / 7 </span><span class="btn btn-primary btn-sm" onclick="$.guideON(5);">' + $.lang[LANG]['editor.guide.next'] + '</span></div>\
                    </h3>\
                </div>\
                ';
                $step4 = $(str);
                var top = $('.addEL-wrap').offset().top + ($('.addEL-wrap').height()/2) - 90;
                $step4.css({
                    'top' : top + 'px',
                    'left': '50%',
                    'margin-left' : '100px'
                });
                $('.guideModal').find('.content').append($step4);
                $step4.fadeIn();
                break;
            default : 
                var settings = {
                    'showGuide' : 'none'
                };
                $.post('/template/settings',{ sid : SID, settings : JSON.stringify(settings), el : 'site_settings' }, function(data) {
                    checkError(data);
                },'json');

                $('.guideModal').find('.popover').fadeOut().remove();
                $('.menu-config.edit-menu').removeClass('active');
                $('.menu-config.edit-site').removeClass('active');
                $('.el_0_ctrl .config-element').css('z-index','4');
                $('.addElementButton').css('z-index','1').hide();
                $('.config-image-edit').hide();
                $('.config-element').removeClass('disabled');
                $('.add-block').removeClass('disabled');
                $('.config-element-section.active').removeClass('active').fadeOut();
                $('.guideModal').fadeOut().remove();
                //$.quickON(0);
                $.guideVideoON();
                break;
        }
    }

    jQuery.quickON = function(menu) {
        hideElementListPanel();
        var $quick = $('<div class="quickModal"></div>'),
            $content = $('<div class="content"></div>');

        if ($('.quickModal').length < 1) {
            $('body').prepend($quick);
            /*$content.on('click',function() {
                $.quickOFF();
            });*/
            $content.css({
                'width' : '100%',
                'height' : '100%',
                'background-color' : 'rgba(0,0,0,0.6)',
                'display' : 'none'
            });

            $quick.append($content);
            $quick.css({
                'display': 'inherit',
                'position': 'fixed',
                'z-index': '99999999',
                'top': '0',
                'left': '0',
                'width': '100%',
                'height': '100%',
                'text-align': 'center',
                'background-color' : 'transparent'
            });
            $quick.fadeIn();

            var hostAry = HOST.split('.');

            if (hostAry.length >= 3) {
                HOST = hostAry[1]+'.'+hostAry[2];
            }
            var supportUrl = (LANG == 'ko') ? 'https://supportcenter.creatorlink.net/creatorlink/' : 'https://supportcenter.creatorlink.net/creatorlink-support-center/';

            var $guide = $('<div class="guide">'),
                $close = $('<div class="close"><img src="https://storage.googleapis.com/i.addblock.net/fa-close-modal.png" alt="close" /></div>'),
                $header = $('<div class="header"><h2>' + $.lang[LANG]["editor.guide-title"] + '</h2></div>'),
                $linksWrap = $('<div class="links-wrap"></div>'),
                $mainguide = $('<span class="mainguide"><i class="fa fa-plus-circle"></i>' + $.lang[LANG]["editor.guide.walkthrough"] + '</sort-page-linen>'),
                $supportLink = $('</div><span class="support-link-wrap"><a class="support-link" href="' + supportUrl + '" target="_blank"><i class="fa fa-plus-circle"></i>' + $.lang[LANG]["editor.guide.support-center"] + '</a></span>'),
                $body = $('<div class="body"></div>'),
                $sidebar = $('<div class="sidebar"></div>'),
                nav = new Array( $.lang[LANG]["editor.guide.tutorial-video"], $.lang[LANG]["editor.menu-config"], $.lang[LANG]["editor.site-config"], $.lang[LANG]["config.element-config"], $.lang[LANG]["editor.guide.add-blocks"], $.lang[LANG]["editor.image.add-change"], $.lang[LANG]["editor.guide.edit-text"], $.lang[LANG]["editor.guide.gallery"], $.lang[LANG]["editor.guide.preview-publish"]),
                $nav = $('<ul class="nav"></ul>'),
                $bottom = $('<div class="bottom"></div>');

            $mainguide.on('click', function() {
                $.quickOFF();
                $.guideON(1);
            });

            $close.on('click',function() { $.quickOFF(); });

            // 임시 - 한국어 동영상이 완료될 때까지 만 
            if (LANG != 'en') {
               nav.shift();
            }

            $.each(nav, function(i,v){
                $li = $('<li class="'+i+'">'+v+'<img src="https://storage.googleapis.com/i.addblock.net/config/fa_thin_right_w.png" alt="" /></li>');
                $nav.append($li);
            });
            $navli = $nav.children();
            $navli.on('click',function() {
                var classtext = $(this).attr('class');
                $.quickON(Number(classtext.substring(0,1)));
            });
            $sidebar.append($nav).append($bottom);

            var $contentbox = $('<div class="contentbox"></div>');

            $body.append($sidebar).append($contentbox);
            $linksWrap.append($mainguide, $supportLink);
            $header.append($linksWrap);
            $guide.append($header).append($close).append($body);
            $content.append($guide);
            $content.fadeIn();

        }

        var $thisContent = $('.quickModal .contentbox'),
            $thisMenu = $('.quickModal .sidebar .nav li');
        $thisMenu.removeClass('active');
        $thisMenu.eq(menu).addClass('active');

        var lang;

        if (LANG == 'en') {
            lang = '_' + LANG;

            // 제임스: 임시로 여기로 옮겼음 (나중에 한 switch으로 할 예정)
            switch(menu) {
                case 0 :  /* 가이드 동영상 */

                    var str = '\
                    <ul>\
                        <li><h4>' + $.lang[LANG]["editor.guide.tutorial-video"] + '</h4></li>\
                        <li><p>' + $.lang[LANG]["editor.guide.tutorial-video.text"] + '</p></li>\
                    </ul>\
                    ';

                    var $quickVideoWrap = $('<li></li>'),
                        $tutorialVideo = $('<div class="tutorial-video"></div>'),
                        $videoWrap = $('<div class="video-wrap guideVideo-stopPlay"><div id="quick-guide-video-overlay"></div></div>');

                    $menu0 = $(str);
                    $tutorialVideo.append( $videoWrap ); 
                    $quickVideoWrap.append( $tutorialVideo );
                    $menu0.append( $quickVideoWrap );

                    $thisContent.empty();
                    $thisContent.append($menu0);
                    $menu0.fadeIn();

                    $videoWrap.on('click', function() {

                        $(this).toggleClass('guideVideo-stopPlay');

                        if(!$(this).hasClass('guideVideo-stopPlay')) {
                            if ( LANG == 'en' )
                                var link = 'https://www.youtube.com/embed/p6fyIMl2BcI';

                            var html = '<iframe class="video embed-responsive-item" width="765" height="380" src="' + link + '?enablejsapi=1&rel=0&vq=large&wmode=opaque&showinfo=0&controls=1&autoplay=0&loop=0;playlist=Fn0Mpyh3xto;" frameborder="0" allowfullscreen></iframe>';
                            $(this).html(html);
                        }
                    });   

                    break;
                case 1 :  /*메뉴 설정*/
                    var str = '\
                    <ul>\
                        <li><h4>' + $.lang[LANG]["editor.menu-config"] + '</h4></li>\
                        <li><p>' + $.lang[LANG]["editor.guide.menu-config.text.1"] + '</p></li>\
                        <li><img src="https://storage.googleapis.com/i.addblock.net/config/quickguid_0_1' + lang + '.png " alt="" /></li>\
                    </ul>\
                    ';
                    $menu1 = $(str);

                    $thisContent.empty();
                    $thisContent.append($menu1);
                    $menu1.fadeIn();
                    break;
                case 2 :  /*사이트 설정*/
                    var str = '\
                    <ul>\
                        <li><h4>' + $.lang[LANG]["editor.site-config"] + '</h4></li>\
                        <li><p>' + $.lang[LANG]["editor.guide.site-config.text.1"] + '</p></li>\
                        <li><img src="https://storage.googleapis.com/i.addblock.net/config/quickguid_1_1' + lang + '.png" alt="" /></li>\
                    </ul>\
                    ';
                    $menu2 = $(str);
                    $thisContent.empty();
                    $thisContent.append($menu2);
                    $menu2.fadeIn();
                    break;
                case 3 :  /*블럭 설정*/
                    var str = '\
                    <ul>\
                        <li><h4>' + $.lang[LANG]["config.element-config"] + '</h4></li>\
                        <li><p>' + $.lang[LANG]["editor.guide.element-config.text.1"] + '</p></li>\
                        <li><h6><img src="https://storage.googleapis.com/i.addblock.net/config/fa_exclamation.png" alt="" class="fa"/> ' + $.lang[LANG]["editor.guide.element-config.text.note"] + '</h6></li>\
                        <li><img src="https://storage.googleapis.com/i.addblock.net/config/quickguid_2_1' + lang + '.png" alt="" /></li>\
                    </ul>\
                    ';
                    $menu3 = $(str);
                    $thisContent.empty();
                    $thisContent.append($menu3);
                    $menu3.fadeIn();
                    break;
                case 4 :  /*블럭 추가*/
                    var str = '\
                    <ul>\
                        <li><h4>' + $.lang[LANG]["editor.guide.add-blocks"] + '</h4></li>\
                        <li><p>' + $.lang[LANG]["editor.guide.add-block.text.1"] + '</p></li>\
                        <li><img src="https://storage.googleapis.com/i.addblock.net/config/quickguid_3_1' + lang + '.png" alt="" /></li>\
                    </ul>\
                    ';
                    $menu4 = $(str);
                    $thisContent.empty();
                    $thisContent.append($menu4);
                    $menu4.fadeIn();
                    break;
                case 5 :  /*이미지 추가/변경*/
                    var str = '\
                    <ul>\
                        <li><h4>' + $.lang[LANG]["editor.image.add-change"] + '</h4></li>\
                        <li><p>' + $.lang[LANG]["editor.guide.add-change-images.text.1"] + '</p></li>\
                        <li><h6><img src="https://storage.googleapis.com/i.addblock.net/config/fa_exclamation.png" alt="" class="fa"/>' + $.lang[LANG]["editor.guide.add-change-images.text.note"] + '</h6></li>\
                        <li><img src="https://storage.googleapis.com/i.addblock.net/config/quickguid_4_1.png" alt="" /></li>\
                    </ul>\
                    ';
                    $menu5 = $(str);
                    $thisContent.empty();
                    $thisContent.append($menu5);
                    $menu5.fadeIn();
                    break;
                case 6 :  /*텍스트*/
                    var str = '\
                    <ul>\
                        <li><h4>' + $.lang[LANG]["config.text"] + '</h4></li>\
                        <li><p>' + $.lang[LANG]["editor.guide.edit-text.text.1"] + '</p></li>\
                        <li><img src="https://storage.googleapis.com/i.addblock.net/config/quickguid_5_1' + lang + '.png" alt="" /></li>\
                    </ul>\
                    ';
                    $menu6 = $(str);
                    $thisContent.empty();
                    $thisContent.append($menu6);
                    $menu6.fadeIn();
                    break;
                case 7 :  /*갤러리*/
                    var str = '\
                    <ul>\
                        <li><h4>' + $.lang[LANG]["editor.block.gallery"] + '</h4></li>\
                        <li><p>' + $.lang[LANG]["editor.guide.gallery.text.1"] + '</p></li>\
                        <li><img src="https://storage.googleapis.com/i.addblock.net/config/quickguid_6_1.png" alt="" /></li>\
                        <li><hr /></li>\
                        <li><p>' + $.lang[LANG]["editor.guide.gallery.text.2"] + '</p></li>\
                        <li><img src="https://storage.googleapis.com/i.addblock.net/config/quickguid_6_2' + lang + '.png" alt="" /></li>\
                        <li><h6><img src="https://storage.googleapis.com/i.addblock.net/config/fa_exclamation.png" alt="" class="fa"/> ' + $.lang[LANG]["editor.guide.gallery.text.note"] + '</h6></li>\
                    </ul>\
                    ';
                    $menu7 = $(str);
                    $thisContent.empty();
                    $thisContent.append($menu7);
                    $menu7.fadeIn();
                    break;
                case 8 :  /*저장/게시*/
                    var str = '\
                    <ul>\
                        <li><h4>' + $.lang[LANG]["editor.guide.preview-publish"] + '</h4></li>\
                        <li><img src="https://storage.googleapis.com/i.addblock.net/config/quickguid_7_1' + lang + '.png" alt="" style="margin-top: 0"/></li>\
                        <li><p>' + $.lang[LANG]["editor.guide.preview-publish.text.1"] + '</p></li>\
                        <li><h6><img src="https://storage.googleapis.com/i.addblock.net/config/fa_exclamation.png" alt="" class="fa"/> ' + $.lang[LANG]["editor.guide.preview-publish.text.note"] + '</h6></li>\
                    </ul>\
                    ';
                    $menu8 = $(str);
                    $thisContent.empty();
                    $thisContent.append($menu8);
                    $menu8.fadeIn();
                    break;
                default : 
                    $.quickOFF();
                    break;
            }
        }
        else {
            lang = '';

            // 제임스: 임시로 여기로 옮겼음 (나중에 한 switch으로 할 예정)
            switch(menu) {
                case 0 :  /*메뉴 설정*/
                    var str = '\
                    <ul>\
                        <li><h4>' + $.lang[LANG]["editor.menu-config"] + '</h4></li>\
                        <li><p>' + $.lang[LANG]["editor.guide.menu-config.text.1"] + '</p></li>\
                        <li><img src="https://storage.googleapis.com/i.addblock.net/config/quickguid_0_1' + lang + '.png " alt="" /></li>\
                    </ul>\
                    ';
                    $menu0 = $(str);

                    $thisContent.empty();
                    $thisContent.append($menu0);
                    $menu0.fadeIn();
                    break;
                case 1 :  /*사이트 설정*/
                    var str = '\
                    <ul>\
                        <li><h4>' + $.lang[LANG]["editor.site-config"] + '</h4></li>\
                        <li><p>' + $.lang[LANG]["editor.guide.site-config.text.1"] + '</p></li>\
                        <li><img src="https://storage.googleapis.com/i.addblock.net/config/quickguid_1_1' + lang + '.png" alt="" /></li>\
                    </ul>\
                    ';
                    $menu1 = $(str);
                    $thisContent.empty();
                    $thisContent.append($menu1);
                    $menu1.fadeIn();
                    break;
                case 2 :  /*블럭 설정*/
                    var str = '\
                    <ul>\
                        <li><h4>' + $.lang[LANG]["config.element-config"] + '</h4></li>\
                        <li><p>' + $.lang[LANG]["editor.guide.element-config.text.1"] + '</p></li>\
                        <li><h6><img src="https://storage.googleapis.com/i.addblock.net/config/fa_exclamation.png" alt="" class="fa"/> ' + $.lang[LANG]["editor.guide.element-config.text.note"] + '</h6></li>\
                        <li><img src="https://storage.googleapis.com/i.addblock.net/config/quickguid_2_1' + lang + '.png" alt="" /></li>\
                    </ul>\
                    ';
                    $menu2 = $(str);
                    $thisContent.empty();
                    $thisContent.append($menu2);
                    $menu2.fadeIn();
                    break;
                case 3 :  /*블럭 추가*/
                    var str = '\
                    <ul>\
                        <li><h4>' + $.lang[LANG]["editor.guide.add-blocks"] + '</h4></li>\
                        <li><p>' + $.lang[LANG]["editor.guide.add-block.text.1"] + '</p></li>\
                        <li><img src="https://storage.googleapis.com/i.addblock.net/config/quickguid_3_1' + lang + '.png" alt="" /></li>\
                    </ul>\
                    ';
                    $menu3 = $(str);
                    $thisContent.empty();
                    $thisContent.append($menu3);
                    $menu3.fadeIn();
                    break;
                case 4 :  /*이미지 추가/변경*/
                    var str = '\
                    <ul>\
                        <li><h4>' + $.lang[LANG]["editor.image.add-change"] + '</h4></li>\
                        <li><p>' + $.lang[LANG]["editor.guide.add-change-images.text.1"] + '</p></li>\
                        <li><h6><img src="https://storage.googleapis.com/i.addblock.net/config/fa_exclamation.png" alt="" class="fa"/>' + $.lang[LANG]["editor.guide.add-change-images.text.note"] + '</h6></li>\
                        <li><img src="https://storage.googleapis.com/i.addblock.net/config/quickguid_4_1.png" alt="" /></li>\
                    </ul>\
                    ';
                    $menu4 = $(str);
                    $thisContent.empty();
                    $thisContent.append($menu4);
                    $menu4.fadeIn();
                    break;
                case 5 :  /*텍스트*/
                    var str = '\
                    <ul>\
                        <li><h4>' + $.lang[LANG]["config.text"] + '</h4></li>\
                        <li><p>' + $.lang[LANG]["editor.guide.edit-text.text.1"] + '</p></li>\
                        <li><img src="https://storage.googleapis.com/i.addblock.net/config/quickguid_5_1' + lang + '.png" alt="" /></li>\
                    </ul>\
                    ';
                    $menu5 = $(str);
                    $thisContent.empty();
                    $thisContent.append($menu5);
                    $menu5.fadeIn();
                    break;
                case 6 :  /*갤러리*/
                    var str = '\
                    <ul>\
                        <li><h4>' + $.lang[LANG]["editor.block.gallery"] + '</h4></li>\
                        <li><p>' + $.lang[LANG]["editor.guide.gallery.text.1"] + '</p></li>\
                        <li><img src="https://storage.googleapis.com/i.addblock.net/config/quickguid_6_1.png" alt="" /></li>\
                        <li><hr /></li>\
                        <li><p>' + $.lang[LANG]["editor.guide.gallery.text.2"] + '</p></li>\
                        <li><img src="https://storage.googleapis.com/i.addblock.net/config/quickguid_6_2' + lang + '.png" alt="" /></li>\
                        <li><h6><img src="https://storage.googleapis.com/i.addblock.net/config/fa_exclamation.png" alt="" class="fa"/> ' + $.lang[LANG]["editor.guide.gallery.text.note"] + '</h6></li>\
                    </ul>\
                    ';
                    $menu6 = $(str);
                    $thisContent.empty();
                    $thisContent.append($menu6);
                    $menu6.fadeIn();
                    break;
                case 7 :  /*저장/게시*/
                    var str = '\
                    <ul>\
                        <li><h4>' + $.lang[LANG]["editor.guide.preview-publish"] + '</h4></li>\
                        <li><img src="https://storage.googleapis.com/i.addblock.net/config/quickguid_7_1' + lang + '.png" alt="" style="margin-top: 0"/></li>\
                        <li><p>' + $.lang[LANG]["editor.guide.preview-publish.text.1"] + '</p></li>\
                        <li><h6><img src="https://storage.googleapis.com/i.addblock.net/config/fa_exclamation.png" alt="" class="fa"/> ' + $.lang[LANG]["editor.guide.preview-publish.text.note"] + '</h6></li>\
                    </ul>\
                    ';
                    $menu7 = $(str);
                    $thisContent.empty();
                    $thisContent.append($menu7);
                    $menu7.fadeIn();
                    break;
                default : 
                    $.quickOFF();
                    break;
            }
        }

    }

    jQuery.quickOFF = function() {
        $('.quickModal').fadeOut(function() {
            $(this).remove();  
        });
    }

    $('.quickModal').live({
        click: function(e) {
            if($(e.target).parents('.guide').length < 1) $.quickOFF();
        }
    });

    jQuery.setAloneBlockError = function(centerArea,return_v) {
        if(typeof return_v != 'boolean') return_v = false;

        var onoff = false;
        if(typeof centerArea == 'undefined' || $(centerArea).length === 0) {
            if(return_v) return onoff;
        } else {
            var center_b = $(centerArea).find('.reorderBlock').length,
                center_lb = $(centerArea).find('.reorderBlock[data-mode="shopping"]').length,
                center_fb = $(centerArea).find('.reorderBlock[data-feature*="fixedscroll"]').length,
                check_lux = (LUX && (center_lb > 1)) ? true : false,
                check_fixedscroll = (center_fb > 1 || (center_fb == 1 && center_b > 1)) ? true : false;
            onoff = (check_lux || check_fixedscroll) ? true : false;

            if(onoff) {
                var error_str = (check_lux) ? $.lang[LANG]['config.lux.shopping.not-supported.reorder'] : $.lang[LANG]['config.premium.gallery.fixedscroll.not-supported.reorder'];
                $('.reorderModal').addClass('aloneBlockError');
                if($('.reorderModal .alone_b_error').length === 0) $('.reorderModal').append('<div class="alone_b_error">' + error_str + '</div>');
                $('.reorderModal .alone_b_error').slideDown(200);
            } else {
                $('.reorderModal .alone_b_error').slideUp(200, function() {
                    $('.reorderModal').removeClass('aloneBlockError');    
                });
            }

            if(return_v) return onoff;
        }
    }

    jQuery.reorderON = function(pageMenuStr) {
        $.processON('Loading blocks ...');
        if(pageMenuStr == 'index') pageMenuStr = '';
        if(prevPAGE == 'index') prevPAGE = '';
        if(prevONE) prevPAGE = ORG_PAGES[selectID];
        window.currentPageMenu = pageMenuStr ? pageMenuStr.toString() : prevPAGE;
        window.currentPageMenuIdx = -1;
        window.copy_menu_list = MENULIST;
        // if(copy_menu_list[0] == 'INTRO') copy_menu_list.splice(0, 1);

        var enable = true;
        if(!window.basketBlockHtml)
            window.basketBlockHtml = '';

        if(!window.pageListChangeFlag) window.pageListChangeFlag = [];

        if($('.ctrl-reorder').hasClass('disabled')) return;
        
        // var el = [], idx = 0;
        // var toolbar = ($('.editor-navbar').css('display')=='none') ? 0 : 35;
        // var sidebar = ($('header').hasClass('sidebar')) ? true : false;
        var el_fixed = (reorderFIXED) ? reorderFIXED.split(':') : [];

        // $.each($('.element'),function(i,v) {
        //     if( $(v).data('el') == 'el-menu' || 
        //         $(v).data('el') == 'el-footer' || 
        //         $(v).hasClass('add-footer-information') ||
        //         $(v).hasClass('cl-s-product-review') ||
        //         $(v).hasClass('cl-s-product-qna')
        //     ) return true;

        //     if(reorderFIXED) {
        //         if($(v).hasClass('el-fixedblock')) {
        //             if($(v).attr('data-posby') != el_fixed[2]) return true;
        //         } else return true;
        //     } else {
        //         if($(v).hasClass('el-fixedblock')) return true;
        //     }

        //     el[idx] = $(v).attr('data-el') + '|' + ($(v).offset().top - toolbar) + '-' + $(v).outerHeight();    
        //     idx++;
        // });
        // eloffSet = el.toString();

        var $reorder = $('<div class="reorderModal"></div>');
        if($('.reorderModal').length < 1) {
            $('body').prepend($reorder);
            $reorder.css({
                'position' : 'fixed',
                'width' : '100%',
                'height' : '100%',
                'background' : '#eef0f4',
                'z-index' : '1049',
                'display' : 'none',
                'overflow' : 'auto'
            });
        } else {
            // $('.reorderModal').empty();
            $reorder = $(".reorderModal");
        }
                           //<div class="scale" style="margin-top: 0; height: 100%; width: calc(388px * 5); margin-left: calc((-388px * 5) /2 + 50%); ">\
        var reorder_title = (reorderFIXED) ? $.lang[LANG]['editor.reorder-blocks.title.'+el_fixed[2]] : $.lang[LANG]['editor.reorder-blocks.title'],
        $content = $('<div class="content" style="display: flex;"></div>'),
        $left_area = $('<div class="left-area ' + (VIEW ? ' view-exist ' : '')  + '" style="flex: 1 1 40%; max-width: calc(48% - 155px);">\
                            <div style="display: flex; -webkit-box-pack: end; -ms-flex-pack: end; justify-content: flex-end;">\
                                <div class="" style="max-width: 385px; height: 100%; background-color: #fff; position: fixed; width: calc(48% - 155px);">\
                                    <div class="" style="text-align: center; padding-top: 30px; padding-bottom: 53px;"><h4 style="margin-top: 10px;">' + $.lang[LANG]['config.blockmove.moveblock'] + '</h4></div>\
                                    <div class="scale" style="margin-top: 0; width: calc(100% / 0.166); height: calc(100% / 0.166 - (124px / 0.166)) !important; overflow-y: auto; overflow-x: hidden; transform: scale(.166);">\
                                        <div class="el-sortable">\
                                            <div class="sort-empty guide-text">' + $.lang[LANG]['config.blockmove.movehere'] + '</div>\
                                        </div>\
                                    </div>\
                                </div>\
                            </div>\
                        </div>'),
        $center_area = $('<div class="center-area ' + (VIEW ? ' view-exist ' : '') + ' " style="flex: 1 1 40%; max-width: calc(47% - 155px);"><div class="block-area" style="max-width: 400px; margin: 0 auto;"><div class="page-list-area"><div class="btn-group"></div></div></div></div>'),
        $right_area = $('<div class="right-area" style="flex: 1 1 30%; padding: 30px 40px 0 0; position: fixed; right: 0; z-index: 4;"></div>'),
        // $scale = $('<div class="scale" style="width: calc(388px * 5); margin-left: calc((-388px * 5) /2 + 50%);"></div>');
        $scale = $('<div class="scale" style="width: 500%;"></div>'),
        $save = $('<span class="btn btn-primary btn-flat btn-sm pull-right">' + $.lang[LANG]['config.save'] + '</span>'),
        $close = $('<span class="btn btn-default btn-flat btn-sm pull-right">' + $.lang[LANG]['config.cancel'] + '</span>').css('margin-right','10px');

        $close.on('click',function() {
            $.processON('','#fff');
            $.reorderOFF();

            setConfigLogs('block.reorder','cancel',{'seq':selectID},PAGE);

            if(!VIEW && (prevPAGE || PAGE)) {
                var refer = prevPAGE ? prevPAGE.replace(',','/view/') : PAGE.replace(',','/view/');
                location.replace('/'+CONFIG_URL+'config/page/' + refer);
            } else {
                location.reload();
                $.processOFF();
            }
        });

        $save.on('click',function() {
            if(basketBlockHtml != '') {
                alert($.lang[LANG]['config.blockmove.blockleft']);
                return false;
            }

            var checkAloneBlock = $.setAloneBlockError($center_area,true);
            if(checkAloneBlock) {
                console.log('error');
                return false;
            }


            $.processON($.lang[LANG]['config.reorder.loading']);

            // var rPage = '';
            // $.each($('.el-sortable').children(), function(i,v) {
            //     var page_name = $(v).attr('data-result-page');
            //     if(typeof page_name !='undefined' && page_name && $(v).hasClass('sort-empty')) {
            //         rPage = $(v).attr('data-result-page');
            //         return true;
            //     }

            //     $(v).attr('data-reorder-page',rPage);
            // });
            var r = [];
            // $.each($('.center-area .reorderBlock'), function(i,v) {
            //     tmp = $(this).attr('data-reorder-page') + ':' + $(this).attr('data-id');
            //     if(reorderFIXED) tmp += ':' + el_fixed[2];
            //     r.push(tmp);
            // });

            var clog_more_obj = {};
            $(pageList).each(function(idx) {
                var loopPage = this;
                if(!ONE && typeof pageListChangeFlag[idx] == 'undefined') return true;
                if(typeof pageList[idx] == 'undefined') return true;

                var loop_pagename = (!VIEW) ? window.copy_menu_list[idx] : currentPageMenu;
                clog_more_obj[loop_pagename] = {
                    'before': clogPageList[idx],
                    'after' : loopPage,
                };

                $(loopPage).each(function() {
                    var tmp = loop_pagename + ':' + this;
                    if(reorderFIXED) tmp += ':' + el_fixed[2];
                    r.push(tmp);
                });
            });

            setConfigLogs('block.reorder','save.click',{'seq':selectID, 'more_obj':clog_more_obj},PAGE);
            var view_page = (reorderFIXED) ? el_fixed[1] : currentPageMenu;
            $.ajax({
                type: 'POST',
                url: '/template/update/type/block-reorder',
                data: { s: JSON.stringify(r), id: SID, page: view_page, onepage : ONE},
                async:true,
                cache: false,
                success: function (data) {
                    var type = getElementType();
                    setLogs(type,'block.reorder','block-sort','','product-manager','el');
                    $('.element').removeClass('active').removeClass('el-active');
                    $('#el-property').hide();


                    setConfigLogs('block.reorder','save.end',{'seq':selectID},PAGE);
                    if(!VIEW && (prevPAGE || PAGE)) {
                        var refer = prevPAGE ? prevPAGE.replace(',','/view/') : PAGE.replace(',','/view/');
                        location.replace('/'+CONFIG_URL+'config/page/' + refer);
                    } else {
                        location.reload();
                    }
                    $.processOFF();
                    $.reorderOFF();
                    checkError(data);
                }
            });
            /*
            var ids = [];
            $.each($('.render'), function(i,v) {
                if(typeof $(v).attr('data-id') != 'undefined') ids.push($(v).attr('data-id').trim());
            });

            $.post('/template/update/type/block-reorder',{ id : SID, page : PAGE, s:ids.join(',')}, function(data) {
                checkError(data);
            },'json');
            return false;
            */
        });

        $content.append($left_area);

        if(window.basketBlockHtml && window.basketBlockHtml != '') {
            $left_area.find(".el-sortable").append(window.basketBlockHtml);
            $left_area.find(".sort-empty").hide();
            $left_area.find(".reorderBlock").removeClass("active");
        }

        $right_area.append($save);
        $right_area.append($close);
        $content.append($center_area);
        $content.append($right_area);
        $center_area.find(".block-area").append($scale);
        $reorder.html($content);

        var $sort = $('<div class="el-sortable"></div>');
        $sort.css('color',$('.dsgn-body').css('color'));

        if(!$(".new-dsgn-body").length) {
            var temp_dsgn_body = $('<div class="new-dsgn-body"><div class="elements"></div></div>');
            $("body").append(temp_dsgn_body);
        } else {
            var temp_dsgn_body = $(".reorderModal .new-dsgn-body");
            // temp_dsgn_body.empty();
        }

        $reorder.fadeIn();

        //var $scale = $('<div class="scale"></div>');
        //$scale.css('color',$('.dsgn-body').css('color'));
        var elIndex = 0;

        window.pageMenu = [];
        // if(PAGE == 'index') {
        //     $.each(MENULINK,function(i,v) {
        //     //$.each(SMENU,function(i,v) {
        //         pageMenu.push(v.replace(/ /g,'-'));
        //         //if(v.display == 'on') pageMenu.push(v.name);
        //     });
        // } else {
        var view_page = (reorderFIXED) ? el_fixed[1] : PAGE;
        pageMenu.push(view_page);
        // }

        var pageMenuSelect = '';

        if(!VIEW) {
            if(!window.currentPageMenu || window.currentPageMenu == '') window.currentPageMenu = copy_menu_list[0];

            pageMenuSelect += '\
                <button type="button" class="btn btn-sm fsm dropdown-toggle" data-toggle="dropdown">\
                    <span>' + currentPageMenu + '</span> ' + ($("#nestable").find("[data-id='" + currentPageMenu + "']").children(".menu-ctrl").find(".menu-visible").hasClass('invisible') ? ' <svg viewBox="0 0 14 12" width="14" height="14"><path d="M12.29 0l-1.88 1.88C9.39 1.32 8.23 1 7 1 3.83 1 1.12 3.07 0 6c0.56 1.46 1.53 2.68 2.73 3.56L1 11.29 1.71 12 13 0.71 12.29 0zM1.09 6C2.15 3.64 4.4 2 7 2c0.95 0 1.86 0.23 2.67 0.62L8.73 3.56C8.24 3.21 7.65 3 7 3 5.34 3 4 4.34 4 6c0 0.65 0.21 1.24 0.56 1.73L3.44 8.85C2.44 8.15 1.62 7.17 1.09 6zM5 6c0-1.1 0.9-2 2-2 0.37 0 0.71 0.11 1.01 0.28L5.28 7.01C5.11 6.71 5 6.37 5 6z"></path><path d="M12.05 3.06l-0.71 0.71C11.99 4.4 12.53 5.15 12.91 6c-1.05 2.36-3.3 4-5.91 4 -0.57 0-1.12-0.09-1.65-0.24l-0.8 0.8C5.32 10.84 6.14 11 7 11c3.17 0 5.88-2.07 7-5C13.57 4.87 12.89 3.87 12.05 3.06z"></path></svg> ' : '') + ' <span class="caret"></span>\
                </button>\
                <ul class="dropdown-menu" role="menu">\
            ';
            $(copy_menu_list).each(function(idx) {
                var active_cls = '';
                var depth_cls = '';
                var visible_cls = '';
                var visible_svg = '';

                var menu_str = this;
                if(menu_str == '전체상품') return true;
                if(currentPageMenu == this) {
                    currentPageMenuIdx = idx;
                    active_cls = ' active ';
                }

                $("#nestable").find(".dd-first, .dd-item:not(.dd-dummy)").each(function () {
                    var dd_item_id = $(this).attr("data-id");
                    if(!dd_item_id) return true;
                    
                    dd_item_id = dd_item_id.replace(/ /g, '-');
                    if(dd_item_id == menu_str) {
                        if($(this).parents(".dd-item").length) {
                            depth_cls = ' indent ';
                        }        

                        if($(this).children(".menu-ctrl").find(".menu-visible").hasClass("invisible")) {
                            visible_cls = ' visibleoff ';
                            visible_svg = ' <svg viewBox="0 0 14 12" width="14" height="14"><path d="M12.29 0l-1.88 1.88C9.39 1.32 8.23 1 7 1 3.83 1 1.12 3.07 0 6c0.56 1.46 1.53 2.68 2.73 3.56L1 11.29 1.71 12 13 0.71 12.29 0zM1.09 6C2.15 3.64 4.4 2 7 2c0.95 0 1.86 0.23 2.67 0.62L8.73 3.56C8.24 3.21 7.65 3 7 3 5.34 3 4 4.34 4 6c0 0.65 0.21 1.24 0.56 1.73L3.44 8.85C2.44 8.15 1.62 7.17 1.09 6zM5 6c0-1.1 0.9-2 2-2 0.37 0 0.71 0.11 1.01 0.28L5.28 7.01C5.11 6.71 5 6.37 5 6z"></path><path d="M12.05 3.06l-0.71 0.71C11.99 4.4 12.53 5.15 12.91 6c-1.05 2.36-3.3 4-5.91 4 -0.57 0-1.12-0.09-1.65-0.24l-0.8 0.8C5.32 10.84 6.14 11 7 11c3.17 0 5.88-2.07 7-5C13.57 4.87 12.89 3.87 12.05 3.06z"></path></svg> ';
                        }
                    }
                });

                

                // pageMenuSelect += '<option value="' + this + '" ' + (currentPageMenu == this ? ' selected ' : '') + '>' + this + '</option>';
                pageMenuSelect += '<li class="gallery-name ' + active_cls + depth_cls + visible_cls +' " data-page="' + menu_str + '">' + '<span>' + menu_str + '</span>' +  visible_svg + '</li>';
            });
            pageMenuSelect += '</ul>';
            $center_area.find(".page-list-area .btn-group").append(pageMenuSelect);
        } else {
            currentPageMenuIdx = 0;
        }

        if(reorderFIXED) {
            if(el_fixed[2] == 't') {
                $center_area.find(".page-list-area .btn-group").html('<h4>' + $.lang[LANG]['config.blockmove.fixedtopblock'] + '</h4><span class="sub">' + $.lang[LANG]['config.blockmove.dragblock'] + '</span>');
            } else if(el_fixed[2] == 'b') {
                $center_area.find(".page-list-area .btn-group").html('<h4>' + $.lang[LANG]['config.blockmove.fixedbottomblock'] + '</h4><span class="sub">' + $.lang[LANG]['config.blockmove.dragblock'] + '</span>');
            }
        } else if(VIEW) {
            $center_area.find(".page-list-area .btn-group").html('<h4>' + $.lang[LANG]['config.blockmove.title'] + '</h4><span class="sub">' + $.lang[LANG]['config.blockmove.dragblock'] + '</span>');
        }

        setTimeout(function() {

            if(typeof pageList[currentPageMenuIdx] == 'undefined' || typeof pageListChangeFlag[currentPageMenuIdx] == 'undefined') {
               
                $('.new-dsgn-body .contents[data-page="' + currentPageMenu + '"]').remove();
                var pageIndex = 0;
                PAGE = currentPageMenu.toString();
                var dsgn_body_clone = $('.dsgn-body').clone().empty().addClass('contents');
                $('.dsgn-body').removeClass('dsgn-body').addClass('prev-dsgn-body');
                $('.new-dsgn-body .elements').append(dsgn_body_clone);
                
                showPageCallback(showPage); //qwer
                
                $('.new-dsgn-body .contents.dsgn-body').removeClass('dsgn-body').attr('data-page', currentPageMenu);
                $('.prev-dsgn-body').removeClass('prev-dsgn-body').addClass('dsgn-body');
                PAGE = prevPAGE ? prevPAGE.toString() : '';
             
                pageList[currentPageMenuIdx] = [];
                $.each($('.new-dsgn-body .contents[data-page="' + currentPageMenu + '"] .element'),function(i,v) {
                    if( $(v).hasClass('el-menu') || 
                        $(v).hasClass('el-footer') || 
                        $(v).hasClass('add-footer-information') ||
                        $(v).hasClass('cl-s-product-detail') ||
                        $(v).hasClass('cl-s-product-review') ||
                        $(v).hasClass('cl-s-product-qna') || 
                        $(v).hasClass('cl-s-product-info-notice') ||
                        $(v).hasClass('el-fixedcontact')
                    ) {
                        return true;
                    }

                    if(reorderFIXED) {
                        if($(v).hasClass('el-fixedblock')) {
                            if($(v).attr('data-posby') != el_fixed[2]) return true;
                        } else return true;
                    } else {
                        if($(v).hasClass('el-fixedblock')) return true;
                    }
                    
                    if ($(v).hasClass('addEL-wrap')) {
                        return true;
                    } 
                    
                    pageList[currentPageMenuIdx][pageIndex] = (LUX && $(v).is('.lux-product-block')) ? 'lux-product-block' : $(v).data('id');

                    $(v).find('.hideBlockWrap .blockOn').hide();
                    if($(v).find('.hideBlockWrap').length > 0) $(v).addClass('block_checkOnOff');
                    pageIndex++;
                });
                pageListChangeFlag[currentPageMenuIdx] = true;
            }

            PAGE = prevPAGE ? prevPAGE.toString() : '';

            var $empty = $('<div class="render sort-empty" data-result-page="' + currentPageMenu + '">&nbsp;</div>'),
                $pageLine = $('<div class="sort-page-line"></div>'),
                pageName = currentPageMenu.replace(/,/,'/'),
                menulist_index = $.inArray(pageName,MENULIST),
                pageNameOrg = pageName=='INTRO' ? pageName : $('#nestable').find('.dd-item').eq(menulist_index-1).attr('data-id'),
                $pageInfo = $('<div class="sort-page-info">' + pageNameOrg + '</div>'),
                isLink = pageName=='INTRO' || menulist_index == -1 ? false : $('#nestable').find('.dd-item').eq(menulist_index-1).find('.menu-link').first().hasClass('active');
                
            if(pageName.indexOf('/')>-1 || reorderFIXED) $pageInfo.addClass('hide');

            // $empty.append($pageLine);
            // $empty.append($pageInfo);

            $empty = (isLink) ? $empty.addClass('use-link') : $empty;
                // if(!isLink) $sort.append($empty);

            $(pageList[currentPageMenuIdx]).each(function(i,v) {
                if(v == 'lux-product-block') {
                    var element_selector = ($('.new-dsgn-body .lux-product-block').hasClass('reorderBlock')) ? 'reorderBlock' : 'element',
                        $ndb_el = $('.new-dsgn-body .lux-product-block.' + element_selector);
                } else {
                    var element_selector = ($('.new-dsgn-body [data-id="'+v + '"][data-type]').hasClass('reorderBlock')) ? 'reorderBlock' : 'element',
                        $ndb_el = $('.new-dsgn-body .' + element_selector + '[data-id="'+v + '"]');
                }

                $ndb_el.removeClass('element')
                        .removeClass('el-active')
                        .removeClass('active')
                        .removeClass('emptyGallery')
                        .removeClass('el-fixedblock')
                        .removeAttr('data-parallax')
                        .addClass('render')
                        .addClass('reorderBlock')
                        .attr('data-reorder-page',currentPageMenu);

                var $el = $ndb_el.clone();
                var isLink = $('#nestable .dd-item[data-id="'+pageNameOrg+'"] > span > .menu-link').hasClass('active');
                if($el.attr('data-parallax')=='true') {
                    $el.css('background-attachment','inherit');
                }

                if(elIndex==0) {
                    $el.css('margin','0px');
                    if(VIEW && ($el.attr('data-type')=='project' || $el.attr('data-type')=='product')) return true;//$el.addClass('unsort').hide();
                }
                if($el.attr('data-msny')=='true' && $el.find('.container').hasClass('full-width')) {
                    $el.css('padding-left',$('header.sidebar').width()+'px');
                }

                if($ndb_el.css('background-color')=='rgba(0, 0, 0, 0)' || $ndb_el.css('background-color')=='transparent') {
                    $el.css('background-color', '#fff');
                }

                $el.find('[data-edit="true"]').removeAttr('data-edit');
                $el.css('position','relative');
                $el.css('min-height','0px');
                $el.css('margin-bottom','120px');

                if($el.attr('data-layout')=="true") $el.css('overflow','');

                if(v == 'lux-product-block') {
                    $el.html('<div class="lux-product-sample"><h1>본사 상품 상세 정보 블럭</h1></div>');
                }
                if(!isLink) $sort.append($el);
                elIndex++;

            });
            var $last = $('<div class="sort-empty guide-text" style="display: none;">' + $.lang[LANG]['config.blockmove.movehere'] + '</div>');
            if(pageList[currentPageMenuIdx].length == 0 || typeof pageList[currentPageMenuIdx] == 'undefined') $last.show();
            $sort.append($last);
            $scale.append($sort);

            $scale.css('height', 'auto');

            var target_contents = $('.new-dsgn-body .elements .contents[data-page="' + currentPageMenu + '"]');
            var setting_height = target_contents.height() / 5 + $(".page-list-area").outerHeight() + 120;

            $scale.height(setting_height);
            $center_area.height(setting_height);

            $center_area.find('.reorderBlock[data-msny="true"]').each(function() {
                var cnt = 0;
                var total = $(this).find(".row").data("view");
                var target = this;
                $(target).imagesLoaded().progress(function(imgload, image) {
                    cnt ++;
                    if(total == cnt || cnt == $(target).find(".row .gallery-item").length) {
                        setTimeout(function() {
                            $(target).find(".row").masonry();    
                        }, 1)
                    }
                });
            });

            if($center_area.find('[data-map_kind="kakao"]').length && (typeof kakao == 'undefined' || typeof kakao.maps == 'undefined' || kakao.maps == null || VALIDPLAN == '')) {
                $center_area.find('[data-map_kind="kakao"]').html('지도연결해제됨. Javascript키 확인');
                    $center_area.find('[data-map_kind="kakao"]').html('<iframe class="google-map" src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3165.5659473821083!2d127.0282496015659!3d37.494568!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x357ca1598c361b2b%3A0xdbf9af292beff3c!2z6rCV64Ko!5e0!3m2!1sko!2skr!4v1637303748377!5m2!1sko!2skr" width="600" height="450" style="border:0;" allowfullscreen="" loading="lazy"></iframe>');
            } else {
                $center_area.find('[data-map_kind="kakao"]').each(function() {
                    var container = this;
                    var lat = $(this).data("lat");
                    var lng = $(this).data("lng");
                    var options = { center: new kakao.maps.LatLng(lat, lng), level: 3};
                    var c_map = new kakao.maps.Map(container, options);
                    var marker = new kakao.maps.Marker({ position: new kakao.maps.LatLng(lat, lng), map: c_map});
                    var zoomInOut = $(this).data("zoominout");
                    var mapTitle = $(this).data("maptitle");
                    var mapContent = $(this).data("mapcontent");
                    var useTitle = $(this).data("usetitle");
                    var useContent = $(this).data("usecontent");
                    if(typeof zoomInOut == 'undefined' || !zoomInOut) zoomInOut = false;
                    if(typeof mapTitle == 'undefined' || !mapTitle) mapTitle = '';
                    if(typeof mapContent == 'undefined' || !mapContent) mapContent = '';
                    if(typeof useTitle == 'undefined' || !useTitle) useTitle = false;
                    if(typeof useContent == 'undefined' || !useContent) useContent = false;

                    if(zoomInOut == true) {
                        // var mapTypeControl = new kakao.maps.MapTypeControl();
                        // c_map.addControl(mapTypeControl, kakao.maps.ControlPosition.TOPRIGHT);
                        // var zoomControl = new kakao.maps.ZoomControl();
                        // c_map.addControl(zoomControl, kakao.maps.ControlPosition.RIGHT);
                        var zoomControlHtml = '';
                        zoomControlHtml += '\
                            <div class="zoom-control" style="margin-top: 8px; margin-right: 8px; right: 0; width: 30px; position: absolute; background-color: #fff; z-index: 1; border-radius: 3px; box-shadow: 0 2px 3px 0 rgba(0, 0, 0, 0.16);">\
                                <div class="btn-zoom-control" data-inout="I" style="cursor: pointer; width: 30px; height: 30px;">\
                                    <svg style="fill: #6b6b6b; margin: 3px;" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24"><path d="M17 11h-4V7c0-.55-.45-1-1-1s-1 .45-1 1v4H7c-.55 0-1 .45-1 1s.45 1 1 1h4v4c0 .55.45 1 1 1s1-.45 1-1v-4h4c.55 0 1-.45 1-1s-.45-1-1-1z"/></svg>\
                                </div>\
                                <div class="slider-wrap-container" style="height: 130px;">\
                                    <div class="slider-wrap small" style="text-align: center; height: 100%;">\
                                        <div style="max-height: 100%;" class="zoom-control-slider"></div>\
                                    </div>\
                                </div>\
                                <div class="btn-zoom-control" data-inout="O" style="cursor: pointer; width: 30px; height: 30px;">\
                                    <svg style="fill: #6b6b6b; margin: 3px;" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24"><path d="M17 13H7c-.55 0-1-.45-1-1s.45-1 1-1h10c.55 0 1 .45 1 1s-.45 1-1 1z"/></svg>\
                                </div>\
                            </div>\
                        ';
                        var $zoomController = $(zoomControlHtml);
                        $(container).append($zoomController);
                        var zoom_slider = $zoomController.find('.zoom-control-slider').slider({
                            'orientation': 'vertical',
                            'min' : 1,
                            'max' : 14,
                            'step' : 1,
                            'value' : 3,
                            'handle' : 'square',
                            // 'reversed' : true,
                            'tooltip' : 'hide',
                        }).on('slide', function(data) {
                            c_map.setLevel(data.value);
                            c_map.setCenter(marker.getPosition());
                        }).on('slideStop', function(data) {
                            c_map.setLevel(data.value);
                            c_map.setCenter(marker.getPosition());
                        });

                        $zoomController.find('.btn-zoom-control').on('click', function() {
                            if($(this).data('inout') == 'I') {
                                c_map.setLevel(c_map.getLevel() - 1);
                                zoom_slider.slider('setValue', c_map.getLevel());
                            } else if($(this).data('inout' == 'O')) {
                                c_map.setLevel(c_map.getLevel() + 1);
                                zoom_slider.slider('setValue', c_map.getLevel());
                            }
                        });

                        kakao.maps.event.addListener(c_map, 'zoom_changed', function() {
                            zoom_slider.slider('setValue', c_map.getLevel());
                        });
                    }
                        
                    if((useTitle == true || useContent == true) && (mapTitle || mapContent)) {
                        var iwContent = '';
                        if(useTitle == true && mapTitle) {
                            iwContent = '<div class="title">' + mapTitle + '</div>';
                        }
                        if(useContent == true && mapContent) {
                            iwContent += '<div class="content">' + mapContent + '</div>';
                        }

                        if(iwContent) {
                            iwContent = '<div class="contact-map-info-window"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16"><path d="M8 0C4.69 0 2 2.69 2 6s1 4 6 10c5-6 6-6.69 6-10s-2.69-6-6-6zm0 8.3a2.3 2.3 0 1 1 0-4.6 2.3 2.3 0 0 1 0 4.6z"/></svg>' + iwContent + '</div>';
                            var infoWindow = $(iwContent);
                            $(container).append(infoWindow);
                            // infoWindow.css('bottom', 'calc(-100% + ' + (infoWindow.outerHeight() + 36) + 'px)');  
                        }
                    }

                    $(window).on("resize", function() {
                        c_map.setCenter(marker.getPosition());
                    });
                });
            }
    
            if($center_area.find('[data-map_kind="naver"]').length && (typeof naver == 'undefined' || typeof naver.maps == 'undefined' || naver.maps == null || VALIDPLAN == '')) {
                $center_area.find('[data-map_kind="naver"]').html('지도연결해제됨. Client ID 확인');
                    $center_area.find('[data-map_kind="naver"]').html('<iframe class="google-map" src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3165.5659473821083!2d127.0282496015659!3d37.494568!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x357ca1598c361b2b%3A0xdbf9af292beff3c!2z6rCV64Ko!5e0!3m2!1sko!2skr!4v1637303748377!5m2!1sko!2skr" width="600" height="450" style="border:0;" allowfullscreen="" loading="lazy"></iframe>');
            } else {
                $center_area.find('[data-map_kind="naver"]').each(function() {
                    var container = this;
                    var lat = $(this).data("lat");
                    var lng = $(this).data("lng");
                    var options = { center: new naver.maps.LatLng(lat, lng), zoom: 17};
                    var zoomInOut = $(this).data("zoominout");
                    var mapTitle = $(this).data("maptitle");
                    var mapContent = $(this).data("mapcontent");
                    var useTitle = $(this).data("usetitle");
                    var useContent = $(this).data("usecontent");
                    if(typeof zoomInOut == 'undefined' || !zoomInOut) zoomInOut = false;
                    if(typeof mapTitle == 'undefined' || !mapTitle) mapTitle = '';
                    if(typeof mapContent == 'undefined' || !mapContent) mapContent = '';
                    if(typeof useTitle == 'undefined' || !useTitle) useTitle = false;
                    if(typeof useContent == 'undefined' || !useContent) useContent = false;

                    var c_map = new naver.maps.Map(container, options);
                    var marker = new naver.maps.Marker({ position: new naver.maps.LatLng(lat, lng), map: c_map});

                    if(zoomInOut == true) {
                        // options.zoomControl = true;
                        // options.zoomControlOptions = {
                        //     position: naver.maps.Position.RIGHT_CENTER
                        // };

                        var zoomControlHtml = '';
                        zoomControlHtml += '\
                            <div class="zoom-control" style="margin-top: 8px; margin-right: 8px; right: 0; width: 30px; position: absolute; background-color: #fff; z-index: 1; border-radius: 3px; box-shadow: 0 2px 3px 0 rgba(0, 0, 0, 0.16);">\
                                <div class="btn-zoom-control" data-inout="I" style="cursor: pointer; width: 30px; height: 30px;">\
                                    <svg style="fill: #6b6b6b; margin: 3px;" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24"><path d="M17 11h-4V7c0-.55-.45-1-1-1s-1 .45-1 1v4H7c-.55 0-1 .45-1 1s.45 1 1 1h4v4c0 .55.45 1 1 1s1-.45 1-1v-4h4c.55 0 1-.45 1-1s-.45-1-1-1z"/></svg>\
                                </div>\
                                <div class="slider-wrap-container" style="height: 130px;">\
                                    <div class="slider-wrap small" style="text-align: center; height: 100%;">\
                                        <div style="max-height: 100%;" class="zoom-control-slider"></div>\
                                    </div>\
                                </div>\
                                <div class="btn-zoom-control" data-inout="O" style="cursor: pointer; width: 30px; height: 30px;">\
                                    <svg style="fill: #6b6b6b; margin: 3px;" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24"><path d="M17 13H7c-.55 0-1-.45-1-1s.45-1 1-1h10c.55 0 1 .45 1 1s-.45 1-1 1z"/></svg>\
                                </div>\
                            </div>\
                        ';
                        var $zoomController = $(zoomControlHtml);
                        $(container).append($zoomController);
                        var zoom_slider = $zoomController.find('.zoom-control-slider').slider({
                            'orientation': 'vertical',
                            'min' : 6,
                            'max' : 21,
                            'step' : 1,
                            'value' : 17,
                            'handle' : 'square',
                            'reversed' : true,
                            'tooltip' : 'hide',
                        }).on('slide', function(data) {
                            c_map.setZoom(data.value);
                            c_map.setCenter(marker.getPosition());
                        }).on('slideStop', function(data) {
                            c_map.setZoom(data.value);
                            c_map.setCenter(marker.getPosition());
                        });
                        $zoomController.find('.btn-zoom-control').on('click', function() {
                            if($(this).data('inout') == 'I') {
                                c_map.setZoom(c_map.getZoom() + 1);
                                zoom_slider.slider('setValue', c_map.getZoom());
                            } else if($(this).data('inout' == 'O')) {
                                c_map.setZoom(c_map.getZoom() - 1);
                                zoom_slider.slider('setValue', c_map.getZoom());
                            }
                        });

                        naver.maps.Event.addListener(c_map, 'zoom_changed', function(zoom) {
                            zoom_slider.slider('setValue', c_map.getZoom());
                        });
                    }

                    if((useTitle == true || useContent == true) && (mapTitle || mapContent)) {
                        var iwContent = '';
                        if(useTitle == true && mapTitle) {
                            iwContent = '<div class="title">' + mapTitle + '</div>';
                        }
                        if(useContent == true && mapContent) {
                            iwContent += '<div class="content">' + mapContent + '</div>';
                        }

                        if(iwContent) {
                            iwContent = '<div class="contact-map-info-window"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16"><path d="M8 0C4.69 0 2 2.69 2 6s1 4 6 10c5-6 6-6.69 6-10s-2.69-6-6-6zm0 8.3a2.3 2.3 0 1 1 0-4.6 2.3 2.3 0 0 1 0 4.6z"/></svg>' + iwContent + '</div>';
                            var infoWindow = $(iwContent);
                            $(container).append(infoWindow);
                            // infoWindow.css('bottom', 'calc(-100% + ' + (infoWindow.outerHeight() + 36) + 'px)');  
                        }
                    }
                    $(window).on("resize", function() {
                        c_map.setCenter(marker.getPosition());
                    });

                    c_map.setSize(new naver.maps.Size($(container).outerWidth(), $(container).outerHeight()));
                });
            }

            // $.each($('.sort-empty'),function(i,v) {
            //     if($(this).next().hasClass('sort-empty') && !$(this).next().hasClass('page')) {
            //         var $empty = $('<div class="sort-empty page">PAGE EMPTY</div>');
            //         //var $empty = ($(this).hasClass('use-link')) ?  $('<div class="sort-empty page">PAGE LINKED</div>') :  $('<div class="sort-empty page">PAGE EMPTY</div>');
            //         if(!$(this).hasClass('page')) $(this).after($empty);
            //     }
            // });

            // $('.reorderModal').scrollTo('.reorderBlock[data-id="' + selectID + '"]',{offset:-200});
            // $('.reorderBlock[data-id="' + selectID + '"]').addClass('active');

            // reorder page click
            $center_area.find(".page-list-area .gallery-name").on("click", function() {
                $.reorderON($(this).data('page'));
            });
            $center_area.find('.video-gallery-url').attr('data-gallery','');
            
            // reorder gallery gjs setting
            $('.reorderModal .center-area .reorderBlock[data-type="gallery"][data-type2="premium"]').each(function() {
                setGalleryJS('reorder-block',$(this));
            });

            blockSortable();
            $.processOFF();
        });
    }

    jQuery.reorderOFF = function() {
        window.basketBlockHtml = '';
        window.pageList = [];
        window.pageListChangeFlag = [];
        $(".new-dsgn-body").remove();
        $('.reorderModal').fadeOut(function() {
            $(this).remove();
            reorderFIXED = '';
        });
    }

    jQuery.viewON = function() {
        var $view = $('<div class="viewModal"></div>');

        if ($('.viewModal').length < 1) {
            $view.css({
                'position' : 'fixed',
                'width' : '100%',
                'height' : '100%',
                'background' : '#FFF url(https://storage.googleapis.com/i.addblock.net/preloader2.gif) center center no-repeat',
                'z-index' : '10000000000',
                'display' : 'none',
                'overflow' : 'auto'
            });
            $('body').prepend($view);
            var $content = $('<div class="content"></div>'),
                $h1 = $('<h1></h1>').css({
                    'position' : 'absolute',
                    'z-index' : '100001',
                    'right' : '0px'
                }),
                $close = $('<div class="pull-right"><i class="fa fa-times"></i></div>').css({
                    'margin-right' : '18px',
                    'margin-top' : '-16px',
                    'background-color': '#556273',
                    'color': '#fff',
                    'font-size': '18px',
                    'padding': '6px 9px',
                    'cursor': 'pointer',
                    'border-radius' : '20px'
                }),
                $iframe = $('<iframe src="http://' + SID + '.' + HOST + '/render/' + PAGE + '"></iframe>');

            $iframe.css({
                'position' : 'absolute',
                'top' : '0',
                'left' : '0',
                'width' : '100%',
                'height' : '100%',
                'z-index' : '100000',
                'border' : 'none'
            });


            $close.on('click',function() {
                $.viewOFF();
            });
            $content.append($h1).append($iframe);
            $h1.append($close);
            $view.append($content);
            $view.fadeIn();
        }
    }

    jQuery.viewOFF = function() {
        $('.viewModal').fadeOut(function() {
            $(this).remove();  
        });
    }

    jQuery.historyON = function() {
        viewmode('view');
    }

    $.fn.showUpgradePlanModal = function(sid, plan, upgrade_plan, fn) {
        if($('.site-upgrade-wrap').length > 0 || typeof checkUpgradeModal != "undefined" && checkUpgradeModal) return false;
        var checkUpgradeModal = true;

        var check_plan = (!plan || plan == 'FR' || plan == 'FREE') ? false : true,
            log_fn = (!fn) ? '' : '.' + fn,
            log_plan = (!upgrade_plan) ? '' : '.' + upgrade_plan,
            upgrade_plan = (!upgrade_plan) ? '' : '/plan/' + upgrade_plan,
            upgrade_url = (!upgrade_plan) ? '/upgrade' : ((check_plan) ? '/upgrade/change/site/' + sid + upgrade_plan : '/upgrade/buy/site/' + sid + upgrade_plan),
            modal_title = $.lang[LANG]['config.upgrade-plan' + log_plan + log_fn + '.title'],
            modal_description =  $.lang[LANG]['config.upgrade-plan' + log_plan + log_fn + '.description'],
            str = '\
                <div class="site-upgrade-wrap">\
                    <p class="description">' + modal_description + '</p>\
                    <div class="btn-box">\
                        <a href="' + upgrade_url + '"><i class="fa fa-level-up"></i>'+$.lang[LANG]['config.upgrade-plan.btn']+'</a>\
                    </div>\
                </div>\
            '; 

        var modal = $(this).showModalFlat(modal_title, str, false, false, '', '', '', '', '', '', '', function() {
            checkUpgradeModal = false;
        });
    }

    $.fn.showModal = function (header, content, footer, cancel, confirm, callback, backdrop) {
        $('.editor-navbar').css('z-index','1030');
        var HTML = '<div class="modal modal-default fade" id="generic-modal">' +
            '   <div class="modal-dialog" style="padding-top:5%;">' +
            '       <div class="modal-content">' +
            '           <button type="" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true"><img src="https://storage.googleapis.com/i.addblock.net/fa-close-modal.png" alt="close"></span></button>' +
            '           <div class="modal-body">' +
            '               <h3 class="modal-title">' + header +
            '               </h3>' + content +
            '           </div>';
            if(footer==true) {
                HTML = HTML + '<div class="modal-footer">';
                if(cancel == true) {
                    HTML = HTML + '<button type="button" class="btn btn-default btn-sm" data-dismiss="modal">취소</button>';
                } else if(confirm == true) {
                    HTML = HTML + '<button type="button" class="btn btn-primary btn-sm ok-button-dialog">확인</button>';
                }
                HTML = HTML +
                '       </div>';
            }
            HTML = HTML +
            '       </div>' +
            '   </div>' +
            '</div>';

        var container = $('<div class="generic-modal"></div>').html(HTML);
        $('body').append(container);
        var newInstance = jQuery.extend(true, {}, container);
        newInstance.find('.ok-button-dialog').bind('click', function () {
            callback();
        });
        var modalElement = newInstance.find('#generic-modal');
        if(backdrop) modalElement.modal({ backdrop : 'static', keboard : false});
        else modalElement.modal();

        modalElement.on('hidden.bs.modal', function(e) {
            // $('.editor-navbar').css('z-index','1040');
            $('.generic-modal').remove();
            $('.modal-backdrop').remove();
        });

        return modalElement;
    }

    $.fn.showModalFlat = function (header, content, footer, confirm, callback, closetext, oktext, size, backdrop, closecallback, showcallback, hidecallback, buttontop) {
    /**
     * @param header
     * @param content
     * @param footer
     * @param confirm
     * @param callback
     * @param closetext
     * @param oktext
     * @param size
     * @param backdrop
     * @param closecallback
     * @param showcallback
     * @param hidecallback
     * */
        // if($('#flat-modal.event').length) return;

        size = (typeof size == 'undefined') ? '' : size;

        var buttontop = (typeof buttontop != 'undefined' && buttontop) ? buttontop : false;
        var reg_zindex = /\bzindex(\d+)\b/,
            matches = size.match(reg_zindex),
            zindex = (matches) ? matches[1] * 1 : -1;

        if(size.indexOf(',') > -1) {
            var modal_name = size.split(','),
                modal_class = '';

            size = modal_name[0];
            modal_class = modal_name[1];
        }

        backdrop = (typeof backdrop != 'undefined' && backdrop === true) ? true : false;

        // $('.editor-navbar').css('z-index','1030');

        var checkCLBtnMode = (size.indexOf('cl-s-btn') > -1) ? true : false,
            close_btn = $.lang[LANG]['config.close'],
            close_btn_class = 'btn-default',
            ok_btn = $.lang[LANG]['config.ok'],
            ok_btn_class = 'btn-primary',
            btn_html = '';

        if( closetext == 'cancel') {
            close_btn = $.lang[LANG]['config.cancel'];
        } else if( closetext == 'close' ) {
            close_btn = $.lang[LANG]['config.close'];
        } else if( closetext == 'ok' || closetext == 'notice.ok' ) {
            close_btn = $.lang[LANG]['config.'+closetext];
            close_btn_class = 'btn-primary ok-button-dialog';
        } else if ( typeof closetext != 'undefined') {
            if( closetext.match(/\./g) !== null ) close_btn = $.lang[LANG][closetext];
            else if(closetext.length > 0) close_btn = closetext;
        }
        if( oktext == 'save' ) {
            ok_btn = $.lang[LANG]['config.save'];
        } else if( oktext == 'send' ) {
            ok_btn = $.lang[LANG]['config.send'];
        } else if( oktext == 'ok' ) {
            ok_btn = $.lang[LANG]['config.ok'];
        } else if ( typeof oktext != 'undefined') {
            if( oktext.match(/\./g) !== null ) ok_btn = $.lang[LANG][oktext];
            else if(oktext.length > 0) ok_btn = oktext;
        } 
        var flat_modal_cnt = $('.modal-default').length,
            flat_modal_id = (flat_modal_cnt == 0) ? 'flat-modal': 'flat-modal'+flat_modal_cnt,
            btn_html_close = '<button type="button" class="btn '+ close_btn_class +' btn-sm close-button-dialog" data-dismiss="modal">' + close_btn + '</button>';             

        if(confirm == true) {
            if(checkCLBtnMode) {
                var btn_html_ok = '<button type="button" class="btn '+ ok_btn_class +' btn-sm ok-button-dialog">' + ok_btn + '</button>';                
                btn_html_ok = (buttontop && (oktext == '')) ? '' : btn_html_ok;
                btn_html = btn_html_ok + btn_html_close;
            } else {
                btn_html = btn_html_close + '<button type="button" class="btn '+ ok_btn_class +' btn-sm ok-button-dialog">' + ok_btn + '</button>';
            }
        } else btn_html = btn_html_close;

        var HTML = '<div class="modal modal-default fade" id="'+flat_modal_id+'">' +
            '   <div class="modal-dialog '+size+'">' +
            '       <div class="modal-content" data-buttontop="'+buttontop+'">' +
            '           <button type="" class="close close-button-dialog" data-dismiss="modal" aria-label="Close"><span aria-hidden="true"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16"><path d="M8.71 8l7.15-7.15c0.2-0.2 0.2-0.51 0-0.71s-0.51-0.2-0.71 0L8 7.29 0.85 0.15c-0.2-0.2-0.51-0.2-0.71 0s-0.2 0.51 0 0.71L7.29 8l-7.15 7.15c-0.2 0.2-0.2 0.51 0 0.71C0.24 15.95 0.37 16 0.5 16s0.26-0.05 0.35-0.15L8 8.71l7.15 7.15c0.1 0.1 0.23 0.15 0.35 0.15s0.26-0.05 0.35-0.15c0.2-0.2 0.2-0.51 0-0.71L8.71 8z"/></svg></span></button>' +
            '           <div class="modal-body">';
            HTML += (buttontop) ? '\
                            <div class="modal-top">\
                                <div class="modal-title-wrap">\
                                    <h3 class="modal-title">' + header + '</h3>\
                                </div>\
                                <div class="modal-title-button">' + btn_html_close + btn_html_ok + '</div>\
                            </div>' : '<h3 class="modal-title">' + header + '</h3>';
            HTML += content +'\
                        </div>';
            if(footer==true) {
                HTML = HTML + 
                '      <div class="modal-footer">';
                HTML = HTML + btn_html + 
                '      </div>';
            }
            HTML = HTML +
            '       </div>' +
            '   </div>' +
            '</div>';

        var time = new Date().getTime();
        var container = $('<div class="flat-modal"></div>').html(HTML);
        
        if(typeof modal_class != "undefined" && modal_class) container.addClass(modal_class);
        if(size && size.indexOf('cl-modal') > 0 || (size && size.indexOf('cl-cmmodal') > -1)) {
            var mobile_close_btn = '\
                    <button class="cl-mobile-btn close" data-dismiss="modal" aria-label="Close">\
                        <span aria-hidden="true">\
                            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16">\
                                <polygon points="16 1 15 0 8 7 1 0 0 1 7 8 0 15 1 16 8 9 15 16 16 15 9 8 "/>\
                            </svg>\
                        </span>\
                    </button>\
                    ';

            container.find('.modal').prepend(mobile_close_btn);
            
            if(confirm==false && (closetext=='close' || closetext=='cancel')) container.find('.close-button-dialog').addClass('clostbtnfalse'); //닫기 버튼 하나일 경우 공통 class
            if(footer==true && container.find('.cl-cmmodal').hasClass('fullcover-modal-scroll') && container.find('.modal-footer').find('button').length==1) container.find('.cl-cmmodal').addClass('single-btn'); // fullcover 버튼 하나일경우

            if(size.indexOf('cl-modal') > -1) container.addClass('cl-flat-modal');
            else if(size.indexOf('cl-cmmodal') > -1) container.addClass('cl-common-modal');
            if(size.indexOf('cl-alert') > -1) container.addClass('cl-alert-modal');

            if(size.indexOf('confirm-resource-folder-delete') && size.indexOf('modal-over-1') > -1) container.addClass('modal-over-1');

            if(size.indexOf('pg-modal') > -1) container.addClass('pg-modal-wrap'); 
            else if(size.indexOf('cl-common-notice') > -1) {  //공통 notice icon 추가
                var svg = '\
                    <svg xmlns="http://www.w3.org/2000/svg" class="cl-notice-icon" viewBox="0 0 90 90" width="90" height="90"><path d="M45 4c22.61 0 41 18.39 41 41S67.61 86 45 86 4 67.61 4 45 22.39 4 45 4M45 0C20.15 0 0 20.15 0 45s20.15 45 45 45 45-20.15 45-45S69.85 0 45 0L45 0z"/>\
                        <path d="M45 20L45 20c1.1 0 2 0.9 2 2v32c0 1.1-0.9 2-2 2h0c-1.1 0-2-0.9-2-2V22C43 20.9 43.9 20 45 20z"/><circle cx="45" cy="67" r="3"/>\
                    </svg>\
                    ';
                container.find('.modal-title').before(svg);
                if(size.indexOf('modal-over-1') > -1) container.addClass('modal-over-1');
            } else if(size.indexOf('guidePopup') > -1) {
                container.find('.modal-title').not('.guidetitle').remove();
                container.addClass('guidePopup-wrap');
            } else if(size.indexOf('modal-product-badge') > -1) {
                container.addClass('modal-product-badge-wrap');
                if(size.indexOf('cl-change-badge-design') > -1) {
                    container.addClass('modal-change-badge-design-wrap');
                }
            } else if(size.indexOf('cl-delete-badge-image') > -1) {
                container.addClass('modal-delete-badge-image');
            } else if(size.indexOf('modal-addFranchiseBar') > -1) {
                container.addClass('modal-addFranchiseBar-wrap');
            }
        }

        $('body').append(container);
        var newInstance = jQuery.extend(true, {}, container);
        var modalElement = newInstance.find('#'+flat_modal_id);
        if(backdrop) modalElement.modal({ backdrop : 'static'});
        else modalElement.modal();
        
        if(zindex > -1) {
            modalElement.css('z-index', zindex);
            modalElement.closest('.flat-modal').next('.modal-backdrop').attr('style','z-index: '+(zindex-1)+'!important;');
        }

        newInstance.find('.ok-button-dialog').bind('click', function () {
            if(typeof callback == 'function')
                callback();
        });

        newInstance.find('.close-button-dialog').bind('click', function () {
            if(typeof closecallback == 'function') {
                closecallback();
            }
        });

        modalElement.on('shown.bs.modal', function(e) {
            if($('#ch-plugin').length > 0) $('#ch-plugin').attr('style','z-index: 1 !important; pointer-events: none !important;');
            var modal = document.querySelector('.modal');
            // modal.style.position = 'absolute';
            // setTimeout(function() {
                modal.style.position = 'fixed';
            // },0);
            if(typeof showcallback == 'function') showcallback();
        });

        modalElement.on('hide.bs.modal', function(e) {
            if($(this).find('input:focus').length > 0) {
                e.preventDefault();
                return false;
            }
        });
        
        modalElement.on('hidden.bs.modal', function(e) {
            if(typeof isEDIT != 'undefined' && isEDIT === false) editEL = '';
            if(typeof hidecallback == 'function') hidecallback();
            var flat_modal_id = $(this).attr('id');
            // $('.editor-navbar').css('z-index','1040');
            var this_modal = $('#'+flat_modal_id).closest('.flat-modal');
            this_modal.next('.modal-backdrop').remove();
            this_modal.remove();

            if($('.modal-backdrop').length) {
                setTimeout(function() {
                    $('body').addClass('modal-open');    
                },10);                
            }
            $('body').removeClass('no-fixed');
            if($('#ch-plugin').length > 0) $('#ch-plugin').attr('style','z-index: 10000000 !important; pointer-events: auto !important;');
        });

        return modalElement;
    }

    $.fn.showPopupModal = function (data,sid) {
        // console.log('showPopupModal');
        
        var img_count = data.length,
            img_w = new Array(), 
            img_h = new Array(), 
            counter = 0,
            sid = (typeof sid != 'undefined') ? sid : SID,
            popup_data = new Array();

        $('#el-empty').html('');
        $.each(data,function(i,v) {
            var check_img = v.popupimg + '?' + new Date().getTime();
            var $img = $('<img/>').attr('src',check_img);
            $img.error(function() {
                data[i]['popupimg'] = '//storage.googleapis.com/i.addblock.net/img_broken_fill_500.png';
                $(this).attr('src', '//storage.googleapis.com/i.addblock.net/img_broken_fill_500.png');
            });
            $('#el-empty').append($img);
        });

        var $imgs = $('#el-empty img');
        $.each($imgs,function(i,v) {
            $(this).one('load',function() {
                counter++;
                img_w[i] = this.width;
                img_h[i] = this.height;
                if(counter == img_count) getPopupFunction();
            });
            if(this.complete) $(this).load();
        });

        function getPopupFunction() {
            $('#el-empty').html('');
            var html = '',
                display = new Array();

            $.each(data, function(i,o) {
                var isCookie = ($.cookie(sid + 'Popup' + i)) ? 'style= display:none;' : '';
                display.push(isCookie);

                var plink = (typeof o.popuplink != 'undefined' && o.popuplink != 'javascript:;' && o.popuplink.length > 0) ? o.popuplink : 'javascript:;',
                    plink_target = (typeof o.popuplink_target != 'undefined' && o.popuplink_target === true) ? 'target="_blank"' : '',
                    link_option = '';

                if(typeof o.popuplink == 'undefined') o.popuplink = '';
                if(typeof o.popuplink_target == 'undefined') o.popuplink_target = '';
                if(typeof o.popuptime == 'undefined') o.popuptime = '';

                if(plink != '' && plink != 'javascript:;') {
                    if(checkBase64Encode(plink)) plink = Base64.decode(plink);
                    var _menuList = (PAGE_MODE == 'c') ? MENULIST : property.MENULIST;
                    
                    if(plink.match(/^\@/g) !== null) {                                                  // link-type: link-bookmark ==> a[attr-bookmark]
                        var _settings = (PAGE_MODE == 'c') ? SETTINGS : property.SETTINGS,
                            bookmark_seq = plink.replace(/^\@/g,'');
                            
                        if(typeof _settings == 'undefined' || typeof _settings.blockBookmarkList == 'undefined' || _settings.blockBookmarkList['bookmark' + bookmark_seq] == 'undefined') {
                            plink = '';
                            link_option = '';
                        } else {
                            link_option = 'attr-bookmark="' + bookmark_seq + '"';
                        }
                    } else if(plink.match(/^flink\@[0-9]/gi) !== null) {                                // link-type: link-file     ==> a[attr-flink]
                        link_option = 'attr-flink="' + plink.replace(/^flink\@/gi,'') + '"';
                        plink_target = '';
                    } else if(_menuList.indexOf(plink.replace(/^\//g,"").replace(/ /g,"-")) > -1) {     // link-type: link-menu     ==> a[data-user-link]
                        link_option = 'data-user-link="' + plink + '"';
                    } else {                                                                            // link-type: link-out      ==> a[attr-link]
                        link_option = 'attr-link="' + plink + '"';
                    }

                    plink = (PAGE_MODE == 'c') ? makeLinkUrl(plink, ONE, VIEW) : makeLinkUrl(plink, property.ONE, property.VIEW);
                }

                html = html + '<div class="modal-popup" id="' + sid + 'Popup' + i + '" data-link="' + plink + '" data-target="' + o.popuplink_target + '" data-time="' + o.popuptime + '" data-idx="' + i + '" ' + display[i] + '>' + 
                '   <div class="popup-content">' +
                '       <div class="popup-header">' +
                '           <button type="button" class="close popup-close"><span aria-hidden="true"><svg viewBox="0 0 12 12" width="12" height="12"><path d="M6.71 6l5.15-5.15c0.2-0.2 0.2-0.51 0-0.71s-0.51-0.2-0.71 0L6 5.29 0.85 0.15c-0.2-0.2-0.51-0.2-0.71 0s-0.2 0.51 0 0.71L5.29 6l-5.15 5.15c-0.2 0.2-0.2 0.51 0 0.71C0.24 11.95 0.37 12 0.5 12s0.26-0.05 0.35-0.15L6 6.71l5.15 5.15c0.1 0.1 0.23 0.15 0.35 0.15s0.26-0.05 0.35-0.15c0.2-0.2 0.2-0.51 0-0.71L6.71 6z"/></svg></span></button>' +
                '       </div>' +
                '       <div class="popup-body">' +
                '          <a href="' + plink + '" ' + plink_target  + ' ' + link_option + '>' +
                '             <div class="img-wrap">' +
                '               <img src="' + o.popupimg + '" alt="" class="img-responsive img-popup" />' +
                '             </div>' +
                '          </a>' +
                '       </div>' +
                '       <div class="popup-footer clearfix">' +
                '           <ul class="text-center">' +
                '               <li class="sitePopupTodayHide">' +
                '                   <input type="checkbox" value="" class="hide">' +
                '                   ' + $.lang[LANG]['editor.popup.close-24hours'] + 
                '               </li>' +
                '               <li class="sitePopupClose">' + $.lang[LANG]['config.close'] + '</li>' +
                '           </ul>' +
                '       </div>' +
                '   </div>' +
                '</div>';
                if(data.length == (i+1) )  setPopupFunction(html,display);
            });

        }

        function setPopupFunction(html, display) {

            var container = $('<div class="popup"></div>').html('<div class="popup-modal">' + html + '</div>');
            if($('.dsgn-body').find('.popup').length > 0 )  { 
                $('.dsgn-body').find('.popup').replaceWith(container);
            } else { 
                $('.dsgn-body').append(container); 
            }

            var newInstance = jQuery.extend(true, {}, container);
            var sitePopupElement  = newInstance.find('.popup-modal');

            var total_w = 0,
                add_w = 0, 
                d_top = $('.header.el-menu > header').outerHeight() + 15, 
                d_left = 0,
                x = 0, y = 0, y_r = 0;

            var checkDsgnDodyW = $('.dsgn-body').width() + $('.dsgn-body').css('padding-left').replace('px','') * 1;
            if($('.header.el-menu').hasClass('sidebar') && checkDsgnDodyW > 752 ) d_top = 15;

            for(i=0; i<img_w.length; i++) {
                if(parseInt(img_w[i]) > $('.dsgn-body').width()-30 ) {
                    img_w[i] = $('.dsgn-body').width()-30;
                }
                if(display[i]) { 
                    continue;
                } else {
                    total_w = total_w + parseInt(img_w[i]) + 30;
                }
            }
           
            var isOverflow = ($('.dsgn-body').width() < total_w) ? true : false,
                display_i = -1;
            
            if(isOverflow) { sitePopupElement.addClass('popupimg-overflow-y');
            } else { sitePopupElement.removeClass('popupimg-overflow-y'); }

            $.each(img_w, function(i,v) {
                if(display[i]) {
                    return true;
                } else {
                    display_i++;
                }

                if(isOverflow) {
                    x = (display_i==0) ? d_top : d_top + (display_i*30);
                    y = d_left + ((display_i+1)*30);
                    y_r = 120 - y;

                    img_w[i] = 'auto';
                } else {
                    d_left = ($('.dsgn-body').width() - total_w)/2;

                    x = d_top;
                    y = d_left + add_w + (i*15);
                }
                add_w = add_w + v;

                var css_val = (isOverflow) ? {'top': x +'px', 'left': y+'px', 'right': y_r+'px', 'margin-left': '0px', 'width': img_w[i], 'max-width': v} : {'top': x +'px', 'left': y+'px' , 'width': img_w[i]};
                sitePopupElement.find('#'+sid +'Popup'+ i).css(css_val);
            });
            return sitePopupElement;
        }
    }

    jQuery.guideVideoON = function() {
        // 편집 모드를 처음으로 보는 경우가 아니면 ( 주요기능을 이미 둘려봤으면 )
        if( LANG == 'ko' || typeof SETTINGS.showGuide != 'undefined')
            return false;

        hideElementListPanel();
        var $guideVideoModal = $('<div class="guideVideoModal config-modal"></div>'),
            $content = $('<div class="content"></div>');

        if ($('.guideVideoModal').length < 1) {
            $('body').prepend($guideVideoModal);
            $content.css({
                "width" : "100%",
                "height" : "100%",
                "background-color" : "rgba(0,0,0,0.6)",
                "display" : "none"
            });

            $guideVideoModal.append($content);
            $guideVideoModal.css({
                "display": "inherit",
                "position": "fixed",
                "z-index": "99999999",
                "top": "0",
                "left": "0",
                "width": "100%",
                "height": "100%",
                "text-align": "center",
                "background-color" : "transparent"
            });
            $guideVideoModal.fadeIn();

            var $guideVideo = $('<div class="guideVideo">'),
                $close = $('<div class="close"><img src="https://storage.googleapis.com/i.addblock.net/fa-close-modal.png" alt="close" /></div>'),
                $close2 = $('<button type="button" class="btn btn-primary btn-sm ok-button-dialog">' + $.lang[LANG]['config.ok'] + '</button>');
                $header = $('<div class="header"><h2>' + $.lang[LANG]["editor.guide.tutorial-video"] + '</h2></div>'),
                $body = $('<div class="body"></div>'),
                $contentbox = $('<div class="contentbox"></div>'),
                $tutorialVideo = $('<div class="tutorial-video"></div>'),
                $videoWrap = $('<div class="video-wrap guideVideo-stopPlay"><div id="guide-video-modal-video-overlay"></div></div>'),
                $watchAgainNote = $('<span class="watch-again-note">' + $.lang[LANG]['tutorial-video.watch-again-note'] + '</span>'),
                $bottom = $('<div class="bottom"></div>');

            $close.on('click',function() { $.guideVideoOFF(); });
            $close2.on('click',function() { $.guideVideoOFF(); });

            $videoWrap.on('click', function() {

                $(this).toggleClass('guideVideo-stopPlay');

                if(!$(this).hasClass('guideVideo-stopPlay')) {
                    if ( LANG == 'en' )
                        var link = "https://www.youtube.com/embed/p6fyIMl2BcI";

                    var html = '<iframe class="video embed-responsive-item" width="765" height="380" src="' + link + '?enablejsapi=1&rel=0&vq=large&wmode=opaque&showinfo=0&controls=1&autoplay=0&loop=0;playlist=Fn0Mpyh3xto;" frameborder="0" allowfullscreen></iframe>';

                    $(this).html(html);

                }
            });

            $tutorialVideo.append( $videoWrap );
            $contentbox.append( $tutorialVideo );

            $bottom.append($close2).append($watchAgainNote);
            $body.append($contentbox).append($bottom);
            $guideVideo.append($header).append($close).append($body);
            $content.append($guideVideo);
            $content.fadeIn();

        }

        var $thisContent = $('.guideVideoModal .contentbox');
        
    }

    jQuery.guideVideoOFF = function() {
        $('.guideVideoModal').fadeOut(function() {
            $(this).remove();  
        });
    }




    $.fn.siteDelete = function(sid, code) {
        // isDelLangSite : 특정 다국어 삭제시 ( 사이트 삭제에서의 다국어 삭제는 false 임 )
        var isDelLangSite = (code) ? true : false;

        var sdOrgSid = sid,
            sdSid = (isDelLangSite) ? sid + '__' + code : sid,
            sdMore = [''],
            sdResource = [],
            sdResourceIdx = -1,
            sdResourceTotal = 0,
            sdIdx = -1,
            p_w = 0, p_max = 100, p_unit = 1,
            p_step_max = 100, p_step_unit = 1, p_step_plus = 1,
            block_view = { 'gallery':1, 'forum':2, 'form':2 };

        $.sd = {
            initVal: function() {
                p_step_max = 100;
                p_step_unit = 1;
                p_step_plus = 1;

                sdIdx++;

                if(!isDelLangSite) {
                    code = sdMore[sdIdx];
                    sdSid = (code) ? sid + '__' + code : sid;
                }
            },
            strProcess: function(step) {
                // console.log('step: ' + step + '');
                // console.log('p_w: '+ p_w + ', p_unit: ' + p_unit);
                var str = '', cnt = '';

                switch(step) {
                    case 'init':
                        p_max = (isDelLangSite) ? 100 : 100/sdMore.length;
                        p_unit = p_max / 100;

                        str = $.lang[LANG]['site.delete.process.init'];
                        break;

                    case '1':
                        p_w += p_unit * 5;

                        str = $.lang[LANG]['site.delete.process.step1'];
                        break;

                    case 'end':
                        p_w = p_max * (sdIdx+1);

                        var checkEnd = (sdMore.length > sdIdx+1) ? false : true;

                        str = $.lang[LANG]['site.delete.process.step14'];
                        cnt = (checkEnd) ? '' : '<br>' + $.lang[LANG]['site.delete.process.more'];

                        if(checkEnd) {

                            if(isDelLangSite) {
                                var slog_lang = $('.language-contents .settings-language .selected-languages li[data-code="' + code + '"] .language-name').text();
                                setSiteLogs('settings.language','delete',{'lang':slog_lang,'code':code},'settings.language');
                            }

                            setTimeout(function() {
                                $.progressOFF();
                            }, 500);
                        }
                        break;

                    default:
                        if(step == '2') {
                            p_step_max = p_unit * 90;
                            p_step_unit = p_step_max / 13;
                        }

                        if($.inArray(step,['3','4'])>-1) str = $.lang[LANG]['site.delete.process.step3'];
                        else if($.inArray(step,['5','6','7','8','8-more','9'])>-1) str = $.lang[LANG]['site.delete.process.step5'];
                        else str = $.lang[LANG]['site.delete.process.step'+step];

                        if(step == '13-more') {
                            if(sdResource.length == 0) return false;
                            str += '( ' + (sdResourceIdx+1) + ' / ' + sdResource.length + ' )';
                        }

                        if(p_step_plus > 0) p_w += p_step_unit;
                        break;
                }


                if(step == 'init' && sdIdx == 0) {
                    $.progressON(str,'','',true);
                } else {
                    $('.progressModal .progress-header h1').html(str);
                    $('.progressModal .progress-bar').css('width',p_w+'%');
                }

                // console.log('p_w: '+ p_w + ', p_unit: ' + p_unit);
            },
            step0: function() {
                if(sdIdx == 0) $('#loading').addClass('hide');

                var sdStep1 = $.sd.step1();
                sdStep1.done(function() {
                    $.sd.stepMultiCall('2');
                }).fail(function(sdStep1_msg){
                    console.log(sdStep1_msg);

                    $.sd.stepEnd();
                    if(sdStep1_msg) $(this).showModalFlat('ERROR', sdStep1_msg, false, false,'', 'ok','','cl-cmmodal cl-s-btn w560 cl-p130 cl-p0');
                });
            },
            step1: function() { // [del] ln_select
                var step1_deferred = $.Deferred();

                $.post('/template/siteDelete', { step:'1', sid:sdOrgSid, code:code, isDelLangSite:isDelLangSite }, function(r1) {
                    if(typeof r1.error != 'undefiend' && r1.error) {
                        console.log('step1 reject');
                        step1_deferred.reject(r1.error);
                    }
                    $.sd.strProcess('1');

                    setTimeout(function() {
                        step1_deferred.resolve();
                    }, 200);
                }, 'json');
                
                return step1_deferred.promise();
            },
            stepMultiCall: function(call_step) {
                if(call_step == '2') $.sd.strProcess('2');

                if(call_step == '13-more') {
                    var sdStep3 = $.sd.step3();
                    sdStep3.done(function(next_step) {
                        if(next_step) $.sd.stepMultiCall(next_step);
                        else $.sd.stepEnd();
                    }).fail(function(sdStep3_msg) {
                        console.log(sdStep3_msg);

                        $.sd.stepMultiCall('14');
                        if(sdStep3_msg) $(this).showModalFlat('ERROR', sdStep3_msg, false, false,'', 'ok','','cl-cmmodal cl-s-btn w560 cl-p130 cl-p0');
                    });
                } else {
                    var sdStepMulti = $.sd.stepMulti(call_step);
                    sdStepMulti.done(function(next_step) {
                        if(next_step) $.sd.stepMultiCall(next_step);
                        else $.sd.stepEnd();
                    }).fail(function(sdStepMulti_msg){
                        console.log(sdStepMulti_msg);

                        var jump_step = (call_step.indexOf('-more') > -1) ? Number(call_step.replace('-more', ''))+1 : Number(call_step)+1;
                        if(jump_step >= 15) $.sd.stepEnd();
                        else $.sd.stepMultiCall(jump_step.toString());
                        
                        console.log(call_step);
                        console.log('->');
                        console.log(jump_step.toString());

                        if(sdStepMulti_msg) $(this).showModalFlat('ERROR', sdStepMulti_msg, false, false,'', 'ok','','cl-cmmodal cl-s-btn w560 cl-p130 cl-p0');
                    });
                }
            },
            stepMulti: function(sd_step) {
                var stepMulti_deferred = $.Deferred();

                $.post('/template/siteDelete', { step:sd_step, sid:sdOrgSid, code:code }, function(r) {
                    if(typeof r.error != 'undefiend' && r.error) {
                        console.log('stepMulti reject');
                        stepMulti_deferred.reject(r.error);
                    }
                    if(sd_step == '13') {
                        sdResource = (typeof r.r_list != 'undefiend') ? r.r_list : [];
                        sdResourceTotal = (typeof r.r_total != 'undefiend') ? r.r_total : 0;
                    }

                    p_step_plus = (r.next_step=='' || r.next_step.indexOf('-more') > -1) ? 0 : 1;
                    if(r.next_step) $.sd.strProcess(r.next_step);

                    setTimeout(function() {
                        stepMulti_deferred.resolve(r.next_step);
                    }, 100);
                }, 'json');

                return stepMulti_deferred.promise();
            },
            step3: function() {
                var step3_deferred = $.Deferred();

                sdResourceIdx++;
                var r_seq = sdResource[sdResourceIdx];
                if(typeof r_seq != 'undefiend' && r_seq) {
                    $.post('/template/siteDelete', { step:'13-more', sid:sdOrgSid, code:code, r_seq:r_seq }, function(r3) {
                        if(typeof r3.error != 'undefiend' && r3.error) {
                            console.log('step3 reject');
                            step3_deferred.reject(r3.error);
                        }
                        p_step_plus = 0;
                        if(r3.next_step) $.sd.strProcess(r3.next_step);

                        setTimeout(function() {
                            step3_deferred.resolve(r3.next_step);
                        }, 50);
                    }, 'json');
                } else {
                    step3_deferred.resolve('14');
                }

                return step3_deferred.promise();
            },
            stepEnd: function() {
                $.sd.strProcess('end');

                var checkEnd = (sdMore.length > sdIdx+1) ? false : true;
                if(checkEnd) {
                    $('#loading').removeClass('hide');

                    var deleted_modal = $(this).showModalFlat($.lang[LANG]['site.delete.process.end.title'], $.lang[LANG]['site.delete.process.end.description'], true, false, function() {
                        $('.modal.modal-default.fade.in').css('zIndex','');
                        location.href='/';
                    }, 'ok','','cl-cmmodal cl-s-btn w560 cl-p130 cl-p0','','','',function() {
                        location.href='/';
                    });
                } else {
                    $.sd.initVal();
                    setTimeout(function() {
                        $.sd.step0();
                    }, 300);
                }
            }
        }



        if(isDelLangSite) {
            $.sd.initVal();
            $.sd.strProcess('init');
            setTimeout(function() {
                $.sd.step0();
            }, 300);
        } else {
            $.post('/template/siteDelete', { step:'check', sid:sdOrgSid, code:code }, function(r1) {
                if(typeof r1.error != 'undefiend' && r1.error) {
                    alert(r1.error);
                    location.reload();
                    return false;
                }
                sdMore = r1.more_code;

                $.sd.initVal();
                $.sd.strProcess('init');

                setTimeout(function() {
                    $.sd.step0();
                }, 300);
            }, 'json');
        }
    }


    $.fn.siteClone = function(sid, dest_sid, isAddLangSite) {
        var scIdx = -1,
            scSid = [sid],
            scDest = [dest_sid],
            scCheck = { 'popup':false, 'music':false, 'gallery':false, 'forum':false },
            scOrgData = [],
            scDestData = [],
            scTempData = [];

        var p_w = 0, p_max = 100, p_unit = 1,
            p_step_max = 100, p_step_unit = 1, p_step_plus = 1,
            block_view = { 'gallery':1, 'forum':2, 'form':2 };

        $.sc = {
            initVal: function() {
                p_step_max = 100;
                p_step_unit = 1;
                p_step_plus = 1;
              
                scIdx++;
                if(scIdx == 0) {
                    if(isAddLangSite) scCheck = { 'popup':true, 'music':true, 'gallery':true, 'forum':true };
                    else scCheck = { 'popup':false, 'music':false, 'gallery':false, 'forum':false };
                } else if(scIdx > 0) {
                    scDest.push(scSid[scIdx].replace(scSid[0],scDest[0]));
                }

                scOrgData.push({ 'total':0, 'normal_total':0, 'gallery' : { 'total':0 }, 'forum' : { 'total':0 }, 'form' : { 'total':0 } });
                scDestData.push({ 'total':0, 'normal_total':0, 'gallery' : { 'total':0 }, 'forum' : { 'total':0 }, 'form' : { 'total':0 } });
                scTempData.push({ 'gallery':false, 'forum':false, 'form':false });
            },
            strCheck: function() {
                var checkbox = clSVG('checkbox','16','16',false,'');

                return '\
                <div class="check-wrap">\
                    <div class="box">\
                        <div class="newcheckbox hand checkbox">\
                            <label>\
                                <input type="checkbox" class="check-popup" name="check-popup">\
                                ' + checkbox + '\
                            </label>\
                            <span>' + $.lang[LANG]['site.clone.check.popup'] + '</span>\
                        </div>\
                        <div class="newcheckbox hand checkbox">\
                            <label>\
                                <input type="checkbox" class="check-music" name="check-music">\
                                ' + checkbox + '\
                            </label>\
                            <span>' + $.lang[LANG]['site.clone.check.music'] + '</span>\
                        </div>\
                        <div class="newcheckbox hand checkbox">\
                            <label>\
                                <input type="checkbox" class="check-gallery" name="check-gallery">\
                                ' + checkbox + '\
                            </label>\
                            <span>' + $.lang[LANG]['site.clone.check.gallery'] + '</span>\
                        </div>\
                        <div class="newcheckbox hand checkbox">\
                            <label>\
                                <input type="checkbox" class="check-forum" name="check-forum">\
                                ' + checkbox + '\
                            </label>\
                            <span>' + $.lang[LANG]['site.clone.check.forum'] + '</span>\
                        </div>\
                    </div>\
                    <p><span class="error">' + $.lang[LANG]['site.clone.check.info.1'] + '\
                    <svg class="cm-popover-info" viewBox="0 0 13 13"  width="13" height="13" tabindex="0" data-toggle="popover" data-trigger="hover" data-html="true" data-placement="top" data-content="' + $.lang[LANG]['site.clone.check.info.3'] + '">\
                        <path d="M6.5 0C2.91 0 0 2.91 0 6.5S2.91 13 6.5 13 13 10.09 13 6.5 10.09 0 6.5 0zM7 10H6V9h1V10zM7.67 6.75C7.04 7.37 7 7.66 6.99 8H6c0.02-0.63 0.21-1.03 0.88-1.69 0.46-0.47 0.75-0.86 0.76-1.34 0-0.58-0.39-0.95-1.02-0.95 -0.56 0-1 0.14-1.08 0.76C5.53 4.85 5.52 4.93 5.52 5H4.5c-0.01-0.08 0-0.14 0-0.2 0.08-1.3 1.11-1.79 2.17-1.79 1.22 0 2.04 0.84 2.04 1.87C8.7 5.68 8.17 6.27 7.67 6.75z"/>\
                    </svg>' + $.lang[LANG]['site.clone.check.info.2'] + '</span></p>\
                </div>\
                ';
            },
            strProcess: function(step) {
                // console.log('step: ' + step + '');
                // console.log('p_w: '+ p_w + ', p_unit: ' + p_unit);

                var str = '',
                    cnt = '';

                switch(step) {
                    case 'init': // 0%
                        str = $.lang[LANG]['site.clone.process.init'];
                        break;

                    case '1': // 5%
                        if(scIdx == 0) {
                            p_max = 100 / scSid.length;
                            p_unit = p_max / 100;
                        }

                        p_w += p_unit * 5;

                        str = $.lang[LANG]['site.clone.process.step1'];
                        if(!isAddLangSite) {
                            if(!scCheck['popup'] && !scCheck['music']) str = $.lang[LANG]['site.clone.process.step1.1'];
                            else if (scCheck['popup'] && !scCheck['music']) str = $.lang[LANG]['site.clone.process.step1.2'];
                            else if (!scCheck['popup'] && scCheck['music']) str = $.lang[LANG]['site.clone.process.step1.3'];
                        }
                        break;

                    case '2': // 0%
                        str = $.lang[LANG]['site.clone.process.step2'];
                        break;

                    case '2-ok':                        
                        str = $.lang[LANG]['site.clone.process.step2'];
                        cnt = '(0/' + scOrgData[scIdx]['total'] + ')';

                        // step3,4 init
                        p_step_max = p_unit * 60;
                        p_step_unit = p_step_max / scOrgData[scIdx]['total'];
                        break;

                    case '3': // 30%
                        str = $.lang[LANG]['site.clone.process.step3'];
                        cnt = '(' + scDestData[scIdx]['total'] + '/' + scOrgData[scIdx]['total'] + ')';
                        break;

                    case '3-ok':
                        p_w += p_step_unit * p_step_plus;

                        str = $.lang[LANG]['site.clone.process.step3'];
                        cnt = '(' + scDestData[scIdx]['total'] + '/' + scOrgData[scIdx]['total'] + ')';
                        break;

                    case '4': // 5%
                        p_w += p_unit * 5;

                        str = $.lang[LANG]['site.clone.process.step4'];
                        cnt = '(' + scDestData[scIdx]['total'] + '/' + scOrgData[scIdx]['total'] + ')';
                        break;

                    case '5': // 30%
                        p_w += p_step_unit * p_step_plus;

                        str = $.lang[LANG]['site.clone.process.step5'];
                        cnt = '(' + scDestData[scIdx]['total'] + '/' + scOrgData[scIdx]['total'] + ')';
                        break;

                    case '6': // 5%
                        p_w += p_unit * 5;

                        str = $.lang[LANG]['site.clone.process.step6'];
                        cnt = '(' + scDestData[scIdx]['resource']['total'] + '/' + scOrgData[scIdx]['resource']['total'] + ')';

                        // step7 init
                        p_step_max = p_unit * 20;
                        p_step_unit = p_step_max / scOrgData[scIdx]['resource']['total'];
                        break;

                    case '7': // 20%
                        p_w += p_step_unit;

                        str = $.lang[LANG]['site.clone.process.step7'];
                        cnt = '(' + scDestData[scIdx]['resource']['total'] + '/' + scOrgData[scIdx]['resource']['total'] + ')';
                        break;

                    case '8': // 5%
                        p_w = p_max * (scIdx+1);

                        var checkEnd = (scSid.length > 1 && scSid.length > scIdx+1) ? false : true;

                        str = $.lang[LANG]['site.clone.process.step8'];
                        cnt = (checkEnd) ? '' : '<br>' + $.lang[LANG]['site.clone.process.step8.more'];

                        if(checkEnd) {
                            setTimeout(function() {
                                $.progressOFF();
                            }, 500);
                        }
                        break;

                    default:
                        break;
                }


                if(step == 'init' && scIdx == 0) {
                    $.progressON(str,'','',true);
                } else {
                    $('.progressModal .progress-header h1').html(str + cnt);
                    $('.progressModal .progress-bar').css('width',p_w+'%');
                }

                // console.log('p_w: '+ p_w + ', p_unit: ' + p_unit);
            },
            step0: function() {

                var scStep1 = $.sc.step1();
                scStep1.done(function() {
                    var scStep2 = $.sc.step2();
                    scStep2.done(function() {
                        $.sc.step3Call(1);
                    }).fail(function(scStep2_msg) {
                        console.log('scStep2 fail');
                        console.log(scStep2_msg);

                        $.sc.step8();
                        if(scStep2_msg) $(this).showModalFlat('<?=$this->lang->line("lang.delete.modal.title")?>', scStep2_msg, false, false,'', 'ok','','cl-cmmodal cl-s-btn w560 cl-p130 cl-p0');
                    });
                }).fail(function(scStep1_msg){
                    console.log(scStep1_msg);

                    $.sc.step8();
                    if(scStep1_msg) $(this).showModalFlat('<?=$this->lang->line("lang.delete.modal.title")?>', scStep1_msg, false, false,'', 'ok','','cl-cmmodal cl-s-btn w560 cl-p130 cl-p0');
                });
            },
            step1: function() { // [clone] pf_site | [get] org pf_site 
                var step1_deferred = $.Deferred();

                $.post('/template/siteClone', { step:'1', sid:scSid[scIdx], dest_sid:scDest[scIdx], check:scCheck, isAddLangSite:isAddLangSite }, function(r1) {
                    if(typeof r1.error != 'undefiend' && r1.error) {
                        console.log('step1 error: ' + r1.error);

                        var error_msg = (r1.error == 'already_dest') ? '복제가 정상적으로 안되었으니 삭제 후 다시 시도해주세요.' : 'Site Clone Step1 Error';
                        step1_deferred.reject(error_msg);
                    }

                    scOrgData[scIdx]['pfsite'] = r1.org_site;
                    if(scIdx == 0 && r1.site_langs !== null) scSid = r1.site_langs;
                    $.sc.strProcess('1');

                    setTimeout(function() {
                        step1_deferred.resolve();
                    }, 300);
                }, 'json');
                
                return step1_deferred.promise();
            },
            step2: function() { // [get] block total
                var step2_deferred = $.Deferred();
                $.sc.strProcess('2');

                $.post('/template/siteClone', { step:'2', sid:scSid[scIdx], check:scCheck }, function(r2) {
                    if(typeof r2.error != 'undefiend' && r2.error) {
                        console.log('step2 reject');
                        step2_deferred.reject(r2.error);
                    }

                    scOrgData[scIdx]['total'] = r2.data.total;
                    scOrgData[scIdx]['normal_total'] = r2.data.normal_total;
                    $.sc.strProcess('2-ok');

                    setTimeout(function() {
                        step2_deferred.resolve();
                    }, 300);
                }, 'json');
                
                return step2_deferred.promise();
            },
            step3Call: function(page) {

                var view = 100,
                    checkNextStep = (Math.ceil(scOrgData[scIdx]['normal_total']/view) < page) ? true : false;

                if(checkNextStep) {
                    var scStep4 = $.sc.step4();
                    scStep4.done(function(data4) {
                        $('.progress-content').append('\
                            <div class="clone-section" data-sid="' + scSid[scIdx] + '" data-sid="' + scDest[scIdx] + '">\
                                <ul class="clone-block-list"></ul>\
                                <ul class="clone-resource-list"></ul>\
                            </div>\
                        ');
                        $.each(data4, function(key,total) {
                            // if(key == 'gallery_items') return true;
                            if(key == 'total') return true;
                            if(total > 0) {
                                var view = block_view[key],
                                    total_page = (total > view) ? Math.ceil(total/view) : 1,
                                    view_start = 1,
                                    view_end = (total > view) ? view : total;

                                for(var idx=1; idx<=total_page; idx++) {
                                    if(idx > 1) {
                                        view_start = view_end + 1;
                                        view_end = (total > (view*idx)) ? view*idx : total;
                                    }

                                    var btn_target = (view === 1 || view_end == 1) ? '' : '(' + view_start + '~' + view_end + ')',
                                    btn_str = key + ' ' + idx + btn_target,
                                    btn_html = '<button type="button" class="btn btn-primary site-clone-step5" data-start="'+view_start+'" data-end="'+view_end+'">'+btn_str+'</button>';
                                    $('.progress-content .clone-section[data-sid="' + scSid[scIdx] + '"] .clone-block-list').append('<li class="'+ key +'">' + btn_html + '</li>');
                                }
                            }
                        });

                        $.sc.step5Call(0);

                    }).fail(function(scStep4_msg){
                        console.log(scStep4_msg);

                        $.sc.step8();
                        if(scStep4_msg) $(this).showModalFlat('<?=$this->lang->line("lang.delete.modal.title")?>', scStep4_msg, false, false,'', 'ok','','cl-cmmodal cl-s-btn w560 cl-p130 cl-p0');
                    });

                    return false;
                }

                var scStep3 = $.sc.step3(page);
                scStep3.done(function() {
                    $.sc.step3Call(page+1);
                }).fail(function(scStep3_msg){
                    console.log(scStep3_msg);

                    $.sc.step8();
                    if(scStep3_msg) $(this).showModalFlat('<?=$this->lang->line("lang.delete.modal.title")?>', scStep3_msg, false, false,'', 'ok','','cl-cmmodal cl-s-btn w560 cl-p130 cl-p0');
                });

            },
            step3: function(page) { // [clone] pf_page > normal block
                var step3_deferred = $.Deferred();

                $.sc.strProcess('3');
                $.post('/template/siteClone', { step:'3', sid:scSid[scIdx], dest_sid:scDest[scIdx], check:scCheck, page:page, isAddLangSite:isAddLangSite }, function(r3) {
                    if(typeof r3.error != 'undefiend' && r3.error) {
                        console.log('step3 reject');
                        step3_deferred.reject(r3.error);
                    }

                    p_step_plus = r3.data.insert_total;
                    scDestData[scIdx]['total'] += r3.data.insert_total;
                    $.sc.strProcess('3-ok');

                    setTimeout(function() {
                        step3_deferred.resolve();
                    }, 200);
                }, 'json');
                
                return step3_deferred.promise();
            },
            step4: function() { // [get] (gallery / form / forum) block total
                var step4_deferred = $.Deferred();

                $.post('/template/siteClone', { step:'4', sid:scSid[scIdx], check:scCheck }, function(r4) {
                    if(typeof r4.error != 'undefiend' && r4.error) {
                        console.log('step4 reject');
                        step4_deferred.reject(r4.error);
                    }

                    scOrgData[scIdx]['gallery']['total'] = r4.data.gallery;
                    scOrgData[scIdx]['forum']['total'] = r4.data.forum;
                    scOrgData[scIdx]['form']['total'] = r4.data.form;
                    $.sc.strProcess('4');

                    setTimeout(function() {
                        step4_deferred.resolve(r4.data);
                    }, 300);
                }, 'json');
                
                return step4_deferred.promise();
            },
            step5Call: function(cnt) {
                var cloneBlock = $('.progress-content .clone-section[data-sid="' + scSid[scIdx] + '"] .clone-block-list li').eq(cnt);
                if(cloneBlock.length == 0) {
                    $.sc.step6();
                    return false;
                }

                var cloneBlockBtn = cloneBlock.find('button'),
                    key = cloneBlock.attr('class'),
                    start = cloneBlockBtn.attr('data-start'),
                    end = cloneBlockBtn.attr('data-end'),
                    more = (typeof cloneBlockBtn.attr('data-more') != 'undefined' && cloneBlockBtn.attr('data-more')) ? cloneBlockBtn.attr('data-more') : '';

                var scStep5 = $.sc.step5(key,cnt,start,end,more);
                scStep5.done(function(checkMore) {
                    if(checkMore) $.sc.step5Call(cnt);
                    else $.sc.step5Call(cnt+1);
                }).fail(function() {
                    console.log('scStep5 fail');
                });
            },
            step5: function(key,cnt,start,end,more) { // [clone] pf_page > (gallery / form / forum) block
                var step5_deferred = $.Deferred();

                var cloneBlock = $('.progress-content .clone-section[data-sid="' + scSid[scIdx] + '"] .clone-block-list li').eq(cnt),
                    cloneBlockBtn = cloneBlock.find('button'),
                    block_insert_data = scTempData[scIdx][key];

                $.post('/template/siteClone', { step:'5', sid:scSid[scIdx], dest_sid:scDest[scIdx], check:scCheck, insert_data:block_insert_data, btype:key, bstart:start, bend:end, more:more }, function(r5) {

                    if(typeof r5.error != 'undefined' && r5.error) {
                        console.log('step5 reject');
                        console.log('Gallery / form / forum Clone error::' + scSid[scIdx] + ', ' + r5.error);
                        $('.progress-content .clone-section[data-sid="' + scSid[scIdx] + '"] .clone-block-list li').eq(cnt).append('<span class="error">'+r5.error+'</span>');
                        step5_deferred.reject();

                    } else $('.progress-content .clone-section[data-sid="' + scSid[scIdx] + '"] .clone-block-list .error').remove();

                    scDestData[scIdx]['total'] = scDestData[scIdx]['total'] + r5.data.total;
                    scTempData[scIdx][key] = Object.assign(block_insert_data, r5.data.insert_data);

                    var check_more = false;
                    if(typeof r5.data.more != 'undefiend' && r5.data.more) {
                        check_more = true;
                        
                        var more_str = r5.data.more,
                            more_arr = more_str.split(','),
                            more_btn_str = more_arr[2]+'/'+more_arr[3];
                        cloneBlockBtn.attr('data-more',r5.data.more);
                        if(cloneBlockBtn.find('.next').length > 0) cloneBlockBtn.find('.next').text(more_btn_str);
                        else cloneBlockBtn.append('<span class="next">('+more_btn_str+')</span>');
                    } else {
                        p_step_plus = r5.data.total;
                        $.sc.strProcess('5');
                        cloneBlockBtn.attr('disabled',true);
                    }

                    setTimeout(function() {
                        step5_deferred.resolve(check_more);
                    }, 200);
                }, 'json');


                return step5_deferred.promise();
            },
            step6: function() { // [get] pf_resource seq & total
                console.log(scSid[scIdx]);

                $.post('/template/siteClone', { step:'6', sid:scSid[scIdx], dest_sid:scDest[scIdx] }, function(r6) {

                    var cloneSection = $('.progress-content .clone-section[data-sid="' + scSid[scIdx] + '"] .clone-resource-list');
                    if(typeof r6.error != 'undefined' && r6.error) {
                        console.log('step6 reject');
                        console.log('Resorce Clone error::' + scSid[scIdx] + ', ' + r6.error);
                        cloneSection.before('<span class="error">'+r6.error+'</span>');
                        return false;
                    } else $('.error').remove();

                    var r_view = 30,
                        r_total = r6.count,
                        r_add = 0;
                    
                    scOrgData[scIdx]['resource'] = {
                        'total' : r_total,
                        'list' : r6.list
                    };
                    scDestData[scIdx]['resource'] = {
                        'total' : 0,
                        'list' : new Array()
                    };
                    $.sc.strProcess('6');

                    if(r_total == 0) {
                        $.sc.step8();
                        return false;
                    }

                    $.each(r6.list, function(rs_i,rs_v) {
                        r_add++;
                        var mod = r_add%r_view;
                        if(mod === 1) cloneSection.append('<li></li>');
                        cloneSection.find('li:last-child').append('<span>' + rs_v.seq + '</span>');

                        if(r_add == r_total) {
                            $.sc.step7Call(0,0);
                        }
                    });
                }, 'json');
            },
            step7Call: function(rs_eq1,rs_eq2) {
                var cloneResource = $('.progress-content .clone-section[data-sid="' + scSid[scIdx] + '"] .clone-resource-list');
                    rs_li_total = cloneResource.find('li').length;
                if(rs_eq1 >= rs_li_total) {
                    $.sc.step8();
                    return false;
                }

                var cloneResourceli = cloneResource.find('li').eq(rs_eq1),
                    rs_span_total = cloneResourceli.find('span').length;
                if(rs_eq2 >= rs_span_total) {
                    $.sc.step7Call(rs_eq1+1,0);
                    return false;
                }

                var cloneResourceSpan = cloneResourceli.find('span').eq(rs_eq2),
                    rs_seq = cloneResourceSpan.text();
                if(rs_seq == '') {
                    $.sc.step8();
                    return false;
                }

                var scStep7 = $.sc.step7(rs_seq);
                scStep7.done(function() {
                    if(rs_eq2+1 < rs_span_total) $.sc.step7Call(rs_eq1,rs_eq2+1);
                    else $.sc.step7Call(rs_eq1+1,0);
                }).fail(function() {
                    console.log('scStep7 fail');
                });
            },
            step7: function(rs_seq) { // [clone] pf_resource
                var step7_deferred = $.Deferred();

                $.post('/template/siteClone', { step:'7', sid:scSid[scIdx], dest_sid:scDest[scIdx], r_seq:rs_seq }, function(r7) {

                    if(typeof r7.error != 'undefined' && r7.error) {
                        console.log('step7 reject');
                        console.log('Resorce Clone error::' + rs_seq + ', ' + r7.error);
                        $('.progress-content .clone-section[data-sid="' + scSid[scIdx] + '"] .clone-resource-list li span[data-seq="' + rs_seq + '"]').addClass('error');
                        step7_deferred.reject();

                    } else $('.progress-content .clone-section[data-sid="' + scSid[scIdx] + '"] .clone-resource-list li .error').remove();

                    scDestData[scIdx]['resource']['total'] = scDestData[scIdx]['resource']['total'] + 1;
                    scDestData[scIdx]['resource']['list'].push(rs_seq);
                    $.sc.strProcess('7');

                    setTimeout(function() {
                        step7_deferred.resolve();
                    }, 100);
                }, 'json');

                return step7_deferred.promise();
            },
            step8: function() { // check other site(language site)
                $.sc.strProcess('8');

                if(isAddLangSite || scIdx+1 == scSid.length) {
                    location.reload();
                } else {
                    $.sc.initVal();
                    setTimeout(function() {
                        $.sc.step0();
                    }, 500);
                }
            }
        }


        $.sc.initVal();
        if(isAddLangSite) {
            $.sc.strProcess('init');
            setTimeout(function() {
                $.sc.step0();
            }, 600);
        } else {
            var scCheckModal = $(this).showModalFlat($.lang[LANG]['site.clone.check.title'], $.sc.strCheck(), true, true, function() {
                $.sc.strProcess('init');

                scCheck.popup = $('.check-popup').prop('checked');
                scCheck.music = $('.check-music').prop('checked');
                scCheck.gallery = $('.check-gallery').prop('checked');
                scCheck.forum = $('.check-forum').prop('checked');
                
                setTimeout(function() {
                    $.sc.step0();
                    scCheckModal.modal('hide');
                }, 600);
            },'cancel','','cl-siteclone cl-cmmodal cl-s-btn w560 cl-p70 cl-p0','','',function() { $('[data-toggle="popover"]').popover(); });
        }
    }

    $.fn.sitePublishVer01 = function(sid,onoff,endCallback) {

        var strTitle = (onoff==1) ? $.lang[LANG]['loading.publishing'] : $.lang[LANG]['loading.publishing.off'];
        $.progressON(strTitle,'',0,true);
        
        var pbSiteCall = function(slist,sidx) {
            if(typeof slist == 'undefined' || typeof slist[sidx] == 'undefined') {
                pbEndCall(false);
                return false;
            }

            var s_obj = slist[sidx],
                s_orgsid = s_obj['sid'],
                s_code = (typeof s_obj['code'] != 'undefined' && s_obj['code']) ? s_obj['code'] : '',
                s_sid = (s_code) ? s_orgsid+'__'+s_code : s_orgsid;

            $.progressON('', s_orgsid + ((s_code) ? $.lang[LANG]['editor.publish.step2.1'] + ' (' + s_code + ')' : '') + $.lang[LANG]['editor.publish.step2.2'],0,true);
            var pbSite_r = pbSite(s_sid,onoff);
            pbSite_r.done(function(r2) {
                $.progressON('', s_orgsid + ((s_code) ? $.lang[LANG]['editor.publish.step3.1'] + ' (' + s_code + ')' : '') + $.lang[LANG]['editor.publish.step3.2'],0,true);
                var w = getProgressWidth() + (20/slist.length) * (sidx+1);
                $('.progress-bar').css('width',w+'%');

                pbGalleryCall(slist,sidx,s_orgsid,s_code,r2.count,0);
            }).fail(function(r2_error) {
                console.log(r2_error);
                pbEndCall(false);
            });
        }

        var pbGalleryCall = function(sitelist,siteidx,sidorg,sidcode,gcount,gpidx) {
            var sitesid = (sidcode) ? sidorg+'__'+sidcode : sidorg;

            var pbGallery_r = pbGallery(sitesid,onoff,gcount,gpidx,sitelist.length,siteidx);
            pbGallery_r.done(function(r3) {
                $.progressON('',sidorg + ((sidcode) ? $.lang[LANG]['editor.publish.step4.1'] + ' (' + sidcode + ')' : '') + $.lang[LANG]['editor.publish.step4.2'],0,true);
                $('.progress-bar').css('width',r3.w+'%');

                if(r3.done == true) pbPagesCall(sitelist,siteidx,sidorg,sidcode,r3.count,0);
                else pbGalleryCall(sitelist,siteidx,sidorg,sidcode,gcount,gpidx+1);

            }).fail(function(r3_error) {
                console.log(r3_error);
                pbEndCall(false);
            });
        }

        var pbPagesCall = function(sitelist,siteidx,sidorg,sidcode,bcount,bpidx) {
            var sitesid = (sidcode) ? sidorg+'__'+sidcode : sidorg;

            var pbPages_r = pbPages(sitesid,onoff,bcount,bpidx,sitelist.length,siteidx);
            pbPages_r.done(function(r4) {
                $('.progress-bar').css('width',r4.w+'%');

                if(r4.done == true) {
                    if(sitelist.length == (siteidx+1)) pbEndCall(true);
                    else pbSiteCall(sitelist,siteidx+1);
                } else {
                    pbPagesCall(sitelist,siteidx,sidorg,sidcode,bcount,bpidx+1);
                }

            }).fail(function(r4_error) {
                console.log(r4_error);
                pbEndCall(false);
            });
        }

        var pbEndCall = function(isCompleted) {
            $('.progress-bar').css('width','100%');
        
            if(!isCompleted) {
                $.progressOFF();
                return false;
            }

            if(typeof endCallback == 'function') {
                endCallback(sid,onoff);
            }
        }

        var sites_r = sites(sid);
        sites_r.done(function(r1) {
            $.progressON('',$.lang[LANG]['editor.publish.step1'],0,true);
            pbSiteCall(r1.lists,0);
        }).fail(function(r1_error) {
            console.log(r1_error);
            pbEndCall(false);
        });
    }

    $.fn.sitePublishVer02 = function(sid) {

        $.progressON($.lang[LANG]['editor.publish.step.start'],'',0,true);

        $.sp = {
            step: 0,

            site_list: {},
            site_total: 0,
            site_idx: 0,
            site_per: 100,

            sid: sid,
            sid_code: '',
            org_sid: sid,

            step_k: {'d':3, 'i':2, 'u':1},
            step_total: [0,0,0,0],
            step_success: [0,0,0,0],

            change_total: 0,
            change_success: 0,
            change_list: {},

            per: 0,
            error_msg: $.lang[LANG]['editor.publish.step.error'],
            end: function(isError) {
                if(typeof isError == 'undefined') isError = false;

                if(isError) {
                    $.progressOFF();
                    $(this).showModalFlat('ERROR',$.sp.error_msg, true, false, '', 'ok', '', 'cl-p130 cl-cmmodal cl-s-btn w560 cl-p0 cl-okbtn-pbt70');
                } else {

                    var isNext = (typeof $.sp.site_list[$.sp.site_idx+1] != 'undefined' && $.sp.site_idx+1 <= $.sp.site_total) ? true : false;
                    if(isNext) {
                        setTimeout(function() {
                            $.progressON('',$.lang[LANG]['editor.publish.step.restart']);
                            $('.progress-bar').css('width','0%');
                            $.sp.site_idx++;
                            setTimeout(function() {
                                $.sp.step1();
                            },1500);
                        },1500);
                    } else {

                        $('.progress-bar').css('width','70%');
                        setTimeout(function() {
                            $('.progress-bar').css('width','100%');

                            if(typeof SLANG != 'undefined' && typeof SLANG.select_code != 'undefined' && SLANG.select_code) {
                                changeLanguage(SLANG.select_code,'sync_publish');
                            }

                            $.progressOFF();
                            $.processON();

                            var time = $.now();
                            $('.processModal p').text('');
                            $('.processModal p').css({
                                'width' : '385px',
                                'height' : '215px',
                                'top' : '0',
                                'margin' : 'auto',
                                'background' : 'none',
                            });

                            if($('.processModal').length ==1) {
                                $.processOFF();
                                var modal = $(this).showModalFlat($.lang[LANG]['editor.publish.priview.title'],$.lang[LANG]['editor.publish.priview'],  true, false ,function(){
                                        window.open(DOMAIN, '_blank');
                                        modal.modal('hide');
                                    },'ok', '', 'cl-p130 cl-cmmodal cl-s-btn w560 cl-p0 cl-okbtn-pbt70 cl-publish-complete','','',function(){
                                        $('.cl-publish-complete .ok-button-dialog, .cl-publish-complete .close').on('click',function(){
                                        $.processOFF();
                                    });
                                }); 
                            }
                        }, 500);

                    }

                }

            },
            step0: function(sid) {
                $.sp.step = 0;

                var sp0_deferred = $.Deferred();
                if(typeof sid == 'undefined') sp0_deferred.reject('sid Undefined :(');
                else {
                    $.ajax({
                        url : '/template/publishSites',
                        data : { sid : sid },
                        type : 'POST',
                        dataType : 'json',
                        async : true,
                        cashe : false,
                        success : function(data) {
                            if(typeof data.error != 'undefined' && data.error) {
                                sp0_deferred.reject(data.error);
                                return false;
                            }

                            $.sp.site_list = data.lists;
                            $.sp.site_total = data.lists.length;
                            $.sp.site_idx = 0;
                            $.sp.site_per = Math.ceil(100 / $.sp.site_total);

                            $.progressON('',$.lang[LANG]['editor.publish.step.0'],0,true);
                            $('.progress-bar').css('width','5%');

                            sp0_deferred.resolve();
                        }
                    });
                }
                return sp0_deferred.promise();
            },
            step1: function() {
                $.sp.step = 1;

                $.sp.org_sid = $.sp.site_list[$.sp.site_idx]['sid'];
                $.sp.sid_code = $.sp.site_list[$.sp.site_idx]['code'];
                $.sp.sid = ($.sp.sid_code) ? $.sp.org_sid+'__'+$.sp.sid_code : $.sp.org_sid;

                if($.sp.site_idx > 0) {
                    $.progressON('', $.sp.org_sid + (($.sp.site_code) ? $.lang[LANG]['editor.publish.step.0.p'] + ' (' + $.sp.site_code + ')' : '') + $.lang[LANG]['editor.publish.step.0.n'],0,true);
                    $('.progress-bar').css('width','5%');
                }
                var sp1_1 = $.sp.step1_1();
                sp1_1.done(function(r1_1) {
                    if(r1_1 > 0) $.sp.step2('d',0);
                    else $.sp.end();
                }).fail(function(r1_1_error) {
                    console.log('r1_1_error: '+r1_1_error);
                    $.sp.end(true);
                });
            },
            step1_1: function() {
                // sites[idx] - pf_site → pb_site (UPDATE or INSERT)
                // sites[idx] - pf_site.activate, pb_site.activate = 1 or 9 (UPDATE)
                // return pf_publish total list
                var sp1_1_deferred = $.Deferred();
                $.progressON('', $.sp.org_sid + (($.sp.site_code) ? $.lang[LANG]['editor.publish.step.1.p'] + ' (' + $.sp.site_code + ')' : '') + $.lang[LANG]['editor.publish.step.1.n'],0,true);

                $.ajax({
                    url : '/template/sitepublish1',
                    data : { sid : $.sp.sid, onoff : 1 },
                    type : 'POST',
                    dataType : 'json',
                    async : true,
                    cashe : false,
                    success : function(data1) {
                        $('.progress-bar').css('width','20%');

                        $.sp.step_total = [0,0,0,0];
                        $.sp.step_success = [0,0,0,0];

                        $.sp.change_total = data1.total;
                        $.sp.change_success = 0;
                        $.sp.change_list = {};
                        $.sp.per = Math.ceil(70 / data1.total);

                        sp1_1_deferred.resolve(data1.total);
                    }
                });

                return sp1_1_deferred.promise();
            },
            step2: function(step,start) {
                // d->i->u

                var sp2_1 = $.sp.step2_1(step,start);
                sp2_1.done(function(r2_1) {
                    if(r2_1 > 0) $.sp.step2(step,r2_1);
                    else {
                        if(step == 'd') $.sp.step2('i',0);
                        else if(step == 'i') $.sp.step2('u',0);
                        else if(step == 'u') $.sp.step3();
                        else $.sp.end();
                    }
                }).fail(function(r2_1_error) {
                    console.log('r2_1_error: '+r2_1_error);
                    $.sp.end(true);
                });
            },
            step2_1: function(this_step,this_start) {
                // sites[idx] - pf_publish.pbs_val == pb_page.seq (DELETE | INSERT | UPDATE)
                // sites[idx] - pf_publish.pbs_val == pb_gallery.seq (DELETE | INSERT | UPDATE)
                // return pb_page.seq, pb_gallery.seq list + (200개씩 처리) more?
                        // $list = array('b'=>array(), 'g'=>array(), 'next_start'=>$start+$limit);
                        // json_result(array('result' => 'done pf_publish delete', 'list' => $list, 'total' => $total));
                var sp2_1_deferred = $.Deferred();
                $.progressON('', $.sp.org_sid + (($.sp.site_code) ? $.lang[LANG]['editor.publish.step.2.p'] + ' (' + $.sp.site_code + ')' : '') + $.lang[LANG]['editor.publish.step.2.n'],0,true);

                $.ajax({
                    url : '/template/sitepublish2/'+this_step,
                    data : { sid : $.sp.sid, start: this_start },
                    type : 'POST',
                    dataType : 'json',
                    async : true,
                    cashe : false,
                    success : function(data2) {
                        var this_step_k = $.sp.step_k[this_step];
                        if(this_start > 0) {
                            $.sp.change_list[this_step].b = $.sp.change_list[this_step].b.concat(data2.list.b);
                            $.sp.change_list[this_step].g = $.sp.change_list[this_step].g.concat(data2.list.g);
                        } else {
                            $.sp.step_total[this_step_k] = data2.total;
                            $.sp.change_list[this_step] = data2.list;
                        }

                        var this_success = data2.list.b.length + data2.list.g.length;
                        $.sp.step_success[this_step_k] = $.sp.step_success[this_step_k] + this_success;
                        $.sp.change_success = $.sp.change_success + this_success;

                        var next_start = ($.sp.step_success[this_step_k] < data2.total) ? data2.list.next_start : 0,
                            bar_w = 20 + ($.sp.per * $.sp.change_success);
                        $('.progress-bar').css('width',bar_w+'%');

                        sp2_1_deferred.resolve(next_start);
                    }
                });
                return sp2_1_deferred.promise();
            },
            step3: function() {
                $('.progress-bar').css('width','95%');

                var sp3_1 = $.sp.step3_1();
                sp3_1.done(function() {
                    $.sp.end();
                }).fail(function(r3_1_error) {
                    console.log('r3_1_error: '+r3_1_error);
                    $.sp.end(true);
                });
            },
            step3_1: function() {
                // sites[idx] - pf_publish.sid == SID (DELETE)
                var sp3_1_deferred = $.Deferred();
                $.progressON('', $.sp.org_sid + (($.sp.site_code) ? $.lang[LANG]['editor.publish.step.3.p'] + ' (' + $.sp.site_code + ')' : '') + $.lang[LANG]['editor.publish.step.3.n'],0,true);

                $.ajax({
                    url : '/template/sitepublish3/',
                    data : { sid : $.sp.sid },
                    type : 'POST',
                    dataType : 'json',
                    async : true,
                    cashe : false,
                    success : function(data3) {
                        $('.progress-bar').css('width','100%');
                        sp3_1_deferred.resolve();
                    }
                });
                return sp3_1_deferred.promise();

            }
        }

        var sp0 = $.sp.step0(sid);
        sp0.done(function() {
            $.sp.step1();
        }).fail(function(r0_error) {
            console.log('r0_error: '+r0_error);
            $.sp.end();
        });
    }


    $.musicON = function(play) {
        play = (typeof play == 'undefined') ? true : play;
        var tpl = '\
            <div id="cl-music-player" class="cl-mplayer"></div>\
            <div id="cl-music-container" class="jp-audio" role="application" aria-label="media player">\
                <div class="jp-type-playlist">\
                    <div class="jp-gui jp-interface">\
                        <div class="jp-controls-holder">\
                            <div class="jp-controls">\
                                <div class="music-player-controls">\
                                    <span class="jp-backward" role="button" tabindex="0"><i class="fa fa-backward" aria-hidden="true"></i></span>\
                                    <span class="jp-play" role="button" tabindex="0"><i class="fa fa-pause" aria-hidden="true"></i></span>\
                                    <span class="jp-forward" role="button" tabindex="0"><i class="fa fa-forward" aria-hidden="true"></i></span>\
                                </div>\
                                <div class="music-player-progress">\
                                    <div class="jp-progress">\
                                        <div class="jp-seek-bar">\
                                            <div class="jp-play-bar"></div>\
                                        </div>\
                                    </div>\
                                </div>\
                                <div class="jp-lists">\
                                    <span class="music-lists" role="button" tabindex="0">LIST</span>\
                                </div>\
                                <div class="music-playlist-wrap">\
                                    <div class="jp-playlist"><ul class="music-playlist"><li></li></li></div>\
                                </div>\
                            </div>\
                        </div>\
                    </div>\
                    <div class="jp-no-solution">\
                        <span>Update Required</span>\
                        To play the media you will need to either update your browser to a recent version or update your <a href="http://get.adobe.com/flashplayer/" target="_blank">Flash plugin</a>.\
                    </div>\
                </div>\
            </div>\
            ',
            equalizer_img = ($('body').width() < 769) ? 'https://storage.googleapis.com/i.addblock.net/equal_stop.gif' : 'https://storage.googleapis.com/i.addblock.net/equal.gif',
            checkFree = (!property.VALIDPLAN || property.VALIDTYPE == 'PK') ? true : false,
            move_position = (checkFree) ? 'class="moved"' : '',
            vpModeOnoff = (property.SETTINGS.vpMode_onoff === true) ? true : false,
            vpOption = (property.SETTINGS.viewportMode) ? property.SETTINGS.viewportMode : '',
            WebType = $.mpcWeb.mpcCheckWebType(),
            checkFnav = ($('.fnav').length > 0 && vpOption=='mobile_web') ? true : false,
            $music_icon = $('<div id="cl-music-player-icon" '+move_position+'><img src="' + equalizer_img + '" class="hand"></div>');

        $('#goto-top').after($music_icon);
        $('#cl-music-player-icon').after(tpl);

        if($('.fnav').length > 0) {
            if(window.innerWidth <= 480) {
                $('#goto-top').addClass('movedOne');
                $music_icon.addClass('movedOne');
            }
        }

        if(vpModeOnoff && WebType == 'MOBILE') $.mpcWeb.mpcMusicandGoTop(checkFnav,vpOption);

        ($('body').width() < 769) ? $('.jp-play i').removeClass('fa-pause').addClass('fa-play').parent().addClass('pause') : '';
        var music = (typeof property == 'undefined') ? [] : property.MUSIC;

        if(music.length==0) {
            $music_icon.addClass('hide');
            $music_icon.removeClass('movedOne');
            $('#goto-top').removeClass('movedOne');
        }
        var myPlaylist = new jPlayerPlaylist({
            jPlayer: '#cl-music-player',
                cssSelectorAncestor: '#cl-music-container'
            }, music, {
            playlistOptions: {
                loop: true,
                autoPlay: play,
                loopOnPrevious: true,
                enableRemoveControls: false
            },
            ended: function() { 
                // var $item = $('.music-playlist li'),
                //     idx = $item.parent().find('.active').index(),
                //     active = (idx+1 > $item.length) ? 0 : idx+1;

                // $item.removeClass('active');
                // $item.eq(active).addClass('active');
            },            
            swfPath: '/js',
            solution: 'html, flash',
            supplied: 'mp3',
            preload: 'metadata',
            volume: 1,
            loop: true,
            muted: false,
            backgroundColor: '#000000',

            smoothPlayBar: true,
            keyEnabled: false,
            audioFullScreen: false // Allows the audio poster to go full screen via keyboard
        });

        $music_icon.click(function() {
            $(this).toggleClass('show');
            if($(this).hasClass('show')) {
                $('#cl-music-container').css('display','block');
            } else {
                $('#cl-music-container').css('display','none');
            }
        });

        var $play = $('.jp-play'),
            $next = $('.jp-forward'),
            $prev = $('.jp-backward'),
            $list = $('.music-lists'),
            $playlist_wrap = $('.music-playlist-wrap'),
            $playlist = $('.music-playlist'),
            $item = $('.music-playlist li');

        $playlist.empty();
        if(myPlaylist.playlist.length) {
            var index = myPlaylist.current;
            $.each(myPlaylist.playlist, function(i,v) {
                var active = (i == index) ? 'jp-playlist-current' : '',
                    item = '<li class="' + active + '" data-music-index="' + i + '"><span class="hand">' + v.title + '</span></li>';
                $playlist.append(item);
            });
        }

        $list.click(function() {
            $playlist_wrap.toggle();
            if($playlist_wrap.css('display') == 'block') {
                $list.text('CLOSE');
            } else {
                $list.text('LIST');
            }
        });

        $('body').on( 'click', '.music-playlist li a', function(e) {
            var $pause_icon = '<i class="fa fa-pause"></i>';
                $equalizer = $("#cl-music-player-icon"),
                src = 'https://storage.googleapis.com/i.addblock.net/equalizer.gif',
            $equalizer.find('img').attr('src',src);
            $('.jp-play').removeClass('pause');
            $('.jp-play').html($pause_icon);
        });

        $('.music-playlist li span').click(function() {
            var idx = $(this).parent().attr('data-music-index');
            if(typeof idx == 'undefined') return;
            myPlaylist.play(idx);
            myPlaylist.current = idx;
            $('.music-playlist li').removeClass('jp-playlist-current');
            $('.music-playlist li').eq(idx).addClass('jp-playlist-current');
            // $.musicPlay();
        });

        $play.click(function() {
            if($(this).hasClass('pause')) {
                $.musicPlay();
            } else {
                $.musicPause();
            }
        });
        $next.click(function() {
            $.musicNext(myPlaylist);

        });
        $prev.click(function() {
            $.musicPrev(myPlaylist);
        })

        document.onkeydown = function(evt) {
            evt = evt || window.event;
            if (evt.keyCode == 27) {
                $.musicPause();
            }
        };
        // myPlaylist.play();
        // $('#cl-music-player').jPlayer('play');
    }
    $.musicPause = function() {
        var $play_icon = '<i class="fa fa-play"></i>',
            $equalizer = $('#cl-music-player-icon'),
            src = 'https://storage.googleapis.com/i.addblock.net/equal_stop.gif';
        $equalizer.find('img').attr('src',src);
        $('.jp-play').addClass('pause');
        $('.jp-play').html($play_icon);
        $('#cl-music-player').jPlayer('pause');
    }
    $.musicPlay = function() {
        var $pause_icon = "<i class='fa fa-pause'></i>";
            $equalizer = $('#cl-music-player-icon'),
            src = 'https://storage.googleapis.com/i.addblock.net/equalizer.gif',
        $equalizer.find('img').attr('src',src);
        $('.jp-play').removeClass('pause');
        $('.jp-play').html($pause_icon);
        $('#cl-music-player').jPlayer('play');
    }
    $.musicStop = function() {
        $('#cl-music-player').jPlayer('stop');
    }
    $.musicRepeat = function() {
    }
    $.musicOFF = function() {
    }
    $.musicNext = function(player) {
        player.next();
        var index = player.current;
        $.musicPlay();
    }
    $.musicPrev = function(player) {
        player.previous();
        var index = player.current;
        $.musicPlay();
    }


    $.slang = {
        init: function(data) {
            console.log('modal plugin slang init');
            if(typeof data != 'undefined' && data) {
                if(PAGE_MODE == 'c') SLANG = data;
                else property.SLANG = data;
            }

            var slang = (PAGE_MODE == 'c') ? SLANG : property.SLANG;
            if(!$.isEmptyObject(slang) && slang.use_language=='on') $.slang.set('on');
            else $.slang.set('off');
        },
        set: function(onoff) {
            if(onoff.match(/on/gi)) $.slang.make();
            else $('#tpl-menu').find('.siteLANG').remove();
        },
        make: function() {
            var slang_data = (PAGE_MODE == 'c') ? SLANG['lists'] : property.SLANG['lists'],
                slang_str = (PAGE_MODE == 'c') ? SLANG['select'] : property.SLANG['select'],
                slang_list = '';

            $.each(slang_data, function(i,o) {
                var active = (o['name'] == slang_str) ? 'active' : '';
                slang_list += '\
                        <li><a href="javascript:;" data-code="' + o['code'] + '">' + o['name'] + '</a></li>\
                ';
            });

            var content = '\
                <li class="siteLANG dropdown">\
                    <a href="javascript:;" class="dropdown-toggle"><span class="slang-active">' + slang_str + '</span> <i class="fa fa-caret-down fa-1" aria-hidden="true"></i></a>\
                    <ul class="dropdown-menu">\
                        ' + slang_list + '\
                    </ul>\
                </li>\
            ';

            if($('#tpl-menu').find('.siteLANG').length > 0) $('#tpl-menu').find('.siteLANG').replaceWith(content);
            else $('#tpl-menu').append(content);
        }
    }


    $.fnav = {
        getFnav: function() {
            var data = (PAGE_MODE == 'c') ? SETTINGS.fnav : property.SETTINGS.fnav;
            if(typeof data == 'undefined' || $.isEmptyObject(data)) data = new Array();
            
            return data;
        },
        getFnavColor: function(target) {
            var color = '';
            if(target == 'font') {
                color = (PAGE_MODE == 'c') ? SETTINGS.fnavFcolor : property.SETTINGS.fnavFcolor;
            } else if(target == 'bg') {
                color = (PAGE_MODE == 'c') ? SETTINGS.fnavBg : property.SETTINGS.fnavBg;
                var hexRegex = /^([0-9a-fA-F]{3}|[0-9a-fA-F]{4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/;
                if(hexRegex.test(color)) color = '#'+color;
            }

            if(typeof color == 'undefined' || !color) return (target == 'font') ? '#ffffff' : '#000000';
            else return color;
        },
        checkFnavON: function(data) {
            var result = false,
                fnav_data = (typeof data != 'undefined') ? data : $.fnav.getFnav();

            $.each(fnav_data, function(i,obj) {
                if(obj['display'] == 'on') result = true;
            });

            return result;
        },
        draw: function(data) {
            var fnav_data = (typeof data != 'undefined') ? data : $.fnav.getFnav(),
                hasON = $.fnav.checkFnavON(fnav_data);

            if (window.location.href.indexOf('_checkout') != -1) hasON = false;

            if(!hasON) {
                $('.fnav.fnav-mobile-fnav').remove();
            } else {
                var fnav_html = $.fnav.listHTML(fnav_data,hasON);
                if(fnav_html.length > 0) {
                    if($('.dsgn-body').find('.fnav.fnav-mobile-fnav').length > 0) $('.dsgn-body .fnav.fnav-mobile-fnav').replaceWith(fnav_html);
                    else $('.dsgn-body').find('.el-footer').before(fnav_html);
                } else {
                    $('.dsgn-body').find('.fnav.fnav-mobile-fnav').remove();
                }
            }
        },
        listHTML: function(fnav_data,hasON) {
            if(typeof fnav_data == 'undefined') fnav_data = $.fnav.getFnav();
            if(typeof hasON == 'undefined') hasON = $.fnav.checkFnavON(fnav_data);

            var fnav_fcolor = $.fnav.getFnavColor('font'),
                fnav_bg = $.fnav.getFnavColor('bg'),
                str = '';
                
            if(hasON) {
                $.each(fnav_data, function(i,v) {
                    str += $.fnav.itemHTML(v.idx, v.name, v.type, v.value, v.target, v.icon, v.display); 
                });
            }

            return '\
                            <div class="fnav fnav-mobile-fnav" style="--fnav-bgcolor: '+fnav_bg+'; --fnav-color: '+fnav_fcolor+'; ">\
                            ' + str + '\
                            </div>\
            ';
        },
        itemHTML: function(idx,name,type,value,target,icon,display) {
            var href = '#', 
                attr_target = (type == "tel") ? ' target=""' : ' target="' + target + '"',
                attr_link = '';

            if(icon == 'empty') icon = '';

            if(value) {
                if(type == "tel") {
                    href = (value.match(/^tel:/)) ? value : 'tel:' + value;
                } else { //link
                    if(checkBase64Encode(decodeURIComponent(value))) value = Base64.decode(decodeURIComponent(value));
                    else value = (checkBase64Encode(value)) ? Base64.decode(value) : value;
                    
                    var menulist = (PAGE_MODE == 'c') ? MENULIST : property.MENULIST,
                        one = (PAGE_MODE == 'c') ? ONE : property.ONE,
                        view = (PAGE_MODE == 'c') ? VIEW : property.VIEW;

                    href = makeLinkUrl(value,one,view);
                    if(menulist.indexOf(value.replace(/ /g,'-'))>-1) {
                        attr_link = 'data-user-link="' + href + '"';
                    } else if(value.match(/^\@/g)) {
                        attr_link = 'attr-bookmark="' + value.replace(/^\@/g,'') + '"';
                    } else {
                        var link = encodeURIComponent(Base64.encode(value));
                        attr_link = 'attr-link="' + link + '"';
                    }
                }

            }

            if(display != 'on') return '';
            else return '\
                                <div class="fnav-item" data-idx="' + idx + '" data-type="' + type + '">\
                                    <a href="' + href + '" ' + attr_target + ' ' + attr_link + '>\
                                        <i class="' + icon + '" aria-hidden="true"></i>\
                                        <span class="fnav-name">' + name + '</span>\
                                    </a>\
                                </div>\
            ';
        },

    }

    $.mpcWeb = {
        init: function(vpOption,contents,WebType,zoom,pagemove) {   
            var device_w = (vpOption=='mobile_pc') ? 1440 : 'device-width',
                scale = (vpOption=='mobile_pc') ? (window.screen.width / 1440) : 1.0,
                zoom = (zoom) ? '' : ', maximum-scale=1, user-scalable=no',
                mpc_icon = (vpOption == 'mobile_pc') ? '<i class="fa fa-mobile mpc_icon" aria-hidden="true"></i>' : '<i class="fa fa-desktop mpc_icon" aria-hidden="true"></i>',
                checkFnav = ($('.fnav').length > 0 && vpOption=="mobile_web") ? true : false;

            //$.mpcWeb.mpcWebShowcase(vpOption,contents,pagemove);

            $('.dsgn-body .mobilepc_ch .mpc_icon').remove();
            $('.dsgn-body .mobilepc_ch').prepend(mpc_icon);
            
            var viewport = document.querySelector('meta[name="viewport"]');
            if(viewport) viewport.setAttribute('content','width='+device_w+', initial-scale='+scale+''+zoom+'');

            /*if($('.dsgn-body').hasClass('sidebar')) {
                $('.dsgn-body').removeClass('sidebar').addClass('removed-sidebar');
            } else if ($('.dsgn-body').hasClass('removed-sidebar')) {
                $('.dsgn-body').removeClass('removed-sidebar').addClass('sidebar');                
            }*/

            $.mpcWeb.mpcMusicandGoTop(checkFnav,vpOption);     

            if(checkFnav && WebType == 'MOBILE') {
                $('.fnav.fnav-mobile-fnav').css('margin-bottom','53px');
                $('.element.el-footer').css('margin-bottom','100px');
            } else {
                $('.mobilepc_ch').css('margin-bottom','0px');
                $('.element.el-footer').css('margin-bottom','0px');
            }
        },


        mpcWebhtml: function(vpOption,contents,zoom,pagemove,sid) {
            //if (window.location.href.indexOf('_checkout') != -1) return false;
            sid = (sid) ? sid : (typeof property != 'undefined' ? property.SID : SID);
            pagemove = ((typeof pagemove == 'undefined') || !pagemove) ? '' : pagemove;
            
            $.mpcWeb.mpcCookie(vpOption,sid);

            if($.cookie('vpmode')) {
                vpOption = $.cookie('vpmode');
            }
            
            var vpChangeText = (vpOption=="mobile_pc") ? $.lang[LANG]['editor.mobile.changePc.mobileWeb'] : $.lang[LANG]['editor.mobile.changePc.mobilePc'],    
                mpc_html = "\
                <div class='mobilepc_ch' data-desktop-option='"+vpOption+"'>\
                    <p class='hand'>\
                        <span class='mpc-name'>" + vpChangeText + "</span>\
                    </p>\
                </div>\
            ",
                WebType = $.mpcWeb.mpcCheckWebType();

            if(WebType == 'MOBILE') {
                if(window.location.href.indexOf('_checkout') == -1) {
                    $('.dsgn-body').find('.mobilepc_ch').remove();
                    $('.dsgn-body').append(mpc_html);
                }                
                $.mpcWeb.init(vpOption,contents,WebType,zoom,pagemove);
                $.mpcWeb.mpcChangeVal(vpOption,contents,WebType,zoom,pagemove,sid);
            }
        },   

        mpcWebShowcase : function(vpOption,contents,pagemove) {
            $.each(contents,function(i,v) {
                var v_el = (pagemove=='pagemove') ? v : v.element;
                if((vpOption == "mobile_pc") && (v_el.type == 'showcase')) $("."+v_el.elname).addClass('mobilePc_height');
                else $("."+v_el.elname).removeClass('mobilePc_height');
            });
            
        },

        mpcChangeVal : function(vpOption,contents,WebType,zoom,pagemove,sid) {
            //if (window.location.href.indexOf('_checkout') != -1) return false;
            sid = (sid) ? sid : (typeof property != 'undefined' ? property.SID : SID);
            $('.mobilepc_ch').on('click', function() {
                vpOption = (vpOption=="mobile_pc") ? 'mobile_web' : 'mobile_pc';
                var vpChangeText = (vpOption=="mobile_pc") ? $.lang[LANG]['editor.mobile.changePc.mobileWeb'] : $.lang[LANG]['editor.mobile.changePc.mobilePc'];
                 
                $.mpcWeb.init(vpOption,contents,WebType,zoom,pagemove);
                
                $(this).find('.mpc-name').text(vpChangeText);
                $(this).attr('data-desktop-option',vpOption);

                if(typeof property != 'undefined') {
                    if(property.ONE && !property.VIEW || property.PAGE == property.MENULINK[0] && !property.VIEW) setSitePopup();
                }
                if($('.element[data-type="gallery"][data-msny="true"]').length > 0) {
                    $('.element[data-type="gallery"][data-msny="true"]').each(function() {
                        RENDER.refreshMasonry($(this).attr('data-name'));
                    });
                }
                $('.element[data-type="gallery"]').each(function() {
                    var elname = 'userEL'+$(this).attr('data-id');
                    if($(this).find('.goption[data-gh]').length>0) {
                        refreshGalleryHeight(elname);  
                    }
                });
                if($('.element[data-type="forum"]').length > 0) {
                    var icon_notice = '<i class="tpl-forum-list-notice-icon cl-icon notice01" aria-hidden="true"></i>';
                    
                    $('.element[data-type="forum"] .tpl-forum-list-title .tpl-forum-list-notice-icon').remove();

                    $('.element[data-type="forum"]').each(function(idx, v) {
                        var $forum = $(v);
                        var type = $(v).attr('data-type2');

                        if($forum.find('.tpl-forum-list-title[data-option="N"]').length > 0) { //forum notice
                            if(vpOption == 'mobile_web' && type == 'thumb') {
                                $forum.find('.tpl-forum-list-num.n').each(function(idx, n){
                                    var num = $(n).attr('data-fm-num');
                                    $(n).html(num);
                                });
                            } else {
                                $forum.find('.tpl-forum-list-num.n').html(icon_notice);
                            }

                            if($forum.find('.tpl-forum-list-num').hasClass('hidden')) { // field_disabled = num
                                 $forum.find('.tpl-forum-list-title[data-option="N"]').prepend(icon_notice);
                            } else {
                                if(vpOption == 'mobile_web') {
                                    $forum.find('.tpl-forum-list-title[data-option="N"]').prepend(icon_notice);
                                    if(type == 'normal' && $forum.find('.tpl-forum-list-num').css('display') != 'none') {
                                        $forum.find('.tpl-forum-list-title .tpl-forum-list-notice-icon').addClass('hide');
                                    }
                                } else {
                                    $forum.find('.tpl-forum-list-num.n').html(icon_notice);
                                }
                            }
                        }
                    });
                }
                
                $.mpcWeb.mpcCookie(vpOption,sid);

                if (window.location.href.indexOf('_checkout') != -1) {
                    $('.dsgn-body').find('.mobilepc_ch').remove();
                }

                if($('body').hasClass('openBandBanner')) $.siteBanner.call('band',false,false,true,true)
                if($('body').hasClass('openPopupBanner')) $.siteBanner.call('popup',false,false,true,true)

                setTimeout(function(){
                    $.fheader.position();
					setFixedMenuCss(false);
				},50);

            });
        },

        mpcCheckWebType : function(){
            var filter = "win16|win32|win64|mac|macintel",
                WebType = "";

            if (navigator.platform) {
                if (filter.indexOf(navigator.platform.toLowerCase()) < 0) WebType = "MOBILE";
                else WebType = "PC";
            }

            return WebType;
        },

        mpcMusicandGoTop : function(checkFnav,vpOption) {
            var checkmpc = ($('.mobilepc_ch').length > 0) ? true : false;

            if(checkmpc && vpOption == 'mobile_pc') {
                if($('#cl-music-player-icon').length > 0) $('#goto-top,#cl-music-player-icon').removeClass('moveMpc movepc movedOne').addClass('moved');
                else $('#goto-top,#cl-music-player-icon').removeClass('movedOne moveMpc movepc').addClass('moved');
            } else {
                if(checkFnav) {
                    if($('#cl-music-player-icon').length > 0) {
                        $('#goto-top').css('bottom','');  
                        $('#goto-top,#cl-music-player-icon').removeClass('movedOne movepc moved').addClass('moveMpc');
                    } else $('#goto-top').removeClass('movedOne movepc moved moveMpc').css('bottom','120px');  
                } else {
                    if($('#cl-music-player-icon').length > 0) $('#goto-top,#cl-music-player-icon').removeClass('moveMpc movepc moved').addClass('movedOne');
                    else $('#goto-top,#cl-music-player-icon').removeClass('movedOne movepc moveMpc moved');
                }          
            }
        },
        mpcCookie : function(vpOption,sid) {
            sid = (sid) ? sid : (typeof property != 'undefined' ? property.SID : SID);
            var date = new Date();
            date.setTime(date.getTime() + 6*60*60*1000); // 6h

            $.cookie('vpmode-'+sid, vpOption, { expires: date, path : '/' });
        },
        mpcGetVpmode : function(vpmode,settings,sid) {
            sid = (sid) ? sid : (typeof property != 'undefined' ? property.SID : SID);
            if($.cookie('vpmode-'+sid)) vpmode = $.cookie('vpmode-'+sid);
            else vpmode = (typeof $('.mobilepc_ch').attr('data-desktop-option') != 'undefined') ? $('.mobilepc_ch').attr('data-desktop-option') : settings.viewportMode;
            
            return vpmode;
        }
    }

    /* menu 추가 버튼 설정 **************************************************************/
    $.menuFixBtn = {
        topSet : function(num,checkmodal,validArray,slang){
            var str = '',
                searchOn = '',
                cartOn = '',
                umOn = '',
                ssid = (PAGE_MODE == 'c') ? SID : property.SID,
                is_templates = checkTemplateSite(ssid),
                s_service = (PAGE_MODE == 'c') ? SERVICE : property.SERVICE,
                checkGabia = (s_service.indexOf('gabia') > -1) ? true : false,
                checkBS = (validArray['validplan'] && (validArray['validtype'] == 'BS' || (checkGabia && (validArray['validtype'] == 'FR')))) ? true : false,
                checkBN = (validArray['validplan'] && validArray['validtype'] == 'BN') ? true : false,
                checkSM = (validArray['validplan'] && validArray['validtype'] == 'SM') ? true : false,
                checkFREE = (!validArray['validplan'] || validArray['validplan'] == 'FR' || validArray['validplan'] == 'PK') ? true : false,
                checkElView = ($('.elviewhtml').length>0) ? true : false,
                fixBtnSITEUM = (checkElView) ? '' : ((PAGE_MODE=='c') ? SITEUM : property.SITEUM),
                checkSITEUM = (!checkElView && ((checkBN && typeof fixBtnSITEUM!='undefined' && Number(fixBtnSITEUM) > 0) || checkSM)) ? true : (checkElView ? true : false),
                checkmodal = (typeof checkmodal != 'undefined' && checkmodal) ? true : false,
                fixon = (typeof $('.el-menu header.navbar').attr('data-fixon') != 'undefined' && $('.el-menu header.navbar').attr('data-fixon')) ? $('.el-menu header.navbar').attr('data-fixon') : '',
                dropdownClass = (PAGE_MODE=='c') ? '' : 'dropdown ',
                slang = (typeof langObj != 'undefined' && langObj) ? langObj : ((PAGE_MODE == 'c') ? SLANG : property.SLANG);
                // lang_str = LANG;
                
                if(!checkElView) {
                    if(checkBN && !checkSITEUM) return '';
                    searchOn = (!checkSM) ? 'style="display:none;"' : '';                    
                    umOn = (checkBS || checkFREE || (checkBN && !checkSITEUM)) ? 'style="display:none;"' : '';   
                    cartOn = (checkFREE) ? 'style="display:none;"' : ((checkSM) ? '' : 'style="display:none;"');
                    if(fixon && (checkBN || checkSM) && checkSITEUM) {
                        searchOn = ((checkSM) && fixon.indexOf('search')>-1) ? '' : 'style="display:none;"';
                        cartOn = ((checkSM) && fixon.indexOf('cart')>-1) ? '' : 'style="display:none;"';
                    }
                } 
               
                if(checkElView || checkmodal || is_templates) {
                    umOn = (checkBS || checkFREE) ? 'style="display:none;"' : '';  
                    searchOn = cartOn = (checkSM) ? '' : 'style="display:none;"';
                }
               
                /* 다국어 / 사이트 언어별 lang 체크 ***/
                // if((typeof slang != 'undefined' && typeof slang.select_code != 'undefined' && slang.select_code)
                //             || (!$.isEmptyObject(slang) && slang.select_code)) {
                //     //searchOn = (slang['select_code']=='ko' && checkSM) ? '' : 'style="display:none;"';
                //     lang_str = (slang['select_code'].toLowerCase()=='ko') ? 'ko' : lang_str;
                // } 

            switch(num) {
                case "01" : 
                    str = '\
                        <li class="siteSEARCH cl-fixbtn '+((!searchOn) ? 'cl-visible' : '')+'" '+searchOn+'><a href="#">SEARCH</a></li>\
                        <li class="siteUM cl-fixbtn '+dropdownClass+''+((!umOn) ? 'cl-visible' : '')+'" '+umOn+'>\
                            <a href="javascript:;" class="cl-login">LOGIN</a>\
                            <a href="javascript:;" class="cl-logout dropdown-toggle" style="display:none;">MY PAGE</a>\
                        </li>\
                        <li class="siteCART cl-fixbtn '+((!cartOn) ? 'cl-visible' : '')+'" '+cartOn+'><a href="#"><span class=\"cart-text\">CART</span><div class=\"cart-active\">5</div></a></li>\
                        '; 
                    break;
                
                case "02" : 
                    str = '\
                        <li class="siteSEARCH cl-fixbtn '+((!searchOn) ? 'cl-visible' : '')+'" '+searchOn+'><a href="#">Search</a></li>\
                        <li class="siteUM cl-fixbtn '+dropdownClass+''+((!umOn) ? 'cl-visible' : '')+'" '+umOn+'>\
                            <a href="javascript:;" class="cl-login">Login</a>\
                            <a href="javascript:;" class="cl-logout dropdown-toggle" style="display:none;">My page</a>\
                        </li>\
                        <li class="siteCART cl-fixbtn '+((!cartOn) ? 'cl-visible' : '')+'" '+cartOn+'>\
                            <a href="#"><span class=\"cart-text\">Basket</span><div class=\"cart-active\">5</div></a>\
                        </li>\
                        ';
                    break;

                case "03" : 
                    str = '\
                        <li class="siteSEARCH cl-fixbtn '+((!searchOn) ? 'cl-visible' : '')+'" '+searchOn+'><a href="#">검색</a></li>\
                        <li class="siteUM cl-fixbtn '+dropdownClass+''+((!umOn) ? 'cl-visible' : '')+'" '+umOn+'>\
                            <a href="javascript:;" class="cl-login">로그인</a>\
                            <a href="javascript:;" class="cl-logout dropdown-toggle" style="display:none;">마이페이지</a>\
                        </li>\
                        <li class="siteCART cl-fixbtn '+((!cartOn) ? 'cl-visible' : '')+'" '+cartOn+'>\
                            <a href="#"><span class=\"cart-text\">장바구니</span>\
                                <div class=\"cart-active\"><span class=\"cart-active-txt\">5</span></div>\
                            </a>\
                        </li>\
                        ';
                    break;
                
                case "04" : 
                    str = '\
                        <li class="siteSEARCH cl-fixbtn '+((!searchOn) ? 'cl-visible' : '')+'" '+searchOn+'><a href="#">'+clSVG('fixbtn_search04',28,28,true)+'</a></li>\
                        <li class="siteUM cl-fixbtn '+dropdownClass+''+((!umOn) ? 'cl-visible' : '')+'" '+umOn+'>\
                            <a href="javascript:;" class="cl-login">'+clSVG('fixbtn_um_login_04',28,28,true)+'</a>\
                            <a href="javascript:;" class="cl-logout dropdown-toggle" style="display:none;">'+clSVG('fixbtn_um_mypage_04',28,28,true)+'</a>\
                        </li>\
                        <li class="siteCART cl-fixbtn '+((!cartOn) ? 'cl-visible' : '')+'" '+cartOn+'>\
                            <a href="#">'+clSVG('fixbtn_cart04',28,28,true)+'\
                                <div class=\"cart-active\"><span class=\"cart-active-txt\">5</span></div>\
                            </a>\
                        </li>\
                        ';
                    break;
                
                case "05" : 
                    str = '\
                        <li class="siteSEARCH cl-fixbtn '+((!searchOn) ? 'cl-visible' : '')+'" '+searchOn+'><a href="#">'+clSVG('fixbtn_search05',28,28,true)+'</a></li>\
                        <li class="siteUM cl-fixbtn '+dropdownClass+''+((!umOn) ? 'cl-visible' : '')+'" '+umOn+'>\
                            <a href="javascript:;" class="cl-login">'+clSVG('fixbtn_um_login05',28,28,true)+'</a>\
                            <a href="javascript:;" class="cl-logout dropdown-toggle" style="display:none;">'+clSVG('fixbtn_um_mypage05',28,28,true)+'</a>\
                        </li>\
                        <li class="siteCART cl-fixbtn '+((!cartOn) ? 'cl-visible' : '')+'" '+cartOn+'>\
                            <a href="#">'+clSVG('fixbtn_cart05',28,28,true)+'\
                                <div class=\"cart-active\"><span class=\"cart-active-txt\">5</span></div>\
                            </a>\
                        </li>\
                        ';
                    break;
                
                case "06" : 
                    str = '\
                        <li class="siteSEARCH cl-fixbtn '+((!searchOn) ? 'cl-visible' : '')+'" '+searchOn+'><a href="#">'+clSVG('fixbtn_search06',28,28,true)+'</a></li>\
                        <li class="siteUM cl-fixbtn '+dropdownClass+''+((!umOn) ? 'cl-visible' : '')+'" '+umOn+'>\
                            <a href="javascript:;" class="cl-login">'+clSVG('fixbtn_um_login06',28,28,true)+'</a>\
                            <a href="javascript:;" class="cl-logout dropdown-toggle" style="display:none;">'+clSVG('fixbtn_um_mypage06',28,28,true)+'</a>\
                        </li>\
                        <li class="siteCART cl-fixbtn '+((!cartOn) ? 'cl-visible' : '')+'" '+cartOn+'>\
                            <a href="#">'+clSVG('fixbtn_cart06',28,28,true)+'\
                                <div class=\"cart-active\"><span class=\"cart-active-txt\">5</span></div>\
                            </a>\
                        </li>\
                        ';
                    break;
                
                case "07" : 
                    str = '\
                        <li class="siteSEARCH cl-fixbtn '+((!searchOn) ? 'cl-visible' : '')+'" '+searchOn+'><a href="#">'+clSVG('fixbtn_search07',28,28,true)+'</a></li>\
                        <li class="siteUM cl-fixbtn '+dropdownClass+''+((!umOn) ? 'cl-visible' : '')+'" '+umOn+'>\
                            <a href="javascript:;" class="cl-login">'+clSVG('fixbtn_um_login07',28,28,true)+'</a>\
                            <a href="javascript:;" class="cl-logout dropdown-toggle" style="display:none;">'+clSVG('fixbtn_um_mypage07',28,28,true)+'</a>\
                        </li>\
                        <li class="siteCART cl-fixbtn '+((!cartOn) ? 'cl-visible' : '')+'" '+cartOn+'>\
                            <a href="#">'+clSVG('fixbtn_cart07',28,28,true)+'\
                                <div class=\"cart-active\">5</div>\
                            </a>\
                        </li>\
                        ';
                    break;

                case "08" : 
                    str = '\
                        <li class="siteSEARCH cl-fixbtn '+((!searchOn) ? 'cl-visible' : '')+'" '+searchOn+'><a href="#">'+clSVG('fixbtn_search08',28,28,true)+'<span class=\"btn_text\">SEARCH</span></a></li>\
                        <li class="siteUM cl-fixbtn '+dropdownClass+''+((!umOn) ? 'cl-visible' : '')+'" '+umOn+'>\
                            <a href="javascript:;" class="cl-login">'+clSVG('fixbtn_um_login08',28,28,true)+'<span class=\"btn_text\">LOGIN</span></a>\
                            <a href="javascript:;" class="cl-logout dropdown-toggle" style="display:none;">'+clSVG('fixbtn_um_mypage08',28,28,true)+'<span class=\"btn_text\">MY PAGE</span></a>\
                        </li>\
                        <li class="siteCART cl-fixbtn '+((!cartOn) ? 'cl-visible' : '')+'" '+cartOn+'>\
                            <a href="#">'+clSVG('fixbtn_cart08',28,28,true)+'\
                                <span class=\"btn_text\">CART</span><div class=\"cart-active\">5</div>\
                            </a>\
                        </li>\
                        ';
                    break;
                
                case "09" : 
                    str = '\
                        <li class="siteSEARCH cl-fixbtn '+((!searchOn) ? 'cl-visible' : '')+'" '+searchOn+'><a href="#">검색</a></li>\
                        <li class="siteUM cl-fixbtn '+dropdownClass+''+((!umOn) ? 'cl-visible' : '')+'" '+umOn+'>\
                            <a href="javascript:;" class="cl-login">로그인</a>\
                            <a href="javascript:;" class="cl-logout dropdown-toggle" style="display:none;">마이페이지</a>\
                        </li>\
                        <li class="siteCART cl-fixbtn '+((!cartOn) ? 'cl-visible' : '')+'" '+cartOn+'>\
                            <a href="#">'+clSVG('fixbtn_cart09',28,28,true)+'\
                                <div class=\"cart-active\">5</div>\
                            </a>\
                        </li>\
                        ';
                    break;
                
                case "10" : 
                    str = '\
                        <li class="siteUM cl-fixbtn '+dropdownClass+''+((!umOn) ? 'cl-visible' : '')+'" '+umOn+'>\
                            <a href="javascript:;" class="cl-login">LOGIN</a>\
                            <a href="javascript:;" class="cl-logout dropdown-toggle" style="display:none;">MY PAGE</a>\
                        </li>\
                        <li class="siteSEARCH cl-fixbtn '+((!searchOn) ? 'cl-visible' : '')+'" '+searchOn+'><a href="#">'+clSVG('fixbtn_search10',28,28,true)+'</a></li>\
                        <li class="siteCART cl-fixbtn '+((!cartOn) ? 'cl-visible' : '')+'" '+cartOn+'>\
                            <a href="#">'+clSVG('fixbtn_cart09',28,28,true)+'\
                                <div class=\"cart-active\"><span class=\"cart-active-txt\">5</span></div>\
                            </a>\
                        </li>\
                        ';
                    break;

                default : 
                    break;
            }
            
            return str;
        },
        sidebarSet : function(num,checkmodal,validArray,slang) {
            var str = '',
                searchOn = '',
                cartOn = '',
                umOn = '',
                ssid = (PAGE_MODE == 'c') ? SID : property.SID,
                is_templates = checkTemplateSite(ssid),
                s_service = (PAGE_MODE == 'c') ? SERVICE : property.SERVICE,
                checkGabia = (s_service.indexOf('gabia') > -1) ? true : false,
                checkBS = (validArray['validplan'] && (validArray['validtype'] == 'BS' || (checkGabia && (validArray['validtype'] == 'FR')))) ? true : false,
                checkBN = (validArray['validplan'] && validArray['validtype'] == 'BN') ? true : false,
                checkSM = (validArray['validplan'] && validArray['validtype'] == 'SM') ? true : false,
                checkFREE = (!validArray['validplan'] || validArray['validplan'] == 'FR' || validArray['validplan'] == 'PK') ? true : false,
                checkElView = ($('.elviewhtml').length>0) ? true : false,
                fixBtnSITEUM = (checkElView) ? '' : ((PAGE_MODE=='c') ? SITEUM : property.SITEUM),
                checkSITEUM = (!checkElView && ((checkBN && typeof fixBtnSITEUM!='undefined' && Number(fixBtnSITEUM) > 0) || checkSM)) ? true : (checkElView ? true : false),
                checkmodal = (typeof checkmodal != 'undefined' && checkmodal) ? true : false,                
                fixon = (typeof $('.el-menu header.navbar').attr('data-fixon') != 'undefined' && $('.el-menu header.navbar').attr('data-fixon')) ? $('.el-menu header.navbar').attr('data-fixon') : '',
                dropdownClass = (PAGE_MODE=='c') ? '' : 'dropdown ',
                slang = (typeof langObj != 'undefined' && langObj) ? langObj : ((PAGE_MODE == 'c') ? SLANG : property.SLANG);
                // lang_str = LANG;
                
                if(!checkElView) {
                    searchOn = (!checkSM) ? 'style="display:none;"' : '';                    
                    umOn = (checkBS || checkFREE || (checkBN && !checkSITEUM)) ? 'style="display:none;"' : '';   
                    cartOn = (checkFREE) ? 'style="display:none;"' : ((checkSM) ? '' : 'style="display:none;"');
                    if(fixon && (checkBN || checkSM) && checkSITEUM) {
                        searchOn = ((checkSM) && fixon.indexOf('search')>-1) ? '' : 'style="display:none;"';
                        cartOn = ((checkSM) && fixon.indexOf('cart')>-1) ? '' : 'style="display:none;"';
                    }
                } 
               
                if(checkElView || checkmodal || is_templates) {
                    umOn = (checkBS || checkFREE) ? 'style="display:none;"' : '';  
                    searchOn = cartOn = (checkSM) ? '' : 'style="display:none;"';
                }
                   
                /* 다국어 / 사이트 언어별 lang 체크 ***/
                // if((typeof slang != 'undefined' && typeof slang.select_code != 'undefined' && slang.select_code)
                //             || (!$.isEmptyObject(slang) && slang.select_code)) {
                //     //searchOn = (slang['select_code']=='ko' && checkSM) ? '' : 'style="display:none;"';
                //     lang_str = (slang['select_code'].toLowerCase()!='ko') ? 'en' : 'ko';
                // } 

            switch(num) {
                case "01" : 
                    str = '\
                        <li class="siteSEARCH cl-fixbtn '+((!searchOn) ? 'cl-visible' : '')+'" '+searchOn+'><a href="#">SEARCH</a></li>\
                        <li class="siteUM cl-fixbtn '+dropdownClass+''+((!umOn) ? 'cl-visible' : '')+'" '+umOn+'>\
                            <a href="javascript:;" class="cl-login">LOGIN</a>\
                            <a href="javascript:;" class="cl-logout dropdown-toggle" style="display:none;">MY PAGE</a>\
                        </li>\
                        <li class="siteCART cl-fixbtn '+((!cartOn) ? 'cl-visible' : '')+'" '+cartOn+'><a href="#"><span class=\"cart-text\">CART</span><div class=\"cart-active\">5</div></a></li>\
                        '; 
                    break;
                
                case "02" : 
                    str = '\
                        <li class="siteSEARCH cl-fixbtn '+((!searchOn) ? 'cl-visible' : '')+'" '+searchOn+'><a href="#">Search</a></li>\
                        <li class="siteUM cl-fixbtn '+dropdownClass+''+((!umOn) ? 'cl-visible' : '')+'" '+umOn+'>\
                            <a href="javascript:;" class="cl-login">Login</a>\
                            <a href="javascript:;" class="cl-logout dropdown-toggle" style="display:none;">My page</a>\
                        </li>\
                        <li class="siteCART cl-fixbtn '+((!cartOn) ? 'cl-visible' : '')+'" '+cartOn+'>\
                            <a href="#"><span class=\"cart-text\">Basket</span><div class=\"cart-active\">5</div></a>\
                        </li>\
                        ';
                    break;

                case "03" : 
                    str = '\
                        <li class="siteSEARCH cl-fixbtn '+((!searchOn) ? 'cl-visible' : '')+'" '+searchOn+'><a href="#">검색</a></li>\
                        <li class="siteUM cl-fixbtn '+dropdownClass+''+((!umOn) ? 'cl-visible' : '')+'" '+umOn+'>\
                            <a href="javascript:;" class="cl-login">로그인</a>\
                            <a href="javascript:;" class="cl-logout dropdown-toggle" style="display:none;">마이페이지</a>\
                        </li>\
                        <li class="siteCART cl-fixbtn '+((!cartOn) ? 'cl-visible' : '')+'" '+cartOn+'>\
                            <a href="#"><span class=\"cart-text\">장바구니</span>\
                                <div class=\"cart-active\"><span class=\"cart-active-txt\">5</span></div>\
                            </a>\
                        </li>\
                        ';
                    break;
                
                case "04" : 
                    str = '\
                        <li class="siteSEARCH cl-fixbtn '+((!searchOn) ? 'cl-visible' : '')+'" '+searchOn+'><a href="#">'+clSVG('fixbtn_search04',28,28,true)+'</a></li>\
                        <li class="siteUM cl-fixbtn '+dropdownClass+''+((!umOn) ? 'cl-visible' : '')+'" '+umOn+'>\
                            <a href="javascript:;" class="cl-login">'+clSVG('fixbtn_um_login_04',28,28,true)+'</a>\
                            <a href="javascript:;" class="cl-logout dropdown-toggle" style="display:none;">'+clSVG('fixbtn_um_mypage_04',28,28,true)+'</a>\
                        </li>\
                        <li class="siteCART cl-fixbtn '+((!cartOn) ? 'cl-visible' : '')+'" '+cartOn+'>\
                            <a href="#">'+clSVG('fixbtn_cart04',28,28,true)+'\
                                <div class=\"cart-active\"><span class=\"cart-active-txt\">5</span></div>\
                            </a>\
                        </li>\
                        ';
                    break;
                
                case "05" : 
                    str = '\
                        <li class="siteSEARCH cl-fixbtn '+((!searchOn) ? 'cl-visible' : '')+'" '+searchOn+'><a href="#">'+clSVG('fixbtn_search05',28,28,true)+'</a></li>\
                        <li class="siteUM cl-fixbtn '+dropdownClass+''+((!umOn) ? 'cl-visible' : '')+'" '+umOn+'>\
                            <a href="javascript:;" class="cl-login">'+clSVG('fixbtn_um_login05',28,28,true)+'</a>\
                            <a href="javascript:;" class="cl-logout dropdown-toggle" style="display:none;">'+clSVG('fixbtn_um_mypage05',28,28,true)+'</a>\
                        </li>\
                        <li class="siteCART cl-fixbtn '+((!cartOn) ? 'cl-visible' : '')+'" '+cartOn+'>\
                            <a href="#">'+clSVG('fixbtn_cart05',28,28,true)+'\
                                <div class=\"cart-active\"><span class=\"cart-active-txt\">5</span></div>\
                            </a>\
                        </li>\
                        ';
                    break;
                
                case "06" : 
                    str = '\
                        <li class="siteSEARCH cl-fixbtn '+((!searchOn) ? 'cl-visible' : '')+'" '+searchOn+'><a href="#">'+clSVG('fixbtn_search06',28,28,true)+'</a></li>\
                        <li class="siteUM cl-fixbtn '+dropdownClass+''+((!umOn) ? 'cl-visible' : '')+'" '+umOn+'>\
                            <a href="javascript:;" class="cl-login">'+clSVG('fixbtn_um_login06',28,28,true)+'</a>\
                            <a href="javascript:;" class="cl-logout dropdown-toggle" style="display:none;">'+clSVG('fixbtn_um_mypage06',28,28,true)+'</a>\
                        </li>\
                        <li class="siteCART cl-fixbtn '+((!cartOn) ? 'cl-visible' : '')+'" '+cartOn+'>\
                            <a href="#">'+clSVG('fixbtn_cart06',28,28,true)+'\
                                <div class=\"cart-active\"><span class=\"cart-active-txt\">5</span></div>\
                            </a>\
                        </li>\
                        ';
                    break;
                
                case "07" : 
                    str = '\
                        <li class="siteSEARCH cl-fixbtn '+((!searchOn) ? 'cl-visible' : '')+'" '+searchOn+'><a href="#">'+clSVG('fixbtn_search07',28,28,true)+'</a></li>\
                        <li class="siteUM cl-fixbtn '+dropdownClass+''+((!umOn) ? 'cl-visible' : '')+'" '+umOn+'>\
                            <a href="javascript:;" class="cl-login">'+clSVG('fixbtn_um_login07',28,28,true)+'</a>\
                            <a href="javascript:;" class="cl-logout dropdown-toggle" style="display:none;">'+clSVG('fixbtn_um_mypage07',28,28,true)+'</a>\
                        </li>\
                        <li class="siteCART cl-fixbtn '+((!cartOn) ? 'cl-visible' : '')+'" '+cartOn+'>\
                            <a href="#">'+clSVG('fixbtn_cart07',28,28,true)+'\
                                <div class=\"cart-active\">5</div>\
                            </a>\
                        </li>\
                        ';
                    break;

                case "08" : 
                    str = '\
                        <li class="siteSEARCH cl-fixbtn '+((!searchOn) ? 'cl-visible' : '')+'" '+searchOn+'><a href="#">'+clSVG('fixbtn_search08',28,28,true)+'<span class=\"btn_text\">SEARCH</span></a></li>\
                        <li class="siteUM cl-fixbtn '+dropdownClass+''+((!umOn) ? 'cl-visible' : '')+'" '+umOn+'>\
                            <a href="javascript:;javascript:;" class="cl-login">'+clSVG('fixbtn_um_login08',28,28,true)+'<span class=\"btn_text\">LOGIN</span></a>\
                            <a href="javascript:;" class="cl-logout dropdown-toggle" style="display:none;">'+clSVG('fixbtn_um_mypage08',28,28,true)+'<span class=\"btn_text\">MY PAGE</span></a>\
                        </li>\
                        <li class="siteCART cl-fixbtn '+((!cartOn) ? 'cl-visible' : '')+'" '+cartOn+'>\
                            <a href="#">'+clSVG('fixbtn_cart08',28,28,true)+'\
                                <span class=\"btn_text\">CART</span><div class=\"cart-active\">5</div>\
                            </a>\
                        </li>\
                        ';
                    break;
                
                case "09" : 
                    str = '\
                        <li class="siteSEARCH cl-fixbtn '+((!searchOn) ? 'cl-visible' : '')+'" '+searchOn+'><a href="#">검색</a></li>\
                        <li class="siteUM cl-fixbtn '+dropdownClass+''+((!umOn) ? 'cl-visible' : '')+'" '+umOn+'>\
                            <a href="javascript:;" class="cl-login">로그인</a>\
                            <a href="javascript:;" class="cl-logout dropdown-toggle" style="display:none;">마이페이지</a>\
                        </li>\
                        <li class="siteCART cl-fixbtn '+((!cartOn) ? 'cl-visible' : '')+'" '+cartOn+'>\
                            <a href="#">'+clSVG('fixbtn_cart09',28,28,true)+'\
                                <div class=\"cart-active\">5</div>\
                            </a>\
                        </li>\
                        ';
                    break;
                
                case "10" : 
                    str = '\
                        <li class="siteUM cl-fixbtn '+dropdownClass+''+((!umOn) ? 'cl-visible' : '')+'" '+umOn+'>\
                            <a href="javascript:;" class="cl-login">LOGIN</a>\
                            <a href="javascript:;" class="cl-logout dropdown-toggle" style="display:none;">My page</a>\
                        </li>\
                        <li class="siteSEARCH cl-fixbtn '+((!searchOn) ? 'cl-visible' : '')+'" '+searchOn+'><a href="#">'+clSVG('fixbtn_search10',28,28,true)+'</a></li>\
                        <li class="siteCART cl-fixbtn '+((!cartOn) ? 'cl-visible' : '')+'" '+cartOn+'>\
                            <a href="#">'+clSVG('fixbtn_cart09',28,28,true)+'\
                                <div class=\"cart-active\"><span class=\"cart-active-txt\">5</span></div>\
                            </a>\
                        </li>\
                        ';
                    break;

                default : 
                    break;
            }
            
            return str;
        },
        fixFhTypeSet : function(pos) {
            var str = '';

            switch(pos) {
                
                case "right" : 

                    str += '\
                        <ul class="menuList">\
                            <li class="cl-menulist"><a href="#">Home</a></li>\
                            <li class="cl-menulist"><a href="#">Portfolio</a></li>\
                            <li class="cl-menulist"><a href="#">Contact</a></li>\
                        </ul>\
                        <ul class="menufixArea">\
                            <li class="siteSEARCH cl-fixbtn"><a href="#">'+clSVG('fixbtn_search04',28,28,true)+'</a></li>\
                            <li class="siteUM cl-fixbtn"><a href="#">'+clSVG('fixbtn_um04',28,28,true)+'</a></li>\
                            <li class="siteCART cl-fixbtn"><a href="#">'+clSVG('fixbtn_cart04',28,28,true)+'</a></li>\
                        </ul>\
                        ';

                    break;

                case "top" : 

                    str += '\
                        <ul class="menufixArea">\
                            <li class="siteSEARCH cl-fixbtn"><a href="#">'+clSVG('fixbtn_search04',28,28,true)+'</a></li>\
                            <li class="siteUM cl-fixbtn"><a href="#">'+clSVG('fixbtn_um04',28,28,true)+'</a></li>\
                            <li class="siteCART cl-fixbtn"><a href="#">'+clSVG('fixbtn_cart04',28,28,true)+'</a></li>\
                        </ul>\
                        <ul class="menuList">\
                            <li class="cl-menulist"><a href="#">Home</a></li>\
                            <li class="cl-menulist"><a href="#">Portfolio</a></li>\
                            <li class="cl-menulist"><a href="#">Contact</a></li>\
                        </ul>\
                        ';

                    break;

                default : 
                    break;
            }
            
            return str;
        },
        fixLangSet : function(num,def,langObj,checkMobile,validArray){
            var checkElView = ($('.elviewhtml').length>0) ? true : false,
                s_service = (PAGE_MODE == 'c') ? SERVICE : property.SERVICE,
                checkGabia = (s_service.indexOf('gabia') > -1) ? true : false,
                checkVALIDPLAN = (PAGE_MODE=='c') ? VALIDPLAN : property.VALIDPLAN,
                checkVALIDTYPE = (PAGE_MODE=='c') ? VALIDTYPE : property.VALIDTYPE,
                checkBS = (checkVALIDPLAN && (checkVALIDTYPE == 'BS' || (checkGabia && (checkVALIDTYPE == 'FR')))) ? true : false,
                slang = (typeof langObj != 'undefined' && langObj) ? langObj : ((PAGE_MODE == 'c') ? SLANG : property.SLANG),
                def = (typeof def!='undefined') ? def : true,
                checkMobile = (typeof checkMobile!='undefined') ? checkMobile : false;
              
            if(typeof validArray != 'undefined') var checkFREE = (!validArray['validplan'] || validArray['validplan'] == 'FR' || validArray['validplan'] == 'PK') ? true : false;
            if(!checkElView && ((typeof slang == 'undefined' && typeof slang.select_code == 'undefined' && !slang.select_code)
                            || ($.isEmptyObject(slang) && checkBS) || slang.select_code=='') || (checkElView && checkFREE) 
                || (typeof slang=='undefined' || !slang.select)) {
                    return false;
                }
          
            var str = '',
                lang_txt = (typeof slang.select != 'undefined' && slang.select) ? slang.select.trim() : '',
                lang_code = (typeof slang.select_code != 'undefined' && slang.select_code) ? slang.select_code.toUpperCase() : '',
                checkDropTopClass = ($('.el-menu > header.navbar').hasClass('sidebar') || checkMobile) ? 'dropup' : 'dropdown',
                dropdownClass = (PAGE_MODE=='c') ? '' : 'dropdown',
                dropdownStr = '';
            
            if(checkMobile) {
                dropdownStr += '\
                <div class="dropdown-menu-wrap" id="m-dropdown-wrap-lang">\
                    <span class="dropdown-close"><img src="//storage.googleapis.com/i.addblock.net/fa-close-modal-white.png" alt="Close Change Multilingual Site"></span></span>\
                ';
            }
                dropdownStr += '\
                    <ul class="dropdown-menu">';
                    $.each(slang.lists, function(i,v){
                    var active = (v.name == slang.select) ? 'active' : '';
                    dropdownStr += '\
                        <li class="'+active+'"><a class="cl-langlist " href="javascript:;" data-code="'+v.code+'">'+v.name+'</a></li>';
                    });
                dropdownStr += '\
                    </ul>';
            if(checkMobile) {
                dropdownStr += '\
                </div>\
                ';
            }                  
          
            var attrMobile = (checkMobile) ? 'data-toggle="dropdown" data-target="#m-dropdown-wrap-lang"' : '';
         
            switch(num) {
                case "01" : 
                    str = (!def) ? '\
                        <div class="siteLANG cl-fixbtn '+checkDropTopClass+' cl-visible" data-fixlang="'+lang_txt+'" data-fixlangcode="'+lang_code+'">\
                            <a href="#" class="cl-lang dropdown-toggle" '+attrMobile+'>\
                                <span class="slang-active">'+lang_code+'</span>\
                                ' + clSVG('fixbtn_arrow01',16,16,true) + '\
                            </a>' + dropdownStr + '\
                        </div>' : '\
                        <li class="siteLANG cl-fixbtn dropdown cl-visible" data-fixlang="'+lang_txt+'" data-fixlangcode="'+lang_code+'">\
                            <a href="#" class="cl-lang dropdown-toggle">\
                                <span class="slang-active">'+lang_code+'</span>\
                                ' + clSVG('fixbtn_arrow01',16,16,true) + '\
                            </a>' + dropdownStr + '\
                        </li>\
                        '; 
                    break;
                
                case "02" : 
                    str = (!def) ? '\
                        <div class="siteLANG cl-fixbtn '+checkDropTopClass+' cl-visible" data-fixlang="'+lang_txt+'" data-fixlangcode="'+lang_code+'">\
                            <a href="#" class="cl-lang dropdown-toggle" '+attrMobile+'>\
                                <span class="slang-active">'+lang_txt+'</span>\
                                ' + clSVG('fixbtn_arrow01',16,16,true) + '\
                            </a>' + dropdownStr + '\
                        </div>' : '\
                        <li class="siteLANG cl-fixbtn dropdown cl-visible" data-fixlang="'+lang_txt+'" data-fixlangcode="'+lang_code+'">\
                            <a href="#" class="cl-lang dropdown-toggle">\
                                <span class="slang-active">'+lang_txt+'</span>\
                                ' + clSVG('fixbtn_arrow01',16,16,true) + '\
                            </a>' + dropdownStr + '\
                        </li>\
                        '; 
                    break;
                
                case "03" : 
                    str = (!def) ? '\
                        <div class="siteLANG cl-fixbtn '+checkDropTopClass+' cl-visible" data-fixlang="'+lang_txt+'" data-fixlangcode="'+lang_code+'">\
                            <a href="#" class="cl-lang dropdown-toggle" '+attrMobile+'>\
                                <span class="slang-active">'+lang_code+'</span>\
                                ' + clSVG('fixbtn_arrow01',16,16,true) + '\
                            </a>' + dropdownStr + '\
                        </div>' : '\
                        <li class="siteLANG cl-fixbtn dropdown cl-visible" data-fixlang="'+lang_txt+'" data-fixlangcode="'+lang_code+'">\
                            <a href="#" class="cl-lang dropdown-toggle">\
                                <span class="slang-active">'+lang_code+'</span>\
                                ' + clSVG('fixbtn_arrow01',16,16,true) + '\
                            </a>' + dropdownStr + '\
                        </li>\
                        '; 
                    break;
                
                case "04" : 
                    str = (!def) ? '\
                        <div class="siteLANG cl-fixbtn '+checkDropTopClass+' cl-visible" data-fixlang="'+lang_txt+'" data-fixlangcode="'+lang_code+'">\
                            <a href="#" class="cl-lang dropdown-toggle" '+attrMobile+'>\
                                <span class="slang-active">'+lang_code+'</span>\
                                ' + clSVG('fixbtn_arrow01',16,16,true) + '\
                            </a>' + dropdownStr + '\
                        </div>\
                        ' : '\
                        <li class="siteLANG cl-fixbtn dropdown cl-visible" data-fixlang="'+lang_txt+'" data-fixlangcode="'+lang_code+'">\
                            <a href="#" class="cl-lang dropdown-toggle" '+attrMobile+'>\
                                <span class="slang-active">'+lang_code+'</span>\
                                ' + clSVG('fixbtn_arrow01',16,16,true) + '\
                            </a>' + dropdownStr + '\
                        </li>\
                        '; 
                    break;
                
                case "05" : 
                    str = (!def) ? '\
                        <div class="siteLANG cl-fixbtn '+checkDropTopClass+' cl-visible" data-fixlang="'+lang_txt+'" data-fixlangcode="'+lang_code+'">\
                            <a href="#" class="cl-lang dropdown-toggle" '+attrMobile+'>\
                                <span class="slang-active" style="display:none;">'+lang_code+'</span>\
                                ' + clSVG('fixbtn_lang05',18,18,true) + '\
                            </a>' + dropdownStr + '\
                        </div>\
                        ' : '\
                        <li class="siteLANG cl-fixbtn dropdown cl-visible" data-fixlang="'+lang_txt+'" data-fixlangcode="'+lang_code+'">\
                            <a href="#" class="cl-lang dropdown-toggle">\
                                <span class="slang-active" style="display:none;">'+lang_code+'</span>\
                                ' + clSVG('fixbtn_lang05',18,18,true) + '\
                            </a>' + dropdownStr + '\
                        </li>\
                        '; 
                    break;

                case "06" : 
                    str = (!def) ? '\
                        <div class="siteLANG cl-fixbtn '+checkDropTopClass+' cl-visible" data-fixlang="'+lang_txt+'" data-fixlangcode="'+lang_code+'">\
                            <a href="#" class="cl-lang dropdown-toggle" '+attrMobile+'>\
                                ' + clSVG('fixbtn_lang05',18,18,true) + '\
                                <span class="slang-active">'+lang_code+'</span>\
                            </a>' + dropdownStr + '\
                        </div>\
                        ' : '\
                        <li class="siteLANG cl-fixbtn dropdown cl-visible" data-fixlang="'+lang_txt+'" data-fixlangcode="'+lang_code+'">\
                            <a href="#" class="cl-lang dropdown-toggle">\
                                ' + clSVG('fixbtn_lang05',18,18,true) + '\
                                <span class="slang-active">'+lang_code+'</span>\
                            </a>' + dropdownStr + '\
                        </li>\
                        '; 
                    break;
                
                case "07" : 
                    str = (!def) ? '\
                        <div class="siteLANG cl-fixbtn '+checkDropTopClass+' cl-visible" data-fixlang="'+lang_txt+'" data-fixlangcode="'+lang_code+'">\
                            <a href="#" class="cl-lang dropdown-toggle" '+attrMobile+'>\
                                <img src="//storage.googleapis.com/i.addblock.net/flag/flag_'+lang_code.toLowerCase()+'_cir.png" class="cl-lang-img img-responsive"/>\
                                <span class="slang-active">'+lang_txt+'</span>\
                                ' + clSVG('fixbtn_arrow01',16,16,true) + '\
                            </a>' + dropdownStr + '\
                        </div>\
                        ' : '\
                        <li class="siteLANG cl-fixbtn dropdown cl-visible" data-fixlang="'+lang_txt+'" data-fixlangcode="'+lang_code+'">\
                            <a href="#" class="cl-lang dropdown-toggle">\
                                <img src="//storage.googleapis.com/i.addblock.net/flag/flag_'+lang_code.toLowerCase()+'_cir.png" class="cl-lang-img img-responsive"/>\
                                <span class="slang-active">'+lang_txt+'</span>\
                                ' + clSVG('fixbtn_arrow01',16,16,true) + '\
                            </a>' + dropdownStr + '\
                        </li>\
                        '; 
                    break;
                
                case "08" : 
                    str = (!def) ? '\
                        <div class="siteLANG cl-fixbtn '+checkDropTopClass+' cl-visible" data-fixlang="'+lang_txt+'" data-fixlangcode="'+lang_code+'">\
                            <a href="#" class="cl-lang dropdown-toggle" '+attrMobile+'>\
                                <img src="//storage.googleapis.com/i.addblock.net/flag/flag_'+lang_code.toLowerCase()+'_rec.png" class="cl-lang-img img-responsive"/>\
                                <span class="slang-active">'+lang_txt+'</span>\
                                ' + clSVG('fixbtn_arrow01',16,16,true) + '\
                            </a>' + dropdownStr + '\
                        </div>\
                        ' : '\
                        <li class="siteLANG cl-fixbtn dropdown cl-visible" data-fixlang="'+lang_txt+'" data-fixlangcode="'+lang_code+'">\
                            <a href="#" class="cl-lang dropdown-toggle">\
                                <img src="//storage.googleapis.com/i.addblock.net/flag/flag_'+lang_code.toLowerCase()+'_rec.png" class="cl-lang-img img-responsive"/>\
                                <span class="slang-active">'+lang_txt+'</span>\
                                ' + clSVG('fixbtn_arrow01',16,16,true) + '\
                            </a>' + dropdownStr + '\
                        </li>\
                        '; 
                    break;

                case "09" : 
                    str = (!def) ? '\
                        <div class="siteLANG cl-fixbtn '+checkDropTopClass+' cl-visible" data-fixlang="'+lang_txt+'" data-fixlangcode="'+lang_code+'">\
                            <a href="#" class="cl-lang dropdown-toggle" '+attrMobile+'>\
                                <img src="//storage.googleapis.com/i.addblock.net/flag/flag_'+lang_code.toLowerCase()+'_cir.png" class="cl-lang-img img-responsive"/>\
                            </a>' + dropdownStr + '\
                        </div>\
                        ' : '\
                        <li class="siteLANG cl-fixbtn dropdown cl-visible" data-fixlang="'+lang_txt+'" data-fixlangcode="'+lang_code+'">\
                            <a href="#" class="cl-lang dropdown-toggle">\
                                <img src="//storage.googleapis.com/i.addblock.net/flag/flag_'+lang_code.toLowerCase()+'_cir.png" class="cl-lang-img img-responsive"/>\
                            </a>' + dropdownStr + '\
                        </li>\
                        '; 
                    break;

                case "10" : 
                    str = (!def) ? '\
                        <div class="siteLANG cl-fixbtn '+checkDropTopClass+' cl-visible" data-fixlang="'+lang_txt+'" data-fixlangcode="'+lang_code+'">\
                            <a href="#" class="cl-lang dropdown-toggle" '+attrMobile+'>\
                                <span class="slang-active">'+lang_code+'</span>\
                            </a>' + dropdownStr + '\
                        </div>' : '\
                        <li class="siteLANG cl-fixbtn dropdown cl-visible" data-fixlang="'+lang_txt+'" data-fixlangcode="'+lang_code+'">\
                            <a href="#" class="cl-lang dropdown-toggle">\
                                <span class="slang-active">'+lang_code+'</span>\
                            </a>' + dropdownStr + '\
                        </li>\
                        '; 
                    break;

                default : 
                    break;
            }
           
            return str;
        },
        getData : function($h) {
            var data = [],
                dataFix = ['fixtype','fixlangtype','fh-type','fixsize','fixlangsize','fixtypeText','fixtypeNum','fixlangtypeNum'];
                
            $.each(dataFix, function(i,v){
                var dataV = 'data-'+v;
                data[v] = (typeof $h.attr(dataV)!='undefined' && $h.attr(dataV)) ? $h.attr(dataV) : '';
                if(data['fixtype']!='undefined' && data['fixtype']) {
                    if(v=='fixtypeText') data[v] = data['fixtype'].replace(/\_\d+/gi,'');
                    else if(v=='fixtypeNum') data[v] = data['fixtype'].replace(/(top|sidebar)\_/gi,'');  
                    else if(v=='fixlangtypeNum') data[v] = data['fixlangtype'].replace(/lang\_/gi,'');
                } 
                
            })

            return data;
        }
    }

    /*** shopping Guide Popup ***/
    $.guidePopup = {
        set: function() {
            var str = '\
                    <div class="guide-top">\
                        <h3 class="modal-title guidetitle">'+$.lang[LANG]['editor.meta.shoppingmall.guide.title']+'</h3>\
                        <div class="guide-menu">\
                            <ul>\
                                <li class="active hand">\
                                    <p>'+$.lang[LANG]['editor.meta.shoppingmall.guide.step.1']+'</p>\
                                    <div class="line right"></div>\
                                </li>\
                                <li class="hand">\
                                    <div class="line left"></div>\
                                    <div class="line right"></div>\
                                    <p>'+$.lang[LANG]['editor.meta.shoppingmall.guide.step.2']+'</p>\
                                </li>\
                                <li class="hand">\
                                    <div class="line left"></div>\
                                    <div class="line right"></div>\
                                    <p>'+$.lang[LANG]['editor.meta.shoppingmall.guide.step.3']+'</p>\
                                </li>\
                                <li class="hand">\
                                    <div class="line left"></div>\
                                    <p>'+$.lang[LANG]['editor.meta.shoppingmall.guide.step.4']+'</p>\
                                </li>\
                            </ul>\
                        </div>\
                    </div>\
                    <div class="guide-wrap">\
                        <div class="step">\
                            <div id="step1">\
                                <h3>'+$.lang[LANG]['editor.meta.shoppingmall.guide.step.1.title']+'</h3>\
                                <p>'+$.lang[LANG]['editor.meta.shoppingmall.guide.step.1.1.contents']+'</p>\
                                <img class="img-responsive" src="//storage.googleapis.com/i.addblock.net/guide_img01_1.jpg">\
                                <p>'+$.lang[LANG]['editor.meta.shoppingmall.guide.step.1.2.contents']+'</p>\
                                <img class="img-responsive" src="//storage.googleapis.com/i.addblock.net/guide_img01_2.jpg">\
                                <p>'+$.lang[LANG]['editor.meta.shoppingmall.guide.step.1.3.contents']+'</p>\
                                <img class="img-responsive" src="//storage.googleapis.com/i.addblock.net/guide_img01_3.jpg">\
                            </div>\
                            <div id="step2">\
                                <h3>'+$.lang[LANG]['editor.meta.shoppingmall.guide.step.2.title']+'</h3>\
                                <p>'+$.lang[LANG]['editor.meta.shoppingmall.guide.step.2.1.contents']+'</p>\
                                <img class="img-responsive" src="//storage.googleapis.com/i.addblock.net/guide_img02_1.jpg">\
                                <p>'+$.lang[LANG]['editor.meta.shoppingmall.guide.step.2.2.contents']+'</p>\
                                <img src="//storage.googleapis.com/i.addblock.net/guide_img02_2.jpg">\
                                <p>'+$.lang[LANG]['editor.meta.shoppingmall.guide.step.2.3.contents']+'</p>\
                                <img class="img-responsive" src="//storage.googleapis.com/i.addblock.net/guide_img02_3.jpg">\
                                <p>'+$.lang[LANG]['editor.meta.shoppingmall.guide.step.2.4.contents']+'</p>\
                                <img class="img-responsive" src="//storage.googleapis.com/i.addblock.net/guide_img02_4.jpg">\
                            </div>\
                            <div id="step3">\
                                <h3>'+$.lang[LANG]['editor.meta.shoppingmall.guide.step.3.title']+'</h3>\
                                <p>'+$.lang[LANG]['editor.meta.shoppingmall.guide.step.3.1.contents']+'</p>\
                                <img class="img-responsive" src="//storage.googleapis.com/i.addblock.net/guide_img03_1.jpg">\
                                <p>'+$.lang[LANG]['editor.meta.shoppingmall.guide.step.3.2.contents']+'</p>\
                                <img class="img-responsive" src="//storage.googleapis.com/i.addblock.net/guide_img03_2.jpg">\
                            </div>\
                            <div id="step4">\
                                <h3>'+$.lang[LANG]['editor.meta.shoppingmall.guide.step.4.title']+'</h3>\
                                <p>'+$.lang[LANG]['editor.meta.shoppingmall.guide.step.4.1.contents']+'</p>\
                                <img class="img-responsive" src="//storage.googleapis.com/i.addblock.net/guide_img04_1.jpg">\
                                <p>'+$.lang[LANG]['editor.meta.shoppingmall.guide.step.4.2.contents']+'</p>\
                                <img class="img-responsive" src="//storage.googleapis.com/i.addblock.net/guide_img04_2.jpg">\
                            </div>\
                        </div>\
                        <div class="modal-footer guideClose">\
                            <button type="button" class="btn btn-default btn-sm close-button-dialog clostbtnfalse" data-dismiss="modal">닫기</button>\
                        </div>\
                    </div>\
                    ';
                                                    
            var shopguideModal = $(this).showModalFlat('',str,true,false,'','close','','guidePopup cl-cmmodal cl-s-btn cover w700', false ,'',function() {
                $.guidePopup.scrollevent();
            });
        },
        scrollevent : function() {
            $('.guidePopup-wrap').on('shown.bs.modal', function(e) {                    
                $('.guidePopup .guide-wrap').scroll(function() {
                    if($(this).hasClass('moving')) return false;
                    var scrollValue = $('.guidePopup .guide-wrap').scrollTop(),
                        issclogin = ($('.guidePopup').attr('class').indexOf('sclogin') > 0 || $('.guidePopup').attr('class').indexOf('naverpay-guide') > 0) ? true : false,
                        isCert = ($('.guidePopup').attr('class').indexOf('cert-guide-modal') > 0)? true : false;

                    if(issclogin || isCert) {
                        if( scrollValue >= $("#step2").position().top && scrollValue < $("#step3").position().top) {
                            $('.guidePopup ul li:visible').eq(1).addClass('active').siblings().removeClass('active');
                            $('.guidePopup ul li:visible').eq(1).css('zIndex', '2').siblings().css('zIndex', '1');
                        } else if( scrollValue >= $("#step3").position().top) {
                            $('.guidePopup ul li:visible').eq(2).addClass('active').siblings().removeClass('active');
                            $('.guidePopup ul li:visible').eq(2).css('zIndex', '2').siblings().css('zIndex', '1');
                        } else {
                            $('.guidePopup ul li:visible').eq(0).addClass('active').siblings().removeClass('active');
                            $('.guidePopup ul li:visible').eq(0).css('zIndex', '2').siblings().css('zIndex', '1');
                        }
                    } else {
                        if( scrollValue >= $("#step2").position().top && scrollValue < $("#step3").position().top) {
                            $('.guidePopup ul li').eq(1).addClass('active').siblings().removeClass('active');
                            $('.guidePopup ul li').eq(1).css('zIndex', '2').siblings().css('zIndex', '1');
                        } else if( scrollValue >= $("#step3").position().top && scrollValue < $("#step4").position().top) {
                            $('.guidePopup ul li').eq(2).addClass('active').siblings().removeClass('active');
                            $('.guidePopup ul li').eq(2).css('zIndex', '2').siblings().css('zIndex', '1');
                        } else if($("#step4").length > 0 && scrollValue >= $("#step4").position().top) {
                            $('.guidePopup ul li').eq(3).addClass('active').siblings().removeClass('active');
                            $('.guidePopup ul li').eq(3).css('zIndex', '2').siblings().css('zIndex', '1');
                        } else {
                            $('.guidePopup ul li').eq(0).addClass('active').siblings().removeClass('active');
                            $('.guidePopup ul li').eq(0).css('zIndex', '2').siblings().css('zIndex', '1');
                        }
                    }
                    
                });

                $('.guidePopup .guide-menu li').click(function() {
                    if($('.guidePopup .guide-wrap').hasClass('moving')) return false;
                    $('.guidePopup .guide-wrap').addClass('moving');
                    var top = ($(this).index())+1,
                        top_position = (top==1) ? $('#step'+top).position().top : ($('#step'+top).position().top)+60;
                   
                    $('.guidePopup .guide-wrap').animate({scrollTop : top_position}, 1000, 'easeInOutExpo');

                    setTimeout(function() {
                        $('.guidePopup .guide-wrap').removeClass('moving');
                    },1000);

                    $(this).addClass('active').siblings().removeClass('active');
                    $(this).css('zIndex', '2').siblings().css('zIndex', '1');                    
                });
            });
        }
    }



    $.siteBanner = {
        checkOffer: function(type) {
            // console.log('checkOffer('+type+')');
            var checkPlan = (typeof VALIDPLAN == 'undefined') ? property.VALIDPLAN : VALIDPLAN,
                checkPlanType = (typeof VALIDTYPE == 'undefined') ? property.VALIDTYPE : VALIDTYPE;
            if(!checkPlan || checkPlanType == 'PK') {
                return false;
            }

            var site_settings = (typeof property != 'undefined') ? property.SETTINGS : SETTINGS
            $.siteBanner.sid = (typeof property != 'undefined') ? property.SID : SID;
            if(typeof $.siteBanner.sid == 'undefined' || !$.siteBanner.sid || typeof site_settings == 'undefined' || !site_settings) {
                return false;
            }

            if(type == 'popup') {
                if(site_settings.SITELOCK) return false;

                var tmp_view = (PAGE_MODE == 'c') ? VIEW : ((typeof property != 'undefined') ? property.VIEW : ''),
                    tmp_one = (PAGE_MODE == 'c') ? ONE : ((typeof property != 'undefined') ? property.ONE : ''),
                    tmp_page  = (PAGE_MODE == 'c') ? PAGE : ((typeof property != 'undefined') ? property.PAGE : ''),
                    tmp_menu  = (PAGE_MODE == 'c') ? MENULINK[0] : ((typeof property != 'undefined') ? property.MENULINK[0] : ''),
                    tmp_clpage = ($('div:is(.element.cl-s-page, .psearch-view)').length > 0) ? true : false,
                    checkFirstPage = (!tmp_view && !tmp_clpage && (tmp_one || !tmp_one && tmp_page == tmp_menu)) ? true : false;

                if(!checkFirstPage) return false;
            }

            return true;
        },
        clearCloseCookie: function(type) {
            // console.log('clearCloseCookie('+type+')');
            var isBoth = (typeof type == 'undefined') ? true : false,
                isBand = (isBoth || !isBoth && type == 'band') ? true : false,
                isPopup = (isBoth || !isBoth && type == 'popup') ? true : false;

            if(isBand) {
                var band_id = $.siteBanner.sid + 'BandBanner';
                $.removeCookie(band_id, { path : '/' });
            }
            if(isPopup) {
                if(typeof $.siteBanner.popup != 'undefined' && typeof $.siteBanner.popup.list != 'undefined') {
                    $.each($.siteBanner.popup.list, function(id,o) {
                        var popup_id = $.siteBanner.sid + 'PopupBanner' + id;
                        $.removeCookie(popup_id, { path : '/' });
                    });
                }
            }
        },
        doNotOffer: function(type,isSC) {
            // console.log('doNotOffer(type:'+type+', isSC: '+isSC+')');
            if(isSC) $.siteBanner.clearCloseCookie(type);

            var isBoth = (typeof type == 'undefined') ? true : false,
                isBand = (isBoth || !isBoth && type == 'band') ? true : false,
                isPopup = (isBoth || !isBoth && type == 'popup') ? true : false;

            if(isBand) {
                $.siteBanner.stopBandRolling();

                $('body, .cl-bandBanner').removeClass('openBandBanner');
                $('.cl-bandBanner, .el-menu_ctrl, .header.el-menu > header').removeInlineCss('margin-top');
                document.querySelector('.dsgn-body').style.setProperty('--bandBanner-height-pc', null, null);
                document.querySelector('.dsgn-body').style.setProperty('--bandBanner-height-mobile', null, null);
                if($('.dsgn-body').hasClass('sidebar')) $('.dsgn-body').removeInlineCss('padding-top');
                $('.cl-bandBanner').remove();
                $('.element[data-type="gallery"][data-type2="premium"]').refreshRootCss();
                
                $.fheader.position();
            }
            if(isPopup) {
                $('body, .cl-popupBanner').removeClass('openPopupBanner');
                $('.cl-popupBanner').remove();
            }
        },
        init: function(checkBand,checkPopup) {
            // console.log('init('+checkBand+','+checkPopup+')');
            if(checkBand) $.siteBanner.call('band',false,true,true,true);
            if(checkPopup) $.siteBanner.call('popup',false,true,true,true);

            if(typeof property == 'undefined') {
                $(document).on('mouseenter', '.cl-bandBanner, .cl-popupBanner', function() {
                    if(isEDIT) return;
                    else outElementButtonDisplay();
                });
            }

            $(document).on('mouseenter', '.cl-bandBanner', function() {
                $.siteBanner.band.paused = true;
            }).on('mouseleave', '.cl-bandBanner', function() {
                $.siteBanner.band.paused = false;
            });

            $(document).on('click','.cl-bandBanner .banner-body > a, .cl-popupBanner .banner-body > a', function() {
                if($(this).is('[href="javascript:;"]') || $(this).hasClass('clicked')) return false;
                $(this).addClass('clicked');

                setTimeout(function() {
                    $(this).removeClass('clicked');
                }, 3000);
            });

            $(document).on('click','.cl-bandBanner .banner-closetoday,\
                                    .cl-bandBanner .banner-close,\
                                    .cl-popupBanner .banner-closetoday,\
                                    .cl-popupBanner .banner-close', function() {
                var bannerEL = $(this).closest('.banner-box'),
                    banner_id = bannerEL.attr('id'),
                    banner_type = bannerEL.attr('data-type'),
                    banner_closetime = bannerEL.attr('data-closetime'),
                    clickBtn = $(this),
                    isCloseToday = $(this).is('.banner-closetoday'),
                    date = new Date();
                if(banner_type == 'band' && !clickBtn.closest('.banner-header').find('.banner-closetoday').hasClass('hide')) isCloseToday = true;

                var time_val = {
                    'always'    : 0,
                    'onlyone'   : 365 * 24 * 60 * 60 * 1000,
                    'week'      : 7 * 24 * 60 * 60 * 1000, 
                    'day'       : 24 * 60 * 60 * 1000, 
                    '12hours'    : 12 * 60 * 60 * 1000, 
                    '6hours'     : 6 * 60 * 60 * 1000, 
                    '2hours'     : 2 * 60 * 60 * 1000, 
                    '1hours'     : 60 * 60 * 1000, 
                    '30min'     : 30 * 60 * 1000, 
                    '10min'     : 10 * 60 * 1000, 
                    '3min'      : 3 * 60 * 1000,
                };

                if(isCloseToday) date.setTime(date.getTime() + time_val['day']);
                else date.setTime(date.getTime() + time_val[banner_closetime]);

                if(banner_type == 'band') {
                    $.siteBanner.stopBandRolling();
                    banner_id = banner_id.replace(/BandBanner[0-9]+$/,'BandBanner');
                }

                $('#'+banner_id).addClass('hide');
                if(isCloseToday || (typeof banner_closetime != 'undefined' && banner_closetime != 'always' && banner_closetime != '')) {
                    $.cookie(banner_id, true, { path: '/', expires: date});
                }
                $.siteBanner[banner_type].total--;
                if(banner_type == 'band') {
                    $.siteBanner.band.used = false;
                    $.siteBanner.call('band',false,false,true,true);
                }
            });
        },

        call: function(type,isSC,isGet,isSet,isPosition) {
            // console.log('call(type: '+type+',isSC: '+isSC+',isGet: '+isGet+',isSet: '+isSet+',isPosition: '+isPosition+')')
            var parentDocument = $(window.parent.document),
                $detail_modal = parentDocument.find('.product-detail-modal');
            if($detail_modal.length) return false;            
            var isOffer = $.siteBanner.checkOffer(type);
            if(!isSC && !isOffer) {
                $.siteBanner.doNotOffer(type,isSC);
                return false;
            }

            var isBand = (type == 'band') ? true : false,
                isPopup = (type == 'popup') ? true : false,
                banner_fn_obj = {'call':false, 'get':false, 'set':false, 'position':false};

            if(isBand) {
                if(typeof $.siteBanner.band == 'undefined') $.siteBanner.band = {'seqs':[], 'paused':false};
                else $.siteBanner.stopBandRolling();

                $.siteBanner.band.body = ($.inArray(PAGE_MODE, ['s','r']) > -1) ? window : '.dsgn-body';
                if(isSC) {
                    var band_fn = banner_fn_obj;
                    if( typeof $.siteBanner.band != 'undefined' && 
                        typeof $.siteBanner.band.fn != 'undefined' &&
                        typeof $.siteBanner.band.fn_keep != 'undefined'
                    ) {
                        band_fn = $.siteBanner.band.fn;
                        delete $.siteBanner.band.fn_keep;
                    }
                    $.siteBanner.band.fn = band_fn;
                }
            }
            if(isPopup) {
                if(typeof $.siteBanner.popup == 'undefined') $.siteBanner.popup = {};
                if(isSC) {
                    var popup_fn = banner_fn_obj;
                    if( typeof $.siteBanner.popup != 'undefined' && 
                        typeof $.siteBanner.popup.fn != 'undefined' &&
                        typeof $.siteBanner.popup.fn_keep != 'undefined'
                    ) {
                        popup_fn = $.siteBanner.popup.fn;
                        delete $.siteBanner.popup.fn_keep;
                    }
                    $.siteBanner.popup.fn = popup_fn;
                }
            }

            var step1 = $.siteBanner.get(type,isSC,isGet);
            step1.done(function() {
                var step2 = $.siteBanner.set(type,isSC,isSet);
                step2.done(function() {
                    if($.siteBanner[type].used) {
                        var step3 = $.siteBanner.position(type,isSC,isPosition);
                        step3.done(function(step3_r) {
                            fixedConfigBtn();
                        }).fail(function(step3_error) {
                        });
                    }
                }).fail(function(step2_error) {
                });
            }).fail(function(step1_error) {
            });
        },

        get: function(type,isSC,isGet) {
            // console.log('get(type: '+type+',isSC: '+isSC+',isGet: '+isGet+')');
            var deferred01 = $.Deferred(),
                isBand = (type == 'band') ? true : false,
                isPopup = (type == 'popup') ? true : false,
                publish = (typeof property != 'undefined') ? property.PUBLISH : false;

            if(!isGet) deferred01.resolve();
            else {
                if(PAGE_MODE == 'c'){ // config(사이트편집)
                    $.post('/template/siteBanner/type/get',{ publish:publish, sid:$.siteBanner.sid, v:type }, function(data) {
                        checkError(data);
                        if(typeof data == 'object') {
                            $.siteBanner[type]['sort'] = data.sort;
                            $.siteBanner[type]['list'] = data.list;
                            $.siteBanner[type]['used'] = data.used;
                            $.siteBanner[type]['total'] = data.sort.length;
                            $.siteBanner[type]['close_time'] = data.close_time;
                            $.siteBanner[type]['close_today'] = data.close_today;
    
                            if(isBand) {
                                $.siteBanner[type]['close_onoff'] = data.close_onoff;
                                $.siteBanner[type]['interval'] = data.interval;
                            }
                            if(isPopup) {
                                $.siteBanner[type]['position'] = data.position;
                            }
                            deferred01.resolve();
                        } else {
                            deferred01.reject('get error');
                        }
                    }, 'json');

                }else{ // render / site
                    // console.log(RENDER.b);
                    if(isBand && RENDER.b.BAND != '') {
                        $.siteBanner['band']['close_onoff'] = RENDER.b.BAND.close_onoff;
                        $.siteBanner['band']['interval'] = RENDER.b.BAND.interval;
                        $.siteBanner['band']['sort'] = RENDER.b.BAND.sort;
                        $.siteBanner['band']['list'] = RENDER.b.BAND.list;
                        $.siteBanner['band']['used'] = RENDER.b.BAND.used;
                        $.siteBanner['band']['total'] = RENDER.b.BAND.sort.length;
                        $.siteBanner['band']['close_time'] = RENDER.b.BAND.close_time;
                        $.siteBanner['band']['close_today'] = RENDER.b.BAND.close_today;
                    }
                    if(isPopup && RENDER.b.POPUP != '') {
                        $.siteBanner['popup']['position'] = RENDER.b.POPUP.position;
                        $.siteBanner['popup']['sort'] = RENDER.b.POPUP.sort;
                        $.siteBanner['popup']['list'] = RENDER.b.POPUP.list;
                        $.siteBanner['popup']['used'] = RENDER.b.POPUP.used;
                        $.siteBanner['popup']['total'] = RENDER.b.POPUP.sort.length;
                        $.siteBanner['popup']['close_time'] = RENDER.b.POPUP.close_time;
                        $.siteBanner['popup']['close_today'] = RENDER.b.POPUP.close_today;
                    }
                    deferred01.resolve();
                }
                
            }

            return deferred01.promise();
        },
        set: function(type,isSC,isSet) {
            // console.log('set(type: '+type+',isSC: '+isSC+',isSet: '+isSet+')');
            var deferred02 = $.Deferred(),
                isBand = (type == 'band') ? true : false,
                isPopup = (type == 'popup') ? true : false,
                onoff = $.siteBanner[type].used;

            if(isSet && onoff) {
                var banner_name = $.siteBanner.sid + (type.charAt(0).toUpperCase() + type.slice(1)) + 'Banner',
                    b_list = '',
                    b_idx = 0, b_show = 0,
                    min = [120, 150],
                    max = [0, 0],
                    sum = [0, 0];

                $.each($.siteBanner[type].sort, function(idx,id) {
                    var o = $.siteBanner[type].list[id],
                        isVisible = (o.visible == 'ON') ? true : false;
                        // console.log(o);
                    if(!isSC && o.period.set && o.period.visible === false) isVisible = false;
                    if(!isSC && isVisible || isSC) {
                        var banner_id =  banner_name + id,
                            banner_cookie = (type == 'band') ? banner_name : banner_id,
                            isCookie = (typeof $.cookie(banner_cookie) != 'undefined' && $.cookie(banner_cookie)) ? true : false;

                        b_idx++;
                        if(!isCookie || isSC) {
                            b_show++;

                            if(isVisible) {
                                if(min[0] > Number(o.img.pc.height)) min[0] = Number(o.img.pc.height);
                                if(max[0] < Number(o.img.pc.height)) max[0] = Number(o.img.pc.height);
                                if(max[1] < Number(o.img.mobile.height)) max[1] = Number(o.img.mobile.height);
                                sum[0] += Number(o.img.pc.width);
                                sum[1] += Number(o.img.mobile.width);
                            }
                        }
                        var period_label = (o.period.chk == 1) ? '' : o.period.label;
                        var banner_label = (isSC) ? '\
                                            <ul class="banner-label" data-period-label="'+period_label+'">\
                                                <li class="period-start">' + $.lang[LANG]['sc.banner.period.label.start'] + '</li>\
                                                <li class="period-end">' + $.lang[LANG]['sc.banner.period.label.end'] + '</li>\
                                            </ul>\
                            ' : '',
                            banner_str = '';
                        if(type == 'band') {
                            var band_img_arr = [o.img.pc.path, o.img.mobile.path],
                                band_img_mobile = (o.img.mobile.chk == '0') ? true : false,
                                band_img_root = (isSC) ? ['--scbandBanner-img-pc','--scbandBanner-img-mobile'] : ['--bandBanner-img-pc','--bandBanner-img-mobile'];
                            $.each(band_img_arr, function(img_i,img_v) {
                                var check_img = $('<img data-id="' + id + '" data-root="' + band_img_root[img_i] + '" data-sc="' + isSC + '"/>').attr('src',img_v);
                                check_img.error(function() {
                                    var img_id = $(this).attr('data-id'),
                                        img_root = $(this).attr('data-root'),
                                        checkSC = $(this).attr('data-sc'),
                                        img_s = (checkSC == 'true') ? 'sc-bandBanner' : 'cl-bandBanner';
                                    document.querySelector('.'+img_s+' .banner-box[data-id="'+img_id+'"] .banner-img').style.setProperty(img_root, 'url(//storage.googleapis.com/i.addblock.net/img_broken_fill_500.png)', null);
                                });
                            });

                            var banner_img_style = `${band_img_root[0]}: url(${band_img_arr[0]}); ${band_img_root[1]}: url(${(band_img_mobile) ? band_img_arr[1] : band_img_arr[0]});`;
                            banner_str = '\
                                <li class="banner-box" id="' + banner_id + '">\
                                    <div class="banner-content">\
                                        <div class="banner-body">\
                                            <a href="javascript:;">\
                                                <div class="banner-img" style="' + banner_img_style + '">\
                                                    <div class="img-banner"></div>\
                                                </div>\
                                            </a>\
                                            ' + banner_label + '\
                                        </div>\
                                        <div class="banner-header">\
                                            <span class="banner-closetoday">' + $.lang[LANG]['editor.banner.close.today'] + '</span>\
                                            ' + clSVG('close',12,12,true,'banner-close') + '\
                                        </div>\
                                    </div>\
                                </li>\
                            ';
                        } else if(type == 'popup') {
                            var popup_img_style = `<img src="${o.img.pc.path}" alt="" class="img-responsive img-banner pc" onerror="this.src=\'//storage.googleapis.com/i.addblock.net/img_broken_fill_500.png\'"/><img src="${(o.img.mobile.chk == '1') ? o.img.pc.path : o.img.mobile.path}" alt="" class="img-responsive img-banner mobile" onerror="this.src=\'//storage.googleapis.com/i.addblock.net/img_broken_fill_500.png\'"/>`;

                            banner_str = '\
                                <li class="banner-box" id="' + banner_id + '">\
                                    <div class="banner-content">\
                                        <div class="banner-header">' + clSVG('close',12,12,true,'banner-close') + '</div>\
                                        <div class="banner-body">\
                                            <a href="javascript:;">\
                                                <div class="banner-img">\
                                                    '+ popup_img_style +'\
                                                </div>\
                                            </a>\
                                            ' + banner_label + '\
                                        </div>\
                                        <div class="banner-footer clearfix">\
                                            <div class="banner-btn-wrap">\
                                                <span class="banner-btn banner-closetoday">' + $.lang[LANG]['editor.banner.close.today'] + '</span>\
                                                <span class="banner-btn banner-close">' + $.lang[LANG]['config.close'] + '</span>\
                                            </div>\
                                        </div>\
                                    </div>\
                                </li>\
                            ';
                        }

                        var bannerItem = $(banner_str);
                        bannerItem.attr('data-id', id);
                        bannerItem.attr('data-type', type);
                        if(isSC) {
                            if(!isVisible) bannerItem.addClass('hide');
                            if(o.link.val) {
                                var blink_o = $.siteBanner.getLINK(o.link.val, o.link.target);
                                if(blink_o.link) {
                                    bannerItem.find('a').addClass('active');
                                }                            
                            }
                        } else {
                            if(isCookie) bannerItem.addClass('hide');
                            bannerItem.attr('data-closetime', $.siteBanner[type].close_time);
                            if(o.link.val) {
                                var blink_o = $.siteBanner.getLINK(o.link.val, o.link.target);
                                if(blink_o.link) {
                                    bannerItem.find('a').attr('href', blink_o.link);
                                    if(blink_o.target) bannerItem.find('a').attr('target', blink_o.target);
                                    $.each(blink_o.option, function(o_k, o_v) {
                                        bannerItem.find('a').attr(o_k, o_v);
                                    });
                                }
                            }
                        }
                        bannerItem.css('background-color',o.img.bgcolor);
                        bannerItem.find('.banner-header .banner-closetoday').css('color',o.close.color);
                        bannerItem.find('.banner-header .banner-close.cl-icon > svg').css('fill',o.close.color);

                        if($.siteBanner[type].close_today == 'OFF') bannerItem.find('.banner-closetoday').addClass('hide');
                        if(type == 'band' && $.siteBanner[type].close_onoff == 'OFF') bannerItem.find('.banner-header').addClass('hide');

                        b_list += bannerItem.outerHTML();
                    }
                });

                if(b_show > 0) {
                    $.siteBanner[type].total = b_show;
                    if(isBand) {
                        $.siteBanner[type].min_h = min;
                    } else if(isPopup) {
                        $.siteBanner[type].total_w = sum;
                        $.siteBanner[type].max_h = max;
                    }

                    if(isSC) {
                        var sc_device = $('#el-siteConfig .sc-device-wrap > li.active').attr('data-device');
                        $('#el-siteConfig .sc-siteBanner').replaceWith('\
                            <div class="sc-siteBanner sc-' + type + 'Banner '+sc_device+'">\
                                <div class="banner-modal">\
                                    <ul>' + b_list + '</ul>\
                                    <div class="banner-description" data-closetoday="m"><span>' + clSVG('info',18,18,true,'') + $.lang[LANG]['sc.banner.band.close.today.m'] + '</span></div>\
                                    <div class="banner-description" data-overflow="x"><span>' + clSVG('info',18,18,true,'') + $.lang[LANG]['sc.banner.popup.position.overflow'] + '</span></div>\
                                </div>\
                            </div>\
                        ');
                    } else {
                        var bannerEL = $('\
                            <div class="cl-' + type + 'Banner">\
                                <div class="banner-modal">\
                                    <ul>' + b_list + '</ul>\
                                </div>\
                            </div>\
                        ');

                        if($('.cl-'+type+'Banner').length > 0) $('.cl-'+type+'Banner').remove();
                        $('.dsgn-body').prepend(bannerEL);
                    }
                } else {
                    delete $.siteBanner[type].min_h;
                    delete $.siteBanner[type].total_w;

                    $.siteBanner[type].total = 0;
                    $.siteBanner[type].used = false;
                    $.siteBanner.doNotOffer(type,isSC);
                }

                deferred02.resolve();
            } else {
                if(isSet && !onoff) $.siteBanner.doNotOffer(type,isSC);
                deferred02.resolve();
            }

            return deferred02.promise();
        },
        position: function(type,isSC,isPosition) {
            // console.log('position(type: '+type+',isSC: '+isSC+',isPosition: '+isPosition+')');
            var deferred03 = $.Deferred(),
                isBand = (type == 'band') ? true : false,
                isPopup = (type == 'popup') ? true : false;

            if(!isPosition) {
                deferred03.resolve();
            } else {

                if(isBand) {
                    $.siteBanner.stopBandRolling();

                    var m_h = $.siteBanner[type].min_h[0],
                        m_h2 = $.siteBanner[type].min_h[1];
                    if(m_h > 120) m_h = 120;
                    if(m_h2 != 50) m_h2 = 50;

                    if(isSC) {
                        $('#el-siteConfig .sc-siteBanner').attr('data-min-p',m_h).attr('data-min-m',m_h2);
                        document.querySelector('#el-siteConfig .sc-siteBanner').style.setProperty('--scbandBanner-height-pc', m_h+'px', null);
                        document.querySelector('#el-siteConfig .sc-siteBanner').style.setProperty('--scbandBanner-height-mobile', m_h2+'px', null);

                        var sc_device = $('#el-siteConfig .sc-device-wrap > li.active').attr('data-device');
                        if(sc_device == 'm') $('#el-siteConfig .sc-siteBanner .banner-description[data-closetoday="m"]').addClass('active');
                        else $('#el-siteConfig .sc-siteBanner .banner-description[data-closetoday="m"]').removeClass('active');
                    } else {
                        document.querySelector('.dsgn-body').style.setProperty('--bandBanner-height-pc', m_h+'px', null);
                        document.querySelector('.dsgn-body').style.setProperty('--bandBanner-height-mobile', m_h2+'px', null);

                        $('body, .cl-bandBanner').addClass('openBandBanner');
                        $('.element[data-type="gallery"][data-type2="premium"]').refreshRootCss();

                        var parentDocument = $(window.parent.document),
                            $detail_modal = parentDocument.find('.product-detail-modal');
                        if($detail_modal.length) $('.cl-bandBanner').addClass('detail');                  

                        var isPB = (typeof property != 'undefined') ? true : false,
                            isHeader = ($('.el-menu header.navbar').hasClass('transparent')) ? true : false,
                            isSidebar = ($('.el-menu header.navbar').hasClass('sidebar')) ? true : false,
                            header_h = (isHeader || (isSidebar && $('body').width() > 767)) ? 0 : $('.el-menu header.navbar').outerHeight(),
                            band_h = ($('body').width() > 767) ? m_h : m_h2;
                        $('.dsgn-body').css('padding-top', (band_h+header_h)+'px'); 

                        if($.siteBanner.band.total > 1) {
                            var rolling_id = setInterval($.siteBanner.setBandRolling, $.siteBanner.band.interval);
                            $.siteBanner.band.seqs.push(rolling_id);
                            $('.cl-bandBanner').attr('data-seq',rolling_id);
                        }

                        $($.siteBanner.band.body).scroll(function(event) {
                            if($('.cl-bandBanner').hasClass('openBandBanner') && $('.element[data-type="gallery"][data-type2="premium"][data-feature*="fixedscroll"]').length == 0) {
                                if($(this).scrollTop() < $('.cl-bandBanner').outerHeight()) {
                                    if($('.header.el-menu > header').hasClass('transparent')) $('.dsgn-body').css('padding-top',$.siteBanner.getBandHeight()+'px');
                                    $('.cl-bandBanner, .el-menu_ctrl, .header.el-menu > header').css('margin-top',-$(this).scrollTop()+'px');
                                } else {
                                    if($('.header.el-menu > header').hasClass('transparent')) $('.dsgn-body').css('padding-top',$.siteBanner.getBandHeight()+'px');
                                    $('.cl-bandBanner, .el-menu_ctrl, .header.el-menu > header').css('margin-top',-$('.cl-bandBanner').outerHeight()+'px');
                                }
                            }
                        });
                    }

                    deferred03.resolve();
                } else if(isPopup) {
                    var body_w = (isSC) ? $('#el-siteConfig .sc-popupBanner').width() : $('.dsgn-body').width(),
                        device_idx = (body_w <= 767) ? 1 : 0,
                        device_offset = 30 + (($.siteBanner.popup.total - 1) * 30),
                        p_overflow = ((body_w - device_offset) <= $.siteBanner.popup.total_w[device_idx]) ? true : false,
                        p_arr = $.siteBanner.popup.position.split(' '),
                        p_justify = (typeof p_arr != 'undefined') ? p_arr[0] : 'center',
                        p_align = (typeof p_arr != 'undefined') ? p_arr[1] : 'center',
                        p_selector = (isSC) ? '.sc-popupBanner' : '.cl-popupBanner';

                    $(p_selector+' > .banner-modal').attr('data-justify', p_justify)
                                                        .attr('data-align', p_align)
                                                        .attr('data-overflow', p_overflow);

                    if(p_overflow) {
                        // 계단식
                        var pi_i = $(p_selector+' .banner-box:not(.hide)').length;
                        $(p_selector+' .banner-box:not(.hide)').each(function(i) {
                            var pi_top = (i+1) * 30,
                                pi_margin_right = pi_i * 30;
                            $(this).css({'top':pi_top+'px', 'left':pi_top+'px', 'margin-right':pi_margin_right+'px'});
                            pi_i--;
                        });
                    } else {
                        // 나열
                        $(p_selector+' .banner-box:not(.hide)').each(function(i) {
                            $(this).removeInlineCss('top left margin-right');
                        });
                    }

                    if(!isSC) {
                        $(window).resize(function() {
                            if(this.resizeTO) {
                                clearTimeout(this.resizeTO);
                            }
                            this.resizeTO = setTimeout(function() {
                                $(this).trigger('resizeEnd');
                            }, 500);
                        });
                        $(window).on('resizeEnd', function() {
                            if($('.cl-popupBanner').hasClass('openPopupBanner')) {
                                var reposition = $.siteBanner.position('popup',isSC,true);
                                reposition.done(function(rp_r) {
                                }).fail(function(rp_error) {
                                });
                            }
                        });

                        setTimeout(function() {
                            var isPB = (typeof property != 'undefined') ? true : false,
                                band_h = $.siteBanner.getBandHeight(),
                                header_h = ($('.el-menu header.navbar').hasClass('transparent')) ? 0 : $('.el-menu header.navbar').outerHeight(),
                                popup_t = band_h + header_h,
                                popup_l = 0;
                            if($('.el-menu header.navbar').hasClass('sidebar')) {
                                if($('body').width() > 767) {
                                    popup_t = band_h;
                                    if(isPB) popup_l = 260;
                                    if($('.dsgn-body').hasClass('mode-render')) document.querySelector('.cl-popupBanner').style.setProperty('width', 'calc(100% - 260px)', null);
                                }
                            }

                            $('.cl-popupBanner').css({'top':parseInt(popup_t)+'px','left':popup_l+'px'});
                            if(!p_overflow) $(p_selector).css('bottom',0);
                            $('body, .cl-popupBanner').addClass('openPopupBanner');
                        }, 300);
                    }
                    deferred03.resolve();
                }
            }
            return deferred03.promise();
        },

        getLINK: function(org_link,org_ltarget) {
            var link = (typeof org_link == 'string' && org_link != 'javascript:;' && org_link.length > 0) ? org_link : 'javascript:;',
                link_target = (typeof org_ltarget != 'undefined' && (org_ltarget == '1' || org_ltarget == 'ON')) ? '_blank' : '',
                link_option = {};

            if(link != '' && link != 'javascript:;') {
                var _menuList = (PAGE_MODE == 'c') ? MENULIST : property.MENULIST;
            
                if(link.match(/^\@/g) !== null) {                                                  // link-type: link-bookmark ==> a[attr-bookmark]
                    var _settings = (PAGE_MODE == 'c') ? SETTINGS : property.SETTINGS,
                        bookmark_seq = link.replace(/^\@/g,'');
                        
                    if(typeof _settings == 'undefined' || typeof _settings.blockBookmarkList == 'undefined' || _settings.blockBookmarkList['bookmark' + bookmark_seq] == 'undefined') {
                        link = '';
                        link_option = {};
                    } else {
                        link_option['attr-bookmark'] = bookmark_seq;
                    }
                } else if(link.match(/^flink\@[0-9]/gi) !== null) {                                // link-type: link-file     ==> a[attr-flink]
                    link_option['attr-flink'] = link.replace(/^flink\@/gi,'');
                    link_target = '';
                } else if(_menuList.indexOf(link.replace(/^\//g,"").replace(/ /g,"-")) > -1) {     // link-type: link-menu     ==> a[data-user-link]
                    link_option['data-user-link'] = link;
                } else {                                                                            // link-type: link-out      ==> a[attr-link]
                    link_option['attr-link'] = link;
                }

                link = (PAGE_MODE == 'c') ? makeLinkUrl(link, ONE, VIEW) : makeLinkUrl(link, property.ONE, property.VIEW);
            }

            return {'link':link, 'target':link_target, 'option':link_option};
        },
        getBandHeight: function() {
            if($('body').hasClass('openBandBanner')) {
                var bandbanner_p = getComputedStyle(document.querySelector('.dsgn-body')).getPropertyValue('--bandBanner-height-pc'),
                    bandbanner_m = getComputedStyle(document.querySelector('.dsgn-body')).getPropertyValue('--bandBanner-height-mobile');

                if($('body').width()>767) return parseInt(bandbanner_p);
                else return parseInt(bandbanner_m);
            } else {
                return 0;
            }
        },
        setBandRolling: function() {
            if($.siteBanner.band.paused) return false;

            var bannerEL = $('.cl-bandBanner[data-seq="'+$.siteBanner.band.seqs[$.siteBanner.band.seqs.length - 1]+'"]');
            if(bannerEL.length == 0) return false;
            var bannerUL = bannerEL.find('.banner-modal > ul'),
                banner_h = $.siteBanner.getBandHeight(),
                banner_l = bannerUL.children('.banner-box:not(.hide)').length;

            bannerUL.animate({ top: -banner_h+'px' }, 1000, 'easeInOutQuart', function() {
                $(this).append($(this).find('li.banner-box:not(.hide)').eq(0).clone().wrapAll('<li />').parent().html());

                $(this).find('li.banner-box:not(.hide)').eq(0).remove();
                $(this).css('top', 0);
            });
        },
        stopBandRolling: function() {
            var seq = ($('.cl-bandBanner').length > 0) ? $('.cl-bandBanner').attr('data-seq') : 0,
                seq_arr = (typeof $.siteBanner.band != 'undefined' && typeof $.siteBanner.band.seqs != 'undefined') ? $.siteBanner.band.seqs : [];

            if(seq) clearInterval(seq);
            $.each(seq_arr, function(i,v) {
                clearInterval(v);
            });

            if(seq_arr.length > 0) {
                $.siteBanner.band.seqs = [];
                $.siteBanner.band.paused = false;
            }
        },
    }

    $.fixedContact = {
        init: function($el) {
            // console.log('fixedContact init');
            let sid = (typeof property != 'undefined')? property.SID : SID;
            let onoff = (typeof $.cookie('fixedcontact-' + sid) != 'undefined')? $.cookie('fixedcontact-' + sid) : 'on';

            $el.addClass('el-fixedcontact');
            if(onoff == 'off') $el.addClass('down');
            
            if($.fnav.checkFnavON()) $el.addClass('has-fnav');
            setTimeout(function(){
                $.fixedContact.addBtn($el);
            }, 100);
        },
        addBtn: function($el) {
            let bgcolor = $el.css('background-color');
            let bgimg = $el.css('background-image');
            let bgPos = $el.css('background-position');
            let btnBackground = 'background-color:'+bgcolor+';';
            let btnHTML = '<div class="fixedcontact-onoff hand" style="' + btnBackground + '"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" width="20" height="20"><path d="M10 13.7 3.6 7.4l.8-.8 5.6 5.7 5.6-5.7.8.8-6.4 6.3z"/></svg></div>';
            $el.append(btnHTML);

            if(PAGE_MODE != 'c') {
                $(document).off('click', '.fixedcontact-onoff');
                $(document).on('click', '.fixedcontact-onoff', function(){
                    let sid = property.SID;
                    let date = new Date();
                    date.setTime(date.getTime() + 6*60*60*1000); // 6h
                    $('.el-fixedcontact').toggleClass('down');
                    if($('.el-fixedcontact').hasClass('down')) {
                        $.cookie('fixedcontact-' + sid, 'off', { expires: date, path : '/' });
                    } else {
                        $.cookie('fixedcontact-' + sid, 'on', { expires: date, path : '/' });
                    }
                });

                $.fixedContact.checkPosition($('.el-fixedcontact'));

                $(window).on('scroll', function() {
                    $.fixedContact.checkPosition($('.el-fixedcontact'));
                });
            }
        },
        checkPosition: function($el) {
            if(PAGE_MODE != 'c' && $el.length > 0) {
                let isNotFixed = $el.hasClass('notfixed');
                let scrollTop = $(window).scrollTop();
                let windowHeight = $(window).height();
                let documentHeight = $(document).height();
                let footerTop = ($('.el-footer').length > 0 && $('.el-footer').hasClass('hide') == false)? $('.el-footer').offset().top : documentHeight - $el.outerHeight();
                if($el.hasClass('has-fnav')) footerTop -= 53;
                let distanceScrolled = (isNotFixed)? Math.max(0, scrollTop + windowHeight - footerTop + $el.outerHeight()) : Math.max(0, scrollTop + windowHeight - footerTop);
                // console.log('windowHeight', windowHeight);
                // console.log('scrollTop', scrollTop);
                // console.log('footerTop', footerTop);
                // console.log('documentHeight', documentHeight);
                // console.log('distanceScrolled', distanceScrolled);

                if (distanceScrolled > 0 && !isNotFixed) {
                    $el.addClass('notfixed');
                } else if (distanceScrolled <= 0 && isNotFixed) {
                    $el.removeClass('notfixed');
                }
            }
        }
    }

    // $(".element").removeInlineCss("color font-size font-weight");
    jQuery.fn.removeInlineCss = function (properties) {
        if (properties == null) return this.removeAttr('style');
        properties = properties.split(/\s+/);
        return this.each(function () {
            for (var i = 0; i < properties.length; i++)
                this.style.removeProperty(properties[i])
        });
    }

    jQuery.fn.refreshRootCss = function(property_key) {
        var isAll = (typeof property_key == 'undefined' || property_key == '') ? true : false;

        // property_key == '--menu-height'
        var mh = getMenuHeight(),
            bh = $.siteBanner.getBandHeight();
        this.each(function() {
            if(!$(this).is('[data-el^="el_"]') || !$(this).is('[data-type="gallery"][data-type2="premium"]')) return true;

            if(isAll || property_key == '--menu-height') {
                var __target = $(this).attr('data-el'),
                    __menu_height = getComputedStyle(document.querySelector('.'+__target)).getPropertyValue('--menu-height');
                if(typeof __menu_height != 'undefined' && __menu_height) document.querySelector('.'+__target).style.setProperty('--menu-height', (mh+bh)+'px', null);
            }
        });
    }

    //mobile정보 가져오기
    var mrequest_uri = location.pathname + location.search;
    function getMobileInfo(data) {        
        var page = location.pathname.split('/')[1],
            mb = data.mb,
            paidUser = data.paidUser,
            settings_url = data.settings_url,
            sid = data.sid,
            valid_plan = data.valid_plan,
            site_nickname =  (typeof $('.site-username').text() != 'undefined' && $('.site-username').text()) ? $('.site-username').text() : data.site_nickname,
            site_profile = (typeof $('#dashboard-image-top image').attr('xlink:href') != 'undefined' && $('#dashboard-image-top image').attr('xlink:href')) ? $('#dashboard-image-top image').attr('xlink:href') : data.site_profile,
            umprofile = data.umprofile,
            newCount = data.newCount,
            checkGabia = (data.service.indexOf('gabia') > -1) ? true : false;

        mb.mb_id = (mb.mb_id) ? mb.mb_id : mb.um_id;

        if(mb.mb_id){
            var empty = (mb.mb_id) ? '' : 'empty',
                newMessage = (newCount == 0) ? false : true,
                badge = newMessage ? "<span class='badge'></span>" : "";

            var adminhtml = (mb.mb_level >= 10) ? '<li><a href="/adm" target="_blank">Admin</a></li>' : '',
                mypage = (checkGabia) ? '/dashboard' : '/mypage',
                uadminmypage = (data.is_uadmin == false) ? mypage : 'javascript:;',
                siteum = (data.is_uadmin == false) ? '' : 'siteUM',
                mypage = (data.is_uadmin == false) ? '' : 'mypage',
                dashboarduadmin = (data.is_uadmin == false) ? '/' : '/_admin/dashboard', 
                marketinguadmin = (data.is_uadmin == false) ? '/marketing' : '/_admin/marketing';


                

            var str = '<div class="nav navbar-nav navbar-right">\
                            <div class="mobile-menu">\
                                    <div class="m-myinfo">\
                                        <div class="profile_left">\
                                            <label class="m-profile hand '+umprofile+'" data-user-img="'+site_profile+'" data-user-plan="'+paidUser+'" data-user-um="'+umprofile+'">\
                                                <svg viewBox="0 0 40 40" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" >\
                                                <pattern id="m-dashboard-image-top" patternUnits="userSpaceOnUse" width="60" height="60">\
                                                    <image xlink:href='+site_profile+' x="-10" width="60" height="40"></image>\
                                                </pattern><circle cx="20" cy="20" r="20" fill="url(#m-dashboard-image-top)"></circle></svg>\
                                            </label>\
                                            <div class="inner-box hand">\
                                                <span class="name-text m-profile m-text-size">'+site_nickname+'</span>\
                                            </div>\
                                        </div>\
                                        <div class="profile_right">';
                                            if(data.is_uadmin) {
                                                str += '<div class="mlogout siteUM"><a href="javascript:;" class="logout">'+$.lang[LANG]['header.logout']+'</a></div>';
                                            } else {
                                                str += '<div class="mlogout"><a href="/member/login/out">'+$.lang[LANG]['header.logout']+'</a></div>';
                                            }
                                str +=  '</div>\
                                    </div>\
                                    <div class="mMymenu-wrap"><ul class="mMymenu">'; 
                                    var newCountlink = (data.is_uadmin == false) ? '/' : '/_admin';
                                            str +=  '<li class="newCount prorightmenu">\
                                                    <a href="'+newCountlink+'" class='+empty+'><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 18 18" width="18px" height="18px"><path d="M16 16.5V9c0-3.6-2.75-6.58-6.25-6.96V0h-1.5v2.04C4.75 2.42 2 5.4 2 9v7.5H0V18h2 14 2v-1.5H16zM3.5 16.5V9c0-3.03 2.47-5.5 5.5-5.5s5.5 2.47 5.5 5.5v7.5H3.5z"/></svg>'+badge+'<span class="menu-title">'+$.lang[LANG]['header.bell']+'</span></a>\
                                                </li>\
                                                <li class="m-mypage prorightmenu '+siteum+'"><a href="'+uadminmypage+'" class="'+mypage+'"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 17 18" width="17px" height="18px"><path d="M11.55 10.08C13.03 9.09 14 7.41 14 5.5 14 2.46 11.54 0 8.5 0 5.46 0 3 2.46 3 5.5c0 1.91 0.97 3.59 2.45 4.58C2.27 11.31 0 14.4 0 18h1.5c0-3.86 3.14-7 7-7s7 3.14 7 7H17C17 14.4 14.73 11.31 11.55 10.08zM4.5 5.5c0-2.21 1.79-4 4-4s4 1.79 4 4c0 2.21-1.79 4-4 4S4.5 7.71 4.5 5.5z"/></svg>\
                                                <span class="menu-title">'+$.lang[LANG]['header.mypage']+'</span></a></li>';
                                        
                                        if(!checkGabia) str += '<li class="m-langselect prorightmenu"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 18 18" width="18px" height="18px"><path d="M9 0C4.03 0 0 4.03 0 9c0 4.97 4.03 9 9 9s9-4.03 9-9C18 4.03 13.97 0 9 0zM15.33 5h-2.75c-0.27-1.2-0.65-2.25-1.11-3.07C13.08 2.49 14.43 3.58 15.33 5zM11.5 9c0 0.9-0.07 1.74-0.17 2.5H6.67C6.57 10.74 6.5 9.9 6.5 9s0.07-1.74 0.17-2.5h4.65C11.43 7.26 11.5 8.1 11.5 9zM9 16.5c-0.57 0-1.48-1.29-2.03-3.5h4.07C10.48 15.21 9.57 16.5 9 16.5zM6.97 5C7.52 2.79 8.43 1.5 9 1.5s1.48 1.29 2.03 3.5H6.97zM6.53 1.93C6.07 2.75 5.69 3.8 5.42 5H2.67C3.57 3.58 4.92 2.49 6.53 1.93zM1.94 6.5h3.22C5.06 7.29 5 8.13 5 9s0.06 1.71 0.16 2.5H1.94C1.66 10.72 1.5 9.88 1.5 9S1.66 7.28 1.94 6.5zM2.67 13h2.75c0.27 1.2 0.65 2.25 1.11 3.07C4.92 15.51 3.57 14.42 2.67 13zM11.47 16.07c0.47-0.82 0.85-1.87 1.11-3.07h2.75C14.43 14.42 13.08 15.51 11.47 16.07zM16.06 11.5h-3.22C12.94 10.71 13 9.87 13 9s-0.06-1.71-0.16-2.5h3.22C16.34 7.28 16.5 8.12 16.5 9S16.34 10.72 16.06 11.5z"/></svg>\
                                            <span class="menu-title">'+$.lang[LANG]['header.changeLang']+'</span></li>';
                                        str += '</ul></div>\
                                    <ul class="dropdown-menu" role="menu">'+adminhtml+
                                        '<li><a href="'+dashboarduadmin+'"  class="myhome-icon"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 18 16"  width="18px" height="16px"><path d="M9 0L0 7.03V16h6 6 6V7L9 0zM7.5 14.5v-4h3v4H7.5zM16.5 14.5H12V9H6v5.5H1.5V7.76L9 1.9l7.5 5.83V14.5z"/></svg>'+$.lang[LANG]['mobile.menu.title.mysite']+'</a></li>';
                                    
                                    var supportlink = (checkGabia) ? 'https://creatorlink-gabia.com/support' : ((LANG == 'ko') ? 'https://supportcenter.creatorlink.net/creatorlink/' : 'https://supportcenter.creatorlink.net/creatorlink-support-center'),
                                        helplink = (checkGabia) ? 'https://creatorlink.gabia.com/consult' : '/help',
                                        helptext = (checkGabia) ? $.lang[LANG]['mobile.menu.title.gabia.gotocts'] : $.lang[LANG]['mobile.menu.title.gotocts'],
                                        is_uadminMember = (data.is_uadmin) ? '_admin' : 'manager',
                                        memberlink = (valid_plan=='' || $.inArray(valid_plan['type'], ['BN','SM']) == -1) ? '#' : '/'+is_uadminMember+'/member/list',
                                        siteNotice = (valid_plan=='' || $.inArray(valid_plan['type'], ['BN','SM']) == -1) ? 'siteNotice("manager");' : '',
                                        kakaositeNotice = (valid_plan['plan'] == '') ? "siteNotice('notificationtalkmail')" : "";

                                    if(kakaositeNotice.length === 0){
                                        kakaotalkuadmin = (data.is_uadmin == false ) ? '/notificationtalkmail' : '/_admin/notificationtalkmail';
                                    } else {
                                        kakaotalkuadmin = '#a';
                                    }

                                    if(data.is_uadmin) helplink = (checkGabia) ? 'https://creatorlink.gabia.com/consult' : '/_admin/help';

                                    str += '<li class="m_memberlist" onclick='+siteNotice+'><a href="'+memberlink+'">'+$.lang[LANG]['mobile.menu.title.memberlist']+'</a></li>';

                                    if(LANG == 'ko' && (!checkGabia || (checkGabia && valid_plan['type'] == 'SM'))) {
                                        var applySm = (valid_plan['type'] == 'SM') ? '' : 'siteNotice(\'shopping\')',
                                            collapsed = (valid_plan['type'] == 'SM') ? 'collapsed' : '',
                                            smHide = ((valid_plan['type'] == 'BN') && (data.is_uadmin==true)) ? 'hide' : '';

                                        str += '\
                                        <li class="'+collapsed+' mshoppingtab '+smHide+'" onclick="'+applySm+'" data-toggle="collapse" data-target=".mshopping_menu" aria-expanded="true">\
                                            <a type="button" class="collapsed hand">' + $.lang[LANG]['mobile.menu.title.shopping'] + '</a>\
                                        ';
                                        
                                        if(valid_plan['type'] == 'SM') {
                                            var admin_url = (data.is_uadmin == false) ? '' : '/_admin';
                                            
                                            str +=  '\
                                                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10" width="10px" height="10px"><polygon points="9 2 5 6 1 2 0 3 4 7 5 8 6 7 10 3 "></polygon></svg>\
                                            </li>\
                                            <ul class="mshopping_menu collapse">\
                                                <li><a href="'+admin_url+'/shopping/product_search/order">'+$.lang[LANG]['mobile.menu.title.shopping.order']+'</a></li>\
                                                <li><a href="'+admin_url+'/shopping/product_search/cancel">'+$.lang[LANG]['mobile.menu.title.shopping.cancel']+'</a></li>\
                                                <li><a href="'+admin_url+'/shopping/product_search/return">'+$.lang[LANG]['mobile.menu.title.shopping.refund']+'</a></li>\
                                                <li><a href="'+admin_url+'/shopping/product_search/exchange">'+$.lang[LANG]['mobile.menu.title.shopping.change']+'</a></li>\
                                                <li><a href="'+admin_url+'/shopping/question_list/P">'+$.lang[LANG]['mobile.menu.title.shopping.qna']+'</a></li>\
                                                <li><a href="'+admin_url+'/shopping/product_search/all">'+$.lang[LANG]['mobile.menu.title.shopping.all']+'</a></li>\
                                                <li><a href="'+admin_url+'/shopping/statistics">'+$.lang[LANG]['mobile.menu.title.shopping.statistics']+'</a></li>\
                                                <li><a href="'+admin_url+'/shopping/point">'+$.lang[LANG]['mobile.menu.title.shopping.point']+'</a></li>\
                                                <li><a href="'+admin_url+'/shopping/coupon">'+$.lang[LANG]['mobile.menu.title.shopping.coupon']+'</a></li>\
                                                <li><a href="'+admin_url+'/shopping/setting/W">'+$.lang[LANG]['mobile.menu.title.shopping.setting']+'</a></li>\
                                            </ul>';
                                        } else {
                                            str += '</li>';
                                        }
                                    }

                                    var slog_li = '\
                                        <li><a href="'+admin_url+'/slog">'+$.lang[LANG]['mobile.menu.title.slog']+'</a></li>\
                                    ';

                                    if(valid_plan) {
                                        
                                        var pageactive = (page == 'settings') ? 'active' : '',
                                            settingslink = (page == 'settings') ? '#' : settings_url,
                                            helpbox = (data.is_uadmin == false) ? '<li><a href="'+helplink+'">'+helptext+'</a></li>' : ((data.su_eadmin == false) ? '' : '<li><a href="'+helplink+'">'+helptext+'</a></li>'),
                                            settingHide = (data.is_uadmin == true && data.su_eadmin == false) ? 'hide' : '';

                                        str += '<li class="m_marketing '+settingHide+'"><a href="'+marketinguadmin+'">'+$.lang[LANG]['mobile.menu.title.marketing']+'</a></li>';
                                             if(!checkGabia) str += '<li class=m_kakao " onClick="'+kakaositeNotice+'"><a href="'+kakaotalkuadmin+'">'+$.lang[LANG]['mobile.menu.title.kakao']+'</a></li>';
                                                str += '<li class="'+settingHide+'"><a href="'+settings_url+'">'+$.lang[LANG]['mobile.menu.title.settings']+'</a></li>\
                                        ';
                                        if(!checkGabia && data.is_uadmin == false) str += '<li class="m_plan '+settingHide+'"><a href="/plan">'+$.lang[LANG]['mobile.menu.title.plan.billing']+'</a></li>';
                                        if(valid_plan['type'] == 'SM' && LANG == 'ko') str += slog_li;
                                        if(!checkGabia &&  LANG == 'ko' && data.is_uadmin == false) {
                                            str += '<li><a href="/edu">교육</a></li>';
                                                    //<li><a href="/production">제작 의뢰 <span class="newicon">New</span></a></li>\
                                        }
                                        if(data.is_uadmin == false) str +='<li><a href="'+supportlink+'">'+$.lang[LANG]['mobile.menu.title.supportcenter']+'</a></li>';
                                        if(!checkGabia && data.is_uadmin == false)str += '<li><a href="/notice">'+$.lang[LANG]['mobile.menu.title.notice']+'</a></li>';
                                        str += helpbox;
                                    }

                            str +=  '</ul>\
                                </div>\
                        </div>'; 
                $('.m-header_user').empty().prepend(str);
        }
        return data;        
    }

    $.mobileToggleMenu = {
        set : function() {
            var request_uri = location.pathname + location.search;
            var returnData = '';

            $.ajax({
                type: 'POST',
                data: { type:'get', sid:SID },
                dataType: 'json',
                url: '/template/getMobileMenu',   
                async:false,
                success : function(data) {
                    returnData = getMobileInfo(data);
                }
            }); 

            $.mobileToggleMenu.clickEvnt();

            return returnData;
            
        },
        setSignIn : function() {
            var langkor = (LANG=='ko') ? '':'hide',
                langen = (LANG=='en') ? '' : 'hide',
                str = '<div class="nav navbar-nav navbar-right signinwrap">\
                        <div class="mobile-menu">\
                                <div class="m-myinfo">\
                                    <div class="profile_left signinwrap_logo">\
                                        <div class="inner-box hand">\
                                            <a href="/">\
                                            <svg viewBox="0 0 168 38" role="img" class="logo-svg logo-b" data-attach="true" alt="Creatorlink logo"><path class="st11" d="M70.71 12.36c-3.48 0-5.9 2.19-5.9 5.34v4.11c0 3.34 2.17 5.25 5.96 5.25 2.06 0 3.98-0.58 5.41-1.64l0.14-0.11 -1.03-1.95 -0.2 0.1c-1.67 0.85-2.74 1.15-4.11 1.15 -2.23 0-3.23-0.87-3.23-2.83v-0.94h8.62v-3.08C76.37 14.13 74.52 12.36 70.71 12.36zM73.52 18.45h-5.77v-0.92c0-1.91 1.53-2.78 2.96-2.78 2.02 0 2.81 0.78 2.81 2.78V18.45z"/><path class="st11" d="M84.38 12.36c-1.52 0-3.34 0.55-4.87 1.47l-0.17 0.1 1.11 1.95 0.19-0.1c1.41-0.69 2.48-0.98 3.59-0.98 2.22 0 2.93 0.51 2.93 2.1v1.29h-3.64c-3.09 0-4.65 1.47-4.65 4.37 0 1.22 0.39 2.33 1.09 3.12 0.76 0.85 1.84 1.3 3.12 1.3 0.09 0 0.18 0 0.26-0.01 1.37-0.06 2.71-0.51 3.97-0.99l0.04 0.79h2.76v-9.76C90.11 13.76 88.39 12.36 84.38 12.36zM87.17 23.79l-0.01 0c-0.83 0.32-1.87 0.72-3.2 0.73h-0.06c-1.46 0-2.08-0.6-2.08-2.01 0-1.37 0.55-1.92 1.89-1.92h3.47V23.79z"/><path class="st11" d="M101.06 24.31c-0.95 0.23-1.63 0.33-2.26 0.33 -1.16 0-1.27-0.36-1.27-1.31v-8.47h3.9l0-2.22h-3.9V9.26l-2.94 0.01v3.38h-2.56v2.22h2.56v8.86c0 2.31 1.18 3.34 3.82 3.34 1.04 0 2.14-0.18 3.11-0.52l0.17-0.06 -0.4-2.23L101.06 24.31z"/><path class="st11" d="M109.95 12.36c-3.88 0-6.11 1.96-6.11 5.36v3.97c0 3.41 2.23 5.36 6.11 5.36 3.88 0 6.11-1.96 6.11-5.36v-3.97C116.06 14.32 113.84 12.36 109.95 12.36zM113.12 21.78c0 1.89-1.04 2.8-3.17 2.8 -2.13 0-3.17-0.92-3.17-2.8v-4.14c0-1.89 1.04-2.8 3.17-2.8 2.13 0 3.17 0.92 3.17 2.8V21.78z"/><path class="st11" d="M59.07 14.72l0.01-2.07H56.3v14.13h2.94v-9.04c1.75-1.89 4.2-3.24 4.2-3.24l-1.4-1.84C62.04 12.65 60.26 13.76 59.07 14.72z"/><path class="st11" d="M121.93 14.72l0.01-2.07h-2.77v14.13h2.94v-9.04c1.75-1.89 4.2-3.24 4.2-3.24l-1.4-1.84C124.91 12.65 123.12 13.76 121.93 14.72z"/><path class="st11" d="M51.54 22.93c-0.96 1.11-2.12 1.66-3.56 1.66 -2.13 0-3.17-0.92-3.17-2.8v-4.14c0-1.89 1.04-2.8 3.17-2.8 1.73 0 2.83 0.77 3.68 1.52l0.13 0.12 1.99-1.39 -0.13-0.17c-0.76-0.95-2.5-2.55-5.67-2.55 -3.88 0-6.11 1.96-6.11 5.36v3.97c0 3.41 2.23 5.36 6.11 5.36 3.03 0 4.76-1.58 5.68-2.91l0.13-0.18 -2.13-1.18L51.54 22.93z"/><rect x="128.71" y="6.68" class="st11" width="1.2" height="20.07"/><rect x="134.41" y="12.69" class="st11" width="1.2" height="14.06"/><rect x="134.41" y="8.29" class="st11" width="1.2" height="2.18"/><path class="st11" d="M148.67 13.44c-1.68-0.98-5.06-0.52-7.21 0.71V12.5h-1.2v14.25h1.2V15.33c1.74-1.3 5.26-1.79 6.61-1 1.38 0.81 1.38 2.37 1.38 2.43v9.99h1.2v-9.99C150.65 16.67 150.63 14.59 148.67 13.44z"/><polygon class="st11" points="158.27 18.97 164.05 12.69 162.6 12.69 156 19.89 156 6.68 154.8 6.68 154.8 26.75 156 26.75 156 21.44 157.54 19.77 163.6 26.75 165 26.75 "/><path class="st11" d="M3 10.79L3 10.79l0 16.42 14.22 8.21 14.22-8.21V10.79L17.22 2.58 3 10.79zM26.7 13.53L26.7 13.53 26.7 13.53l-4.74 2.74h0l-4.74-2.74 -4.74 2.74v5.47l4.74 2.74 4.74-2.74 4.74 2.74 -9.48 5.47 -9.48-5.47V13.53l9.48-5.47L26.7 13.53 26.7 13.53z"/></svg>\
                                            </a>\
                                        </div>\
                                    </div>\
                                    <div class="profile_right msignin">\
                                        <a href="/member/login" class="mlogin-text" id="m_login_btn_head">'+$.lang[LANG]['mobile.menu.signin']+'</button>\
                                    </div>\
                                </div>\
                                <ul class="dropdown-menu" role="menu">';   
                            str += '<li><a href="/upgrade/site" class="logoutmenu">'+$.lang[LANG]['mobile.menu.logout.title.plan']+'</a></li>\
                                    <li><a href="/template" class="logoutmenu">'+$.lang[LANG]['mobile.menu.logout.title.template']+'</a></li>\
                                    <li><a href="/bestlist" class="logoutmenu">'+$.lang[LANG]['mobile.menu.logout.title.bestsite']+'</a></li>';
                                   if(LANG == 'ko') str += '<li><a href="/mainfunction" class="logoutmenu">'+$.lang[LANG]['mobile.menu.logout.title.mainfunc']+'</a></li>';
                                   if(LANG == 'ko') str += '<li><a href="/edu" class="logoutmenu edu">'+$.lang[LANG]['mobile.menu.logout.title.edu']+'</a></li>';
                                   //if(LANG == 'ko') str += '<li><a href="/production" class="logoutmenu">제작 의뢰 <span class="newicon">New</span></a></li>';

                        // str += '</ul>\ 
                        //         <div class="mchange-lang">\
                        //             //<img src="https://storage.googleapis.com/i.addblock.net/lang_kor.png" class="lang-ch '+langkor+'" data-attach="true" alt="Creatorlink logo">\
                        //             //<img src="https://storage.googleapis.com/i.addblock.net/lang_eng.png" class="lang-ch '+langen+'" data-attach="true" alt="Creatorlink logo">\
                        //             <div class="lang-ch '+langkor+'">KR</div>\
                        //             <div class="lang-ch '+langen+'">EN</div>\
                        //         </div>\
                        //     </div>\
                        str += '</ul>\
                                <div class="mchange-lang">\
                                    <div class="hand lang-ch '+langkor+'">KR</div>\
                                    <div class="hand lang-ch '+langen+'">EN</div>\
                                </div>\
                            </div>\
                    </div>';    

            $('.m-header_user').prepend(str);   

            $.mobileToggleMenu.clickEvnt();
        },
        mobileResize : function(data) {
            getMobileInfo(data);
            $.mobileToggleMenu.clickEvnt();
        },
        clickEvnt : function() {
            $('.navbar-toggle').click(function() {
                $.mobileToggleMenu.open();
                $('.m-header_user').css('left','0');
                $('html').css({'overflow': 'hidden'});
            });
            $('.m-langselect,.lang-ch').on('click',function(){  
                $.mobileToggleMenu.langSelect(mrequest_uri);
            });
            /*$('.applySm').click(function(){
                $(this).showModalFlat('INFORMATION', '쇼핑 기능은 심플쇼핑 요금제로 이용이 가능합니다.<br>심플쇼핑 신청 페이지로 이동할까요?', true, true, function() {
                    location.href = '/shoppingevent';
                }, 'cancel', '이동','mUpgradeSmModal');
            });*/
            $('.mshopping_menu').on('show.bs.collapse',function(e){
                $('.mshoppingtab,.mshoppingtab > a').css('background-color','#eeeff3');
                $('.mshoppingtab svg').remove();
                $('.mshoppingtab > a ').prepend('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10" width="10px" height="10px"><polygon points="1 8 5 4 9 8 10 7 6 3 5 2 4 3 0 7 "/></svg>');
            });
            $('.mshopping_menu').on('hide.bs.collapse',function(e){
                $('.mshoppingtab,.mshoppingtab > a').css('background-color','inherit');
                $('.mshoppingtab svg').remove();
                $('.mshoppingtab > a ').prepend('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10" width="10px" height="10px"><polygon points="9 2 5 6 1 2 0 3 4 7 5 8 6 7 10 3 "/></svg>');
            });

            $('#loginModal').on('show.bs.modal', function(e) {
                $.mobileToggleMenu.close();
            });
            $('#loginModal').on('shown.bs.modal', function(e) {
                $('html').css({'overflow': 'inherit'});
            });  
        },
        open : function (){
            var height = window.outerHeight;

            $('#nav.default-nav .header .navbar-header a.navbar-toggle,#nav.default-nav .header .navbar_right').css('zIndex','99');
            $('.mobile-detail-popup.billhead,.mobile-detail-popup.helphead').css('height', '100%');
            $('.m-headermenu').remove();
            $('.m-headerClose').addClass('in');
            $('.m-headerClose').removeClass('hide');
            $.mobileToggleMenu.scrollheight();

            $(window).resize(function (){
                $.mobileToggleMenu.scrollheight();
            });
            $('.m-headerClose').click(function(){
                $.mobileToggleMenu.close();
                $('html').css({'overflow': 'inherit'});
            });
        },
        close : function() {
            $('.m-headermenu').remove();
            $('.m-header_user').css('left','-100%');
            $('.m-headerClose').removeClass('in');
            $('.mobile-detail-popup.billhead,.mobile-detail-popup.helphead').css('height', 'auto');
            $('#nav.default-nav .header .navbar_right').css('zIndex','');
            $('#nav.default-nav .header .navbar-header a.navbar-toggle').css('zIndex','120');
        },
        langSelect : function(request_uri) {
            $('.m-headermenu').remove();
            $('.m-header_user.menu').css('left','-100%');
            $('.m-headerClose').addClass('hide');
            $('#nav.default-nav .header .navbar-header a.navbar-toggle').css('zIndex','120');

            var dashlang = (LANG == 'ko') ? 'ko' : 'en',
                html = "<ul class='dashlang-wrap'>\
                            <li class='dashlang-select'>\
                                <a href='/lang/switchLanguage/korean"+request_uri+"'><p class='mdash-lang'>한국어 (KO)</p>\
                                <span class='cl-icon cl-check-lang "+(dashlang == 'ko' ? 'cl_icon_checked04' : 'cl_icon_unchecked04')+"' data-lang='ko'></span></a>\
                            </li>\
                            <li class='dashlang-select'>\
                                <a href='/lang/switchLanguage/english"+request_uri+"'><p class='mdash-lang'>English (EN)</p>\
                                <span class='cl-icon cl-check-lang "+(dashlang == 'en' ? 'cl_icon_checked04' : 'cl_icon_unchecked04')+"' data-lang='en'></span></a>\
                            </li>\
                        </ul>";

            $('.m-dashboard').showModalFlat('',html,false,false,'','','','changelang');
            $('.modal-dialog.changelang').parents('.modal-default').attr('id','changelangModal');

            $('#changelangModal').on('show.bs.modal', function(e) {
                $('.dashlang-select > a').click(function() {
                    var datalang = $('.dashlang-select .cl-check-lang').attr('data-lang');

                    $('.cl-check-lang').each(function () {
                        $(this).addClass('cl_icon_checked04').removeClass('cl_icon_unchecked04');
                    });
                    $(this).addClass('cl_icon_unchecked04').removeClass('cl_icon_checked04');
                });
            });

            $('#changelangModal').on('hide.bs.modal', function(e) {
                $('#nav.default-nav .header .navbar_right').css('zIndex','');
                $('#nav.default-nav .header .navbar-header a.navbar-toggle').css('zIndex','120');
            });
        },
        upgradePopup : function(){
            $(this).showModalFlat('INFORMATION', '쇼핑 기능은 쇼핑 요금제로 이용이 가능합니다.<br>쇼핑 요금제 신청 페이지로 이동할까요?', true, true, function() {
                location.href = '/shoppingevent';
            }, 'cancel', '이동','mUpgradeSmModal');
        },
        scrollheight : function() {
            var menuheight = $(window).height()-146;
            $('.m-header_user .mobile-menu .dropdown-menu').css('height',menuheight);
        }
    }

    $.notSupported = {
        isPremiumBlock: function(type,type2,feature) {
            if(typeof type == 'undefined') type = '';
            if(typeof type2 == 'undefined') type2 = '';
            if(typeof feature == 'undefined') feature = '';

            return ( type2 == 'premium'
                    || feature == 'premium'
                    || $.inArray(type, ['latest','form','sync','review']) > -1
                    || (type == 'forum' && $.inArray(type2, ['faq','qna']) > -1)
                ) ? true : false; 
        },
        check: function(type,type2,feature) {
            if(typeof type == 'undefined') type = '';
            if(typeof type2 == 'undefined') type2 = '';
            if(typeof feature == 'undefined') feature = '';
            if(typeof fn == 'undefined') fn = '';

            if(!type && !type2 && !feature) return true;

            var tmp_plan = (typeof property != 'undefined') ? property.VALIDPLAN : VALIDPLAN,
                tmp_plantype = (typeof property != 'undefined') ? property.VALIDTYPE : VALIDTYPE,
                checkFree = (!tmp_plan || tmp_plantype == 'PK') ? true : false,
                checkSM = (tmp_plan && tmp_plantype == 'SM') ? true : false,
                checkPremium = $.notSupported.isPremiumBlock(type,type2,feature);
            
            var ns_val = false;
            if(checkFree) {
                if(checkPremium) ns_val = true;
            } else {
                if(!checkSM && $.inArray(type, ['review']) > -1) ns_val = true;
            }

            return ns_val;
        },
        set: function(sid, id, mode, upgrade) {
            
            if(typeof id == 'undefined' || !id || $('[data-id="' + id + '"]:is(.element, .reorderBlock)').length == 0) return false;
     
            var nsEl = $('[data-id="' + id + '"]:is(.element, .reorderBlock)'),
                checkSlim = (nsEl.height() < 351) ? true : false,
                n_service = (typeof PAGE_MODE != 'undefined' && PAGE_MODE=='c') ? SERVICE : property.SERVICE, 
                page_mode = (typeof PAGE_MODE != 'undefined' && PAGE_MODE=='c') ? 'config' : 'render', 
                is_gabia = (n_service.indexOf('gabia') > -1) ? '.gabia' : '',
                title_str = (mode=='video' && !upgrade) ? $.lang[LANG]['config.premium.not-supported.block.video.'+page_mode+'.gfycat'] : $.lang[LANG]['config.premium.not-supported.block'],
                ns_html = `
                    <div class="cl-ns-wrap" data-blockmode="${mode}">
                        <div class="cl-ns-title">${ ($.inArray(mode, ['review']) > -1) ? $.lang[LANG]['config.premium.not-supported.block.SM' + is_gabia] : title_str }</div>
                        <div class="cl-ns-bottom">
                            ${ (upgrade) ? `<a class="cl-ns-btn color-b" href="${ 
                                                (n_service.indexOf('gabia') > -1) ? 'https://www.gabia.com/mygabia/service' : `/upgrade/site/${sid}` 
                                            }" target="_blank">${ $.lang[LANG]['config.premium.not-supported.block.btn.upgrade'] }</a>` : '' 
                            }
                            <span class="cl-ns-btn color-w" onclick="elDelete(${id})">${$.lang[LANG]['config.premium.not-supported.block.btn.delete']}</span></div>
                        </div>
                    </div>
                `;

            if(checkSlim) nsEl.addClass('cl-ns-slim');
            else nsEl.removeClass('cl-ns-slim');

            nsEl.addClass('cl-not-supported');
            nsEl.each(function() {
                if($(this).find('.cl-ns-wrap').length > 0) $(this).find('.cl-ns-wrap').replaceWith(ns_html);
                else $(this).append(ns_html);
            });
        },
        unset: function(id) {
            if(typeof id == 'undefined' || !id || $('[data-id="' + id + '"]:is(.element, .reorderBlock)').length == 0) return false;

            var nsEl = $('[data-id="' + id + '"]:is(.element, .reorderBlock)');
            nsEl.removeClass('cl-not-supported cl-ns-slim');
            nsEl.find('.cl-ns-wrap').remove();
        }
    }


    $.resource = {
        init : function() {
            var freeSearch = {'type' : '', 'page' : 1, 'text' : '', 'total' : 0},
                fileDrag = false,
                depfolderClick = false,
                isFEdit = false,
                mouseX, mouseY;

            $('.modal-resourcebox ul.files').on('scroll', function(e) {
                var thisResourceTab = $('.modal-resourcebox .tab-content > .tab-pane.active'),
                    thisResourceFiles = thisResourceTab.find('ul.files'),
                    rmode = thisResourceTab.attr('id').replace(/storage$/gi,''),
                    fsort = thisResourceTab.find('.resource-ctrl-sort select').val(),
                    fsearch = thisResourceTab.find('.resource-search-stx').val();
                
                if((this.scrollTop + this.clientHeight) > (this.scrollHeight - 100)) {
                    var fitem_cnt = thisResourceFiles.find('.fitem').length;
                    if(rmode == 'my') {
                        if (fitem_cnt == cTotal) return;
                    } else if(rmode == 'free') {
                        if($.inArray(freeSearch.type, ['search','favor','used']) > -1 && freeSearch.total != 0) {
                            if(fitem_cnt == freeSearch.total) return false;
                        }
                    }

                    if(thisResourceFiles.find('.listprogress').length == 0) {
                        thisResourceFiles.append('<li class="listprogress"><svg version="1.1" xmlns="http://www.w3.org/svg/2000" viewBox="0 0 30 30" width="60" style="width:30px; height: 30px;"><circle cy="15" cx="15" r="14" style="stroke:#00baff;"></circle></svg></li>');  
                        if(rmode == 'my') {
                            cPage = cPage + 1;
                            resourceGetPage(cPage,SFOLDER_ACTIVE,fsort,fsearch);
                        } else if(rmode == 'free') {
                            getFreeImage(freeSearch.page,freeSearch.type,freeSearch.text);
                        }
                        
                    }
                }

                if($('.modal-resourcebox ul.files').data('uiSelectableScroll') && $('.modal-resourcebox ul.files').data('uiSelectableScroll').dragged)
                    $('.modal-resourcebox ul.files').data('uiSelectableScroll')._updateUi({ doUpdateHelper: true });
            })

            $(document)
                .on('click', '.resourcebox-frame .view-original', function(e) {
                    e.preventDefault();
                    e.stopPropagation();
                    // thisResourceZoomable.empty();

                    var thisResourceFrame = $('.resourcebox-frame #rframe'),
                        thisResourceSlide = thisResourceFrame.find('.slide').eq(0);
                        thisResourceZoomable = thisResourceFrame.find('.zoomable');
                        thisResourceOrgBtn = $(this);

                    thisResourceOrgBtn.toggleClass('fullscreen');
                    var ww = $(window).width() - 8,
                        cw = thisResourceSlide.find('.slide-content').width(),
                        scale = (thisResourceOrgBtn.hasClass('fullscreen')) ? (ww / cw).toFixed(15) : 1;

                    setSlideIconTooltip('.resourcebox-frame #rframe');
                    if(thisResourceOrgBtn.hasClass('dblclick')) thisResourceOrgBtn.removeClass('dblclick');
                    else thisResourceOrgBtn.tooltip('show');
                    setSlideImgScale(thisResourceSlide, scale);
                })
                .on('dblclick', '.resourcebox-frame .slide-content', function(e) {
                    var thisResourceFrame = $('.resourcebox-frame #rframe'),
                        thisResourceOrgBtn = thisResourceFrame.find('.view-original');
                    
                    thisResourceOrgBtn.addClass('dblclick');
                    thisResourceOrgBtn.click();
                })
                .on('click', '.resourcebox-frame [class*="zoom-"]', function(e) {
                    var thisResourceFrame = $('.resourcebox-frame #rframe'),
                        thisResourceSlide = thisResourceFrame.find('.slide').eq(0),
                        thisResourceOrgBtn = thisResourceFrame.find('.view-original'),
                        scale = thisResourceFrame.find('.zoomable img').attr('data-scale');
                    if(scale === undefined) scale = 1;

                    if($(this).hasClass('zoom-in')) {
                        thisResourceOrgBtn.removeClass('disabled').addClass('fullscreen');
                        scale = Number(scale) + 0.5;
                    } else {
                        if(scale > 1) scale = Number(scale) - 0.5;
                        if(scale < 1) scale = 1;
                        if(scale == 1) {
                            thisResourceOrgBtn.removeClass('fullscreen');
                        }
                    }
                    
                    setSlideIconTooltip('.resourcebox-frame #rframe');
                    setSlideImgScale(thisResourceSlide, scale);
                });

            $('#el-fileupload')
                .on('show.bs.modal', function(e) {
                    var parentDocument = $(window.parent.document),
                        $detail_modal = parentDocument.find('.product-detail-modal');
                    if($detail_modal.length) $detail_modal.addClass('overlap');                    

                    var thisResourceTab = $('.modal-resourcebox .tab-content > .tab-pane.active'),
                        thisResourceFiles = thisResourceTab.find('ul.files'),
                        rmode = thisResourceTab.attr('id').replace(/storage$/gi,''),
                        fsort = thisResourceTab.find('.resource-ctrl-sort select').val(),
                        fsearch = thisResourceTab.find('.resource-search-stx').val();
                
                    ADD = false;
                    UPLOAD = 0;
                    UPLOADED = 0;
                    PROGRESS = 0;

                    var checkProperty = $('.modal-resourcebox .resource-useit').eq(0).attr('data-property');
                    if(rmode == 'my' && checkProperty == 'flink-change') {
                        rmode = 'file';
                        thisResourceTab = $('#filestorage');
                        thisResourceFiles = thisResourceTab.find('ul.files');
                    }

                    var checkReady = thisResourceFiles.hasClass('ready');
                    if(checkReady) {
                        cPage = 1;
                        fsort = 'date_desc';
                        fsearch = '';
                    }
                    $.resource.modalInit();
                    if(checkReady) resourceGetPage(1,SFOLDER_ACTIVE,fsort,fsearch);

                    if(rmode == 'my') {
                        thisResourceTab.find('.selectpicker + .btn.dropdown-toggle').attr('title','');
                        if(thisResourceTab.find('.fli.active').length == 0) thisResourceTab.find('.fli[data-id="all"]').click();
                    }
                })
                .on('hide.bs.modal', function(e) {
                    var parentDocument = $(window.parent.document),
                        $detail_modal = parentDocument.find('.product-detail-modal');
                    if($detail_modal.length) $detail_modal.removeClass('overlap');                    
                    $.resource.setMystorageFolder('nodrag',false);
                    if($('#nestableFolder .fli[data-id="clEmptyFolder"]').length > 0 ) {//new folder name_input open
                        $('#nestableFolder .fli[data-id="clEmptyFolder"]').remove();
                        isFEdit = false;
                    }
                    if($('#nestableFolder .fli .dd-fln').find('input').length > 0 ) { //edit folder name_input open
                        $('#nestableFolder .fli .dd-fln').find('input').val('').closest('li.fli').find('.fln-group').remove();
                        isFEdit = false;
                    }
                    if($('#nestableFolder .fli.active').length > 0) {
                        if($('#nestableFolder').scrollTop() > $('#nestableFolder .fli.active').position().top) {
                            $('#nestableFolder').scrollTop($('#nestableFolder .fli.active').position().top);
                        }
                    }
    
                    if($('#el-property [data-loop-type="matrix"] .attach-thumb[data-toggle="modal"]').length > 0 ) { //clear matrix loop item - modal toggle
                        var idx =  $('#el-property [data-loop-type="matrix"] .attach-thumb[data-toggle="modal"]').attr('idx');
                        $('#el-property [data-loop-type="matrix"] .attach-thumb[data-toggle="modal"]').removeAttr('data-toggle');
    
                        if(!$('#el-property [data-loop-type="matrix"] .ui-sortable').children().first().hasClass('active')) 
                            $('#el-property [data-loop-type="matrix"] .ui-sortable').children().first().click();
                    }
    
                    if(typeof selectEL != 'undefined' && selectEL && typeof $('.'+selectEL).attr('data-parallax') != "undefined" && $('.'+selectEL).attr('data-parallax')) {
                        $('#prop-method-background').attr('data-target','');
                    }
    
                    $('#mystorage .add-folder').attr('data-content','').popover('hide');
                    $('.resource-useit').show();
                    selectCount = 0;
                })
                .on('hidden.bs.modal', function(e) {
                    if(typeof isEDIT != 'undefined' && isEDIT === false) editEL = '';
                    $('.resource-useit').removeClass('clicked');
                    $.resource.modalOpenSET(false);
                })
                .on('mousemove', function(e) {
                    mouseX = e.pageX; 
                    mouseY = e.pageY;
                    if($(this).is(':not(.flink-fileupload)')) {
                        $(this).find('.resource-tooltip').css({'top': mouseY-20,'left':mouseX-20 });
                    }
                })
                .on('mouseup', '.resource-files-content', function(e) {
                    $(this).closest('.modal.in').find('.resource-tooltip').fadeOut();
                    fileDrag = false;
                });


            
            /* modal-resourcebox 00__common */
            $('.modal-resourcebox')
                .on('click', '#btn-resourcebox-fullwidth', function(e) {
                    $(this).closest('#el-fileupload').toggleClass('full-width');
                })
                .on('change', '.resource-ctrl-layout select', function(e) {
                    $(this).next('.btn.dropdown-toggle').attr('title','');
                    var thisResourceFiles = $(this).closest('.tab-pane.active').find('ul.files'),
                        layout = $(this).val();
    
                    thisResourceFiles.attr('data-layout', layout);
                })
                .on('change', '.resource-ctrl-sort select', function(e) {
                    $(this).next('.btn.dropdown-toggle').attr('title','');
                    var thisResourceTab = $(this).closest('.tab-pane.active');
                    if(thisResourceTab.find('ul.files').hasClass('empty') || thisResourceTab.find('ul.files .resource-empty-area').length > 0) return false;
                    else thisResourceTab.find('.resource-search-btn').click();
                })
                .on('keyup', '.resource-search-stx', function(e) {
                    var keyCode = e.keyCode;
                    if(keyCode == 13) $(this).closest('.resource-search-group').find('.resource-search-btn').click();
                })
                .on('click', '.resource-search-btn', function(e) {
                    var thisSearchBtn = $(this),
                        thisSearchInput = thisSearchBtn.closest('.resource-search-group').find('.resource-search-stx'),
                        rmode = thisSearchBtn.attr('id').replace(/\-resource\-search$/gi,'');
                        fsearch = thisSearchInput.val().trim(),
                        fsort = (rmode == 'my') ? thisSearchBtn.closest('.resource-row').find('.resource-ctrl-sort select').val() : '';
    
                    if(thisSearchBtn.hasClass('clicked')) return false;
                    thisSearchBtn.addClass('clicked');
    
                    if(rmode == 'my') {
                        thisSearchInput.val(fsearch);
                        UPLOAD = 0;
                        UPLOADED = 0;
                        PROGRESS = 0;
                        cPage = 1;
                        resourceGetPage(1,SFOLDER_ACTIVE,fsort,fsearch);
                    } else if(rmode == 'free') {
                        if(fsearch == '') {
                            if(!$('#freestorage .resource-folderlist li:eq(0)').hasClass('active')) {
                                $('#freestorage .resource-folderlist li:eq(0)').click();
                            }  
                            thisSearchBtn.removeClass('clicked');
                            return false;
                        }
                        $.resource.modalContentInit('free');
                        $('#freestorage .resource-folderlist li').removeClass('active');

                        freeSearch.type = 'search';
                        freeSearch.page = 1;
                        freeSearch.text = fsearch;
                        freeSearch.total = 0;
                        
                        $.getJSON('/template/translate/' + encodeURIComponent(fsearch), function(data) {
                            search = data.data.translations[0].translatedText;
                            freeSearch.text = fsearch;
                            $('#freestorage .resource-search-stx').val(fsearch);
                            getFreeImage(freeSearch.page,freeSearch.type,fsearch);
                        });
                    }
                })
                .on('scroll', 'ul.files', function(e) {
                })
                .on('mousedown', 'ul.files', function(e) {
                    var thisResourceTab = $(this).closest('.tab-pane.active'),
                        thisResourceFiles = $(this),
                        thisResourceSelected = thisResourceTab.find('.resource-selected-ul'),
                        rmode = thisResourceTab.attr('id').replace(/storage$/gi,'');

                    if(rmode == 'my' && isFEdit) thisResourceTab.find('#nestableFolder .fln-group .btn-fln-cancel').click();

                    if(e.shiftKey) {
                        thisResourceSelected.children('li').each(function () {
                            var set_key = (rmode == 'free') ? 'id' : 'seq',
                                set_val = $(this).attr('data-'+set_key);
                            if(thisResourceFiles.find('.ui-selected .fitem-ctrl > ul[data-' + set_key + '="' + set_val + '"]').length == 0) {
                                thisResourceFiles.find('.fitem-ctrl > ul[data-' + set_key + '="' + set_val + '"]').closest('.fitem').addClass('ui-selected');
                            }
                        });
                    } else {
                        if(!e.ctrlKey && !$(e.target).hasClass('.ui-selected')) {
                            $(e.target).removeClass('ui-selected');
                        }
                    }
                })
                .on('click', '.fitem', function(e) {
                    var thisResourceTab = $(this).closest('.tab-pane.active'),
                        thisResourceSelected = thisResourceTab.find('.resource-selected-ul'),
                        rmode = thisResourceTab.attr('id').replace(/storage$/gi,'');

                    if(e.ctrlKey || e.shiftKey) {
                        if($(this).hasClass('ui-selected')) {
                            $(this).removeClass('ui-selected');
                            var unset_key = (rmode == 'free') ? 'id' : 'seq',
                                unset_val = $(this).find('.fitem-ctrl > ul').attr('data-'+unset_key);
                            thisResourceSelected.children('li[data-' + unset_key + '="' + unset_val + '"]').remove();
                        }

                        setResourceSelectedBox(rmode);
                    }
                })
                .on('click', '.fitem-ctrl-imgview', function(e) {
                    var thisResourceTab = $(this).closest('.tab-pane.active'),
                        thisResourceCtrlImgview = $(this);

                    $('.modal-resourcebox .fitem-ctrl-imgview').removeAttr('href').removeAttr('data-gallery');
                    $('.resourcebox-frame').html('\
                            <div id="rframe" class="blueimp-gallery blueimp-gallery-controls" data-start-slideshow="false" data-slideshow-interval="5000">\
                                <div class="slides"></div>\
                                <div class="zoomable hide"></div>\
                                <h3 class="title"></h3>\
                                <ul class="ctrls">\
                                    <li>\
                                        <a class="view-original" data-toggle="tooltip" data-placement="bottom" data-html="true" data-original-title="' + $.lang[LANG]['gallery.slide.tooltip.view-fullscreen'] + '">\
                                            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 27 27" width="27" height="27"><g><path d="M1 4.12v18.75h25V4.12H1zm23.5 17.26h-22V5.62h22v15.76z"/><path d="M8.03 18.19h1.56V8.81H6.47v1.57h1.56zM12.72 10.38h1.56v1.56h-1.56zM12.72 15.06h1.56v1.56h-1.56zM18.19 18.19h1.56V8.81h-3.13v1.57h1.57z"/></g></svg>\
                                            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 27 27" width="27" height="27"><path d="M24.03 4.03 24 4V3h-1l-.03-.03-.03.03H13.5v1.5h7.94L4.5 21.44V13.5H3v9.44l-.03.03L3 23v1h1l.03.03.03-.03h9.44v-1.5H5.56L22.5 5.56v7.94H24V4.06z"/></svg>\
                                        </a>\
                                    </li>\
                                    <li><a class="zoom-out disabled" data-toggle="tooltip" data-placement="bottom" data-html="true" data-original-title="' + $.lang[LANG]['gallery.slide.tooltip.zoom-out'] + '"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 23 23" width="23" height="23"><g><path d="m23 21.98-6.16-6.16a9.566 9.566 0 0 0 2.32-6.24C19.17 4.29 14.88 0 9.58 0S0 4.29 0 9.58s4.29 9.58 9.58 9.58c2.39 0 4.57-.88 6.24-2.32L21.98 23 23 21.98zM1.44 9.58c0-4.49 3.65-8.15 8.15-8.15 4.49 0 8.15 3.65 8.15 8.15s-3.65 8.15-8.15 8.15-8.15-3.66-8.15-8.15z"></path><path d="M5.75 8.86h7.67v1.44H5.75z"></path></g></svg></a></li>\
                                    <li><a class="zoom-in" data-toggle="tooltip" data-placement="bottom" data-html="true" data-original-title="' + $.lang[LANG]['gallery.slide.tooltip.zoom-in'] + '"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24"><path d="M24 22.94l-6.42-6.42C19.08 14.76 20 12.49 20 10c0-5.52-4.48-10-10-10S0 4.48 0 10s4.48 10 10 10c2.49 0 4.76-0.92 6.52-2.42L22.94 24 24 22.94zM1.5 10c0-4.69 3.81-8.5 8.5-8.5 4.69 0 8.5 3.81 8.5 8.5s-3.81 8.5-8.5 8.5C5.31 18.5 1.5 14.69 1.5 10z"/><polygon points="10.75 6 9.25 6 9.25 9.25 6 9.25 6 10.75 9.25 10.75 9.25 14 10.75 14 10.75 10.75 14 10.75 14 9.25 10.75 9.25 "/></svg></a></li>\
                                    <li><a class="close"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 22 22" width="22" height="22"><polygon points="22 1.06 20.94 0 11 9.94 1.06 0 0 1.06 9.94 11 0 20.94 1.06 22 11 12.06 20.94 22 22 20.94 12.06 11 "/></svg></a><li>\
                                </ul>\
                            </div>\
                    ');
                    thisResourceCtrlImgview.attr('href', $(this).attr('data-url')).attr('data-gallery','#rframe');
                })
                .on('mouseenter', '.resource-selected-ul > li', function(e) {
                    $(this).find('.selected-hover').show();
                })
                .on('mouseleave', '.resource-selected-ul > li', function(e) {
                    $(this).find('.selected-hover').hide();
                })
                .on('click', '.resource-selected-ul > li > .selected-hover', function(e) {
                    $(this).popover('destroy');

                    var thisResourceTab = $(this).closest('.tab-pane.active'),
                        thisResourceFiles = thisResourceTab.find('ul.files'),
                        thisResourceSelected = thisResourceTab.find('.resource-selected-ul'),
                        rmode = thisResourceTab.attr('id').replace(/storage$/gi,'');
    
                    $(this).closest('li').fadeOut(300,function() {
                        var del_key = (rmode == 'free') ? 'id' : 'seq',
                            del_val = $(this).attr('data-'+del_key);
                        $(this).remove();
    
                        thisResourceFiles.find('.fitem.ui-selected .fitem-ctrl > ul[data-' + del_key + '="' + del_val + '"]').closest('.fitem').removeClass('ui-selected');
                        setResourceSelectedBox(rmode);
                    });
    
                    if(thisResourceSelected.children('li').length == 1) {
                        thisResourceTab.find('.resource-useit').removeClass('active');
                    }
                });
            

            /* modal-resourcebox 01__mystorage */
            var mystorageFolderEdit = function(ddfl) {
                var myResourceFolderlist = $('#mystorage #nestableFolder'),
                    edit_fli = ddfl.closest('li.fli'),
                    fln_group_css = (myResourceFolderlist.find('.dd-list.fll').height() >= myResourceFolderlist.height() && $.browser.safari == undefined) ? 'style="max-width: 173px;"' : '',
                    fln_input_css = (myResourceFolderlist.find('.dd-list.fll').height() >= myResourceFolderlist.height() && $.browser.safari == undefined) ? 'style="max-width: 136px;"' : '',
                    checkAdd = (edit_fli.attr('data-id') == 'clEmptyFolder') ? true : false,
                    beforeFln = (checkAdd) ? '' : edit_fli.attr('data-id');

                if(beforeFln.length > 0) beforeFln = beforeFln.replace(/-/g,' ');

                var input_html = '\
                    <div class="fln-group input-group" ' + fln_group_css + '>\
                        <input class="fln-input form-control" type="text" value="' + beforeFln + '"  ' + fln_input_css + '/>\
                        <span class="input-group-btn"><button class="btn-fln-save btn btn-default btn-primary" type="button"><i class="fa fa-check"></i></button></span>\
                        <div class="btn-fln-cancel"><i class="fa fa-times"></i></div>\
                    </div>\
                    ';

                $(input_html).appendTo(edit_fli.find('.dd-fln'));
                if(edit_fli.find('.fln-input').is(':not(:focus)')) edit_fli.find('.fln-input').focus();

                $.resource.setMystorageFolder('nodrag',true);
            }

            var mystorageFolderUpdate = function(prevText,newText) {
                $.ajax({
                    type: 'POST',
                    url: '/template/resource/update-ffolder',
                    data: { sid: SID, prevffolder: prevText, newffolder: newText },
                    async: true,
                    success: function(data) {
                        checkError(data);
                    }
                });
            }

            var mystorageFileDelete = function(file,seq,callback) {
                if(CANCEL) return true;
                $.ajax({
                    type: 'POST',
                    url: '/template/resource/delete',
                    data: { s: file, sid: SID, seq: seq },
                    async: true,
                    success: function(data) {
                        checkError(data);
                        if(typeof callback == 'function') {
                            callback();
                        }
                    }
                });
            }

            $('.modal-resourcebox')
                .on('click', 'a[href="#mystorage"]', function(e) {
                    setResourceSelectedBox('my');
                    if(isFEdit) $('#nestableFolder .fln-group .btn-fln-cancel').click();
                });

            $('.modal-resourcebox #mystorage')
                .on('scroll touchmove mousewheel', '#nestableFolder', function(e) {
                    if(isFEdit || $(this).find('.fln-group.input-group').length > 0) {
                        e.preventDefault();
                        return false;
                    }
                    var myResourceTab = $(this).closest('.tab-pane.active'),
                        myResourceFolderlist = $(this);

                    if(myResourceTab.find('.dd-header .popover.in').length > 0) {
                        var inputEL = myResourceFolderlist.find('.fln-input'),
                            checkScroll = (myResourceFolderlist.find('.dd-list.fll').height() >= myResourceFolderlist.height()) ? true : false,
                            offset = myResourceTab.find('.dd-header').outerHeight() + 3,
                            top = (checkScroll) ? inputEL.closest('li').position().top - myResourceFolderlist.scrollTop() : inputEL.offset().top - myResourceFolderlist.offset().top;
                        myResourceTab.find('.dd-header .popover.in').css('top', offset + top);
                    }
                })
                .on('mouseup', '#nestableFolder .fli', function(e) {
                    var fliFolder = $('#nestableFolder'),
                        fliResourceTab = $(this).closest('.tab-pane.active'),
                        fliResourceFiles = fliResourceTab.find('ul.files'),
                        fliResourceSelected = fliResourceTab.find('.resource-selected-ul'),
                        rmode = fliResourceTab.attr('id').replace(/storage$/gi,''),
                        fsort = fliResourceTab.find('.resource-ctrl-sort select').val(),
                        fsearch = fliResourceTab.find('.resource-search-stx').val();

                    if(fileDrag) {
                        fliResourceFiles.find('.fitem .fitem-visual').removeClass('ui-selected');
                        fliFolder.find('.fli').removeClass('drag-selected');
    
                        // selected-files 파일을 $.post로 보내고 리스트 페이지 갱신
                        var prevffolder = [], fsizes = [], fseqs = [],
                            targetffolder = $(this).attr('data-id');

                        fliResourceSelected.children('li').each(function() {
                            prevffolder.push($(this).attr('data-ffolder')); 
                            fsizes.push(parseInt($(this).find('p.selected-file-size .size').text()));
                            fseqs.push($(this).attr('data-seq'));
                        });
    
                        if(SID) {
                            var activeffolder = fliFolder.find('.fli.active').attr('data-id'),
                                r_pages = Number(fliResourceTab.find('.resource-paging .pagination').attr('data-pages')),
                                r_page = Number(fliResourceTab.find('.resource-paging .pagination li.active').text()),
                                r_file_cnt = fliResourceFiles.find('.fitem').length;
    
                            $.post('/template/resource/update-fmove', { sid: SID, fseqs: fseqs, targetffolder: targetffolder }, function (data) {
                                checkError(data);
                                $.each(fseqs, function(i,v) {
                                    if(prevffolder[i] != targetffolder) {
                                        if(prevffolder[i] != 'all') $.resource.setMystorageFolder('set_fli_state', {'count': -1, 'size': -fsizes[i], ffolder: prevffolder[i], state: 'move'});
                                        if(targetffolder != 'all') $.resource.setMystorageFolder('set_fli_state', {'count': 1, 'size': fsizes[i], ffolder: targetffolder, state: 'move'});
                                    }
                                });
                                updateOutputFolder($('#nestableFolder').data('output', $('#nestableFolder-output')));
    
                                r_page = ((r_file_cnt - fseqs.length) == 0 && r_pages<=r_page && SFOLDER_ACTIVE) ? r_page-1 : r_page;
                                r_page = 1;
                                cPage = 1;
                                resourceGetPage(r_page,SFOLDER_ACTIVE,fsort,fsearch);
                                
                                fliResourceFiles.find('.fitem .resource-image.ui-selected').removeClass('ui-selected');
                                fliResourceFiles.find('.fitem.ui-selected').removeClass('ui-selected');
                                fliResourceSelected.empty();
                                setResourceSelectedBox(rmode);
                            }, 'json');
                        }
                    }
                })
                .on('mouseenter', '#nestableFolder .fli', function(e) {
                    $('#nestableFolder .fli').removeClass('drag-selected');
                    if(fileDrag) {
                        $(this).addClass('drag-selected');
                    }
                })
                .on('mouseleave', '#nestableFolder .fli', function(e) {
                    $(this).removeClass('drag-selected').siblings().removeClass('drag-selected');
                })
                .on('click', '#nestableFolder .fli:not(.active)', function(e) {
                    if( isFEdit ||
                        $(e.target).is('.fln-input, .fli-hover, [class*="btn-fln-"]')
                    ) { return; }

                    if($(this).parents('.fll').length == 2) depfolderClick = true;
                    if($(this).parents('.fll').length == 1 && depfolderClick) {
                        depfolderClick = false;
                        return;
                    } else {
                        $(this).addClass('active').siblings('.fli').removeClass('active');
                        SFOLDER_ACTIVE = ($(this).attr('data-id')!='all') ? $(this).attr('data-id') : '';
                        cPage = 1;
                        
                        var myResourceTab = $('#mystorage'),
                            fsort = myResourceTab.find('.resource-ctrl-sort select').val();
                        myResourceTab.find('.resource-search-stx').val('');
                        resourceGetPage(1,SFOLDER_ACTIVE,fsort,'');
                    }
                })
                .on('click', '#nestableFolder .fli .dd-fle', function(e) {
                    if(isFEdit) { return; }
                    if($(this).parent().closest('.fli').index() > 0) {
                        isFEdit = true;
                        mystorageFolderEdit($(this));
                    }
                })
                .on('click', '#nestableFolder .fli .dd-fln .btn-fln-cancel', function(e) {
                    $('#mystorage .add-folder').attr('data-content','').popover('hide');
                    if($(this).closest('li.fli').attr('data-id') == 'clEmptyFolder') $(this).closest('li.fli').remove();
                    else {
                        $(this).closest('.dd-fln').find('.fln-group').remove();
                        $(this).remove();
                    }
                    isFEdit = false;
                    $.resource.setMystorageFolder('nodrag',false);
                    if($('#nestableFolder .fll .fli.active').length == 0) $('#nestableFolder .fli').eq(0).click();
                })
                .on('click', '#nestableFolder .fli .dd-fln .btn-fln-save', function(e) {
                    var myResourceTab = $(this).closest('.tab-pane.active'),
                        myResourceFiles = myResourceTab.find('ul.files'),
                        myResourceFolderlist = myResourceTab.find('#nestableFolder'),
                        myResourceFolderItem = $(this).closest('li.fli'),
                        checkPageReload = myResourceFolderItem.hasClass('active'),
                        fsort = myResourceTab.find('.resource-ctrl-sort select').val(),
                        fsearch = myResourceTab.find('.resource-search-stx').val(),
                        inputEL = $(this).closest('.fln-group').find('.fln-input'),
                        regExp = /[\{\}\[\]\/!?.,;:|\)*~`^\-_+<>@\#$%&\\\=\(\'\"]/gi,
                        err_str = '',
                        checkAdd = (myResourceFolderItem.attr('data-id') == 'clEmptyFolder') ? true : false,
                        beforeFln = (checkAdd) ? '' : myResourceFolderItem.attr('data-id'),
                        afterFln = inputEL.val().trim();

                    if(afterFln.length == 0) {
                        err_str = $.lang[LANG]['editor.resource.regExp.empty'];
                    } else if(afterFln == 'clEmptyFolder') {
                        err_str = $.lang[LANG]['editor.resource.regExp.clEmptyFolder'];
                    } else if(checkEmojis(afterFln)) {
                        err_str = $.lang[LANG]['config.unable.emoji'];
                    } else if(regExp.test(afterFln)) {
                        err_str = $.lang[LANG]['editor.resource.regExp.specialchar'];
                    } else if($('#nestableFolder .fli[data-id="'+afterFln.replace(/ /g,'-')+'"]').length > 0 && beforeFln != afterFln.replace(/ /g,'-')) {
                        err_str = $.lang[LANG]['editor.resource.regExp.overlap'];
                    } else if(afterFln.length > 20) {
                        err_str = $.lang[LANG]['editor.resource.regExp.maximum'];
                    } else { 
                        err_str = '';
                    }

                    afterFln = afterFln.replace(/ /g,'-');
                    if(err_str!=''){
                        inputEL.focus();
                        myResourceTab.find('.add-folder').attr('data-content',err_str).popover('show');

                        var checkScroll = (myResourceFolderlist.find('.dd-list.fll').height() >= myResourceFolderlist.height()) ? true : false,
                            offset = myResourceTab.find('.dd-header').outerHeight() + 3,
                            top = (checkScroll) ? inputEL.closest('li').position().top - myResourceFolderlist.scrollTop() : inputEL.offset().top - myResourceFolderlist.offset().top;
                        myResourceTab.find('.dd-header .popover.in').css('top', offset + top);
                    } else { 
                        myResourceTab.find('.add-folder').attr('data-content','').popover('hide');

                        inputEL.closest('.fli').attr('data-id',afterFln).find('[attr-id]').attr('attr-id',afterFln);
                        inputEL.closest('.dd-fln').html(afterFln.replace(/-/g,' '));
                        updateOutputFolder($('#nestableFolder').data('output', $('#nestableFolder-output')));
                        mystorageFolderUpdate(beforeFln,afterFln);

                        if(checkPageReload) {
                            SFOLDER_ACTIVE = afterFln;
                            resourceGetPage(1,SFOLDER_ACTIVE,fsort,fsearch);
                        } else {
                            myResourceFiles.find('.fitem .data-ffolder ul[data-ffolder="'+beforeFln+'"]').each(function() {
                                $(this).attr('data-ffolder',afterFln);
                            })
                        }

                        isFEdit = false;
                        $.resource.setMystorageFolder('nodrag',false);
                    }
                })
                .on('keyup', '#nestableFolder .fli .dd-fln .fln-input', function(e) {
                    if(e.keyCode == 13) $(this).closest('.fln-group').find('.btn-fln-save').click();
                })
                .on('click', '#nestableFolder .fli .dd-fld', function(e) {
                    if(isFEdit) { return; }
                    if($('#nestableFolder .fll > .fli').length < 2) { return false; }

                    isFEdit = true;
                    $.resource.setMystorageFolder('nodrag',true);
                    var myResourceTab = $('#mystorage'),
                        myResourceFiles = myResourceTab.find('ul.files'),
                        myResourceSelected = myResourceTab.find('.resource-selected-ul'),
                        myResourceFolderItem = $(this).closest('li.fli'),
                        checkPageReload = (myResourceFolderItem.hasClass('active') || $('#nestableFolder .fli[data-id="all"]').hasClass('active')) ? true : false,
                        fsort = myResourceTab.find('.resource-ctrl-sort select').val(),
                        fsearch = myResourceTab.find('.resource-search-stx').val();

                    var fli_count = myResourceFolderItem.find('.dd-flc').attr('attr-count');
                    fli_count = (typeof fli_count != 'undefined' && /^[0-9]*$/.test(fli_count)) ? fli_count * 1 : 0;
                    if(fli_count > 0) {
                        var prevffolder = myResourceFolderItem.attr('data-id');
                        var modal_str = '\
                                <div class="popup-info edit-link-info">'+$.lang[LANG]['editor.resource.folder.delete.confirm']+'</div>\
                                <ul class="duplicate-gallery-content delete-folder">\
                                    <li class="link-type active">\
                                        <div class="delete">\
                                            ' + clSVG('checkbox_active',20,20,false) + '\
                                            <h5>'+$.lang[LANG]['editor.resource.folder.delete.folderOnly']+'</h5>\
                                        </div>\
                                    </li>\
                                    <li class="link-type">\
                                        <div class="delete-with-resource">\
                                            ' + clSVG('checkbox_active',20,20,false) + '\
                                            <h5>'+$.lang[LANG]['editor.resource.folder.delete.all']+'</h5>\
                                        </div>\
                                    </li>\
                                </ul>\
                        ';

                        var modal = $(this).showModalFlat($.lang[LANG]['editor.resource.folder.delete'], modal_str, true, true, function() {
                            var checked = $('.link-type.active').find('div').attr('class');

                            $.ajaxSetup({ async : true });
                            if(checked == 'delete-with-resource') {
                                checkPageReload = true;
                                $.post('/template/resource/get-folder-resource', { sid: SID, prevffolder: prevffolder }, function (data) {         
                                    checkError(data);

                                    var files = data.files;
                                    var fileDeleteModal = $(this).showModalFlat($.lang[LANG]['config.common.resource.delete.title'],$.lang[LANG]['config.common.resource.delete'], true, true, function() {
                                        fileDeleteModal.modal('hide');
                                        $.progressON();
                                        var seqs = [], sizes = [], ffolders = [];
                                        $.each(files, function(idx, f){
                                            seqs.push(f.seq);
                                            sizes.push(f.file_size);
                                            ffolders.push(f.file_folder);
                                        });
                                        var total = files.length,
                                            deleting = '',
                                            progress = 0;
                                            loading = '<i class="fa fa-circle-o-notch fa-spin fa-3x fa-fw"></i> ';
                                            done = 0; deleting = $('p.fitem-name[data-seq="' + seqs[0] + '"]').text();
                                        $('.progressModal .info1').html(loading + deleting);

                                        $.each(files,function(i,f) {
                                            var t = setTimeout(function() {
                                                if(CANCEL) {
                                                    if(ABORT) {
                                                        resourceGetPage(1,SFOLDER_ACTIVE,fsort,fsearch);
                                                        updateOutputFolder($('#nestableFolder').data('output', $('#nestableFolder-output')));
                                                        ABORT = false;
                                                        $.progressOFF();
                                                    }
                                                    i=0; return false;
                                                }
                                                mystorageFileDelete(f.file_name, f.seq, function() {
                                                    done++;
                                                    progress = parseInt((done / total) * 100,10);
                                                    $('.file-upload-progress .progress-bar').css('width',progress + "%");
                                                    $('.progressModal .info2').text(done.toString() + ' / ' + total.toString());
                                                    
                                                    $.resource.setMystorageFolder('set_fli_state', {'count': -1, 'size': -sizes[i], ffolder: 'all', state: 'delete'});
                                                    if(ffolders[i] != '' && ffolders[i] != 'all') {
                                                        $.resource.setMystorageFolder('set_fli_state', {'count': -1, 'size': -sizes[i], ffolder: ffolders[i], state: 'delete'});
                                                    }                       

                                                    if(total == done) {
                                                        myResourceFolderItem.addClass('deleted');
                                                        setTimeout(function() {
                                                            modal.modal('hide');
                                                        },500);
                                                    } else {
                                                        deleting = $('p.fitem-name[data-seq="' + seqs[i+1] + '"]').text();
                                                        $('.progressModal .info1').html(loading + deleting);
                                                    }
                                                });
                                            },500*i);
                                        });
                                    },'cancel','ok','modal-over-1 cl-cmmodal cl-s-btn cl-common-notice w560',false);
                                    
                                }, 'json');
                            } else { //폴더만 삭제
                                $.processON('delete folder...');
                                var deferred = $.Deferred();
                                $.post('/template/resource/delete-folder-only', { sid: SID, prevffolder: prevffolder }, function (data) {
                                    checkError(data);
                                    myResourceFolderItem.addClass('deleted');
                                    modal.modal('hide');
                                });
                            }
                            
                        }, 'cancel', $.lang[LANG]['editor.resource.folder.delete.btn.delete'], 'modal-over-1 cl-cmmodal cl-s-btn w560 cl-p0 confirm-resource-folder-delete agreement-duplicate-contents', false, '', '', function() {
                            isFEdit = false;
                            $.resource.setMystorageFolder('nodrag',false);

                            if($('.progressModal').length > 0) $.progressOFF();
                            if($('.processModal').length > 0) $.processOFF();
                            if(myResourceTab.find('#nestableFolder .fli.deleted').length > 0) {
                                myResourceTab.find('#nestableFolder .fli.deleted').remove();
                                updateOutputFolder($('#nestableFolder').data('output', $('#nestableFolder-output')));

                                myResourceFiles.find('.fitem.ui-selected').removeClass('ui-selected');
                                myResourceSelected.children('li').remove();
                                if(checkPageReload) $('#nestableFolder .fll > .fli').first().removeClass('active').click();
                            }
                        });
                    } else {
                        var checkModal = $(this).showModalFlat($.lang[LANG]['editor.resource.folder.delete'], $.lang[LANG]['editor.resource.folder.delete.check'], true, true, function() {
                            myResourceFolderItem.remove();
                            updateOutputFolder($('#nestableFolder').data('output', $('#nestableFolder-output')));
                            checkModal.modal('hide');
                        }, 'cancel', 'ok', 'cl-p130 cl-cmmodal cl-s-btn w560 cl-p0 zindex1042', false, '', '', function() {
                            isFEdit = false;
                            $.resource.setMystorageFolder('nodrag',false);

                            if(checkPageReload) $('#nestableFolder .fll > .fli').first().removeClass('active').click();
                            $.processOFF();
                        });
                    }
                })
                .on('click', '.add-folder', function(e) {
                    $('.add-folder').attr('data-content','').popover('hide');
                    var myResourceFolderlist = $('#mystorage #nestableFolder'),
                        myResourceFolderAdd = $(this);

                    if(isFEdit || myResourceFolderlist.find('.fln-input').length > 0) {
                        if(myResourceFolderlist.find('.fln-input').length > 0) myResourceFolderlist.find('.fln-input').focus();
                        isFEdit = true;
                        $.resource.setMystorageFolder('nodrag',true);
                        return; 
                    }
                    var checkPlan = (typeof property == 'undefined') ? ((typeof VALIDPLAN == 'undefined') ? $.gallery.valid_plan : VALIDPLAN) : property.VALIDPLAN,
                        checkPlanType = (typeof property == 'undefined') ? ((typeof VALIDTYPE == 'undefined') ? $.gallery.valid_type : VALIDTYPE) : property.VALIDTYPE,
                        checkFREE = (!checkPlan || checkPlanType == 'PK') ? true : false;
                    var checkMaximum = (    (!checkFREE && myResourceFolderlist.find('.fli').length > 500) || 
                                            (checkFREE && myResourceFolderlist.find('.fli').length > 50)
                                        ) ? true : false;
                    if(checkMaximum) {
                        var max_msg = (!checkFREE) ? $.lang[LANG]['editor.resource.folder.maximum'] : $.lang[LANG]['editor.resource.folder.maximum.free'];
                        var max_modal = $(this).showModalFlat($.lang[LANG]['config.information'], max_msg, true, false,'','close', 'ok', 'cl-cmmodal cl-s-btn w560 cl-p70 cl-p0', false, '', function() {
                            max_modal.closest('.flat-modal').next('.modal-backdrop').attr('style','z-index: 1041!important;');
                        });
                        return;
                    } else {
                        isFEdit = true;

                        if(myResourceFolderlist.find('.fli[data-id="clEmptyFolder"]').length > 0) {
                            myResourceFolderlist.find('.fli[data-id="clEmptyFolder"]').find('.dd-fln').val('');
                        } else {
                            var add_folder = $.resource.getMystorageFolderHtml('clEmptyFolder', 0, 0);
                            myResourceFolderlist.find('.fll').append(add_folder);
                        }

                        var input_html = '\
                            <div class="fln-group input-group">\
                                <input class="fln-input form-control" type="text"/>\
                                <span class="input-group-btn"><button class="btn-fln-save btn btn-default btn-primary" type="button"><i class="fa fa-check"></i></button></span>\
                                <div class="btn-fln-cancel"><i class="fa fa-times"></i></div>\
                            </div>\
                            ';

                        $(input_html).appendTo(myResourceFolderlist.find('.fli[data-id="clEmptyFolder"] .dd-fln')).find('.fln-input').focus();
                        if(myResourceFolderlist.find('.dd-list.fll').height() >= myResourceFolderlist.height() && $.browser.safari == undefined) {
                            myResourceFolderlist.find('.dd-fln').find('.fln-group').css('max-width','182px');
                            myResourceFolderlist.find('.dd-fln').find('.fln-input').css('max-width','155px');
                            myResourceFolderlist.scrollTop(2000);
                        }
                        $.resource.setMystorageFolder('nodrag',true);
                    }
                })
                .on('click', '#mystorageUploadBtn', function(e) {
                    var myResourceTab = $('#mystorage'),
                        fsort = myResourceTab.find('.resource-ctrl-sort select').val(),
                        fsearch = myResourceTab.find('.resource-search-stx').val(),
                        ffolder = (SFOLDER_ACTIVE) ? SFOLDER_ACTIVE : 'all';

                    $.uploadON();
                    $(this).fileupload({
                        url: '/template/resource/upload/ffolder/'+ffolder,
                        dataType: 'json',
                        pasteZone: null,
                        dropZone: null,
                        async: true,
                        prependFiles: true,
                        sequentialUploads: true,
                        add: function(e,data) {
                            var r = $.upload_add(e,data,'image');
                            if(r.submit) {
                                var jqXHR = data.submit();
                                UPLOAD++;
                            } else {
                                data.context.find('.loading').html('<i class="fa fa-times error"></i>');
                                data.context.find('.ing').addClass('error').text(r.err);
                            }

                            $('.uploadModal .upload-cancel .btn, .uploadModal .upload-close').off('click').on('click', function(e) {
                                if(jqXHR != undefined) jqXHR.abort();
                                data.context.fadeOut().remove();
                                $('.uploadModal #file-upload-progress').css('width','0%');
                                $.uploadOFF();
                                UPLOAD = 0;
                                UPLOADED = 0;
                                PROGRESS = 0;

                                updateOutputFolder($('#nestableFolder').data('output', $('#nestableFolder-output')));
                                resourceGetPage(1,SFOLDER_ACTIVE,fsort,fsearch);
                            });
                        },
                        progress: function(e, data) {
                            $.upload_progress(e,data);
                        },                        
                        done: function (e, data) {
                            $.upload_done(e,data);
                            UPLOADED++;

                            var isSuccess = (typeof data._response.result != 'undefined' && typeof data._response.result.error != 'undefined') ? false : true;
                            if(isSuccess) {
                                var add_fls = parseFloat(data.files[0].size / 1024).toFixed(2);

                                $.resource.setMystorageFolder('set_fli_state', {'count': 1, 'size': add_fls, ffolder: 'all', state: 'upload'});
                                if(SFOLDER_ACTIVE != '') $.resource.setMystorageFolder('set_fli_state', {'count': 1, 'size': add_fls, ffolder: SFOLDER_ACTIVE, state: 'upload'});    
                            }

                            if(UPLOADED && data.context.find('.error').length == 0) {
                                //$.uploadON(UPLOADED + " / " + UPLOAD + "<br>images creating...");
                                if(UPLOAD==UPLOADED) {
                                    setTimeout(function() {
                                        $.uploadOFF();
                                        UPLOAD = 0;
                                        UPLOADED = 0;
                                        PROGRESS = 0;

                                        updateOutputFolder($('#nestableFolder').data('output', $('#nestableFolder-output')));
                                        resourceGetPage(1,SFOLDER_ACTIVE,'date_desc','');
                                    },1000);
                                }
                            }
                        },
                        progressall: function (e, data) {
                            $.upload_progressall(e,data);
                        },
                        start : function(e, data) {
                            $.upload_start(e,data);
                            progress1 = 0; progress2 = 0; PROGRESS = 0;
                        },
                        dragover : function(e, data) {
                            e.preventDefault();
                        }
                    }).prop('disabled', !$.support.fileInput)
                        .parent().addClass($.support.fileInput ? undefined : 'disabled');
                })
                .on('mousedown', '.fitem', function(e) {
                    if($(this).hasClass('ui-selected')) fileDrag = true;
                })
                .on('mouseup', '.fitem', function(e) {
                    if($(this).closest('.tab-pane.active').find('#nestableFolder').length > 0) $(this).closest('.tab-pane.active').find('#nestableFolder .fli').removeClass('drag-selected');
                    fileDrag = false;
                })
                .on('mousemove', '.fitem', function(e) {
                    if(fileDrag && $(this).closest('.modal.in').find('.resource-tooltip').css('display') == 'none') {
                        var str_class = ($(this).closest('.tab-pane.active').find('ul.files .ui-selected').length > 1) ? 'multiple' : '',
                            str_count = $(this).closest('.tab-pane.active').find('.resource-selected-ul').children('li').length,
                            str_img = $(this).find('.fitem-img').attr('src');
                        $(this).closest('.modal.in').find('.resource-tooltip').fadeIn().addClass(str_class)
                            .find('img').attr('src',str_img)
                            .next('.count').text(str_count);
                    }
                })
                .on('click', '.fitem-ctrl-del', function(e) {
                    var delResourceTab = $(this).closest('.tab-pane.active'),
                        delResourceFiles = delResourceTab.find('ul.files'),
                        delResourceSelected = delResourceTab.find('.resource-selected-ul'),
                        fsort = delResourceTab.find('.resource-ctrl-sort select').val(),
                        fsearch = delResourceTab.find('.resource-search-stx').val(),
                        file    = $(this).closest('ul').attr('data-source'),
                        seq     = $(this).closest('ul').attr('data-seq'),
                        size    = $(this).closest('ul').attr('data-fsize'),
                        ffolder = $(this).closest('ul').attr('data-ffolder');

                    var modal = $(this).showModalFlat($.lang[LANG]['config.common.resource.delete.title'],$.lang[LANG]['config.common.resource.delete'], true, true, function() {
                        $.processON('Deleting the image(s)...');
                        modal.modal('hide');
                        delResourceFiles.find('.fitem p.fitem-name[data-seq="' + seq + '"]').remove();
                        delResourceSelected.children('li[data-seq="' + seq + '"]').remove();
                        if(delResourceSelected.length == 0) delResourceTab.find('.resource-useit').removeClass('active');

                        mystorageFileDelete(file,seq,function() {
                            $.resource.setMystorageFolder('set_fli_state', {'count': -1, 'size': -size, ffolder: 'all', state: 'delete'});
                            if(ffolder != '' && ffolder != 'all') {
                                $.resource.setMystorageFolder('set_fli_state', {'count': -1, 'size': -size, ffolder: ffolder, state: 'delete'});
                            }
                            updateOutputFolder($('#nestableFolder').data('output', $('#nestableFolder-output')));

                            resourceGetPage(1,SFOLDER_ACTIVE,fsort,fsearch);
                            $.processOFF();
                        });

                    },'cancel','ok','modal-over-1 cl-cmmodal cl-s-btn cl-common-notice w560',false);
                })
                .on('click', '.resource-ctrl-deletes', function(e) {
                    var myResourceTab = $('#mystorage'),
                        myResourceFiles = myResourceTab.find('ul.files'),
                        myResourceSelected = myResourceTab.find('.resource-selected-ul'),
                        fsort = myResourceTab.find('.resource-ctrl-sort select').val(),
                        fsearch = myResourceTab.find('.resource-search-stx').val();
    
                    if(myResourceSelected.children('li').length==0) return;
    
                    var r_pages = Number(myResourceTab.find('.resource-paging .pagination').attr('data-pages')),
                        r_page = Number($('.resource-paging .pagination li.active').text()),
                        r_file_cnt = myResourceFiles.find('.fitem').length;
                        
                    var modal = $(this).showModalFlat($.lang[LANG]['config.common.resource.delete.title'],$.lang[LANG]['config.common.resource.delete'], true, true, function() {
                        modal.modal('hide');
                        $.progressON();              
                        var files = [], seqs = [], sizes = [], ffolders = [];
                        myResourceSelected.children('li').each(function () {
                            files.push($(this).attr('data-source'));
                            seqs.push($(this).attr('data-seq'));
                            sizes.push($(this).find('.selected-file-size .size').text());
                            ffolders.push($(this).attr('data-ffolder'));
                        });
    
                        myResourceSelected.empty();
                        myResourceTab.find('.resource-useit').removeClass('active');
    
                        var total = files.length, deleting = '', progress = 0; loading = '<i class="fa fa-circle-o-notch fa-spin fa-3x fa-fw"></i> ';
                            done = 0; deleting = myResourceFiles.find('p.fitem-name[data-seq="' + seqs[0] + '"]').text();
                        $('.progressModal .info1').html(loading + deleting);
    
                        $.each(files,function(i,v) {
                            var t = setTimeout(function() {
                                if(CANCEL) {
                                    if(ABORT) {
                                        updateOutputFolder($('#nestableFolder').data('output', $('#nestableFolder-output')));
                                        resourceGetPage(1,SFOLDER_ACTIVE,fsort,fsearch);
                                        ABORT = false;
                                        $.progressOFF();
                                    }
                                    i=0; return false;
                                }
    
                                mystorageFileDelete(v,seqs[i],function() {
                                    done++;
                                    progress = parseInt((done / total) * 100,10);
                                    $('.file-upload-progress .progress-bar').css('width',progress + "%");
                                    $('.progressModal .info2').text(done.toString() + ' / ' + total.toString());

                                    $.resource.setMystorageFolder('set_fli_state', {'count': -1, 'size': -sizes[i], ffolder: 'all', state: 'delete'});
                                    if(ffolders[i] != '' && ffolders[i] != 'all') {
                                        $.resource.setMystorageFolder('set_fli_state', {'count': -1, 'size': -sizes[i], ffolder: ffolders[i], state: 'delete'});
                                    }

                                    if(total == done) {
                                        r_page = ((r_file_cnt-files.length) == 0 && r_pages<=r_page) ? r_page-1 : r_page;
                                        r_page = 1;
                                        setTimeout(function() {
                                            updateOutputFolder($('#nestableFolder').data('output', $('#nestableFolder-output')));
                                            resourceGetPage(r_page,SFOLDER_ACTIVE,fsort,fsearch);
                                            $.progressOFF();
                                        },1000);
                                    } else {
                                        deleting = myResourceFiles.find('p.fitem-name[data-seq="' + seqs[i+1] + '"]').text();
                                        $('.progressModal .info1').html(loading + deleting);
                                    }
                                });
                            },500*i);
                        });
    
                    },'cancel','ok','modal-over-1 cl-cmmodal cl-s-btn cl-common-notice w560',false);
                })
                .on('click', '.resource-ctrl-downloads', function(e) {
                    var myResourceTab = $('#mystorage'),
                        myResourceFiles = myResourceTab.find('ul.files'),
                        myResourceSelected = myResourceTab.find('.resource-selected-ul');

                    var files = [], seqs = [], sizes = [], ffolders = [], file_path = [], org_name = [];

                    if(myResourceSelected.children('li').length == 0) {
                        return false;
                    } else if(myResourceSelected.children('li').length == 1) {
                        var seq = $(myResourceSelected.children('li')[0]).data('seq');
                        $('ul[data-seq="' + seq + '"] .fitem-ctrl-down').get(0).click();
                        return false;
                    }

                    myResourceSelected.children('li').each(function () {
                        var src = getServeImage($(this).attr('data-source'), 0, 'https:' + RESOURCE + '/' + SID);
                        var file_name = $(this).find('.selected-file-title').text();
                        file_path.push(src);
                        org_name.push(file_name);
                    });
                    $.processON($.lang[LANG]['editor.resource.batchdownload']);
                    setTimeout(function() {
                        $.ajax({
                            url:'/template/resource/batch-download',
                            type:'post',
                            async: true,
                            data:{
                                'file_path': file_path,
                                'org_name': org_name
                            },
                            dataType:'json',
                            success:function(data) {
                                var filename = data.filename;
                                var base64Data = data.filedata;
                                if(!base64Data) return false;

                                var binaryString = atob(base64Data);
                                var len = binaryString.length;
                                var bytes = new Uint8Array(len);
                                for (let i = 0; i < len; i++) {
                                    bytes[i] = binaryString.charCodeAt(i);
                                }

                                // Blob 객체 생성
                                var blob = new Blob([bytes], { type: 'application/zip' });

                                // Blob URL 생성
                                var url = URL.createObjectURL(blob);

                                // 다운로드 링크 생성 및 클릭하여 파일 다운로드
                                var a = document.createElement('a');
                                a.href = url;
                                a.download = filename;
                                document.body.appendChild(a);
                                a.click();

                                // 링크 제거
                                document.body.removeChild(a);
                                URL.revokeObjectURL(url);
                            }, 
                            complete:function() {
                                $.processOFF();
                            }
                        });
                    });
                });


            $('#mystorage #nestableFolder').nestable({
                    maxDepth: 1,
                    handleClass: 'dd-handle',
                    noDragClass: 'fl-nodrag',
                })
                .on('changing', function(e) {
                    if(isFEdit || $(this).find('.fln-group.input-group').length > 0) {
                        e.preventDefault();
                        return false;
                    }

                    updateOutputFolder($('#nestableFolder').data('output', $('#nestableFolder-output')));
                });

            $('#mystorage ul.files').selectableScroll({
                options:{
                    scrollSnapX: 120,
                    scrollSnapY: 120,
                    scrollAmount: 5
                },
                filter: '.fitem',
                cancel: 'i, .ui-selected, .fitem-ctrl',
                start: function(event, ui) {
                    $('#mystorage ul.files').addClass('__file_selecting');
                },
                selecting: function(event, ui) {
                },
                stop: function(event, ui) {
                    $('#mystorage ul.files').removeClass('__file_selecting');
                },
                selected: function(event, ui) {
                    if($(ui.selected).is('.fitem')) {
                        var myResourceTab = $('#mystorage'),
                            myResourceSelected = myResourceTab.find('.resource-selected-ul'),
                            file_seq = $(ui.selected).find('.fitem-ctrl > ul').attr('data-seq');
                        
                        if(typeof file_seq != 'undefined' && myResourceSelected.find('li[data-seq="'+file_seq+'"]').length == 0) {
                            var magic = $(ui.selected).find('p.fitem-name').attr('data-magic'),
                                file = $(ui.selected).find('p.fitem-name').attr('data-source'),
                                file_path = RPATH + '60/' + file,
                                full_path = (magic == '') ? file_path : magic+'=s60-c',
                                ffolder = $(ui.selected).find('.fitem-ctrl > ul').attr('data-ffolder'),
                                file_title = $(ui.selected).find('p.fitem-name').attr('data-original-title'),
                                file_size = $(ui.selected).find('p.fitem-size .size').attr('data-size'),
                                file_width = $(ui.selected).find('p.fitem-size .width').text(),
                                file_height = $(ui.selected).find('p.fitem-size .height').text(),
                                selected_file_name = (magic) ? magic : file;
                            
                            myResourceSelected.append('<li data-source="' + file + '" data-ffolder="' + ffolder + '" data-seq="'+file_seq+'" data-size="'+file_size+'"><img src="' + full_path + '"><div class="selected-hover">&times;<p class="selected-file-name">' + selected_file_name + '</p><p class="selected-file-title">' + file_title + '</p><p class="selected-file-size"><span class="size">' + file_size + '</span><span class="width">' + file_width + '</span><span class="height">' + file_height + '</span></p></div></li>');
                        }
                    }
                    setResourceSelectedBox('my');
                },
                unselected: function(event, ui) {
                    if($(ui.unselected).is('.fitem')) {
                        if(!event.ctrlKey && !event.shiftKey) {
                            $('#mystorage .resource-selected-ul').empty();
                        }
                    }
                    setResourceSelectedBox('my');
                }
            });


            /* modal-resourcebox 02__freestorage */
            var freestorageFitemHtml = function(src,profile,name,link,color,full,raw,down,width,height,id,type,i) {
                
                var fitem_ctrl_star = (type != 'used') ? '<li><span class="fitem-ctrl-star '+((type=='favor') ? 'active' : '')+'"><svg class="active" viewBox="0 0 16 16" width="16" hegiht="16"><path d="m14.5 6.52-4.52-.88L8 1.5 6.02 5.64l-4.52.88 3.11 3.25-.57 4.73L8 12.43l3.96 2.07-.57-4.73z"/></svg><svg viewBox="0 0 16 16" width="16" hegiht="16"><path d="m8 3.82 1.08 2.25.22.45.49.1 2.73.53-1.85 1.93-.33.34.06.47.34 2.84-2.28-1.19L8 11.3l-.46.24-2.28 1.19.34-2.84.06-.47-.33-.34-1.84-1.93 2.73-.53.49-.1.22-.45L8 3.82M8 1.5 6.02 5.64l-4.52.88 3.11 3.25-.57 4.73L8 12.43l3.96 2.07-.57-4.73 3.11-3.25-4.52-.88L8 1.5z"/></svg></span></li>' : '',
                    fitem_str = '\
                    <li class="fitem" data-idx="' + i + '">\
                        <div class="fitem-wrap">\
                            <div class="fitem-visual">\
                                <div class="fitem-thumb">\
                                    <div class="fitem-mold"><img src="https://storage.googleapis.com/i.addblock.net/sample/sns_cm_1.png"/></div>\
                                    <img class="fitem-img" src="' + src + '">\
                                </div>\
                                <div class="fitem-ctrl">\
                                    <ul data-color="' + color + '" data-username="' + name + '" data-raw="' + raw + '" data-full="' + full + '" data-small="' + src + '" data-down="' + down + '" data-userlink="' + link + '" data-width="' + width + '" data-height="' + height + '" data-id="' + id + '">\
                                        <li><a class="fitem-ctrl-imgview" data-url="' + full + '" data-img-original="ON"><svg viewBox="0 0 13 13" width="13" height="13"><path d="M5.14 1c2.28 0 4.14 1.86 4.14 4.14 0 2.28-1.86 4.14-4.14 4.14S1 7.43 1 5.14C1 2.86 2.86 1 5.14 1m0-1C2.3 0 0 2.3 0 5.14s2.3 5.14 5.14 5.14 5.14-2.3 5.14-5.14S7.98 0 5.14 0z"/><path d="M12.5 13a.47.47 0 0 1-.35-.15L8.22 8.92c-.2-.2-.2-.51 0-.71s.51-.2.71 0l3.93 3.93c.2.2.2.51 0 .71-.1.1-.23.15-.36.15z"/></svg></a></li>\
                                        ' + fitem_ctrl_star + '\
                                    </ul>\
                                </div>\
                            </div>\
                            <div class="fitem-content visible-layout-grid">\
                                <p class="fitem-username">Photo by <a href="' + link + '?utm_source=creatorlink&utm_medium=referral&utm_campaign=api-credit" target="_blank">' + name + '</a></p>\
                                <p class="fitem-size"><span class="width">'+width+'</span><span class="height">'+height+'</span></p>\
                            </div>\
                        </div>\
                    </li>\
                ';

                return fitem_str;
            }

            var rePaintFavor = function() {
                var $org = $('#freestorage .fitem'),
                    $items = {};

                for(var i=0; i<$org.length; i++) {
                    var $i = $('#freestorage .fitem[data-idx="' + i + '"]');
                    $items[i] = $i.clone();
                    $i.remove();
                }

                $.each($items, function(i,v) {
                    $('#freestorage ul.files').append($(this));
                });
            }

            var getFreeImage = function(page,type,stx,collection) {
                type = (typeof type == 'undefined') ? 'new' : type;
                stx = (typeof stx == 'undefined') ? '' : stx;
                page = (typeof page == 'undefined') ? 1 : page;
                collection = (typeof collection == 'undefined') ? '' : collection;
                if(type == 'new') {
                    dest = '/template/free/new/photos';
                } else if(type == 'favor') {
                    dest = '/template/favorite/list/type/F';
                } else if(type == 'search') {
                    dest = '/template/free/search/' + encodeURIComponent(stx);
                } else if(type == 'used') {
                    dest = '/template/favorite/list/type/U';
                }

                if(page>1) dest = dest + '/page/' + page;

                var freeResourceTab = $('#freestorage'),
                    freeResourceFiles = freeResourceTab.find('ul.files'),
                    freeResourceSelected = freeResourceTab.find('.resource-selected-ul');

                $.ajax({
                    type: 'GET',
                    url: dest,
                    dataType: 'json',
                    async:true,
                    success : function(data) {
                        var photos;
                        if(freeSearch.type == 'new') {
                            if(data.photos != null) {
                                photos = data.photos;    
                            } else photos = {};
                        } else {
                            photos = (data.photos == null) ? {} : data.photos.results;
                        }

                        if(photos) {
                            if(photos.length==0 || photos == null) {
                                $.resource.modalFilesEmpty(freeResourceFiles, 'No results found');
                            } else {
                                freeResourceFiles.find('.listprogress').remove();
                                $.each(photos, function(i,v) {
                                    var tpl = freestorageFitemHtml(v.urls.small, v.user.profile_image.small, v.user.username, v.user.links.html, v.color, v.urls.full, v.urls.raw,v.links.download, v.width, v.height, v.id, freeSearch.type, i);
                                    freeResourceFiles.append(tpl);
                                });

                                freeResourceFiles.selectable({ 
                                    filter: '.fitem',
                                    cancel: 'i, .ui-selected, .fitem-username, .fitem-ctrl',
                                    start: function(event, ui) {
                                        freeResourceFiles.addClass('__file_selecting');
                                    },
                                    selecting: function(event, ui) {
                                    },
                                    stop: function(event, ui) {
                                        freeResourceFiles.removeClass('__file_selecting');
                                    },
                                    selected: function(event, ui) {
                                        if($(ui.selected).is('.fitem')) {
                                            var freeResourceTab = $('#freestorage'),
                                                freeResourceSelected = freeResourceTab.find('.resource-selected-ul'),
                                                file_id = $(ui.selected).find('.fitem-ctrl > ul').attr('data-id');

                                            if(typeof file_id != 'undefined' && freeResourceSelected.children('li[data-id="'+file_id+'"]').length == 0) {
                                                var file_small = $(ui.selected).find('.fitem-ctrl > ul').attr('data-small'),
                                                    urls = new getLocation(file_small),
                                                    file = (urls.pathname).replace('/',''),
                                                    file_path = 'https://' + urls.host + urls.pathname + '?ixlib=rb-0.3.5&q=80&fm=jpg&crop=face&cs=tinysrgb&w=60&h=60&fit=crop',
                                                    tmp_image = 'https://' + urls.host + urls.pathname + '?ixlib=rb-0.3.5&q=85&fm=jpg&crop=entropy&cs=srgb',
                                                    file_width = $(ui.selected).find('.fitem-ctrl > ul').attr('data-width'),
                                                    file_height = $(ui.selected).find('.fitem-ctrl > ul').attr('data-height');

                                                freeResourceSelected.append('<li data-source="' + file + '" data-id="' + file_id + '"><img src="' + file_path + '"><div class="selected-hover">&times;<p class="selected-file-name">' + file + '</p><p class="selected-file-title">' + file + '</p><p class="selected-file-size"><span class="size">0</span><span class="width">' + file_width + '</span><span class="height">' + file_height + '</span></p><p class="selected-file-tmp">' + tmp_image + '</p></div></li>');
                                            }
                                        }
                                        setResourceSelectedBox('free');
                                    },
                                    unselected: function(event, ui) {
                                        if($(ui.unselected).is('.fitem')) {
                                            if(!event.ctrlKey && !event.shiftKey) {
                                                freeResourceSelected.empty();
                                            }
                                        }
                                        setResourceSelectedBox('free');
                                    }
                                });
                                if(freeSearch.type == 'search' || freeSearch.type == 'favor' || freeSearch.type == 'used') freeSearch.total = data.photos.total;
                                freeSearch.page = freeSearch.page + 1;

                                freeResourceTab.find('.resource-search-total').text('');
                                if(typeof data.photos.total != 'undefined' && freeSearch.type == 'search') {
                                    if(data.photos.total > 0) freeResourceTab.find('.resource-search-total').text(Number(data.photos.total).format());
                                }

                                freeResourceTab.find('.resource-search-btn').removeClass('clicked');
                                freeResourceFiles.removeClass('ready');
                                freeResourceFiles.find('.listprogress').remove();
                            }                
                        } else {
                            $.resource.modalFilesEmpty(freeResourceFiles, 'Error get photo list');
                        }
                    }
                });

            }
                
            $('.modal-resourcebox')
                .on('click', 'a[href="#freestorage"]', function(e) {
                    $('#freestorage ul.files .listprogress').remove();
                    setResourceSelectedBox('free');

                    var freeResourceTab = $('#freestorage'),
                        freeResourceFolderlist = freeResourceTab.find('.resource-folderlist'),
                        freeResourceFiles = freeResourceTab.find('ul.files'),
                        freeResourceSelected = freeResourceTab.find('.resource-selected-ul');

                    if(freeResourceFiles.hasClass('ready')) {
                        if(freeResourceFolderlist.children('li.active').length == 0) {
                            freeResourceFolderlist.children('li').click(function(e) {
                                var flTab = $(this),
                                    fl_type = (typeof flTab.attr('data-type') != 'undefined') ? flTab.attr('data-type') : '',
                                    fb_type = (typeof freeResourceFiles.attr('data-type') != 'undefined') ? freeResourceFiles.attr('data-type') : '',
                                    checkReload = (fl_type == '' || fl_type != fb_type) ? true : false;

                                flTab.addClass('active').siblings().removeClass('active');
                                if(checkReload) {
                                    freeSearch.type = fl_type;
                                    freeSearch.page = 1;
                                    freeSearch.total = -1;
                                    $.resource.modalContentInit('free');
                                    getFreeImage(freeSearch.page,freeSearch.type);
                                    freeResourceFiles.attr('data-type',fl_type);
                                }

                                if(fl_type == 'favor') {
                                    var items = freeResourceFiles.find('.fitem').length;
                                    if(freeSearch.total == items) return;
                                }

                                freeResourceSelected.empty();
                                setResourceSelectedBox('free');
                            });

                            freeSearch.type = 'new';
                            freeSearch.page = 1;
                            freeSearch.total = -1;
                            $.resource.modalContentInit('free');
                            freeResourceFolderlist.children('li[data-type="new"]').addClass('active').siblings().removeClass('active');
                            getFreeImage(freeSearch.page,freeSearch.type);
                        }
                    }
                });

            $('.modal-resourcebox #freestorage')
                .on('click', '.fitem-ctrl-star', function(e) {
                    var $i = $(this).closest('ul'),
                        $star = $(this),
                        image = {
                            'id' : $i.attr('data-id'),
                            'width' : $i.attr('data-width'),
                            'height' : $i.attr('data-height'),
                            'username' : $i.attr('data-username'),
                            'userlink' : $i.attr('data-userlink'),
                            'raw' : $i.attr('data-raw'),
                            'full' : $i.attr('data-full'),
                            'small' : $i.attr('data-small'),
                            'down' : $i.attr('data-down'),
                            'color' : $i.attr('data-color'),
                            'onoff': ($star.hasClass('active')) ? 'OFF' : 'ON',
                        },
                        $item = $star.closest('.fitem');
    
                    $.post('/template/favorite/image', { image : image },  function(data) {
                        if(data.type == 'insert') {
                            $star.addClass('active');
                        } else if(data.type == 'delete') {
                            $star.removeClass('active');
                            if(freeSearch.type == 'favor') {
                                var idx = $item.attr('data-idx');
                                $('#freestorage .fitem').each(function() {
                                    var cidx = $(this).attr('data-idx');
                                    if(cidx == idx) $(this).remove();
                                    if(idx < cidx) $(this).attr('data-idx',Number(cidx)-1);
                                });
                                freeSearch.total = freeSearch.total -1;
                                rePaintFavor();
                            }
                        }
                    },'json');
                });


            /* modal-resourcebox 03__filestorage */
            $('.modal-resourcebox #filestorage')
                .on('click', '#filestorageUploadBtn', function(e) {
                    if($('.flink-error-modal').length > 0) {
                        e.preventDefault();
                        return false;
                    }
                    var checkPlan = (typeof property == 'undefined') ? ((typeof VALIDPLAN == 'undefined') ? $.gallery.valid_plan : VALIDPLAN) : property.VALIDPLAN,
                        checkPType = (typeof property == 'undefined') ? ((typeof VALIDTYPE == 'undefined') ? $.gallery.valid_type : VALIDTYPE) : property.VALIDTYPE,
                        flink_cnt = $('#filestorage .flink-capacity .flink-cnt').text(),
                        flink_max = $('#filestorage .flink-capacity .flink-max').text(),
                        reg_max = /^[0-9]+$/,
                        error_str = '';

                    if(!checkPlan || checkPType == 'PK') error_str = $.lang[LANG]['editor.link.file.upgrade'];
                    else if(reg_max.test(flink_cnt) && Number(flink_cnt) >= Number(flink_max)) {
                        error_str = $.lang[LANG]['editor.link.file.maximum'];
                        error_str = error_str.replace('@maximum', flink_max);
                    }
                    if(error_str) {
                        var errorModal = $(this).showModalFlat($.lang[LANG]['config.information'], error_str, true, false,'','ok', '', 'cl-p130 cl-cmmodal cl-s-btn w560 cl-p0 cl-okbtn-pbt70 flink-error-modal').css('z-index','1044');
                        errorModal.closest('.flat-modal').addClass('z-1044');
                        return false;
                    }

                    $.uploadON();
                    $(this).fileupload({
                        url: '/down/flink/upload/sid/' + SID,
                        dataType: 'json',
                        pasteZone: null,
                        async: true,
                        cache: false,
                        prependFiles: true,
                        sequentialUploads: true,
                        add: function(e,data) {
                            var r = $.upload_add(e,data,'flink');

                            if(r.submit) {
                                var jqXHR = data.submit();
                                UPLOAD++;
                            } else {
                                data.context.find('.loading').html('<i class="fa fa-times error"></i>');
                                data.context.find('.ing').addClass('error').text(r.err);
                            }

                            $('.uploadModal .upload-cancel .btn, .uploadModal .upload-close').off('click').on('click', function(e) {
                                if(jqXHR != undefined) jqXHR.abort();
                                data.context.fadeOut().remove();
                                $('.uploadModal #file-upload-progress').css('width','0%');
                                $.uploadOFF();
                                UPLOAD = 0;
                                UPLOADED = 0;
                                PROGRESS = 0;

                                resourceGetPage(1,SFOLDER_ACTIVE,'date_desc','');
                            });
                        },
                        progress: function(e, data) {
                            $.upload_progress(e,data);
                        },                        
                        done: function (e, data) {
                            if(typeof data.result.error != 'undefined' && data.result.error) {
                                $('.uploadModal .upload-header h1').html($.lang[LANG]['editor.upload.title.1']);
                                $('.uploadModal .upload-content .upload-cancel .btn-default').text($.lang[LANG]['config.close']);
                                $('.file-upload-progress .progress-bar').css('width','0%');
                                $('.uploadModal .info1, .uploadModal .info2').addClass('hide');

                                data.context.find('.progress-bar').css('width','0%');
                                data.context.find('.loading').html('<i class="fa fa-times error"></i>');
                                data.context.find('.ing').addClass('error').text(data.result.error);
                                return false;
                            }
                            
                            $.upload_done(e,data);
                            UPLOADED++;
                            
                            if(UPLOADED) {
                                if(UPLOAD==UPLOADED) {
                                    setTimeout(function() {
                                        $.uploadOFF();
                                        UPLOAD = 0;
                                        UPLOADED = 0;
                                        PROGRESS = 0;
    
                                        resourceGetPage(1,SFOLDER_ACTIVE,'date_desc','');
                                    },1000);
                                }
                            }
                        },
                        progressall: function (e, data) {
                            $.upload_progressall(e,data);
                        },
                        start : function(e, data) {
                            $.upload_start(e,data);
                            progress1 = 0; progress2 = 0; PROGRESS = 0;
                        },
                        dragover : function(e) {
                            e.preventDefault();
                            e.stopPropagation();
                        },
                        drop : function(e) {
                            e.preventDefault();
                            e.stopPropagation();
                        },
                    }).prop('disabled', !$.support.fileInput)
                        .parent().addClass($.support.fileInput ? undefined : 'disabled');

                })
                .on('click', '.fitem', function(e) {
                    $(this).toggleClass('selected').siblings().removeClass('selected');
                    if($(this).hasClass('selected')) $('#filestorage .resource-useit').addClass('active');
                    else $('#filestorage .resource-useit').removeClass('active');
                })
                .on('click', '.fitem-ctrl-del', function(e) {
                    $(this).closest('.fitem').addClass('selected');
                    var selectedFlink = $('#filestorage ul.files .fitem.selected'),
                        file = selectedFlink.find('p.fitem-name').attr('data-source'),
                        id = selectedFlink.find('p.fitem-name').attr('data-seq');
                    if(typeof file == 'undefined' || typeof id == 'undefined') return false;
                    var modal = $(this).showModalFlat($.lang[LANG]['config.flink.resource.delete'],$.lang[LANG]['config.flink.resource.delete.str'], true, true, function() {

                        selectedFlink.remove();
                        $.processON('Deleting the file(s)...');
                        modal.modal('hide');
                        $('.resource-useit').removeClass('active');

                        $.ajax({
                            type: 'POST',
                            url: '/down/flink/delete',
                            data: { s: file, id: id },
                            dataType: 'json',
                            async: true,
                            success: function(data) {
                                if(typeof data.error != 'undefined' && data.error) {
                                    $(this).showModalFlat('ERROR',data.error,true,false,'','ok');
                                    return false;
                                }
                                resourceGetPage(1,SFOLDER_ACTIVE,'date_desc','');
                                $.processOFF();
                            }
                        });

                    },'cancel','ok','modal-over-1 cl-cmmodal cl-s-btn cl-common-notice w560',false);
                    modal.closest('.modal-over-1').addClass('z-1044');
                });
        },
        modalOpenSET: function(open) {
            $('.modal-resourcebox .nav-tabs li').removeClass('disabled');
            var property = (open) ? $('.modal-resourcebox .resource-useit').eq(0).attr('data-property') : '';
            if(!open) $('.modal-resourcebox .resource-useit').removeAttr('data-property');

            if(open) {
                switch(property) {
                    case 'flink-change':
                        $('#mystorage,#freestorage').removeClass('active').removeClass('in');
                        $('.modal#el-fileupload').css('z-index','1043');
                        $('#el-fileupload').addClass('flink-fileupload');
                        $('#el-fileupload').find('.modal-header h4').html($.lang[LANG]['editor.resource.file']);
                        $('#el-fileupload .nav-tabs li:nth-child(3) a').click();
                        $('#el-fileupload .nav-tabs li:not(:nth-child(3))').addClass('disabled');
                        break;

                    case 'popup-change':
                        $('.modal#el-fileupload').css('z-index','1043');
                        $('#el-fileupload').addClass('popup-fileupload');
                        break;

                    case 'upload-badge-image':
                        $('.modal#el-fileupload').css('z-index','1044');
                        break;
            
                    default:
                        $('#filestorage').removeClass('active').removeClass('in');
                        $('.modal#el-fileupload').css('z-index','1041');
                        $('#el-fileupload').removeClass('flink-fileupload');
                        $('#el-fileupload').removeClass('popup-fileupload');
                        $('#el-fileupload').find('.modal-header h4').html($.lang[LANG]['editor.resource.title']);
            
                        if($('#el-fileupload .nav-tabs li:nth-child(3)').hasClass('active')) $('#el-fileupload .nav-tabs li:nth-child(1) a').click();
                        $('#el-fileupload .nav-tabs li:nth-child(3)').addClass('disabled');
                        break;
                }
            } else {
                $('.modal#el-fileupload').css('z-index','1041');
                $('#el-fileupload').removeClass('flink-fileupload');
                $('#el-fileupload').removeClass('popup-fileupload');
                $('#el-fileupload').find('.modal-header h4').html($.lang[LANG]['editor.resource.title']);
        
                if($('#el-fileupload .nav-tabs li:nth-child(3)').hasClass('active')) $('#el-fileupload .nav-tabs li:nth-child(1) a').click();
                $('#el-fileupload .nav-tabs li:nth-child(3)').addClass('disabled');
                $('#filestorage').removeClass('active').removeClass('in');
            }
        },
        modalInit: function() {
            $('#progress .progress-bar').css({'width' : '0%', 'padding-right' : '0px'}).text('');
            $('.modal-resourcebox .resource-useit').removeClass('active');
            $('.modal-resourcebox .resource-selected-ul').empty();
            $('.modal-resourcebox .resource-ctrl-selectedinfo .count').text(0).closest('label').hide();
            $('.modal-resourcebox .resource-ctrl-btns').removeClass('active');
            $('.modal-resourcebox .fitem').removeClass('ui-selected');
            $.resource.modalOpenSET(true);
        },
        modalContentInit: function(mode) {
            if(typeof mode == 'undefined' || !mode) mode = 'my';

            $('#'+mode+'storage .resource-useit').removeClass('active');
            $('#'+mode+'storage .resource-search-stx').val('');
            $('#'+mode+'storage ul.files, #'+mode+'storage .resource-selected-ul').empty();

            if(mode == 'free') {
                $('#freestorage .resource-search-total').text('');
                if($('#freestorage ul.files .listprogress').length == 0) {
                    $('#freestorage ul.files').append('<li class="listprogress"><svg version="1.1" xmlns="http://www.w3.org/svg/2000" viewBox="0 0 30 30" width="60" style="width:30px; height: 30px;"><circle cy="15" cx="15" r="14" style="stroke:#00baff;"></circle></svg></li>');
                }
            }
        },
        modalFilesEmpty: function(ulFiles,empty_str) {
            if(ulFiles.length > 0) {
                empty_str = (typeof empty_str != 'undefined' && empty_str) ? empty_str : 'No results';
                ulFiles.addClass('empty').empty();
                ulFiles.append('\
                    <li class="resource-empty-area">\
                        <div class="resource-empty">\
                            <div class="img-wrap"><img src="//storage.googleapis.com/i.addblock.net/config/fa_resource_img_icon.png" alt="image storage" /></div>\
                            <p>' + empty_str + '</p>\
                        </div>\
                    </li>\
                ');

                if(ulFiles.closest('.resource-container').find('.resource-search-btn').length > 0) ulFiles.closest('.resource-container').find('.resource-search-btn').removeClass('clicked');
                ulFiles.closest('.tab-pane.active').find('ul.files').removeClass('ready');
                ulFiles.closest('.tab-pane.active').find('.listprogress').remove();
            }
        },
        getMystorageFlc: function() {
            var check_ffolder = (SFOLDER_ACTIVE != '') ? SFOLDER_ACTIVE : 'all',
                ftotal = -1;
            
            $.each(SFOLDER, function(i, o) {
                if(o.name == check_ffolder) {
                    ftotal = o.fcount;
                    return false;
                }
            })

            return ftotal;
        },
        getMystorageFolderHtml: function(flname, flcount, flsize) {
            if(!flname) return '';

            var checkAdd = (flname == 'clEmptyFolder') ? true : false,
                fln_val = flname.replace(/-/g,' '),
                fln_tooltip = (!checkAdd && flname.length > 6) ? ' data-toggle="tooltip" data-placement="top" data-original-title="' + flname + '"' : '',
                flc = (/^[0-9]*$/.test(flcount)) ? flcount * 1 : 0,
                fls = (/^[0-9.]*$/.test(flsize)) ? flsize * 1 : 0,
                fls_obj = formatFileSize(fls, 2, 'obj');

            return '\
                <li class="dd-item fli" data-id="' +  flname + '">\
                    <div class="fli-wrap dd-handle">\
                        ' + clSVG('move_handle', 20, 20, true, 'dd-icon cl-icon cl-handle') + '\
                        ' + clSVG('folder', 16, 12, true, 'dd-icon cl-icon cl-folder') + clSVG('folder_open', 16, 12, true, 'dd-icon cl-icon cl-folder-open') + '\
                        <span class="dd-fln fl-nodrag" ' + fln_tooltip + '>' + fln_val + '</span>\
                        <span class="dd-flc" attr-count="' + flc + '">' + flc + '</span>\
                        <span class="dd-fls fli-hidden" attr-size="' + fls + '" attr-size-unit="' + fls_obj['unit'] + '">' + fls_obj['val'] + '</span>\
                        <span class="dd-fle fli-hover fl-nodrag" attr-id="' + flname + '">' + clSVG('pencil', 12, 12) + '</span>\
                        <span class="dd-fld fli-hover fl-nodrag" attr-id="' + flname + '">' + clSVG('delete', 12, 12) + '</span>\
                    </div>\
                </li>\
            ';
        },
        setMystorageFolder: function(mode, val) {
            var myResourceTab = $('#mystorage'),
                myResourceFolderlist = myResourceTab.find('#nestableFolder');

            switch(mode) {
                case 'set_fll':
                    myResourceFolderlist.removeClass('ready');
                    // myResourceFolderlist.nestable('init');
                    // if(typeof val != 'undefined' && val !== null && val.length > 0) SFOLDER = val;
                    $.each(SFOLDER, function (i, o) {
                        if(o['name'] == 'clEmptyFolder') return true;
    
                        if(i == 0) {
                            var flc = (/^[0-9]*$/.test(o['fcount'])) ? o['fcount'] * 1 : 0,
                                fls = (/^[0-9.]*$/.test(o['fsize'])) ? o['fsize'] * 1 : 0,
                                fls_obj = formatFileSize(fls, 2, 'obj');
    
                            myResourceFolderlist.find('.fli[data-id="all"] .dd-flc').attr('attr-count',flc).text(flc);
                            myResourceFolderlist.find('.fli[data-id="all"] .dd-fls').attr({'attr-size':fls, 'attr-size-unit':fls_obj['unit']}).text(fls_obj['val']);
                            return true;
                        }
    
                        if(myResourceFolderlist.find('.fli[data-id="' + o['name'] + '"]').length > 0) return true;
                        var add_folder = $.resource.getMystorageFolderHtml(o['name'], o['fcount'], o['fsize']);
                            myResourceFolderlist.find('.fll').append(add_folder);
                    });

                    // if(SFOLDER_ACTIVE != '' && SFOLDER_ACTIVE != myResourceFolderlist.find('.fll.active').attr('data-id')) myResourceFolderlist.find('.fli[data-id="' + SFOLDER_ACTIVE + '"]').addClass('active');
                    break;

                case 'set_fli_state':
                    var is_change = (val.ffolder == 'all' && val.state == 'move') ? false : true;

                    if(is_change) {
                        var flc = $('#nestableFolder .fli[data-id="'    + val.ffolder +'"]').find('.dd-flc').attr('attr-count'),
                            fls = $('#nestableFolder .fli[data-id="'+ val.ffolder +'"]').find('.dd-fls').attr('attr-size'),
                            new_flc = val.count * 1,
                            new_fls = val.size * 1;

                        flc = (/^[0-9]*$/.test(flc)) ? flc * 1 : 0;
                        new_flc += flc;
                
                        fls = (/^[0-9.]*$/.test(fls)) ? fls * 1 : 0;
                        new_fls += fls;

                        var fls_obj = (new_flc < 1) ? {'val': 0, 'unit': 'Bytes'} : formatFileSize(new_fls, 2, 'obj');
                        $('#nestableFolder .fli[data-id="'+ val.ffolder +'"]').find('.dd-flc').attr('attr-count',new_flc).text(new_flc);
                        $('#nestableFolder .fli[data-id="'+ val.ffolder +'"]').find('.dd-fls').attr({'attr-size':new_fls, 'attr-size-unit':fls_obj['unit']}).text(fls_obj['val']);
                    }
                    break;

                case 'nodrag':
                    if(val) {
                        myResourceFolderlist.find('*').addClass('fl-nodrag');
                        myResourceFolderlist.find('.fli-wrap').removeClass('dd-handle');
                    } else {
                        myResourceFolderlist.find('.fl-nodrag:not(:is(.dd-fln, .fli-hover))').removeClass('fl-nodrag');
                        myResourceFolderlist.find('.fli:not(.fli-first) .fli-wrap').addClass('dd-handle');
                    }
                    break;

                default:
                    break;
            }
        },
        open: function() {
            $('#el-fileupload').modal('show');
        },
        close: function() {
            $('#el-fileupload').modal('hide');
            $('.uploadModal').remove();
        },
        selected: function() {
            var selected = new Array(),
                rmode = (myStorageActive()) ? 'my' : 'free',
                thisResourceSelected = $('#'+rmode+'storage .resource-selected-ul');

            thisResourceSelected.children('li').each(function() {
                selected.push($(this).find('p.selected-file-name').text());
            });

            return selected;
        },
    }

    $.category = {
        delete : [],
        init : function() {
            $(document).on('click', '#prod-category-text', function(e) { 
                e.stopPropagation();
                if($('.category-wrap').hasClass('open')) {
                    $('.category-lists').slideUp(200, function() {
                        $('.category-wrap').removeClass('open');    
                    }); 
                } else {
                    $('.category-wrap').toggleClass('open');
                    $('.category-lists').slideDown(200); 
                }
            });
            $(document).on('click','.form-ctrl-button.category, .gallery-ctrl-category', function(e) { 
                e.stopPropagation();
                var s = $(this).attr('data-category');
                $.category.open(s); 
            });
            $(document).on('click','.cl-category-modal-close',function(e) { $.category.close(); });
            $(document).on('mousedown', '.prod-option-move', function(){
               $(this).closest('.prod-option-list').css('overflow-y', 'auto');
            });
            $(document).on('mouseup', '.prod-option-move', function(){
               $(this).closest('.prod-option-list').css('overflow-y', '');
            });
            $(document).on('blur','.edit-option-title input', function(e) {
                // 중복값 체크
                checkDuplicateOptionName($(this));
            });

            $(document).on('focus', '.edit-option-quantity .option-price-quantity', function() {
                $(this).attr('data-before_val', Number(removeCommas($(this).val())));
                // var cnt = Number(removeCommas($(this).val()));
                // if(cnt == 0)
                // if($(this).closest('.prod-option-edit').find('.edit-option-select .option-price-status-str').attr('data-val') == 'O') {
                //     $(this).closest('.prod-option-edit').find('.edit-option-select .option-price-status-select [data-val="S"]').click();
                // }
            }).on('input', '.edit-option-quantity .option-price-quantity', function() {
                var before_val = Number(removeCommas($(this).attr('data-before_val')));
                var cnt = Number(removeCommas($(this).val()));
                if(before_val == 0 && cnt > 0 && $(this).closest('.prod-option-edit').find('.edit-option-select .option-price-status-str').attr('data-val') == 'O') {
                    $(this).closest('.prod-option-edit').find('.edit-option-select .option-price-status-select [data-val="S"]').click();
                } else if(cnt == 0 && $(this).closest('.prod-option-edit').find('.edit-option-select .option-price-status-str').attr('data-val') == 'S') {
                    $(this).closest('.prod-option-edit').find('.edit-option-select .option-price-status-select [data-val="O"]').click();
                }
            });

            $(document).on('click','.prod-option-title, .prod-option-price, .prod-option-quantity, .prod-option-status, .prod-option-desc, .prod-option-require', function(e) {
                e.stopPropagation();
                var submit = true;
                var parent = $(this).closest('.prod-option');
                $('.prod-option-item').each(function () {
                    $(this).closest('li').removeClass('err');
                });
                
                if($('.prod-option-edit').length <= 2) {
                    $('.prod-option-edit .edit-option-delete').addClass('hide');
                } else {
                    $('.prod-option-edit .edit-option-delete').removeClass('hide');
                }

                if($('.prod-option-list .prod-option-item.hide').length) {
                    $.each($('.prod-option-item.hide'), function(i,v) {
                        var opt_title = $(v).parent().find('.prod-option-edit .edit-option-title input').val(),
                            opt_desc = $(v).parent().find('.prod-option-edit .edit-option-desc input').val(),
                            opt_price = $(v).parent().find('.prod-option-edit .edit-option-price input').val(),
                            opt_quantity = $(v).parent().find('.prod-option-edit .edit-option-quantity input').val(),
                            opt_status = $(v).parent().find('.prod-option-edit .option-price-status-str').attr('data-val'),
                            opt_text_require = $(v).parent().find('.prod-option-edit .option-require-str').attr('data-val');

                        $(v).closest('li').removeClass('err');
                        if(product_options.advanced == 'false') {
                            if(opt_title.length == 0) {
                                $(v).closest('li').addClass('err').find('.edit-option-title input');
                                submit = false;
                                return true;
                            }
                        }
                        switch(opt_status) {
                            case "S" : str = '판매'; break;
                            case "O" : str = '품절'; break;
                            case "H" : str = '숨김'; break;
                            default : str = '판매'; break;
                        }
                        var check;
                        // if(opt_text_require == 'TR') {
                        //     check = "\
                        //         <span>필수</span>\
                        //         <svg class='active' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' width='16' height='16'>\
                        //         <path d='M13 0H3C1.34 0 0 1.34 0 3v10c0 1.66 1.34 3 3 3h10c1.66 0 3-1.34 3-3V3C16 1.34 14.66 0 13 0zM13.03 6.03l-5.5 5.5C7.38 11.68 7.19 11.75 7 11.75s-0.38-0.07-0.53-0.22l-3.5-3.5c-0.29-0.29-0.29-0.77 0-1.06s0.77-0.29 1.06 0L7 9.94l4.97-4.97c0.29-0.29 0.77-0.29 1.06 0S13.32 5.74 13.03 6.03z'/>\
                        //         </svg>";
                        // } else {
                        //     check = "\
                        //         <span>필수</span>\
                        //         <svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' width='16' height='16'>\
                        //         <path d='M13 0H3C1.3 0 0 1.3 0 3v10c0 1.7 1.3 3 3 3h10c1.7 0 3-1.3 3-3V3C16 1.3 14.7 0 13 0zM15 13c0 1.1-0.9 2-2 2H3c-1.1 0-2-0.9-2-2V3c0-1.1 0.9-2 2-2h10c1.1 0 2 0.9 2 2V13z'/>\
                        //         </svg>";
                        // }
                        var soption = String(opt_price);
                        if(soption.replace('+','') == '' || soption.replace('-','') == '') opt_price = 0;
                        opt_price = removeCommas(opt_price);
                        opt_quantity = removeCommas(opt_quantity);
                        if (!opt_quantity) opt_quantity = 0;
                        if (!opt_price || isNaN(opt_price) === true) opt_price = 0;

                        opt_quantity = (opt_quantity * 1);
                        opt_price = (opt_price * 1);

                        var abs_price = Math.abs(opt_price),
                            str_price = addCommas(abs_price.toString()),
                            str_quantity = addCommas(opt_quantity.toString());

                        $(v).find('.prod-option-title').text(opt_title);
                        $(v).find('.prod-option-desc').text(opt_desc);
                        $(v).find('.prod-option-price').text(str_price).attr('data-option-price',opt_price);
                        $(v).find('.prod-option-quantity').text(opt_quantity);
                        $(v).find('.prod-option-status').text(str).attr('data-val',opt_status);
                        $(v).find('.prod-option-require').html(check).attr('data-val',opt_status);
                        $(v).parent().find('.prod-option-edit').addClass('hide');
                        $(v).removeClass('hide');

                        // 다른 옵션 input 선택시 기존 값 0됨
                        // if(opt_price < 0) {
                        //     $(this).find('.prod-option-price').text(str_price);
                        //     $(this).find('.prod-option-price').find('.prod-option-price').addClass('minus');
                        // } else {
                        //     $(this).find('.prod-option-price').text(str_quantity);
                        //     $(this).find('.prod-option-price').find('.prod-option-price').removeClass('minus');
                        // }
                    });
                }

                var title = $(this).parent().find('.prod-option-title').text(),
                    title_html = $(this).parent().find('.prod-option-title').html(),
                    desc = $(this).parent().find('.prod-option-desc').text(),
                    price = $(this).parent().find('.prod-option-price').attr('data-option-price'),
                    quantity = $(this).parent().find('.prod-option-quantity').text(),
                    status = $(this).parent().find('.prod-option-status').attr('data-val'),
                    text_require = $(this).parent().find('.prod-option-require').attr('data-val'),
                    $title = $(this).parent().siblings('.prod-option-edit').find('.edit-option-title input'),
                    $title_html = $(this).parent().siblings('.prod-option-edit').find('.edit-option-title'),
                    $desc = $(this).parent().siblings('.prod-option-edit').find('.edit-option-desc input'),
                    $price = $(this).parent().siblings('.prod-option-edit').find('.edit-option-price input'),
                    $quantity = $(this).parent().siblings('.prod-option-edit').find('.edit-option-quantity input'),
                    $status = $(this).parent().siblings('.prod-option-edit').find('.option-price-status-str'),
                    $text_require = $(this).parent().siblings('.prod-option-edit').find('.option-require-str');
      
                if(price == 'NaN') price = 0;
                switch(status) {
                    case "S" : str = '판매'; break;
                    case "O" : str = '품절'; break;
                    case "H" : str = '숨김'; break;
                    default : str = '판매'; break;
                }
                price = removeCommas(price);
                quantity = removeCommas(quantity);
                if (!quantity) quantity = 0;
                if (!price || isNaN(price)) price = 0;

                price = (price * 1);
                quantity = (quantity * 1);

                if(product_options.advanced == 'true') {
                    $title_html.html(title_html);
                } else {
                    $title.val(title);
                }
                $desc.val(desc);
                $price.val(addCommas(price.toString()));
                $quantity.val(addCommas(quantity.toString()));
                $status.text(str).attr('data-val', status);
                // $text_require.html(check).attr('data-val', text_require);

                $(this).parent().addClass('hide');
                $(this).parent().siblings('.prod-option-edit').removeClass('hide');
                if($(this).hasClass('prod-option-title')) $title.focus();
                if($(this).hasClass('prod-option-price')) $price.focus();
                if($(this).hasClass('prod-option-quantity')) $quantity.focus();
            });

            $(document).on('keydown', '.edit-option-title input, .options-input', function(e) {
                var keyCode = e.keyCode,
                    shiftKey =  e.shiftKey;
                
                if(keyCode == 222) 
                    if(shiftKey) return false;

                if(keyCode == 191) {
                    if(shiftKey) return;
                    e.stopPropagation();
                    return false;
                }

                if($(this).hasClass('options-input')) {
                    var value = $(this).val(),
                        last = value.split("").pop();
                    if(last == "," && keyCode == 188) {
                        alert('옵션 값을 알맞게 입력해주세요');
                        return false;
                    }
                }
            });

            $(document).on('keyup keydown click','.edit-option-title input, .edit-option-desc input, .edit-option-price input, .edit-option-quantity input',function(e) {
                e.stopPropagation();
                var keyCode = e.keyCode || e.which,
                    eType = e.type,
                    target = e.target,
                    $title = $(this).parents('.form-wrap').find('.edit-option-title input'),
                    $desc = $(this).parents('.form-wrap').find('.edit-option-desc input'),
                    $price = $(this).parents('.form-wrap').find('.edit-option-price input'),
                    $quantity = $(this).parents('.form-wrap').find('.edit-option-quantity input'),
                    $status = $(this).parents('.form-wrap').find('.option-price-status-str'),
                    $text_require = $(this).parents('.form-wrap').find('.option-price-status-str');

                if(eType == 'keydown' && keyCode == 13) e.preventDefault(); //enter submit 방지

                var price = removeCommas($price.val())*1,
                    quantity = removeCommas($quantity.val())*1;

                var $li = $(this).parents('li');

                if(price < 0) {
                    $li.find('.prod-option-price').text(Math.abs(price));
                    $li.find('.prod-option-price').addClass('minus');
                } else {
                    $li.find('.prod-option-price').text(price);
                    $li.find('.prod-option-price').removeClass('minus');
                }

                var abs_price = Math.abs(price),
                    str_price = addCommas(abs_price.toString()),
                    str_quantity = addCommas(quantity.toString());

                $li.find('.prod-option-title').text($title.val());
                $li.find('.prod-option-desc').text($desc.val());
                $li.find('.prod-option-price').text(str_price);
                $li.find('.prod-option-price').attr('data-option-price', price);
                $li.find('.prod-option-quantity').text(str_quantity);
                $li.find('.prod-option-status').text($status.text());

                var submit = false;
                var isDuplicate = true;
                if(eType == 'click' && !$(target).is('.prod-option-list') && !$(target).is('input')) { //다른 옵션 클릭 시 입력
                    isDuplicate = checkDuplicateOptionName($title);
                    submit = true;   
                }

                if(eType == 'keyup') {
                    if(keyCode == 13) {
                        isDuplicate = checkDuplicateOptionName($title);
                        e.preventDefault();
                        submit = true;  
                    }

                    if($('.switch-quantity').prop('checked') == true) { //재고관리 on
                        if(keyCode == 9 && !$('.option-price-number').is(':focus') && !$('.option-price-quantity').is(':focus')) { //tab
                            isDuplicate = checkDuplicateOptionName($title);
                            submit = true;
                        }
                    } else { //재고관리 off
                        if(keyCode == 9 && !$('.option-price-number').is(':focus')) { //tab
                            isDuplicate = checkDuplicateOptionName($title);
                            submit = true;
                        }
                    }  
                }

                if(submit && isDuplicate == false) {
                    shoppingSetOption($('.prod-option-item.hide'));
                }          
            });

            $(document).on('click', function(e) {
                if(!$(e.target).is('.prod-discount-unit-select') && $(e.target).closest('.prod-discount-unit-select').length == 0) {
                    $('.discount-unit-select').hide();
                }
                if(!$(e.target).is('.prod-option-list')) {
                    shoppingSetOption($('.prod-option-item.hide'));
                }

                if($('.prod-modal').has(e.target).length) {
                    if(!$('.delivery-template-list').has(e.target).length && $('.delivery-template-list').get(0) != e.target && !$('#delivery_template_seq').has(e.target).length && $('#delivery_template_seq').get(0) != e.target) {
                        $('.delivery-template-list').slideUp(200);
                        $('#delivery_template_seq.open').removeClass('open');
                    }

                    if(!$('#prod-category-lists').has(e.target).length && $('#prod-category-lists').get(0) != e.target && !$('#prod-category-text').has(e.target).length && $('#prod-category-text').get(0) != e.target) {
                        $('#prod-category-lists').slideUp(200);
                        $('.category-wrap.open').removeClass('open');
                    }
                }
            });

            $(document).on('click', '#delivery_template_seq:not(.limit-disabled)', function() {
                $(this).toggleClass('open');
                if($(this).hasClass('open')) {
                    $('.delivery-template-list').slideDown(200);
                } else {
                    $('.delivery-template-list').slideUp(200);
                }
            });

            $(document).on('input', '#product_weight', function(e) {
                var val = $(this).val().replace(/,/g, '');
                if(val.indexOf('.') > -1 && val.indexOf('.') < val.length-4) {
                    val = Number((Math.floor(Number(val) * 1000) / 1000).toFixed(3));
                }

                if(Number(val) > 100) {
                    val = number_format(100);
                }

                $(this).val(val);
            }).on('blur', '#product_weight', function() {
                var val = $(this).val().replace(/,/g, '');
                if(val.indexOf('.') > -1 && val.indexOf('.') == val.length-1) {
                    $(this).val(number_format(val.replace(/\./g, '')));
                }
            });

            $(document).on('click', '.btn-delivery-template-setting', function() {
                var shopping_url = $(this).data('shopping_url');
                deliveryTemplateListModal(shopping_url, function() {
                    $.processON();
                    var site = (typeof SID == 'undefined') ? property.SID : SID,
                        // page = (typeof PAGE == 'undefined') ? ((typeof PROD_PAGE == 'undefined') ? property.PAGE : PROD_PAGE) : PAGE,
                        pid = (typeof selectID == 'undefined') ? null : selectID,
                        id = $('#prod-no').val();
                    setTimeout(function() {
                        $.ajax({
                            url: '/template/products/',
                            data: { type:'get', sid:site, id:id, pid:pid },
                            dataType: 'json',
                            type: 'POST',
                            async: false,
                            cache: false,
                            success: function (data) {
                                if(data.error != 'undefined' && data.error) {
                                    alert(data.error);
                                    return false;
                                }
                                var i = data.item,
                                    url = (typeof RESOURCE == 'undefined') ? property.RESOURCE : RESOURCE,
                                    folder = '', f = '';

                                var delivery_template_str = '';
                                if(i.delivery_template) {
                                    $.each(i.delivery_template, function(k, v) {
                                        var template_desc = '';
                                        template_desc += '(';
                                        template_desc += $.lang[LANG]['shopping.delivery.template.mix_yn.' + v.mix_yn.toLowerCase()];
                                        var delivery_type_arr = v.delivery_type.split(',');
                                        var delivery_type_str = '';
                                        $.each(delivery_type_arr, function(idx, delivery_type) {
                                            if(delivery_type_str) delivery_type_str += ', ';
                                            delivery_type_str += $.lang[LANG]['shopping.delivery.template.delivery_type.' + delivery_type.toLowerCase()];
                                        });
                                        if(delivery_type_str) 
                                            template_desc += ' / ' + delivery_type_str;
                                        
                                        if(delivery_type_arr.indexOf('DELIVERY') > -1) {
                                            template_desc += ' / ' + $.lang[LANG]['shopping.delivery.' + v.delivery_company.toLowerCase()];
                                        }

                                        template_desc += ' / ' + $.lang[LANG]['shopping.delivery.template.price_type.' + v.price_type.toLowerCase()];

                                        if(v.price_type == 'FIX') {
                                            template_desc += '(' + number_format(v.delivery_fee) + '원)';
                                        } else if(v.price_type == 'QUANTITY' || v.price_type == 'WEIGHT') {
                                            var price_type_detail = v.price_type_detail ? JSON.parse(v.price_type_detail) : {};
                                            
                                            if(price_type_detail.method == 'DIFFERENTIAL') {
                                                var detail = '';
                                                if(price_type_detail.detail) {
                                                    $.each(price_type_detail.detail, function(i, j) {
                                                        var value = Object.keys(j);
                                                        var price = Object.values(j);

                                                        if(v.price_type == 'QUANTITY') {
                                                            if(i < 2) {
                                                                if(detail) detail += ', ';
                                                                detail += value + '개 이상(' + number_format(price) + '원)';
                                                            }
                                                        } else if(v.price_type == 'WEIGHT') {
                                                            if(i < 2) {
                                                                if(detail) detail += ', ';
                                                                detail += value + 'Kg 이상(' + number_format(price) + '원)';
                                                            }
                                                        }
                                                    });
                                                }
                                                if(template_desc) {
                                                    detail = '(차등 / ' + detail + ')';
                                                    template_desc += detail;
                                                }
                                            } else if(price_type_detail.method == 'REPEAT') {
                                                var detail = '';
                                                var value = Object.keys(price_type_detail.detail);
                                                var price = Object.values(price_type_detail.detail);

                                                if(v.price_type == 'QUANTITY') {
                                                    detail += value + '개 구매시마다 ' + number_format(price) + '원 반복 부과';
                                                } else if(v.price_type == 'WEIGHT') {
                                                    detail += value + 'Kg마다 ' + number_format(price) + '원 반복 부과';
                                                }

                                                if(detail) {
                                                    detail = '(반복 / ' + detail + ')';
                                                    template_desc += detail;
                                                }
                                            }
                                        }

                                        if(v.additional_yn == 'Y') {
                                            template_desc += ' / 도서산간 지역 추가 배송비 (제주 ' + number_format(v.additional_jeju_price) + '원, 제주 외 도서산간 ' + number_format(v.additional_land_price) + '원)';
                                        }

                                        template_desc += ' / ' + $.lang[LANG]['shopping.delivery.template.pay_type.' + v.pay_type.toLowerCase()];

                                        if(v.free_condition_yn == 'Y') {
                                            template_desc += ' / ' + number_format(v.free_condition) + '원 이상 무료 배송';
                                        }

                                        if(v.make_to_order_yn == 'Y') {
                                            template_desc += ' / 주문 확인 후 ' + v.due_date + '일 후 배송 예정';
                                        }
                                        if(v.install_fee_yn == 'Y') {
                                            template_desc += ' / 별도 설치비 있음';
                                        }
                                        template_desc += ')';

                                        delivery_template_str += '\
                                        <li data-val="' + v.seq + '" data-weight="' + (v.price_type == 'WEIGHT' ? 'true' : 'false') + '">\
                                            <input type="radio" id="delivery_template_seq_' + v.seq + '" name="delivery_template_seq" value="' + v.seq + '" />\
                                            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 18 18" width="18" height="18"><path d="M9 0a9 9 0 1 0 .001 18.001A9 9 0 0 0 9 0zm0 17c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z"></path></svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 18 18" width="18" height="18"><path d="M9 0a9 9 0 1 0 .001 18.001A9 9 0 0 0 9 0zm0 17c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z"></path><circle cx="9" cy="9" r="6"></circle></svg>\
                                            <label for="delivery_template_seq_' + v.seq + '">\
                                                <span class="template-name">' + v.name + '</span>\
                                                <span class="template-desc">' + template_desc + '</span>\
                                            </label>\
                                        </li>';
                                    });
                                }

                                $('.option-delivery-template-select').html(delivery_template_str);

                                if(typeof i.delivery_template_seq != 'undefined' && i.delivery_template_seq) {
                                    $('.option-delivery-template-select input[name="delivery_template_seq"][value="' + i.delivery_template_seq + '"]').prop('checked', true);

                                    $('.option-delivery-template-str').html($('.option-delivery-template-select li[data-val="' + i.delivery_template_seq + '"] label').html());

                                    if($('.option-delivery-template-select li[data-val="' + i.delivery_template_seq + '"]').data('weight') == false) {
                                        $('.product-weight').hide();
                                        $('#product_weight').val('');
                                    } else {
                                        $('.product-weight').show();
                                        $('#product_weight').val(number_format(i.p.product_weight) + 'kg');
                                    }
                                } else {
                                    $('.option-delivery-template-select input[name="delivery_template_seq"]:first').prop('checked', true).change();
                                }
                            },
                            complete: function() {
                                $.processOFF();
                            }
                        });
                    });
                });
            });

            // $(document).off('click','.prod-option-add');
            $(document).on('click','.prod-option-add', addProductOption);

            $(document).on('click', '.cl_etc_state_check', function () {
                $('.cl_etc_state_check').each(function () {
                    $(this).removeClass('active');
                });

                $(this).addClass('active');
                var val = $(this).attr('data-val');
                $('#etc-date-state').val(val);

                switch(val) {
                    case 'Y':
                        $('.etc-setting').removeClass('hide');
                        $('.time-setting').addClass('hide');
                        break;
                    case 'T':
                        $('.etc-setting').removeClass('hide');
                        $('.time-setting').removeClass('hide');
                        break;
                    default:
                        $('.etc-setting').addClass('hide');
                        break;
                }
            });
        
            $(document).on('click', '.cl_etc_status_check', function () {
                $('.cl_etc_status_check').each(function () {
                    $(this).removeClass('active');
                });

                $(this).addClass('active');
                var val = $(this).attr('data-val');

                $('#etc-date-status').val(val);
            });
        
            // $(document).on('click', '.cl_etc_week_check', function () {
            //     $('.cl_etc_week_check').each(function () {
            //         $(this).removeClass('active');
            //     });

            //     $(this).addClass('active');
            //     var val = $(this).attr('data-val');
            //     $('#etc-date-week').val(val);
            //     exceptPicker.disabledDays = null;
            //     if(val == 'W') {
            //         exceptPicker.disabledDays = [0, 6];
            //     } else if(val == 'K') {
            //         exceptPicker.disabledDays = [1, 2, 3, 4, 5];
            //     } else {
            //         exceptPicker.disabledDays = null;
            //     }
            //     //exceptPicker.generateDates(true);
            //     exceptPicker.setSelectedDates($('#etc-start-date-txt').val(), 'start');
            //     exceptPicker.setSelectedDates($('#etc-end-date-txt').val(), 'end');
            //     setExceptPicker();
            // });
        
            // $(document).on('click', '.cl_etc_date_time', function () {
            //     $('.cl_etc_date_time').each(function () {
            //         $(this).removeClass('active');
            //     });

            //     $(this).addClass('active');
            //     var startDate = $(this).attr('data-start_date');
            //     var endDate = $(this).attr('data-end_date');
            //     $('#etc-start-date-txt').val(startDate);
            //     $('#etc-end-date-txt').val(endDate);
            //     //exceptPicker.generateDates(true);
            //     exceptPicker.setSelectedDates(startDate, 'start');
            //     exceptPicker.setSelectedDates(endDate, 'end');
            //     setExceptPicker();
            // });

            $(document).on('click', '.cl_product_state_check', function (e) {
                var state = $(this).attr('for');
                var cnt = $('.prod-option[data-option_mode="normal"] .prod-option-list > li').length;
                var tax = $('#tax').attr('data-total-tax');
                var productNumber = $('#prod-no').val();
                var status = true;

                var current = $('input[name="product_state"]:checked').val();
                if(current == "N" && product_options.advanced == 'true') {
                    if(e.originalEvent != 'undefined' && (state == 'download-product' || state == 'etc-product')) {
                        var str = (state == 'download-product') ? '다운로드' : '기타무형';
                        if(confirm(str + ' 상품은 고급설정을 지원하지 않아 등록된 옵션정보가 초기화 됩니다. 상품 유형을 변경하시겠습니까?') == false) return false;
                        else {
                            $('.options-config').hide();
                            resetOptions();
                        }
                    }
                }
                // console.log(state);
                if(state != 'normal-product') {
                    $('.delivery-template, .product-weight, .brand').hide();
                }

                if (state == "download-product") { //다운로드상품 선택
                    //입력옵션 비활성화
                    $('.prod-option[data-option_mode="text"]').addClass('hide');
                    $('#text-option').prop('checked', false).closest('.newcheckbox').hide();
                    //추가옵션 비활성화
                    $('.prod-option[data-option_mode="additional"]').addClass('hide');
                    $('#additional-option').prop('checked', false).closest('.newcheckbox').hide();

                    if($('.prod-option-tab .prod-option.hide').length == 3) { //탭 모두 비활성화일때
                        $('.prod-option-tab').addClass('hide');
                        if($('.switch-quantity').is(":checked") == true) {
                            $('.quantity-label').removeClass('on');
                        }
                    }
                    
                    $('#state-append').fadeIn(0);
                    $('#etc-calendar').hide();
                    if ($('#normal-option').is(':checked') === false) { //일반옵션 없음
                        if ($('.real-file-name').length < 1) {
                            $('.switch-product[value="off"]').prop('checked', true);
                            $('#status-append').fadeOut(0);
                            $('#sale-calendar').hide();
                        }
                        var html = '<div class="form-group" id="product-state">\
                                        <input type="file" id="upload-file" name="files">\
                                        <div class="product-state-box" id="add-upload-check">\
                                            <div class="product-upload">\
                                                <div class="title">파일 업로드</div>\
                                                <div class="download-contents">\
                                                    <span class="cl_icon_upload02" data-cnt="0">업로드</span>\
                                                    <div id="none-option-file">\
                                                    </div>\
                                                </div>\
                                            </div>\
                                            <div class="download-setting">\
                                                <div class="title">다운로드<br>한도설정';
                                                /*html += '<span class="cl-icon cl_icon_info01"></span>';*/
                                                html += '</div>\
                                                <div id="download-contents">\
                                                    <div class="input-box">\
                                                        <div class="title">기간 제한</div>\
                                                        <div class="textbox">\
                                                            <input type="text" numberOnly class="download-input" id="download-date" value="1" maxlength="90">\
                                                            <span>일</span>\
                                                        </div>\
                                                    </div>\
                                                    <div class="input-box">\
                                                        <div class="title">횟수 제한</div>\
                                                        <div class="textbox">\
                                                            <input type="text" numberOnly class="download-input" id="download-count" value="1" maxlength="10">\
                                                            <span>회</span>\
                                                        </div>\
                                                    </div>\
                                                </div>\
                                            </div>\
                                        </div>\
                                    </div>';
                        // console.log(html);            
                        $('#product-state').remove();
                        $('#state-append').append(html);
                        
                        $('.prod-option[data-option_mode="normal"] .prod-option-list > li').each(function () {
                            var $checkTag = $(this).children('.product-status');
                            if ($checkTag.hasClass('product-status') === false) {
                                var item = '<div class="form-group product-status">\
                                            <div class="product-state-box">\
                                                <div class="product-upload">\
                                                    <div class="title">파일 업로드</div>\
                                                    <div class="download-contents">\
                                                        <span class="cl_icon_upload02" data-cnt="0">업로드</span>\
                                                        <div class="file-box-list" id="file-box-0"></div>\
                                                    </div>\
                                                </div>\
                                            </div>\
                                        </div>';
                                fileUpdateCnt++;

                                $(this).append(item);
                            } else {
                                var $loadTag = $('.prod-option[data-option_mode="normal"] .prod-option-list > li').eq(0).find('.download-contents div');
                                // console.log($loadTag.html());
                                $('#none-option-file').html($loadTag.html());
                            }
                        });
                    } else { //다운로드 외 다른상품
                        var html = '<div class="form-group" id="product-state">\
                                        <input type="file" id="upload-file" name="files" data-cnt="'+fileUpdateCnt+'">\
                                        <div class="product-state-box" id="add-upload-check">\
                                            <div class="download-setting">\
                                                <div class="title">다운로드<br>한도설정';
                                                /*html += '<span class="cl-icon cl_icon_info01"></span>';*/
                                                html += '</div>\
                                                <div class="download-contents">\
                                                    <div class="input-box">\
                                                        <div class="title">기간 제한</div>\
                                                        <div class="textbox">\
                                                            <input type="text" numberOnly class="download-input" id="download-date" value="1" maxlength="90">\
                                                            <span>일</span>\
                                                        </div>\
                                                    </div>\
                                                    <div class="input-box">\
                                                        <div class="title">횟수 제한</div>\
                                                        <div class="textbox">\
                                                            <input type="text" numberOnly class="download-input" id="download-count" value="1" maxlength="10">\
                                                            <span>회</span>\
                                                        </div>\
                                                    </div>\
                                                </div>\
                                            </div>\
                                        </div>\
                                    </div>';

                        $('#product-state').remove();
                        $('#state-append').append(html);

                        $('.prod-option[data-option_mode="normal"] .prod-option-list > li').each(function () {
                            var $checkTag = $(this).children('.product-status');
                            var option_mode = $(this).closest('.prod-option').attr('data-option_mode');
                            var name = $(this).find('.prod-option-title').text();
                           
                            if ($checkTag.hasClass('product-status') === false && option_mode == 'normal') {
                                var item = '<div class="form-group product-status">\
                                            <div class="product-state-box">\
                                                <div class="product-upload">\
                                                    <div class="title">파일 업로드</div>\
                                                    <div class="download-contents">\
                                                    <span class="cl_icon_upload02" data-cnt="'+fileUpdateCnt+'">업로드</span>';
                                                    if (name == 'noneOption') item += '<div class="file-box-list" id="file-box-0">';
                                                    else item += '<div class="file-box-list" id="file-box-'+fileUpdateCnt+'">';
                                                    item += '</div>\
                                                    </div>\
                                                </div>\
                                            </div>\
                                        </div>';
                                fileUpdateCnt++;

                                $(this).find('.prod-option-status').text('품절').attr('data-val', 'O');
                                $(this).find('.option-price-status-str').text('품절').attr('data-val', 'O');

                                $(this).append(item);
                            }
                        });
                    }
                    fileUpdateCnt++;
                } else {
                    if($('#product-state').length == 0) {
                        $('#text-option').closest('.newcheckbox').show();
                        $('#additional-option').closest('.newcheckbox').show();
                    }
                    
                    if (state=='normal-product' && taxUse != 'TG03' && $('#product-state').length == 0) {
                        $('.options-config').show();
                        $('#state-append').fadeOut(0);  
                    }
                    else {
                        $('#state-append').fadeIn(0);
                    }
                    if (productNumber) {
                        var admin_url = (uadmin == 'um')? '/_admin':'';
                        $.ajax({
                            url: admin_url + '/shopping/download_list_check',
                            type: 'post',
                            dataType: 'json',
                            data: {'product_number': productNumber, 'option_seq': 0},
                            success: function (data) {
                                if (data.code == 'fail') {
                                    alert(data.message);
                                    status = false;
                                    return false;
                                }
                            }
                        });
                    }

                    if (status == false) return false;

                    if (cnt > 0) {
                        var checkFile = $('.file-name').length;
                        if (checkFile > 0) {
                            if (confirm('상품 유형을 변경할 경우 옵션에 등록된 파일이 삭제됩니다.\n계속하시겠습니까?') === true) {
                                $('#product-state').remove();
                                $('.product-status').remove();
                            } else return false;
                        } else {
                            $('#product-state').remove();
                            $('.product-status').remove();
                        }
                    } else {
                        $('#product-state').remove();
                        $('.product-status').remove();
                    }

                    if (state == "etc-product") {
                        $('#etc-calendar').show();
                    } else {
                        $('#etc-calendar').hide();
                    }

                    if (state == 'normal-product') {
                        if(!$('.delivery-template-list').find('[data-val]').find('input[name="delivery_template_seq"]:checked').length) {
                            $('.delivery-template-list').find('[data-val]:first').find('input[name="delivery_template_seq"]').prop('checked', true).change();
                        }
                        $('.delivery-template, .brand').show();
                    }
                }

                if(state != 'normal-product') {
                    $('.options-config').hide();
                    $('.culture-benefit').hide();
                    $('#pccc-yn').hide();
                } else {
                    $('.options-config').show();
                    $('.culture-benefit').show();
                    $('#pccc-yn').show();
                }

                if(state != 'download-product') {
                    if($('#product-state').length == 0) {
                        $('#text-option').closest('.newcheckbox').show();
                        $('#additional-option').closest('.newcheckbox').show();
                    }
                }
                
                $('.cl_product_state_check').each(function () {
                    $(this).children('.cl-icon').removeClass('cl_icon_check02_on').removeClass('cl_icon_check02_off').addClass('cl_icon_check02_off');
                    $(this).removeClass('active');
                });

                $(this).children('.cl-icon').removeClass('cl_icon_check02_off').addClass('cl_icon_check02_on');

                $(this).addClass('active');
            });
            
            /* product.add.html common tooltip  ******/
            $(document).on('mouseenter', '.cl-tooltip-info', function () {
                var info_type = ($(this).attr('data-infotype')) ? $(this).attr('data-infotype') : '';
                $('.cl-prod-info.'+info_type+'-info').fadeIn(100);
            }).on('mouseleave', '.cl-tooltip-info', function () {
                var info_type = ($(this).attr('data-infotype')) ? $(this).attr('data-infotype') : '';
                $('.cl-prod-info.'+info_type+'-info').fadeOut(100);
            });

            $(document).on('mouseenter', '.cl-pccc-info', function () {
                $('.cl-prod-info.pccc-info').fadeIn(100);
            }).on('mouseleave', '.cl-pccc-info', function () {
                $('.cl-prod-info.pccc-info').fadeOut(100);
            });

            $(document).on('mouseenter', '.cl-culture-benefit-info', function () {
                $('.cl-prod-info.culture-benefit-info').fadeIn(100);
            }).on('mouseleave', '.cl-culture-benefit-info', function () {
                $('.cl-prod-info.culture-benefit-info').fadeOut(100);
            });

            $(document).on('mouseenter', '.cl-discount-info', function () {
                $('.cl-prod-info.discount-info').fadeIn(100);
            }).on('mouseleave', '.cl-discount-info', function () {
                $('.cl-prod-info.discount-info').fadeOut(100);
            });

            $(document).on('mouseenter', '.cl-status-info', function () {
                $('.cl-prod-info.status-info').fadeIn(100);
            }).on('mouseleave', '.cl-status-info', function () {
                $('.cl-prod-info.status-info').fadeOut(100);
            });

            $(document).on('mouseenter', '.cl-open-info', function () {
                $('.cl-prod-info.open-info').fadeIn(100);
            }).on('mouseleave', '.cl-open-info', function () {
                $('.cl-prod-info.open-info').fadeOut(100);
            });

            $(document).on('mouseenter', '.cl-product-info', function () {
                $('.cl-prod-info.product-info').fadeIn(100);
            }).on('mouseleave', '.cl-product-info', function () {
                $('.cl-prod-info.product-info').fadeOut(100);
            });

            $(document).on('mouseenter', '.cl-option-info', function () {
                $('.cl-prod-info.option-info').fadeIn(100);
            }).on('mouseleave', '.cl-option-info', function () {
                $('.cl-prod-info.option-info').fadeOut(100);
            });

            $(document).on('mouseenter', '.cl-text-option-info', function () {
                $('.cl-prod-info.text-option-info').fadeIn(100);
            }).on('mouseleave', '.cl-text-option-info', function () {
                $('.cl-prod-info.text-option-info').fadeOut(100);
            });

            $(document).on('mouseenter', '.cl-prod-info-notice', function () {
                $('.cl-prod-info.cl-prod-info-notice').fadeIn(100);
            }).on('mouseleave', '.cl-prod-info-notice', function () {
                $('.cl-prod-info.cl-prod-info-notice').fadeOut(100);
            });

            $(document).on('click', '.cl_icon_close', function () {
                var checkCnt = $(this).attr('data-cnt');
                var productNumber = $(this).attr('data-pn');
                var seq = ($('#normal-option').is(':checked'))? $(this).attr('data-seq') : 0;
                var file = $(this).attr('data-file');
                var $parentFile = $(this).parent().parent();
                var $closeFile = $(this).parent();
                var $this = $(this);
                var admin_url = (uadmin == 'um')? '/_admin' : '';

                if (productNumber!=='null' && productNumber!==undefined && seq!=='null' && seq!==undefined) {   
                    $.ajax({
                        url: admin_url + '/shopping/download_list_check',
                        type: 'post',
                        dataType: 'json',
                        data: {'product_number': productNumber, 'option_seq': seq},
                        success: function (data) {
                            if (data.code == 'fail') {
                                alert(data.message);
                                return false;
                            } else {
                                if (confirm(data.message) === true) {
                                    $.processON('Deleting File...');
                                    $.ajax({
                                        type: 'POST',
                                        url: admin_url + '/shopping/file_delete',
                                        data: { s: file, seq: seq},
                                        async: true,
                                        success: function(data) {
                                            checkError(data);
                                            if (checkCnt || checkCnt == 0) {
                                                $closeFile.remove();
                                                $('.file-name-'+checkCnt).remove();
                                                    $this.parent().parent().parent().parent().parent().parent().find('.prod-option-status').text('품절').attr('data-val', 'O');
                                                    $this.parent().parent().parent().parent().parent().parent().find('.option-price-status-str').text('품절').attr('data-val', 'O');

                                            } else $closeFile.remove();
                                            
                                            var $fileCnt = $parentFile.find('.file-name');
                                            if ($fileCnt.length < 1) {
                                                if ($('#none-option-file').length > 0) {
                                                    $('.switch-product[value="off"]').prop('checked', true);
                                                    $('#status-append').fadeOut(0);
                                                    $('#sale-calendar').hide();
                                                }
                                                $.ajax({
                                                    url: admin_url + '/shopping/file_zero',
                                                    type: 'post',
                                                    data: {'product_number': productNumber}
                                                });
                                            }

                                            $.processOFF();
                                        }
                                    });
                                }
                            }
                        }
                    });
                } else {
                    $.processON('Deleting File...');
                    $.ajax({
                        type: 'POST',
                        url: admin_url + '/shopping/file_delete',
                        data: {s: file},
                        async: true,
                        success: function(data) {
                            checkError(data);
                            if (checkCnt || checkCnt == 0) {
                                $closeFile.remove();
                                $('.file-name-'+checkCnt).remove();
                            } else $closeFile.remove();
                                            
                            var $fileCnt = $parentFile.find('.file-name');
                            if ($fileCnt.length < 1) {
                                $('.switch-product[value="off"]').prop('checked', true);
                                $('#status-append').fadeOut(0);
                                $('#sale-calendar').hide();
                            }

                            $.processOFF();
                        }
                    });
                }
            });

            $(document).on('click', '.cl_icon_upload02', function () {
                var cnt = $(this).attr('data-cnt'),
                    fileCnt = 0;
                $('#file-box-'+cnt).find('.real-file-name').each(function () {fileCnt++;});
                if ($('#none-option-file').find('.real-file-name').length > 0 || $('#none-option-file').find('.none-real-file-name').length > 0) fileCnt++;

                if (fileCnt >= 1) {
                    // alert('파일은 1개만 업로드 가능합니다.\n여러 파일을 업로드할 경우 압축 파일을 이용해 주세요.');
                    var modal = $(this).showModalFlat('','파일은 1개만 업로드 가능합니다.\n여러 파일을 업로드할 경우 압축 파일을 이용해 주세요.',true,false,'','ok','','cl-cmmodal cl-s-btn w560 cl-p130 cl-t80 cl-modal cl-none-title cl-close-btn','','',function() {
                        $(document).on('keydown', function(e) {
                            if(e.keyCode == 27) modal.modal('hide');
                        });
                    });
                    return false;
                }

                $thisUploadCheck = $(this);
                $('#product-state').find('input[type="file"]').attr('data-cnt', cnt).click();
            });

            $(document).on('click', '#upload-file', function (data) {
                var sid = (typeof SID == 'undefined') ? property.SID : SID
                    uid = '',
                    cnt = $(this).attr('data-cnt');
                $.uploadON();
                var route = (CONFIG_URL) ? '/_admin' : '';
                $(this).fileupload({
                    url: route + '/shopping/image_upload/type/file/sid/'+sid+'/uid/'+uid,
                    dataType: 'json',
                    pasteZone: null,
                    async: true,
                    change: function(e, data) {
                        var ext = ['zip', 'txt', 'pdf', 'docx', 'xlsx', 'xls', 'csv', 'ppt', 'pptx', 'gif', 'jpg', 'jpeg', 'png', 'ico', 'webp', 'hwp', 'mp3', 'wav', 'wma', 'mp4'];
                        var extAry = data.fileInput[0]['files'][0]['name'].split(".");
                        if (ext.indexOf(extAry[extAry.length - 1]) == -1) {
                            alert('지원하지 않는 파일 형식이거나 파일이 손상되어 업로드할 수 없습니다. 확인 후 다시 시도해 주시기 바랍니다.');
                            return false;
                        }

                        var maxSize  = 1024 * 1024 * 512;
                        var fileSize = data.fileInput[0]['files'][0]['size'];
                        if (fileSize > maxSize) {
                            alert($.lang[LANG]['editor.upload.max.500'] + $.lang[LANG]['editor.upload.max.2']);
                            return false;
                        }
                    },
                    add: function(e, data) {
                        $('.uploadModal').show();
                        var submit = true, err = '';                        
                        var ext = ['zip', 'txt', 'pdf', 'docx', 'xlsx', 'xls', 'csv', 'ppt', 'pptx', 'gif', 'jpg', 'jpeg', 'png', 'ico', 'webp', 'hwp', 'mp3', 'wav', 'wma', 'mp4'];
                        var extAry = data.fileInput[0]['files'][0]['name'].toLowerCase().split('.');
                        if (ext.indexOf(extAry[extAry.length - 1]) == -1) {
                            err = $.lang[LANG]['editor.upload.error.ext'];
                            submit = false;
                        }

                        var maxSize  = 1024 * 1024 * 512;
                        var fileSize = data.fileInput[0]['files'][0]['size'];
                        if (fileSize > maxSize) {
                            err = $.lang[LANG]['editor.upload.max.500'] + $.lang[LANG]['editor.upload.max.2'];
                            submit = false;
                        }
                        $('#loading').css('left','-100%');

                        var fileSize = (data.files[0].size/1024/1024).toFixed(1) + 'MB';
                        var tpl = '<div class="file">\
                            <div class="progress"><div class="progress-bar"></div></div>\
                            <div class="progress-info"><span class="file-name">' + data.files[0].name + '</span><span class="file-size">' + fileSize + '</span><span class="ing">' + $.lang[LANG]['editor.upload.response'] + '</span></div>\
                            <div class="preview"></div>\
                            </div>';
                        data.context = $(tpl).insertBefore($('.uploadModal .upload-content .upload-cancel'));
                        data.context.find('.preview').addClass('not_image');
                        if(submit) {
                            var jqXHR = data.submit();
                            UPLOAD++;
                        } else {
                            data.context.find('.loading').html('<i class="fa fa-times error"></i>');
                            data.context.find('.ing').addClass('error').text(err);
                        }

                        $('.uploadModal .upload-cancel .btn, .uploadModal .upload-close').off('click').on('click', function(e) {
                            if(jqXHR != undefined) jqXHR.abort();
                            data.context.fadeOut().remove();
                            $('.uploadModal #file-upload-progress').css('width','0%');
                            $.uploadOFF();
                            UPLOAD = 0;
                            UPLOADED = 0;
                            PROGRESS = 0;
                        });

                    },
                    progress: function(e, data) {
                        var rate = (data.bitrate/1024).toFixed(1) + ' kbps';
                        var progress = parseInt((data.loaded / data.total) * 100, 10);
                        if(typeof data.context != 'undefined') {
                            data.context.find('.res').text(data.bitrate);
                            data.context.find('.progress-bar').css('width',progress + "%");
                            data.context.find('.ing').text(progress + "%");
                            data.context.find('.rate').text(rate);
                            if(progress == 100) {
                                data.context.find('.ing').text($.lang[LANG]['editor.upload.response']);
                            }
                        }
                    },                        
                    done: function(e, data) {
                        if(typeof data.result.error != 'undefined' && data.result.error) {
                            alert(data.result.error);
                            $.uploadOFF();
                            UPLOAD = 0;
                            UPLOADED = 0;
                            PROGRESS = 0;
                            return;
                        }
                        var fileSize = data.result.file_size, unit = 'KB';

                        if (fileSize >= 1000) {
                            fileSize = fileSize / 1000;
                            fileSize = fileSize.toFixed(2);
                            unit = 'MB';
                            if (fileSize >= 1000) {
                                fileSize = fileSize / 1000;
                                fileSize = fileSize.toFixed(2);
                                unit = 'GB';
                            }
                        }

                        var fileName = data.result.client_name, totalByte = 0, strFileName = '';
                        if (!fileName) {
                            alert('업로드 도중 오류가 발생했습니다. 다시 시도해 주세요.\n지속적으로 문제가 발생한다면 관리자에게 문의해 주세요.');
                            $.uploadOFF();
                            UPLOAD = 0;
                            UPLOADED = 0;
                            PROGRESS = 0;
                            return false;
                        }
                        
                        var fn_lastIndex = fileName.lastIndexOf('.');
                        var file = [fileName.slice(0, fn_lastIndex), fileName.slice(fn_lastIndex + 1)];
                        var fileLen = file[0].length;
                        for (var i=0;i<fileLen;i++) {
                            oneChar = file[0].charAt(i);
                            if (escape(oneChar).length > 4) {
                                totalByte += 2;
                            } else {
                                totalByte++;
                            }

                            if (totalByte > 10) {
                                strFileName += '..';
                                break;
                            }

                            strFileName += oneChar;
                        }
                        strFileName = strFileName+"."+file[(file.length - 1)];
                        var splitUrl = data.result.full_path.split('/');
                        var fileCnt = $('.file-name').length;

                        var file = '<div class="file-name file-name-'+fileCnt+'">\
                                        <span class="real-file-name">'+fileName+'</span>\
                                        <span class="file-name-detail" title="'+fileName+'">'+strFileName+'</span>\
                                        <span class="file-size">'+fileSize+unit+'</span>\
                                        <span class="cl-icon cl_icon_close" data-cnt="'+fileCnt+'" data-file="'+splitUrl[8]+'" data-pn="'+closeProductNumber+'"></span>\
                                        <span class="file-url">'+data.result.full_path+'</span>\
                                    </div>';

                        // console.log(file);
                        var licnt = $('.prod-option-list > li').length;
                        if ($thisUploadCheck.parent().parent().find('#none-option-file').length <= 0) {
                            $thisUploadCheck.parent().parent().parent().parent().parent().find('.prod-option-status').text('판매').attr('data-val', 'S');
                            $thisUploadCheck.parent().parent().parent().parent().parent().find('.option-price-status-str').text('판매').attr('data-val', 'S');
                        }
                        if ($('#normal-option').is(':checked') === false) {
                            var noneFile = '<div class="none-file-name">\
                                            <span class="none-real-file-name">'+fileName+'</span>\
                                            <span class="none-file-name-detail" title="'+fileName+'">'+strFileName+'</span>\
                                            <span class="none-file-size">'+fileSize+unit+'</span>\
                                            <span class="cl-icon cl_icon_close" data-cnt="'+fileCnt+'" data-file="'+splitUrl[8]+'" data-pn="'+closeProductNumber+'"></span>\
                                            <span class="none-file-url">'+data.result.full_path+'</span>\
                                        </div>';
                            // console.log('file-box-cnt: '+cnt);

                            $('[id^="file-box-"]:first').append(file);
                            $('#none-option-file').append(noneFile);
                        } else {
                            $('#file-box-'+cnt).append(file);
                        }
                        // console.log(noneFile);
                        progress1 = parseInt(UPLOADED / UPLOAD * 100,10);
                        PROGRESS = progress1 + progress2;
                        $('.file-upload-progress .progress-bar').css({
                            'width' : PROGRESS + '%',
                            'text-align' : 'right',
                            'padding-right' : '5px'
                        }).text(PROGRESS + '% ');

                        UPLOADED++;
                        if(UPLOADED) {
                            //$.uploadON(UPLOADED + " / " + UPLOAD + "<br>images creating...");
                            if(UPLOAD==UPLOADED) {
                                UPLOAD = 0;
                                UPLOADED = 0;
                                PROGRESS = 0;

                                $('.file-upload-progress .progress-bar').css({
                                    'width' :  PROGRESS + '%',
                                    'padding-right' : '0px'
                                }).text('');
                            }
                        }

                        $.uploadOFF();
                    },
                    progressall: function(e, data) {
                        var total = (data.total/1024/1024).toFixed(1) + 'MB';
                        $('.uploadModal .info1').text($.lang[LANG]['editor.upload.size.total'] + total);
                        $('.uploadModal .info2').text((UPLOADED+1) + ' / ' + UPLOAD.toString());
                        var progress = parseInt((data.loaded / data.total) * 100, 10);
                        $('.file-upload-progress .progress-bar').css('width',progress + "%");
                    },
                    start : function(e, data) {
                        $('.uploadModal .upload-header h1').text($.lang[LANG]['editor.upload.title.2']);
                        $('.uploadModal .upload-content .upload-cancel .btn-default').text($.lang[LANG]['config.cancel']);
                        progress1 = 0; progress2 = 0; PROGRESS = 0;
                    },
                    dragover : function(e, data) {
                        e.preventDefault();
                    }
                }).prop('disabled', !$.support.fileInput)
                    .parent().addClass($.support.fileInput ? undefined : 'disabled');
            });

            $(document).on('keyup', '#download-date', function () {
                var $this_val = strReplace($(this).val(), ',', '');
                if ($this_val != '') {
                    if ($this_val > 90) {
                        // alert('기간 제한은 최소 1일에서 최대 90일입니다.');
                        $(this).blur();
                        var modal = $(this).showModalFlat('','기간 제한은 최소 1일에서 최대 90일입니다.',true,false,'','ok','','cl-cmmodal cl-s-btn w560 cl-p130 cl-t80 cl-modal cl-none-title cl-close-btn','','',function() {
                            $(document).on('keydown', function(e) {
                                if(e.keyCode == 27) modal.modal('hide');
                            });
                        });
                        $(this).val(90);
                        return false;
                    }

                    if ($this_val < 1) {
                        // alert('기간 제한은 최소 1일에서 최대 90일입니다.');
                        $(this).blur();
                        var modal = $(this).showModalFlat('','기간 제한은 최소 1일에서 최대 90일입니다.',true,false,'','ok','','cl-cmmodal cl-s-btn w560 cl-p130 cl-t80 cl-modal cl-none-title cl-close-btn','','',function() {
                            $(document).on('keydown', function(e) {
                                if(e.keyCode == 27) modal.modal('hide');
                            });
                        });
                        $(this).val(1);
                        return false;
                    }
                }
            });

            $(document).on('focusout', '#download-date', function () {
                var $this_val = strReplace($(this).val(), ',', '');
                if ($this_val == '') {
                    // alert('기간 제한은 최소 1일에서 최대 90일입니다.');
                    $(this).blur();
                    var modal = $(this).showModalFlat('','기간 제한은 최소 1일에서 최대 90일입니다.',true,false,'','ok','','cl-cmmodal cl-s-btn w560 cl-p130 cl-t80 cl-modal cl-none-title cl-close-btn','','',function() {
                        $(document).on('keydown', function(e) {
                            if(e.keyCode == 27) modal.modal('hide');
                        });
                    });
                    $(this).val(1);
                    return false;
                }
            });

            $(document).on('keyup', '#download-count', function () {
                var $this_val = strReplace($(this).val(), ',', '');
                if ($this_val != '') {
                    if ($this_val > 10) {
                        // alert('다운로드 횟수는 최소 1회에서 최대 10회입니다.');
                        $(this).blur();
                        var modal = $(this).showModalFlat('','다운로드 횟수는 최소 1회에서 최대 10회입니다.',true,false,'','ok','','cl-cmmodal cl-s-btn w560 cl-p130 cl-t80 cl-modal cl-none-title cl-close-btn','','',function() {
                            $(document).on('keydown', function(e) {
                                if(e.keyCode == 27) modal.modal('hide');
                            });
                        });
                        $(this).val(10);
                        return false;
                    }

                    if ($this_val < 1) {
                        // alert('다운로드 횟수는 최소 1회에서 최대 10회입니다.');
                        $(this).blur();
                        var modal = $(this).showModalFlat('','다운로드 횟수는 최소 1회에서 최대 10회입니다.',true,false,'','ok','','cl-cmmodal cl-s-btn w560 cl-p130 cl-t80 cl-modal cl-none-title cl-close-btn','','',function() {
                            $(document).on('keydown', function(e) {
                                if(e.keyCode == 27) modal.modal('hide');
                            });
                        });
                        $(this).val(1);
                        return false;
                    }
                }
            });

            $(document).on('focusout', '#download-count', function () {
                var $this_val = strReplace($(this).val(), ',', '');
                if ($this_val == '') {
                    // alert('다운로드 횟수는 최소 1회에서 최대 10회입니다.');
                    $(this).blur();
                    var modal = $(this).showModalFlat('','다운로드 횟수는 최소 1회에서 최대 10회입니다.',true,false,'','ok','','cl-cmmodal cl-s-btn w560 cl-p130 cl-t80 cl-modal cl-none-title cl-close-btn','','',function() {
                        $(document).on('keydown', function(e) {
                            if(e.keyCode == 27) modal.modal('hide');
                        });
                    });
                    $(this).val(1);
                    return false;
                }
            });

            $(document).on('click','.option-price-status-str', function(e) {
                e.stopPropagation();
                var check = $(this).attr('data-val');
                if($(this).hasClass('open')) {
                    $(this).next().slideUp(200, function() {
                        $('.option-price-status-str').removeClass('open');    
                    }); 
                } else {
                    $(this).addClass('open');
                    $(this).next().find('li').removeClass('active');
                    $(this).next().find('li[data-val="' + check + '"]').addClass('active');
                    $(this).next().slideDown(200); 
                }

            });

            // $(document).on('change', '.option-require-str input', function(){
            //     var $option_li = $(this).closest('li');
            //     if($(this).is(':checked')) {
            //         $option_li.find('.option-require-str').attr('data-val', 'TR');
            //         $option_li.find('.prod-option-require').attr('data-val', 'TR');
            //     } else {
            //         $option_li.find('.option-require-str').attr('data-val', 'T');
            //         $option_li.find('.prod-option-require').attr('data-val', 'T');
            //     }
            // });

            $(document).on('click', '.option-price-status-select li', function(e) {
                e.stopPropagation();
                $('.option-price-status-select li').removeClass('active');
                $(this).addClass('active');
                var str = $(this).text(),
                    val = $(this).attr('data-val');

                $(this).parents('.edit-option-select').find('.option-price-status-str').text(str).attr('data-val',val).removeClass('open');
                $(this).parents('li').find('.prod-option-status').text(str).attr('data-val',val);

                $(this).parent().slideUp(200);
            });

            $(document).on('change', '.option-delivery-template-select input[name="delivery_template_seq"]', function(e) {
                e.stopPropagation();
                var str = $(this).parent('li').find('label').html(),
                    val = $(this).val();

                $('#delivery_template_seq').html(str);

                if($(this).parent('li').data('weight') == true) {
                    $('.product-weight').show();
                } else {
                    $('.product-weight').hide();
                    $('#product_weight').val('');
                }
                $('.delivery-template-list').slideUp(200);
                $('#delivery_template_seq').removeClass('open');
                $('.prod-modal').scrollTop($('.prod-modal').scrollTop() + $('.form-wrap.delivery-template').offset().top - $('.prod-modal .prod-header').outerHeight())
            });

            $(document).on('click','.edit-option-delete', function(e) { 
                var $option = $(this),
                    // seq = ($('#normal-option').is(':checked'))? $(this).attr('data-seq') : 0,
                    seq = $(this).attr('data-seq'),
                    sid = (typeof SID == 'undefined') ? property.SID : SID;
                    option_mode = $option.closest('.prod-option').attr('data-option_mode'),
                    fileName = $option.closest('li').find('.real-file-name').text();
                var status = true;
                var productNumber = $('#prod-no').val();
                var admin_url = (uadmin == 'um')? '/_admin' : '';

                if (option_mode == "normal" && seq!==undefined && productNumber && fileName) {
                    $.ajax({
                        url: admin_url + '/shopping/download_list_check',
                        type: 'post',
                        dataType: 'json',
                        data: {'product_number': productNumber, 'option_seq': seq},
                        success: function (data) {
                            if (data.code == 'fail') {
                                alert(data.message);
                                status = false;
                                return false;
                            }
                        }
                    });
                }
                
                if (status == false) return false;
                var modal = $(this).showModalFlat($.lang[LANG]['config.information'], '선택한 옵션을 삭제하시겠습니까?', true, true, function() {
                    if(typeof seq != "undefined" || seq) {
                        var deleted = ($('#options-delete-list').val()) ? $('#options-delete-list').val().split(",") : [];
                            deleted.push(seq);
                        // var deleted_items = [...new Set(deleted)];
                        var deleted_items = deleted.filter(onlyUnique);
                        $('#options-delete-list').val(deleted_items.join(","));
                        $option.parents('li').remove(); 

                        var liTotal = 0;
                        $('.prod-option-list > li').each(function () { liTotal++; });
                        if (liTotal < 2) $('.plus-price').addClass('hide');
                    } else {
                        var optionMode = $option.closest('.prod-option').attr('data-option_mode');
                        $option.parents('li').remove(); 

                        var liTotal = 0;
                        $('.prod-option-list > li').each(function () { liTotal++; });
                        if (liTotal < 2) $('.prod-str-price').text('');
                    }

                    if($('.switch-quantity').is(":checked") == true) {
                        if($('#normal-option').is(':checked') === true) {
                            // $('#prod-quantity').attr('readonly','true').removeClass('hide').attr('placeholder','옵션에서 재고 관리');
                            $('.quantity-label').addClass('on');
                            $('.plus-quantity').removeClass('hide');
                        } else if($('#normal-option').is(':checked') === false && $('#additional-option').is(':checked') === true) {
                            $('.quantity-label').removeClass('on');
                            $('#prod-quantity').removeAttr('readonly').removeClass('hide');
                            $('.plus-quantity').removeClass('hide');
                        } else {
                            $('.quantity-label').removeClass('on');
                            $('#prod-quantity').removeAttr('readonly').removeClass('hide');
                            $('.plus-quantity').addClass('hide');
                        }
                    } else {
                        $('.quantity-label').removeClass('on');
                        $('.switch-quantity').parents('.form-wrap').addClass('disabled');
                        $('#prod-quantity').addClass('hide');
                        $('.prod-option-quantity, .prod-plus-quantity, .edit-option-quantity').hide();
                        $('.plus-quantity').addClass('hide');
                    }

                    // var normalCnt = $('.prod-option[data-option_mode="normal"] .prod-option-list > li').length;
                    if ($('#normal-option').is(':checked') === false) {
                        var html = '\
                        <div class="product-upload">\
                            <div class="title">파일 업로드</div>\
                            <div class="download-contents">\
                                <span class="cl_icon_upload02" data-cnt="'+fileUpdateCnt+'">업로드</span>\
                                <div id="none-option-file"></div>\
                            </div>\
                        </div>\
                        ';

                        fileUpdateCnt++;

                        $('#add-upload-check').prepend(html);
                        if ($('#none-option-file').length > 0) {
                            $('.switch-product[value="off"]').prop('checked', true);
                            $('#status-append').fadeOut(0);
                            $('#sale-calendar').hide();
                        }
                    }

                    if(LUX && (productNumber < 0 || !productNumber || productNumber >= 1000000000) && option_mode == 'normal' && $('.prod-option[data-option_mode="'+option_mode+'"] .prod-option-list > li').length == 1) {
                        addProductOption('normal');    
                    }

                    var cnt = $('.prod-option[data-option_mode="'+option_mode+'"] .prod-option-list > li').length;
                    if(option_mode == 'normal') {
                        if(cnt == 1) {
                            $('.prod-option[data-option_mode="normal"]').addClass('hide');
                            $('#normal-option').prop('checked', false);
                        }
                    } else {
                        if(cnt == 0) {
                            $('.prod-option[data-option_mode="'+option_mode+'"]').addClass('hide');
                            $('#'+option_mode+'-option').prop('checked', false);
                        }
                        if(option_mode == 'text' && cnt < 7) {
                            $('.prod-option[data-option_mode="text"] > .prod-option-add').removeClass('disabled');
                        }
                    }

                    if($('.prod-option-tab .prod-option.hide').length == 3) {
                        $('.prod-option-tab').addClass('hide');
                    }
                    if($('.prod-option-edit').length <= 2) {
                        $('.prod-option-edit .edit-option-delete').addClass('hide');
                    } else {
                        $('.prod-option-edit .edit-option-delete').removeClass('hide');
                    }

                    modal.modal('hide');
                },'cancel', 'ok', 'cl-p130 cl-cmmodal cl-s-btn w560 cl-p0');            
            });
            $(document).on('click','.category-lists li', function(e) { 
                e.stopPropagation();
                $(this).toggleClass('active'); 
                var selected = $('.category-lists li.active').map(function() {
                    return $(this).text();
                }).get().join(', ');
                selected = (selected.length==0) ? '카테고리를 선택하세요' : selected;
                $('#prod-category-text').text(selected);
            });
            $(document).on('click','.category-wrap', function(e) { 
                var txt = $(this).find('.category-text').text(),
                    selected = $.map(txt.split(","), $.trim);
                
                $.each($('.category-lists li'), function(i,v) {
                    var s = $.trim($(this).text());
                    if(selected.indexOf(s) > -1) {
                        $(this).addClass('active');
                    }
                });
                // $('.category-lists').slideToggle(); 
            });
            /*--------- move -------------*/
            $(document).on('click','.category-title', function() {
                var submit = true;
                if($('.category-move.delete').length) {
                    $.each($('.category-move.delete'), function(i,v) {
                        $(this).removeClass('delete').find('i').removeClass('fa-trash-o').addClass('fa-arrows');
                        var txt = $(this).parents('li').find('.category-input').val();
                        if(txt.length == 0) {
                            submit = false;
                            return true;
                        }
                        $(this).parents('li').find('.category-title').text(txt).removeClass('hide');
                    });
                }

                if(submit) {
                    var v = $(this).text();
                    if(!$(this).hasClass('hide')) {
                        $(this).addClass('hide');
                        $(this).siblings('.form-wrap').find('.category-input').val(v).focus();
                    }
                    $(this).parents('li').find('.category-move').addClass('delete').html('<i class="fa fa fa-trash-o" aria-hidden="true">');
                }
            });
            $(document).on('focus', '.category-input', function(e) {
                var submit = true;
                if($('.category-move.delete').length) {
                    $.each($('.category-move.delete'), function(i,v) {
                        $(this).removeClass('delete').find('i').removeClass('fa-trash-o').addClass('fa-arrows');
                        var txt = $(this).parents('li').find('.category-input').val();
                        if(txt.length == 0) {
                            submit = false;
                            return true;
                        }
                        $(this).parents('li').find('.category-title').text(txt).removeClass('hide');
                    });
                }

                $(this).parents('li').find('.category-move').addClass('delete').find('i').removeClass('fa-arrows').addClass('fa-trash-o');
            });
            $(document).on('keyup', '.category-input', function(e) {
                var keyCode = e.keyCode,
                    search = $(this).val().trim(),
                    v = $(this).val().trim();

                $(this).parents('.form-wrap').siblings('.category-title').text(v);
                if(checkEmojis(v)) {
                    e.preventDefault();
                    errorEmojisModal('10002');
                    return false;
                }
                if(v.length==0) return false;
                if(keyCode == 13) {
                    if($.category.check()) {
                        // alert('카테고리명 중복입니다');
                        var modal = $(this).showModalFlat('','카테고리명 중복입니다',true,false,'','ok','','cl-cmmodal cl-s-btn w560 cl-p130 cl-t80 cl-modal cl-none-title cl-close-btn','','',function() {
                            $(document).on('keydown', function(e) {
                                if(e.keyCode == 27) modal.modal('hide');
                            });
                        });
                        return false;
                    }
                    $(this).parents('.form-wrap').siblings('.category-title').removeClass('hide');
                    $(this).parents('.form-wrap').siblings('.category-move').removeClass('delete').html('<i class="fa fa-arrows" aria-hidden="true"></i>');
                }
            });
            $(document).on('blur', '.category-input', function(e) {
                if(checkEmojis($(this).val().trim())) {
                    e.preventDefault();
                    var focus_input = $(this);
                    errorEmojisModal('10002');
                }
            });

            $(document).on('click','.item-add', function() {
                if($(this).closest('.category-edit').find('li:not(.item-add) .category-title.hide').length > 0) {
                    $(this).closest('.category-edit').find('li:not(.item-add) .category-title.hide').eq(0).closest('li').find('.form-wrap .form-group input.category-input').focus();
                    return false;
                }

                $('.category-edit li:last-child').before($('<li><div class="form-wrap"><div class="form-group"><input type="text" class="category-input" required="required"/><label for="input" class="control-label">'+ $.lang[LANG]['editor.block.gallery.category.edit.name'] +'</label><i class="bar"></i></div></div><div class="category-move delete"><i class="fa fa-trash-o" aria-hidden="true"></i></div><div class="category-title hide"></div></li>'));
                $('.category-input:last-child').focus();
            });
            $(document).on('click','.category-move.delete', function(e) {
                if($(this).closest('.category-edit').children('li:not(.item-add)').length <= 1) {
                    $(this).showModalFlat($.lang[LANG]['config.information'], $.lang[LANG]['editor.gallery.category.delete.last'], true, false, '', 'ok','', 'cl-cmmodal cl-s-btn w560 cl-p130 cl-p0 cl-okbtn-pbt70 category-error', false, '', function() {
                        $('.modal-dialog.category-error').closest('.flat-modal').next('.modal-backdrop').attr('style','z-index: 10001!important;');
                        $('.modal-dialog.category-error').closest('.modal').attr('style','display: block; z-index: 10002;'); 
                    });
                    return false;
                }

                ($.category.delete).push($(this).next().text());
                $(this).parents('li').find('.category-input').val('');
                $(this).parents('li').remove();
            });
            $(document).on('click','.prod-button .modal-close', function(e) { $.products.close(); });
            $(document).on('click','.category-modal .cl-category-modal-ok', function(e) {
                var change = [], 
                    del = $.category.delete,
                    regexp = /^[ㄱ-ㅎ가-힣ㅏ-ㅣa-zA-Z0-9\# ]+$/i,
                    checkRegexp = false,
                    checkMin = false,
                    checkMax = false;

                var category_lists = $('.category-edit .category-title').map(function(){
                    var org = $(this).attr('data-org'),
                        val = $(this).text().trim();

                    if(val.length < 1) checkMin = true;
                    if(val.length > 20) checkMax = true;

                    if(org != val) change.push(org + '|' + val);
                    if(val != '') { 
                        if(!regexp.test(val)) checkRegexp = true;
                        
                        return val;
                    }
                }).get();

                var error_str = '';
                if(checkMin)            error_str = $.lang[LANG]['board.enter-min-chars.1'];
                else if(checkMax)       error_str = $.lang[LANG]['board.enter-max-chars'];
                else if(checkRegexp)    error_str = $.lang[LANG]['board.allowed-chars'];

                if(error_str.length > 0) {
                    $(this).showModalFlat($.lang[LANG]['config.information'], error_str, true, false, '', 'ok','', 'cl-cmmodal cl-s-btn w560 cl-p130 cl-p0 cl-okbtn-pbt70 category-error', false, '', function() {
                        $('.modal-dialog.category-error').closest('.flat-modal').next('.modal-backdrop').attr('style','z-index: 10001!important;');
                        $('.modal-dialog.category-error').closest('.modal').attr('style','display: block; z-index: 10002;'); 
                    });
                    return false;
                }

                if(checkEmojis(category_lists.toString())) {
                    e.preventDefault();
                    errorEmojisModal('10002');
                    return false;
                }

                if($.category.check()) {
                    // alert('카테고리명 중복입니다');
                    var modal = $(this).showModalFlat('','카테고리명 중복입니다',true,false,'','ok','','cl-cmmodal cl-s-btn w560 cl-p130 cl-t80 cl-modal cl-none-title cl-close-btn','','',function() {
                        $(document).on('keydown', function(e) {
                            if(e.keyCode == 27) modal.modal('hide');
                        });
                    });
                    return false;
                }

                var $category = $('#prod-category-text');
                var cate = ($category.text().trim()) ? $category.text().trim().split(', ') : [];

                if(cate.length && del.length) {
                    $.each(del, function(i,v) {
                        var idx = cate.indexOf(v);
                        if(idx > -1) cate.splice(idx, 1)
                    });
                    $category.text(cate.join(', '));
                }

                if(cate.length && change.length) {
                    $.each(change, function(i,v) {
                        var s = v.split('|'),
                            idx = cate.indexOf(s[0]);
                        if(idx > -1) cate[idx] = s[1];
                    });
                    $category.text(cate.join(', '));
                }
                if($category.text() == '') $category.text('카테고리를 선택하세요');
                
                var pid = ($('.prod-modal').length) ? $('#prod-pid').val() : $('.gallery-ctrl-category').attr('data-pid'),
                    gid = $('#prod-no').val();

                $.post('/template/gallery/category', { sid : SID, s : category_lists, mode : 'block', seq : pid, gid : gid, change : change, del : del }, function(r) {
                    if(typeof r.error !='undefined' && r.error) {
                        alert(r.error);
                        return false;
                    }

                    $('#prod-category-lists ul, .toolbar-category .item-submenu').empty();
                    $('.gallery-category li.category-text').remove();
                    var s = '';
                    $.each(category_lists, function(i,v) {
                        var li_str = '<li>' + v + '</li>',
                            li_str2 = '<li class="category-text">' + v + '</li>';
                        s = s + li_str;
                        $('#prod-category-lists ul').append(li_str);
                        $('.toolbar-category .item-submenu').append(li_str);
                        $('.gallery-category .gallery-category-onoff').before(li_str2);
                    });
                    $.gallery.cates = s;
                    $('#prod-category, .gallery-ctrl-category, .gallery-modal').attr('data-category',category_lists.toString());


                    $category = $('#prod-category-text');
                    var cate = ($category.text().trim()) ? $category.text().trim().split(', ') : [];
                    $.each($('.category-lists li'), function(i,v) {
                        // IE ERROR_includes__H.20210603
                        // if(cate.includes($(this).text())) $(this).addClass('active');
                        if($.inArray($(this).text(),cate) > -1) $(this).addClass('active');
                    });
                    $.category.close();
                    if($('.gallery-modal').hasClass('shopping') && $('.prod-modal.cl-p-modal').length == 0) $.gallery.show($.gallery.block_id,1,$.gallery.category);
                    $.gallery.update = true;

                }, 'json');
            });
        },
        open : function(s) {
            if($('.cl-category-modal-backdrop').length >0) $('.cl-category-modal-backdrop').remove();
            var text = (typeof s != 'string') ? [] : s.split(',');
            var $backdrop = $('<div class="cl-category-modal-backdrop"></div>'),
                $title = $('<h1 class="category-modal-title">' + $.lang[LANG]['editor.block.gallery.category.edit.title'] + '</h1>'),
                $modal = $('<div class="cl-category-modal cl-p-modal category-modal"></div>'),
                $lists = $('<ul class="category-edit"></ul>'),
                $item_add = $('<li class="item-add"></li>');
                $modal_footer = $('<div class="cl-category-modal-footer"><div class="cl-category-modal-close">' + $.lang[LANG]['editor.cancel'] + '</div><div class="cl-category-modal-ok">' + $.lang[LANG]['config.save'] + '</div></div>');

            $.each(text, function(i,v) {
                var item = "\
                    <li>\
                        <div class='form-wrap'>\
                            <div class='form-group'>\
                                <input type='text' class='category-input' required='required' value='" + v + "'>\
                                <label for='input' class='control-label'>"+ $.lang[LANG]['editor.block.gallery.category.edit.name'] +"</label><i class='bar'></i>\
                            </div>\
                        </div>\
                        <div class='category-move'><i class='fa fa-arrows' aria-hidden='true'></i></div>\
                        <div class='category-title' data-org='" + v + "'>" + v + "</div>\
                    </li>\
                ";
                $lists.append($(item));
            });

            // $('.category-edit').append($(item));

            $lists.append($item_add);
            $modal.append($title).append($lists).append($modal_footer);
            $backdrop.append($modal);
            $('body').append($backdrop);
            $backdrop.fadeIn(500);
            $('.category-edit').sortable({
                handle : ".category-move"
            });
        },
        close : function() {
            $('.cl-category-modal-backdrop').fadeOut(500, function() { $(this).remove(); });
        },
        check : function() {
            var category = $.category.list(),
                // set_category = new Set(category);
                set_category = category.filter(onlyUnique);

            // IE ERROR (filter)
            // check = category.filter((s => v => s.has(v) || !s.add(v))(new Set)); 

            // 변경 없이 저장시 중복 체크 이슈 생김
            // return (category.length !== set_category.size) ? true : false;
            return (category.toString() !== set_category.toString()) ? true : false;
        },
        list : function() {
            var category_lists = $('.category-edit .category-title').map(function(){
                var org = $(this).attr('data-org'),
                    val = $(this).text().trim();
                if($(this).text().trim()) {
                    return $(this).text().trim();
                }
            }).get();
            return category_lists;            
        }
    }


    $.shoppingmall = {        
        orderStatusDetailsModal: function(sid, pnum, onum, ognum, kind) {
            if(typeof sid == "undefined" || typeof pnum == "undefined" || typeof onum == "undefined" || typeof kind == "undefined") {
                alert('정보가 올바르지 않습니다');
                return false;
            }

            $.post('/_check_order', { sid:sid, pnum:pnum, onum:onum, ognum:ognum,mode:'kind/'+kind }, function(data) {

                if(typeof data.error != "undefined" && data.error) {
                    $(this).showModalFlat('ERROR', data.error, true, false, '', 'close');
                    return false;
                }
                var c_data = data.r,
                    status = c_data.odata.reason_d_status,
                    kind_str = c_data.odata.kind_str,
                    product_status_str = c_data.odata.product_status_str,
                    payClass = c_data.odata.class;
                   
                    option_name = (typeof c_data.pdata.option != "undefined" && c_data.pdata.option) ? c_data.pdata.option : '',
                    etc_str = (typeof c_data.pdata.etc_date != "undefined" && c_data.pdata.etc_date) ? '<br><span class="osd-gray">선택일자: '+c_data.pdata.etc_date+'</span>' : '',

                    // option_str = (option_name) ? '<br><span class="osd-gray">옵션: '+option_name+'</span>' : '',
                    now_status_html = '',
                    delivery_info = c_data.pay_info.delivery,
                    option_title = (c_data.pdata.option_type == 'A') ? '추가옵션: ' + (c_data.pdata.option_group ? c_data.pdata.option_group + ': ' : '') : '옵션: ';
                if(option_name) {
                    option_str = (c_data.pdata.option_text_str)? '<br><span class="osd-gray">' + option_title + option_name+' / '+c_data.pdata.option_text_str+'</span>':'<br><span class="osd-gray">'+ option_title + option_name+'</span>';
                } else {
                    option_str = (c_data.pdata.option_text_str)? '<br><span class="osd-gray">' + option_title + c_data.pdata.option_text_str + '</span>' : '';
                }
                if(etc_str) option_str += etc_str;
                
                if(status.length > 1) {
                    var now_title = c_data.odata.product_status_str.replace(/ /g,'').replace('거부재발송','거부'),
                        now_msg = (status.indexOf('W') > -1) ? c_data.odata.h_msg : 

                        c_data.odata.adm_msg,
                        now_msg_html = (jQuery.inArray(status, ['CY','EY','RY']) > -1) ? '' : '\
                                <tr>\
                                    <td class="label">' + now_title + '사유</td>\
                                    <td>' + now_msg + '</td>\
                                </tr>\
                        ',
                        now_msg_date = (jQuery.inArray(status, ['EW','RW']) > -1) ? c_data.odata.h_date : c_data.odata.adm_date;

                    now_status_html = '\
                        <h6 class="osd-title">' + now_title + '정보</h6>\
                        <table class="osd-table">\
                            <tbody>\
                                <tr>\
                                    <td class="label">' + now_title + '일자</td>\
                                    <td>' + now_msg_date + '</td>\
                                </tr>\
                    ';
                    if(status != 'CY' && status != 'RY') {
                        $.each(delivery_info, function(i, v){
                            delivery_info[i] = (v===null)? '':v;
                        });
                        if(status == 'RD' || status == 'ED' || status == 'EY'|| status == 'ES') {
                            if(delivery_info.new_postcode !== '') {
                                now_status_html+= '<tr>\
                                            <td class="label">배송지1</td>\
                                            <td>' + delivery_info.new_postcode + ' ' + delivery_info.new_addr + ' ' + delivery_info.new_addr2 + '</td>\
                                        </tr>\
                                ';
                            }

                            if(delivery_info.new_delivery_type) {
                                now_status_html += '\
                                    <tr>\
                                        <td class="label">배송수단</td>\
                                        <td>' + $.lang[LANG]['shopping.delivery.template.delivery_type.' + delivery_info.new_delivery_type.toLowerCase()] + '</td>\
                                    </tr>\
                                '
                            }

                            if(delivery_info.new_delivery_company) {
                                now_status_html+= '\
                                        <tr>\
                                            <td class="label">배송회사</td>\
                                            <td>' + delivery_info.new_delivery_str + '</td>\
                                        </tr>';
                            }
                            if(delivery_info.new_delivery_str != '자가배송' && delivery_info.new_delivery_number != '') {
                                now_status_html+= '<tr>\
                                            <td class="label">송장번호</td>\
                                            <td>' + delivery_info.new_delivery_number + '</td>\
                                        </tr>';
                            }
                        }
                        
                        now_status_html += now_msg_html;
                    }
                    now_status_html+= '\
                            </tbody>\
                        </table>\
                    ';
                }

                var r_requests = (c_data.odata.requests != '')? c_data.odata.requests : '-';
                var modal_str = '\
                    <div class="osd-body">\
                        \
                        <h6 class="osd-title">기본정보</h6>\
                        <table class="osd-table">\
                            <tbody>\
                                <tr>\
                                    <td class="label">주문번호</td>\
                                    <td>' + ognum + '</td>\
                                </tr>\
                                <tr>\
                                    <td class="label">상품명</td>\
                                    <td>' + c_data.pdata.name + option_str + '</td>\
                                </tr>\
                                <tr>\
                                    <td class="label">주문수량</td>\
                                    <td>' + c_data.odata.quantity + '개</td>\
                                </tr>';
                                modal_str += '<tr>\
                                        <td class="label">'+kind_str+'상태</td>\
                                        <td>' + product_status_str + '</td>\
                                    </tr>';
                                if ((status.indexOf('R') !== -1 || (c_data.odata.p_status != 'W' && status.indexOf('C') !== -1)) && (payClass == '무통장 입금' || payClass == '가상계좌')) {
                                    modal_str += '<tr>\
                                        <td class="label">환불계좌</td>\
                                        <td>' + c_data.odata.return_bank + ' ' + c_data.odata.return_bank_number + '<br>' + c_data.odata.return_bank_name + '</td>\
                                    </tr>';
                                }
                            modal_str += '</tbody>\
                        </table>\
                        \
                        ' + now_status_html +'\
                        \
                        <h6 class="osd-title">' + kind_str + '요청정보</h6>\
                        <table class="osd-table">\
                            <tbody>\
                                <tr>\
                                    <td class="label">' + kind_str + '요청일자</td>\
                                    <td>' + c_data.odata.date + '</td>\
                                </tr>\
                                <tr>\
                                    <td class="label">' + kind_str + '요청사유</td>\
                                    <td>' + c_data.odata.reason + '</td>\
                                </tr>\
                                <tr>\
                                    <td class="label">상세사유</td>\
                                    <td>' + r_requests + '</td>\
                                </tr>\
                            </tbody>\
                        </table>\
                        \
                    </div>\
                    \
                    ';

                /*
                var c_data = data.r,
                    status = c_data.odata.d_status,
                    kind_str = c_data.odata.kind_str,
                    product_status_str = c_data.odata.product_status_str,
                    option_name = (typeof c_data.pdata.option != "undefined" && c_data.pdata.option) ? c_data.pdata.option : '',
                    option_str = (option_name) ? '<br><span>옵션: '+option_name+'</span>' : '',
                    status_str = '',
                    response_str = '',
                    request_str = '\
                        <table class="osd-table">\
                            <tbody>\
                                <tr>\
                                    <td class="label">' + kind_str + '요청사유</td>\
                                    <td>' + c_data.odata.reason + '</td>\
                                </tr>\
                                <tr>\
                                    <td class="label">상세사유</td>\
                                    <td>' + c_data.odata.requests + '</td>\
                                </tr>\
                            </tbody>\
                        </table>\
                    ';

                if(jQuery.inArray(status, ['CN','CY','EN','EW','RN','RW']) > -1) {
                    var status_str = (status.indexOf('W') > -1) ? c_data.odata.h_msg : c_data.odata.adm_msg,
                        status_msg = (jQuery.inArray(status, ['CY']) > -1) ? '' : '\
                                <tr>\
                                    <td class="label">' + c_data.odata.product_status_str.replace(/ /g,'') + '사유</td>\
                                    <td>' + status_str + '</td>\
                                </tr>\
                    ',
                        status_date = (jQuery.inArray(status, ['EW','RW']) > -1) ? c_data.odata.h_date : c_data.odata.adm_date;

                    status_str = '\
                        <h6 class="osd-title">' + c_data.odata.product_status_str.replace(/ /g,'') + '정보</h6>\
                        <table class="osd-table">\
                            <tbody>\
                                <tr>\
                                    <td class="label">' + c_data.odata.product_status_str.replace(/ /g,'') + '일자</td>\
                                    <td>' + status_date + '</td>\
                                </tr>\
                                ' + status_msg + '\
                            </tbody>\
                        </table>\
                    ';
                }

                if(jQuery.inArray(status, ['EN', 'EW', 'RN', 'RW']) > -1) {
                    response_str = '\
                                <tr>\
                                    <td class="label">' + kind_str + ' ' + c_data.odata.h_kind_str + '사유</td>\
                                    <td>' + c_data.odata.h_reason + '</td>\
                                </tr>\
                                <tr>\
                                    <td class="label">상세사유</td>\
                                    <td>' + c_data.odata.h_msg + '</td>\
                                </tr>\
                    ';
                }

                var modal_str = '\
                    <div class="osd-body">\
                        \
                        <h6 class="osd-title">기본정보</h6>\
                        <table class="osd-table">\
                            <tbody>\
                                <tr>\
                                    <td class="label">주문번호</td>\
                                    <td>' + onum + '</td>\
                                </tr>\
                                <tr>\
                                    <td class="label">상품명</td>\
                                    <td>' + c_data.pdata.name + option_str + '</td>\
                                </tr>\
                                <tr>\
                                    <td class="label">주문수량</td>\
                                    <td>' + c_data.odata.quantity + '개</td>\
                                </tr>\
                                <tr>\
                                    <td class="label">' + kind_str + '요청일자</td>\
                                    <td>' + c_data.odata.date + '</td>\
                                </tr>\
                                <tr>\
                                    <td class="label">진행상태</td>\
                                    <td>' + product_status_str + '</td>\
                                </tr>\
                                ' + response_str + '\
                            </tbody>\
                        </table>\
                        \
                        ' + status_str +'\
                        \
                        <h6 class="osd-title">' + kind_str + '요청정보</h6>\
                        ' + request_str +'\
                        \
                    </div>\
                    \
                    ';

                */
                var osdModal = $(this).showModalFlat(kind_str + ' 상세정보', modal_str, true, false, '', 'ok', '', 'cl-s-order-status-details cl-modal cl-s-btn cover', false);

            },'json');

        },
        orderCancelModal: function(sid, pnum, onum, ognum, status, dStatus, pclass) {
            if(typeof sid == "undefined" || typeof pnum == "undefined" || typeof onum == "undefined") {
                alert('정보가 올바르지 않습니다');
                return false;
            }
            var escrow = status;
            $.post('/_check_order', { sid:sid, pnum:pnum, onum:onum, mode:'cancel', ognum: ognum }, function(data) {
                var LUX = false;
                if(data.lux) LUX = data.lux;
                if(typeof data.error != "undefined" && data.error) {
                    $(this).showModalFlat('ERROR', data.error, true, false, '', 'close');
                    return false;
                }


                var c_data = data.r, checkboxNone = '', noneAll = '', noneChecked = '', checkNoneAll = '', checkEscrowFooter = '', checkEscrowClass = '', checkDepositCancel = '';
                var checkEscrow = '';
                var dtl = c_data.delivery_template_list;
                var used_code_coupon = false;
                
                if (escrow == 'Y') {
                    checkboxNone = 'checked';
                    noneAll = ' noneAll';
                    checkNoneAll = 'fule';
                    checkEscrow = '<div class="escrow-warring top-escrow">\
                                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 13 13" width="15" height="15">\
                                        <path fill="#4789e7" d="M6.5 0C2.91 0 0 2.91 0 6.5S2.91 13 6.5 13 13 10.09 13 6.5 10.09 0 6.5 0zM6.5 12C3.47 12 1 9.53 1 6.5S3.47 1 6.5 1 12 3.47 12 6.5 9.53 12 6.5 12z"/>\
                                        <rect fill="#4789e7" x="6" y="3" width="1" height="5"/>\
                                        <rect fill="#4789e7" x="6" y="9" width="1" height="1"/>\
                                    </svg>\
                                    에스크로 결제 상품은 취소/반품 요청 시 전체선택만 가능합니다.\
                                </div>';

                    checkEscrowFooter = '<div class="escrow-warring bottom-escrow">\
                                            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 13 13" width="15" height="15">\
                                                <path fill="#4789e7" d="M6.5 0C2.91 0 0 2.91 0 6.5S2.91 13 6.5 13 13 10.09 13 6.5 10.09 0 6.5 0zM6.5 12C3.47 12 1 9.53 1 6.5S3.47 1 6.5 1 12 3.47 12 6.5 9.53 12 6.5 12z"/>\
                                                <rect fill="#4789e7" x="6" y="3" width="1" height="5"/>\
                                                <rect fill="#4789e7" x="6" y="9" width="1" height="1"/>\
                                            </svg>\
                                            에스크로 환불 안내\
                                            <div class="escrow-return-info">- 취소처리 시 구매자의 환불정산액에서 취소 수수료(330원)가 차감됩니다.</div>\
                                            <div class="escrow-return-info">- 환불정산액은 취소처리 후 1~3영업일 후에 지급됩니다.</div>\
                                        </div>';
                    checkEscrowClass = 'cl-s-escrow-info';
                } else {
                    if(c_data.order_status == 'W') {
                        checkboxNone = 'checked';
                        noneAll = ' noneAll';
                        checkNoneAll = 'fule';
                        checkDepositCancel = '<div class="modal-comment deposit-cancel-desc">\
                                    <div class="desc-box">\
                                        <div class="desc-title">입금대기 주문취소 안내</div>\
                                        <div class="section">- 입금대기 주문 건은 <span class="cl-red">전체 취소</span>만 가능하며 <span class="cl-red">취소완료</span>로 처리됩니다.</div>\
                                        <div class="section">- 전체취소 후 구매를 원하는 상품은 다시 주문해주세요.</div>\
                                        <div class="section">- 혹시나 입금을 하신 경우 별도로 문의 주시기 바랍니다.</div>\
                                    </div>\
                                </div>\
                            ';
                    }
                }

                if(c_data.pay_info.coupon_list && c_data.pay_info.coupon_list.length) {
                    $.each(c_data.pay_info.coupon_list, function(k, v) {
                        if(v.kind == 'C') {
                            used_code_coupon = true;
                        }
                    })
                }

                if(c_data.order_status != 'W' && used_code_coupon) {
                    checkboxNone = 'checked';
                    noneAll = ' noneAll';
                    checkNoneAll = 'fule';
                    checkDepositCancel = '<div class="modal-comment deposit-cancel-desc">\
                                <div class="desc-box">\
                                    <div class="desc-title">코드쿠폰 사용 주문취소 안내</div>\
                                    <div class="section">- 코드쿠폰 사용 주문 건은 <span class="cl-red">전체 취소</span>만 가능합니다.</div>\
                                    <div class="section">- 전체취소 후 구매를 원하는 상품은 다시 주문해주세요.</div>\
                                </div>\
                            </div>\
                        ';
                }
                
                var modal_str = '\
                    <form name="cancel_form" method="post" action="/_return">\
                        <input type="hidden" name="sid" value="' + sid + '">\
                        <input type="hidden" name="order_group" id="cancel-order-group" value="' + ognum + '">\
                        <input type="hidden" name="order_number" id="cancel-order-number" value="' + onum + '">\
                        <input type="hidden" name="extra_charge" id="extra_charge" value="' + data.r.pay_info.extra_charge + '">\
                        '+checkEscrow+'\
                        <div class="cancel-product-title">\
                            <div class="newcheckbox hand">\
                                <label>\
                                    <input type="checkbox" class="'+noneAll+'" id="product-check" '+checkboxNone+'>\
                                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16">\
                                        <path d="M13 0H3C1.3 0 0 1.3 0 3v10c0 1.7 1.3 3 3 3h10c1.7 0 3-1.3 3-3V3C16 1.3 14.7 0 13 0zM15 13c0 1.1-0.9 2-2 2H3c-1.1 0-2-0.9-2-2V3c0-1.1 0.9-2 2-2h10c1.1 0 2 0.9 2 2V13z"/>\
                                    </svg>\
                                    <svg class="active" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16">\
                                        <path d="M13 0H3C1.34 0 0 1.34 0 3v10c0 1.66 1.34 3 3 3h10c1.66 0 3-1.34 3-3V3C16 1.34 14.66 0 13 0zM13.03 6.03l-5.5 5.5C7.38 11.68 7.19 11.75 7 11.75s-0.38-0.07-0.53-0.22l-3.5-3.5c-0.29-0.29-0.29-0.77 0-1.06s0.77-0.29 1.06 0L7 9.94l4.97-4.97c0.29-0.29 0.77-0.29 1.06 0S13.32 5.74 13.03 6.03z"/>\
                                    </svg>\
                                </label>\
                            </div>\
                            취소요청 상품\
                        </div>';
                        var my_point = Number(data.r.my_point);

                        var weight_template_product = {};
                        for (var i=0;i<data.r.odata.length;i++) {
                            if(c_data.odata[i].state != 'normal') continue;
                            var dts = c_data.odata[i].state == 'normal' ? c_data.odata[i].delivery_template_seq : '';
                            if(c_data.odata[i].state == 'normal' && c_data.odata[i].mix_yn != 'Y') dts += '-' + c_data.odata[i].product_number;
                            var dt = c_data.odata[i].state == 'normal' ? c_data.odata[i].delivery_type : '';

                            if(dtl[dts]['price_type'] == 'WEIGHT') {
                                if(!weight_template_product.hasOwnProperty(dts)) weight_template_product[dts] = {};
                                if(!weight_template_product[dts].hasOwnProperty(dt)) weight_template_product[dts][dt] = {};
                                if(!weight_template_product[dts][dt].hasOwnProperty(c_data.odata[i].product_number)) weight_template_product[dts][dt][c_data.odata[i].product_number] = data.r.odata[i];
                            }
                            var tooltip = '';
                            if(dtl[dts]['price_type'] == 'WEIGHT' || dtl[dts]['price_type'] == 'QUANTITY') {
                                if(dtl[dts]['price_type_detail']['method'] == 'DIFFERENTIAL') {
                                    if(dtl[dts]['price_type'] == 'QUANTITY') {
                                        tooltip += '<li class=\'title\'>수량별 배송비</li>';
                                        $(dtl[dts]['price_type_detail']['detail']).each(function(k, detail) {
                                            var d_v = Object.keys(detail)[0];
                                            var d_p = detail[d_v];
                                            tooltip += '<li class=\'item\'>' + d_v + '개 이상 ' + number_format(d_p) + '원</li>';
                                        });
                                    } else if(dtl[dts]['price_type'] == 'WEIGHT') {
                                        tooltip += '<li class=\'title\'>무게별 배송비</li>';
                                        $(dtl[dts]['price_type_detail']['detail']).each(function(k, detail) {
                                            var d_v = Object.keys(detail)[0];
                                            var d_p = detail[d_v];
                                            tooltip += '<li class=\'item\'>' + d_v + 'Kg 이상 ' + number_format(d_p) + '원</li>';
                                        });
                                    }
                                } else if(dtl[dts]['price_type_detail']['method'] == 'REPEAT') {
                                    if(dtl[dts]['price_type'] == 'QUANTITY') {
                                        tooltip += '<li class=\'title\'>수량별 배송비</li>';
                                        tooltip += '<li class=\'item\'>' + number_format(dtl[dts]['repeat_value']) + '개 구매시마다 ' + number_format(dtl[dts]['repeat_price']) + '원 반복 부과</li>';
                                    } else if(dtl[dts]['price_type'] == 'WEIGHT') {
                                        tooltip += '<li class=\'title\'>무게별 배송비</li>';
                                        tooltip += '<li class=\'item\'>' + number_format(dtl[dts]['repeat_value']) + 'Kg마다 ' + number_format(dtl[dts]['repeat_price']) + '원 반복 부과</li>';
                                    }
                                }
                                if(tooltip && (dt == 'DELIVERY' || dt == 'DIRECT'))  {
                                    if(!LUX) tooltip += '<li class=\'desc\'>추가 상품은 배송비 조건에 반영되지 않습니다.</li>';

                                    if(dtl[dts]['price_type'] == 'WEIGHT' && weight_template_product[dts][dt]) {
                                        tooltip += '<li class=\'title product-weight\'>상품별 무게</li>';
                                        $.each(weight_template_product[dts][dt], function(k, v) {
                                            tooltip += '<li class=\'item\'>' + v.product_name + ' : ' + number_format(v.product_weight) + 'kg</li>';
                                        });
                                    }

                                    tooltip = '<ul class=\'delivery-tooltip\'>' + tooltip + '</ul>';
                                    dtl[dts]['tooltip'] = tooltip;
                                }
                            }
                        }

                        modal_str += '<table class="table product-table">';
                        for (var i=0;i<data.r.odata.length;i++) {
                            if (c_data.odata[i].d_status == '' || c_data.odata[i].d_status == 'CN') {
                                noneChecked = '';
                                if (!checkNoneAll) noneAll = '';
                            } else {
                                if (!checkNoneAll) noneAll = 'noneAll';
                                noneChecked = 'noneChecked';
                            }
                            if (c_data.odata[i].p_status == 'W') {
                                if (!checkNoneAll) noneAll = 'noneAll';
                                noneChecked = 'noneChecked';
                                checkboxNone = 'checked';
                            }
                            var curr_point = 0;
                            var usable_point = 0;
                            var refund_point = 0;
                            var expired_point = 0;

                            if(c_data.odata[i].used_point) {
                                curr_point = Math.abs(c_data.odata[i].used_point.point);
                                usable_point = Math.abs(c_data.odata[i].used_point.usable_point);
                            }

                            // if(c_data.odata[i].refund_point) {
                            //     refund_point = c_data.odata
                            // }

                            if(c_data.odata[i].expired_point) {
                                expired_point = Math.abs(c_data.odata[i].expired_point.point);
                            }


                            var dts = c_data.odata[i].state == 'normal' ? c_data.odata[i].delivery_template_seq : '';
                            if(c_data.odata[i].state == 'normal' && c_data.odata[i].mix_yn != 'Y') dts += '-' + c_data.odata[i].product_number;
                            var dt = c_data.odata[i].state == 'normal' ? c_data.odata[i].delivery_type : '';

                            modal_str += '\
                            <tr class="cl-s-product-jumbotron clearfix">\
                                <td ' + (c_data.odata[i].state != 'normal' ? 'colspan="2"' : '') + '>\
                                <div class="newcheckbox hand">\
                                    <label>\
                                        <input type="checkbox" class="status-checkbox cancel-info-data '+noneAll+' '+noneChecked+'" data-curr_point="' + curr_point + '" data-usable_point="' + usable_point + '" data-expired_point="' + expired_point + '" data-type="'+c_data.pdata[i].state+'" name="order_number_ary[]" value="'+c_data.odata[i].order_number+'" '+checkboxNone+' data-option_type="' + c_data.pdata[i].option_type + '" data-product_number="' + c_data.odata[i].product_number + '" data-mix_yn="' + (c_data.odata[i].state == 'normal' ? c_data.odata[i].mix_yn : '') + '" data-delivery_template_seq="' + (c_data.odata[i].state == 'normal' ? dts : '') + '" data-delivery_type="' + (c_data.odata[i].state == 'normal' ? c_data.odata[i].delivery_type : '') + '" data-quantity="' + c_data.odata[i].quantity + '" data-product_weight="' + (c_data.odata[i].state == 'normal' ? c_data.odata[i].product_weight : 0) + '" data-delivery_price="' +  (c_data.odata[i].state == 'normal' && dtl[dts]['pay_type'] == 'PREPAY' ? c_data.odata[i].delivery_price : 0) + '">\
                                        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16">\
                                        <path d="M13 0H3C1.3 0 0 1.3 0 3v10c0 1.7 1.3 3 3 3h10c1.7 0 3-1.3 3-3V3C16 1.3 14.7 0 13 0zM15 13c0 1.1-0.9 2-2 2H3c-1.1 0-2-0.9-2-2V3c0-1.1 0.9-2 2-2h10c1.1 0 2 0.9 2 2V13z"/>\
                                        </svg>\
                                        <svg class="active" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16">\
                                        <path d="M13 0H3C1.34 0 0 1.34 0 3v10c0 1.66 1.34 3 3 3h10c1.66 0 3-1.34 3-3V3C16 1.34 14.66 0 13 0zM13.03 6.03l-5.5 5.5C7.38 11.68 7.19 11.75 7 11.75s-0.38-0.07-0.53-0.22l-3.5-3.5c-0.29-0.29-0.29-0.77 0-1.06s0.77-0.29 1.06 0L7 9.94l4.97-4.97c0.29-0.29 0.77-0.29 1.06 0S13.32 5.74 13.03 6.03z"/>\
                                        </svg>\
                                    </label>\
                                </div>\
                                <div class="cl-s-product-thumb">\
                                    <img src="' + c_data.pdata[i].img + '" alt="' + c_data.pdata[i].name + '" class="' + c_data.pdata[i].img_align + '" />\
                                </div>\
                                <div class="cl-s-product-info">\
                                    <h5 class="cl-s-product-title">' + c_data.pdata[i].name + '</h5>\
                            ';

                            console.log(c_data.odata[i]);

                            var price = (Number(c_data.odata[i].sale_price) > 0) ? c_data.odata[i].sale_price : c_data.odata[i].price,
                                quantity = Number(c_data.odata[i].quantity),
                                optionPrice = c_data.odata[i].price * quantity,
                                sum_price = quantity * price,
                                option_name = (typeof c_data.pdata[i].option != "undefined" && c_data.pdata[i].option) ? c_data.pdata[i].option : '',
                                option_str = '',
                                etc_str = (typeof c_data.pdata[i].etc_date != "undefined" && c_data.pdata[i].etc_date) ? '<span class="etc-date">선택일자: '+c_data.pdata[i].etc_date+'</span>' : '',
                                option_title = (c_data.pdata[i].option_type == 'A') ? '추가옵션: ' + (c_data.pdata[i].option_group ? c_data.pdata[i].option_group + ': ' : '') : '옵션: ';
                            if(option_name) {
                                option_str = (c_data.pdata[i].option_text_str) ? '<span class="' + (etc_str ? 'option-name' : '') + '">' + option_title + option_name+' / '+c_data.pdata[i].option_text_str+'</span>' : '<span class="' + (etc_str ? 'option-name' : '') + '">' + option_title + option_name+'</span>';
                            } else {
                                option_str = (c_data.pdata[i].option_text_str) ? '<span class="' + (etc_str ? 'option-name' : '') + '">' + option_title + c_data.pdata[i].option_text_str+'</span>' : '';
                            }
                            modal_str += '\
                                    <div class="option-str option-check" data-optionPrice="'+optionPrice+'">' + option_str + etc_str + '<span>' + quantity + '개</span><div class="price"><span>' + number_format(optionPrice) + '</span> 원</div></div>\
                                </div>\
                                </td>\
                            ';

                            if(c_data.odata[i].state == 'normal') {
                                var delivery_cnt = dtl[dts]['dtype'][dt].delivery_cnt;
                                if(!dtl[dts]['dtype'][dt].hasOwnProperty('counter')) {
                                    dtl[dts]['dtype'][dt]['counter'] = 0;
                                }

                                dtl[dts]['dtype'][dt]['counter']++;

                                if(dtl[dts]['dtype'][dt]['counter'] == 1) {                            
                                    modal_str +='\
                                        <td rowspan="' + delivery_cnt + '" class="delivery-price"><div>배송비</div><div class="price"><span>';
                                    if(dt == 'DELIVERY' || dt == 'DIRECT') {
                                        if(dtl[dts]['price_type'] == 'ETC') {
                                            modal_str += '별도안내</span>';
                                        } else {
                                            modal_str += number_format(dtl[dts]['dtype'][dt]['price']) + '</span> 원';    
                                        }
                                        if(dtl[dts]['pay_type'] == 'DELIVERED') modal_str += '(착불)';

                                        if(dtl[dts]['price_type'] == 'FREE_CONDITION') {
                                            modal_str += '<div class="price-desc">' + number_format(dtl[dts]['free_condition']) + '원 이상<br>배송비 무료</div>';
                                        }
                                    } else {
                                        modal_str += $.lang[LANG]['shopping.delivery.template.delivery_type.' + dt.toLowerCase()] + '</span>';
                                        if(dt == 'QUICK') modal_str += '(착불)';
                                    }
                                    if(dtl[dts]['tooltip'] && (dt == 'DELIVERY' || dt == 'DIRECT')) {
                                        modal_str += '<svg class="cm-popover-info" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 13 13" width="13" height="13" tabindex="0" data-trigger="hover" data-toggle="popover" fill="#4789e7" data-html="true" data-placement="top" data-content="' + dtl[dts]['tooltip'] + '" data-original-title="" title=""><path d="M6.5 0C2.91 0 0 2.91 0 6.5S2.91 13 6.5 13 13 10.09 13 6.5 10.09 0 6.5 0zM6.5 12C3.47 12 1 9.53 1 6.5S3.47 1 6.5 1 12 3.47 12 6.5 9.53 12 6.5 12z"></path><path d="M6.66 3.01C5.61 3.01 4.58 3.5 4.5 4.8c0 0.06-0.01 0.12 0 0.2h1.02c0-0.07 0.01-0.15 0.02-0.23 0.08-0.62 0.52-0.76 1.08-0.76 0.63 0 1.02 0.37 1.02 0.95 -0.01 0.48-0.3 0.87-0.76 1.34C6.21 6.97 6.02 7.37 6 8h0.99C7 7.66 7.04 7.37 7.67 6.75 8.17 6.27 8.7 5.68 8.7 4.87 8.7 3.85 7.89 3.01 6.66 3.01z"></path><rect x="6" y="9" width="1" height="1"></rect></svg>';
                                    }
                                    modal_str +='</div></td>\
                                    ';
                                }

                                modal_str += '\
                                </tr>';

                                if(dtl[dts]['dtype'][dt]['counter'] == dtl[dts]['dtype'][dt]['delivery_cnt']) {
                                    modal_str += '\
                                        <tr class="cl-s-product-jumbotron clearfix delivery-price delivery-price-mobile">\
                                            <td><div class="delivery-title">묶음 배송비</div><div class="delivey-price"><span>';

                                    if(dtl[dts]['tooltip'] && (dt == 'DELIVERY' || dt == 'DIRECT')) {
                                        modal_str += '<svg class="cm-popover-info" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 13 13" width="13" height="13" tabindex="0" data-trigger="hover" data-toggle="popover" fill="#4789e7" data-html="true" data-placement="top" data-content="' + dtl[dts]['tooltip'] + '" data-original-title="" title=""><path d="M6.5 0C2.91 0 0 2.91 0 6.5S2.91 13 6.5 13 13 10.09 13 6.5 10.09 0 6.5 0zM6.5 12C3.47 12 1 9.53 1 6.5S3.47 1 6.5 1 12 3.47 12 6.5 9.53 12 6.5 12z"></path><path d="M6.66 3.01C5.61 3.01 4.58 3.5 4.5 4.8c0 0.06-0.01 0.12 0 0.2h1.02c0-0.07 0.01-0.15 0.02-0.23 0.08-0.62 0.52-0.76 1.08-0.76 0.63 0 1.02 0.37 1.02 0.95 -0.01 0.48-0.3 0.87-0.76 1.34C6.21 6.97 6.02 7.37 6 8h0.99C7 7.66 7.04 7.37 7.67 6.75 8.17 6.27 8.7 5.68 8.7 4.87 8.7 3.85 7.89 3.01 6.66 3.01z"></path><rect x="6" y="9" width="1" height="1"></rect></svg>';
                                    }
                                    
                                    if(dt == 'DELIVERY' || dt == 'DIRECT') {
                                        modal_str += number_format(dtl[dts]['dtype'][dt]['price']) + '</span> 원';
                                        if(dtl[dts]['pay_type'] == 'DELIVERED') modal_str += '(착불)';
                                        if(dtl[dts]['price_type'] == 'FREE_CONDITION') {
                                            modal_str += '<div class="price-desc">' + number_format(dtl[dts]['free_condition']) + '원 이상 배송비 무료</div>';
                                        }
                                    } else {
                                        modal_str += $.lang[LANG]['shopping.delivery.template.delivery_type.' + dt.toLowerCase()] + '</span>';
                                        if(dt == 'QUICK') modal_str += '(착불)';
                                    }

                                    modal_str += '</div></td>\
                                        </tr>\
                                    ';
                                }
                            }
                        }
                        modal_str += '</table>';

                        modal_str += '<div class="order-cancel-content">\
                            <div class="cl-s-form-selector">\
                                <select class="selectpicker dropdown" id="cancel-reason" name="reason">\
                                    <option value="구매의사 취소">구매의사 취소</option>\
                                    <option value="다른 상품 잘못 주문">다른 상품 잘못 주문</option>\
                                    <option value="기타">기타</option>\
                                </select>\
                                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 8 4" width="8" height="4"><polygon points="0 0 4 4 8 0 "></polygon></svg>\
                            </div>\
                            <div class="cl-s-form-wrap">\
                                <div class="cl-s-form-group input-label-hide">\
                                    <textarea class="cl-s-form-control control-textarea" id="cancel-requests" name="requests" maxlength="500" required="required"></textarea>\
                                    <label for="input" class="cl-s-control-label">자세한 내용을 적어주세요. (500자 이내)</label>\
                                </div>\
                            </div>\
                        </div>';

                        modal_str += '<div class="order-cancel-content">\
                            <div class="cancel-info-box">\
                                <div class="cancel-info"><span class="cancel-info-title">취소상품 합계</span><span class="cancel-info-price" id="cancel-price">0원</span></div>\
                                <div class="cancel-info"><span class="cancel-info-title">취소 배송비 합계</span><span class="cancel-info-price" id="cancel-delivery-price">0원</span></div>\
                                <div class="cancel-info"><span class="cancel-info-title">적립금</span><span class="cancel-info-price" id="cancel-point-price">0원</span></div>\
                                <div class="cancel-info"><span class="cancel-info-title">쿠폰</span><span class="cancel-info-price" id="cancel-coupon-price">0원</span></div>\
                                <div class="cancel-info"><span class="cancel-info-title cancel-coupon-title"></span><span class="cancel-info-price" id="cancel-coupon-detail"></span></div>\
                                <div class="cancel-info-line"></div>\
                                <div class="return-total-info"><span class="cancel-info-title">환불 예정금액</span><span class="cancel-info-price"><span id="return-total-price">0</span>원</span></div>\
                            </div>'+checkEscrowFooter+'\
                        </div>';
                        modal_str += checkDepositCancel;

                    var status = [];
                    for (var i=0;i<c_data.pdata.length;i++) {
                        status.push(c_data.pdata[i].p_status);
                    }

                    if (pclass == '무통장 입금' || pclass == '가상계좌') {
                        var returnClass = '';
                        if (c_data.return_bank.length > 1 && c_data.return_bank.indexOf('')===-1) returnClass = 'returnDisabled';
                        modal_str += '\
                            <div class="modal-sub-title">환불 계좌</div>\
                            <ul class="qna-writer clearfix">\
                                <li class="">\
                                    <div class="cl-s-form-wrap '+returnClass+'">\
                                        <div class="cl-s-form-group">';
                                        if (c_data.return_bank.length > 1 && c_data.return_bank.indexOf('')===-1) modal_str += '<input type="text" class="cl-s-form-control has-value" id="no-bank" name="no_bank" readonly required="required" value="'+c_data.return_bank[1]+'">';
                                        else modal_str += '<input type="text" class="cl-s-form-control" id="no-bank" name="no_bank" required="required" value="">';
                                        modal_str += '<label for="input" class="cl-s-control-label">은행명</label>\
                                        </div>\
                                    </div>\
                                </li>\
                                <li>\
                                    <div class="cl-s-form-wrap '+returnClass+'">\
                                        <div class="cl-s-form-group">';
                                        if (c_data.return_bank.length > 1 && c_data.return_bank.indexOf('')===-1) modal_str += '<input type="text" class="cl-s-form-control has-value" id="no-bank-name" readonly name="no_bank_name" required="required" value="'+c_data.return_bank[2]+'">';
                                        else modal_str += '<input type="text" class="cl-s-form-control" id="no-bank-name" name="no_bank_name" required="required">';
                                        modal_str += '<label for="input" class="cl-s-control-label">예금주</label>\
                                        </div>\
                                    </div>\
                                </li>\
                                <li>\
                                    <div class="cl-s-form-wrap '+returnClass+'">\
                                        <div class="cl-s-form-group">';
                                        if (c_data.return_bank.length > 1 && c_data.return_bank.indexOf('')===-1) modal_str += '<input type="text" class="cl-s-form-control has-value" id="no-bank-number" name="no_bank_number" readonly data-type="email" required="required" value="'+c_data.return_bank[3]+'">';
                                        else modal_str += '<input type="text" class="cl-s-form-control" id="no-bank-number" name="no_bank_number" data-type="email" required="required" value="">';
                                        modal_str += '<label for="input" class="cl-s-control-label">계좌번호</label>\
                                        </div>\
                                    </div>\
                                </li>\
                            </ul>';
                        if(status.indexOf('W')===-1) modal_str += '\
                            <div class="modal-comment">동일 주문 내 여러 상품을 환불 요청하시는 경우, 최초 입력한 환불계좌로 일괄 환불처리됩니다.</div>\
                        ';
                    }

                    modal_str += '\
                            <div class="modal-comment point-used-desc hide">\
                                <div class="desc-box">\
                                    <div class="desc-title">적립금 환불 안내</div>\
                                    <div class="section">상품(들)을 구매하여 적립된 적립금 <span id="disp_used_point_total" class="point-color"></span>원이 이미 사용되거나 유효기간이 만료되었습니다.</div>\
                                    <div class="section">현재 보유 적립금이 <span class="point-color">' + addCommas(my_point) + '</span>원 으로 구매 적립된 적립금 <span id="disp_cancel_after_point" class="point-color"></span>원을 취소 처리할 수 없습니다.</div>\
                                    <div class="section">미 취소된 적립금에 대한 처리는 판매자와 협의해주세요.</div>\
                                </div>\
                                <div class="newcheckbox hand">\
                                    <label style="margin-left: 25px;">\
                                        <input type="checkbox" class="cancel-agree" />\
                                        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16">\
                                            <path d="M13 0H3C1.3 0 0 1.3 0 3v10c0 1.7 1.3 3 3 3h10c1.7 0 3-1.3 3-3V3C16 1.3 14.7 0 13 0zM15 13c0 1.1-0.9 2-2 2H3c-1.1 0-2-0.9-2-2V3c0-1.1 0.9-2 2-2h10c1.1 0 2 0.9 2 2V13z"></path>\
                                        </svg>\
                                        <svg class="active" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16">\
                                            <path d="M13 0H3C1.34 0 0 1.34 0 3v10c0 1.66 1.34 3 3 3h10c1.66 0 3-1.34 3-3V3C16 1.34 14.66 0 13 0zM13.03 6.03l-5.5 5.5C7.38 11.68 7.19 11.75 7 11.75s-0.38-0.07-0.53-0.22l-3.5-3.5c-0.29-0.29-0.29-0.77 0-1.06s0.77-0.29 1.06 0L7 9.94l4.97-4.97c0.29-0.29 0.77-0.29 1.06 0S13.32 5.74 13.03 6.03z"></path>\
                                        </svg>\
                                    위 내용을 확인하였습니다.</label>\
                                </div>\
                                <div class="point-used-cancel-agree-desc">\
                                    <svg viewBox="0 0 13 13" width="13" height="13"><path d="M6.5 0C2.91 0 0 2.91 0 6.5S2.91 13 6.5 13 13 10.09 13 6.5 10.09 0 6.5 0zM6.5 12C3.47 12 1 9.53 1 6.5S3.47 1 6.5 1 12 3.47 12 6.5 9.53 12 6.5 12z"/><rect x="6" y="3" width="1" height="5"/><rect x="6" y="9" width="1" height="1"/></svg>\
                                    적립금 환불 안내에 동의해주세요.\
                                </div>\
                            </div>\
                            ';

                    modal_str += '</form>\
                ';

                var ocModal = $(this).showModalFlat('취소 요청', modal_str,true,true,function () {

                    var f = document.cancel_form;
                    if(ocModal.find('#cancel-reason').prop('value') == '') {
                        // $('#cancel-reason').selectpicker('toggle');
                        // return false;
                        $('#cancel-reason').closest('.cl-s-form-selector').addClass('empty');
                    }

                    ocModal.find('.cl-s-form-wrap').each(function() {
                        var check_input = $(this).find('.cl-s-form-control'),
                            val = check_input.val().trim();

                        if(val.length == 0) {
                            $(this).removeClass('error').addClass('empty');
                            $(this).find('.cl-s-control-label.error').remove();
                        } else {
                            if($(this).hasClass('error')) {
                                check_input.focus();
                            }
                        }
                    });
                    var checkCnt = 0;

                    $(".status-checkbox").each(function (i, index) {
                        if ($(this).is(":checked") === true) {
                            checkCnt++;
                        }
                    });

                    if (checkCnt < 1) {
                        alert('상품을 1개 이상 선택해 주세요');
                        return false;
                    }

                    if(ocModal.find('.cl-s-form-wrap.empty, .cl-s-form-wrap.error').length > 0) {
                        // ocModal.find('.cl-s-form-wrap.empty, .cl-s-form-wrap.error').eq(0).find('.cl-s-form-control').focus();
                        return false;
                    }

                    if(ocModal.find("input[type='checkbox'].cancel-agree:visible").length && ocModal.find("input[type='checkbox'].cancel-agree:visible").length != ocModal.find("input[type='checkbox'].cancel-agree:visible:checked").length) {
                        $(".point-used-cancel-agree-desc").show();
                        return false;
                    } else {
                        $(".point-used-cancel-agree-desc").hide();
                    }

                    $.processON();

                    f.submit();
                    ocModal.modal('hide');

                },'close','등록하기','cl-s-order-cancel cl-modal cl-s-btn cover ' + checkEscrowClass, false, '', function() {
                    var totalCnt = 0, totalNomalCheck = 0, nomalCheck = 0, price = 0, deliveryPrice = 0,
                        $form = $('form[name="cancel_form"]');

                    $('.status-checkbox').each(function(i, index) {
                        if ($(this).is(":checked") === true) {
                            price += ($(this).closest('.cl-s-product-jumbotron').find('.option-check').attr('data-optionPrice') * 1);
                            totalCnt++;
                            if ($(this).attr('data-type') == 'normal') {
                                nomalCheck++;
                                var mix_yn = $(this).data('mix_yn');
                                var delivery_price = 0;
                                var delivery_template_seq = $(this).data('delivery_template_seq');
                                var delivery_type = $(this).data('delivery_type');
                                if(ocModal.find('input[name="order_number_ary[]"][data-delivery_type="' + delivery_type + '"][data-delivery_template_seq="' + delivery_template_seq + '"]').length == ocModal.find('input[name="order_number_ary[]"][data-delivery_type="' + delivery_type + '"][data-delivery_template_seq="' + delivery_template_seq + '"]:checked').length) {
                                    delivery_price = Number($(this).data('delivery_price'));
                                }
                                deliveryPrice += delivery_price;
                            }
                        }

                        if ($(this).attr('data-type') == 'normal') {
                            totalNomalCheck++;
                        }
                    });

                    if(c_data.order_status == 'W') {
                        $("#product-check, .status-checkbox").click(function(e){
                            return false;
                        });
                    }
                    var product_price = price + deliveryPrice,
                        rePayment = parseInt(c_data.pay_info.request.payment.total) - parseInt(c_data.pay_info.request.payment.coupon) - parseInt(c_data.pay_info.request.cancel.total) - parseInt(c_data.pay_info.request.return.total);

                    rePayment = (rePayment > 0) ? rePayment : 0;

                    // coupon 처리
                    var coupon = c_data.pay_info.coupon_list,
                        cancel_coupon_price = 0;
                    if(coupon.length) {
                        var checked_order_number = $('.cancel-info-data:checked').map(function(){ return this.value; }).toArray();

                        $.each(coupon, function(i,v) {
                            if(checked_order_number.indexOf(v.order_number) > -1 || v.kind == 'C') {
                                cancel_coupon_price += parseInt(v.discount_price);

                                // 환불금에서 쿠폰처리
                                if($('.coupon-detail-info[data-seq="' + v.seq + '"]').length == 0) {
                                    $('.cancel-coupon-title').append('<span class="coupon-name coupon-detail-info" data-seq="' + v.seq + '">' + v.coupon_name + '</span>');
                                    $('#cancel-coupon-detail').append('<span class="coupon-price coupon-detail-info" data-seq="' + v.seq + '">-' + number_format(parseInt(v.discount_price)) + '원</span>');
                                }
                            } else {
                                $('.coupon-detail-info[data-seq="' + v.seq + '"]').remove();
                            }
                        });
                        // 취소된 쿠폰 저장
                    }
                    product_price = product_price - parseInt(cancel_coupon_price);
                    
                    var use_point = (rePayment - product_price > 0) ? 0 : rePayment - product_price;
                    product_price = product_price + use_point;

                    $('#cancel-price').html(number_format(price)+'원');
                    $('#cancel-delivery-price').html(number_format(deliveryPrice)+'원');
                    $('#cancel-point-price').html(number_format(use_point)+'원');
                    $('#cancel-coupon-price').html(((cancel_coupon_price > 0) ? '-' + number_format(cancel_coupon_price) : '0')+'원');
                    $('#return-total-price').html(number_format(product_price));

                    $('.cancel-info-data').on('change', function (e) {
                        if($(this).hasClass('noneAll')) return;    
                        var cancel_after_point = my_point;
                        var disp_used_point_total = 0;
                        var deliveryPrice = 0;
                        var extra_delivery_flag = {};
                        var dtl_copy = JSON.parse(JSON.stringify(dtl));


                        var product_number = $(this).attr('data-product_number');
                        if($(this).attr('data-option_type') != 'A' && !$('input[name="order_number_ary[]"][data-product_number="' + product_number + '"][data-option_type!="A"]:not(:checked)').length) {
                            $('input[name="order_number_ary[]"][data-product_number="' + product_number + '"][data-option_type="A"]').prop('checked',true);
                        } else if($(this).attr('data-option_type') == 'A' && !$('input[name="order_number_ary[]"][data-product_number="' + product_number + '"][data-option_type!="A"]:not(:checked)').length && !$(this).prop('checked')) {
                            $('input[name="order_number_ary[]"][data-product_number="' + product_number + '"][data-option_type!="A"]:last').prop('checked',false);
                        }

                        if($("input[name='order_number_ary[]']:checked").length) {
                            coupon.map(function(v,k) {  coupon[k]['apply'] = '' });
                            $("input[name='order_number_ary[]']:checked").each(function() {
                                cancel_after_point = Number(cancel_after_point) + ((Number($(this).data("expired_point"))) - Number($(this).data("curr_point")));
                                disp_used_point_total += ((Number($(this).data("expired_point"))) - Number($(this).data("curr_point")));
                                c_ord_num = $(this).val();

                                if($(this).data('type') != 'normal' || $(this).data('option_type') == 'A') return;
                                var mix_yn = $(this).data('mix_yn');
                                var delivery_price = 0;
                                var delivery_template_seq = $(this).data('delivery_template_seq');
                                var delivery_type = $(this).data('delivery_type');
                                var product_weight = $(this).data('product_weight');

                                if(delivery_type != 'DELIVERY' && delivery_type != 'DIRECT') return;
                                // if(dtl[delivery_template_seq]['price_type'] != 'WEIGHT' && dtl[delivery_template_seq]['price_type'] != 'QUANTITY') {
                                if(ocModal.find('input[name="order_number_ary[]"][data-delivery_type="' + delivery_type + '"][data-delivery_template_seq="' + delivery_template_seq + '"]').length == ocModal.find('input[name="order_number_ary[]"][data-delivery_type="' + delivery_type + '"][data-delivery_template_seq="' + delivery_template_seq + '"]:checked').length) {
                                    delivery_price = Number($(this).data('delivery_price'));
                                    
                                    coupon.map(function(v,k) { if(v.order_number == c_ord_num && delivery_price > 0 && v.benefit == 'DELIVERY') coupon[k]['apply'] = '1';  });
                                }

                                if(dtl[delivery_template_seq]['price_type'] != 'WEIGHT' && dtl[delivery_template_seq]['price_type'] != 'QUANTITY') {
                                } else {
                                    dtl_copy[delivery_template_seq]['dtype'][delivery_type]['real_weight'] -= Number((Number($(this).data('product_weight')) * Number($(this).data('quantity'))).toFixed(3));
                                    dtl_copy[delivery_template_seq]['dtype'][delivery_type]['real_weight'] = Number(dtl_copy[delivery_template_seq]['dtype'][delivery_type]['real_weight'].toFixed(3));
                                    dtl_copy[delivery_template_seq]['dtype'][delivery_type]['real_quantity'] -= Number($(this).data('quantity'));

                                    if(dtl[delivery_template_seq]['price_type_detail']['method'] == 'REPEAT') {
                                        if(dtl[delivery_template_seq]['price_type'] == 'WEIGHT') {
                                            dtl_copy[delivery_template_seq]['dtype'][delivery_type]['real_price'] = Math.ceil(dtl_copy[delivery_template_seq]['dtype'][delivery_type]['real_weight'] / dtl[delivery_template_seq]['repeat_value']) * dtl[delivery_template_seq]['repeat_price'];
                                        } else if(dtl[delivery_template_seq]['price_type'] == 'QUANTITY') {
                                            dtl_copy[delivery_template_seq]['dtype'][delivery_type]['real_price'] = dtl_copy[delivery_template_seq]['dtype'][delivery_type]['real_price'] - Math.ceil(dtl_copy[delivery_template_seq]['dtype'][delivery_type]['real_quantity'] / dtl[delivery_template_seq]['repeat_value']) * dtl[delivery_template_seq]['repeat_price'];
                                        }
                                        // if()
                                    } else if(dtl[delivery_template_seq]['price_type_detail']['method'] == 'DIFFERENTIAL') {
                                        if(dtl[delivery_template_seq]['price_type'] == 'WEIGHT') {
                                            $.each(dtl[delivery_template_seq]['price_type_detail'].detail, function() {
                                                var r_value = Number(Object.keys(this)[0]);
                                                var r_price = Number(Object.values(this)[0]);
                                                if(dtl_copy[delivery_template_seq]['dtype'][delivery_type]['real_weight'] == 0) {
                                                    dtl_copy[delivery_template_seq]['dtype'][delivery_type]['real_price'] = 0;
                                                } else if(dtl_copy[delivery_template_seq]['dtype'][delivery_type]['real_weight'] >= r_value) {
                                                    dtl_copy[delivery_template_seq]['dtype'][delivery_type]['real_price'] = r_price;
                                                }                                                  
                                            });
                                        } else if(dtl[delivery_template_seq]['price_type'] == 'QUANTITY') {
                                            $.each(dtl[delivery_template_seq]['price_type_detail'].detail, function() {
                                                var r_value = Number(Object.keys(this)[0]);
                                                var r_price = Number(Object.values(this)[0]);
                                                if(dtl_copy[delivery_template_seq]['dtype'][delivery_type]['real_quantity'] == 0) {
                                                    dtl_copy[delivery_template_seq]['dtype'][delivery_type]['real_price'] = 0;
                                                } else if(dtl_copy[delivery_template_seq]['dtype'][delivery_type]['real_quantity'] >= r_value) {
                                                    dtl_copy[delivery_template_seq]['dtype'][delivery_type]['real_price'] = r_price;
                                                }                                                  
                                            });
                                        }
                                    }
                                    if(dtl[delivery_template_seq]['dtype'][delivery_type]['real_price'] > dtl_copy[delivery_template_seq]['dtype'][delivery_type]['real_price'] && dtl_copy[delivery_template_seq]['dtype'][delivery_type]['real_price'] > 0) 
                                        extra_delivery_flag[delivery_template_seq+'|'+delivery_type] = true;
                                    else 
                                        extra_delivery_flag[delivery_template_seq+'|'+delivery_type] = false;
                                }
                                deliveryPrice += delivery_price;
                            });
                        }

                        $form.find('.extra-delivery-fee-box').remove();

                        if(cancel_after_point < 0) {
                            $(".point-used-desc #disp_cancel_after_point").html(addCommas(Math.abs(cancel_after_point)));
                            $(".point-used-desc #disp_used_point_total").html(addCommas(Math.abs(disp_used_point_total)));
                            $(".point-used-desc").removeClass("hide");
                        } else {
                            $(".point-used-desc").addClass("hide");
                            $(".point-used-desc #disp_cancel_after_point").html("");
                            $(".point-used-desc #disp_used_point_total").html("");
                        }

                        var price = 0;
                        var oLength = $('.option-check').length;
                        var totalCnt = 0, totalNomalCheck = 0, nomalCheck = 0;
                        
                        $form.find('.order-cancel-content.extra-info').remove();

                        if ($(this).hasClass('noneAll') === true) {
                            if ($(this).hasClass('noneChecked') === true) {
                                $(this).prop('checked', false);
                            } else {
                                $(this).prop('checked', true);
                                $(".status-checkbox").each(function () {
                                    if ($(this).prop('disabled') !== true) $(this).prop('checked', true);
                                });
                            }
                        }

                        $(".status-checkbox").each(function (i, index) {
                            if ($(this).is(":checked") === true) {
                                price += ($(this).closest('.cl-s-product-jumbotron').find('.option-check').attr('data-optionPrice') * 1);
                                totalCnt++;
                                if ($(this).attr('data-type') == 'normal') nomalCheck++;
                            }

                            if ($(this).attr('data-type') == 'normal') totalNomalCheck++;
                        });

                        var product_price = price + deliveryPrice,
                            rePayment = parseInt(c_data.pay_info.request.payment.total) - parseInt(c_data.pay_info.request.cancel.total) - parseInt(c_data.pay_info.request.return.total);

                        rePayment = (rePayment > 0) ? rePayment : 0;
                        
                        // coupon 처리
                        var cancel_coupon_price = 0;
                        if(coupon.length) {
                            var checked_order_number = $('.cancel-info-data:checked').map(function(){ return this.value; }).toArray();
                            $.each(coupon, function(i,v) {
                                rePayment -= v.discount_price;
                                v.apply = (v.apply || v.benefit != 'DELIVERY') ? '1' : '';
                                if((checked_order_number.indexOf(v.order_number) > -1 && v.apply) || v.kind == 'C') {
                                    cancel_coupon_price += parseInt(v.discount_price);
                                    // 환불금에서 쿠폰처리
                                    if($('.coupon-detail-info[data-seq="' + v.seq + '"]').length == 0) {
                                        $('.cancel-coupon-title').append('<span class="coupon-name coupon-detail-info" data-seq="' + v.seq + '">' + v.coupon_name + '</span>');
                                        $('#cancel-coupon-detail').append('<span class="coupon-price coupon-detail-info" data-seq="' + v.seq + '">-' + number_format(parseInt(v.discount_price)) + '원</span>');
                                    }
                                } else {
                                    $('.coupon-detail-info[data-seq="' + v.seq + '"]').remove();
                                }
                            });
                            // 취소된 쿠폰 저장
                        }

                        product_price = product_price - parseInt(cancel_coupon_price);

                        var use_point = (rePayment - product_price > 0) ? 0 : rePayment - product_price;
                        product_price = product_price + use_point;

                        $('#cancel-price').html(number_format(price)+'원');
                        $('#cancel-delivery-price').html(number_format(deliveryPrice)+'원');
                        $('#cancel-point-price').html(number_format(use_point)+'원');
                        $('#cancel-coupon-price').html(((cancel_coupon_price > 0) ? '-' + number_format(cancel_coupon_price) : '0')+'원');
                        $('#return-total-price').html(number_format(product_price));

                        var priceSumArr = [];
                        var extra_charge_flag = {};
                        if(ocModal.find('.cancel-info-data:checked').length) {
                            ocModal.find('.cancel-info-data:checked').each(function() {
                                if($(this).data('type') != 'normal') 
                                    return;

                                var dts = $(this).data('delivery_template_seq');
                                if(dtl[dts]['price_type'] != 'FREE_CONDITION') return;
                                var dt = $(this).data('delivery_type');
                                if(dt != 'DELIVERY' && dt != 'DIRECT') return;

                                if(!priceSumArr.hasOwnProperty(dts)) {
                                    priceSumArr[dts] = [];
                                
                                }

                                if(!priceSumArr[dts].hasOwnProperty(dt)) {
                                    priceSumArr[dts][dt] = 0;
                                }
                                // cancel_after_point = Number(cancel_after_point) + ((Number($(this).data("usable_point")) + Number($(this).data("expired_point"))) - Number($(this).data("curr_point")));
                                var selectedPrice = 0;
                                selectedPrice = Number($(this).closest('tr').find('[data-optionprice]').data('optionprice'));
                                priceSumArr[dts][dt] += selectedPrice;

                                if(dtl[dts]['dtype'][dt]['product_price'] - priceSumArr[dts][dt] < dtl[dts]['free_condition'] && dtl[dts]['dtype'][dt]['product_price'] - priceSumArr[dts][dt] > 0 && dtl[dts]['dtype'][dt]['price'] == 0) {
                                    extra_charge_flag[dts + '|' + dt] = true;
                                } else {
                                    extra_charge_flag[dts + '|' + dt] = false;
                                }
                            });
                        }
                        
                        extra_charge_info($form, 'C', Object.values(extra_charge_flag).indexOf(true) > -1 ? true : false, Object.values(extra_delivery_flag).indexOf(true) > -1 ? true : false);

                        if($('input[name="order_number_ary[]"]').length == $('input[name="order_number_ary[]"]:checked').length) $('#product-check').prop('checked', true);
                        else $('#product-check').prop('checked', false);
                    });

                    $(document).on('click', '#product-check', function () {
                        var price = 0;
                        var deliveryPrice = 0;
                        var totalCnt = 0, totalNomalCheck = 0, nomalCheck = 0;
                        $form.find('.order-cancel-content.extra-info').remove();
                        if ($(this).hasClass('noneAll') === true) {
                            $(this).prop('checked', true);
                            $(".status-checkbox").each(function () {
                                if ($(this).prop('disabled') !== true) $(this).prop('checked', true).change();
                            });
                        }
                        if ($(this).is(":checked") === true) {
                            $(".status-checkbox").each(function (i) {
                                if ($(this).prop('disabled') !== true) {
                                    $(this).prop('checked', true).change();
                                }

                            });
                        } else {
                            $(".status-checkbox").each(function () {
                                if ($(this).prop('disabled') !== true) $(this).prop('checked', false).change();
                            });

                            $('#cancel-price').html('0원');
                            $('#cancel-delivery-price').html('0원');
                            $('#cancel-point-price').html('0원');
                            $('#return-total-price').html('0');
                        }
                    });

                    /* first option setting */
                    $('.cl-s-order-cancel .cl-s-form-selector').each(function(e) {
                        var checkSelectOption = ($(this).find('select option').length > 0) ? true : false;
                        if(checkSelectOption) {
                            var selectId = $(this).find('select').attr('id'),
                                val = $(this).find('select').children().eq(0).val();
                            $(this).find('select').selectpicker({'val':val, dropupAuto:false});
                        }
                    });

                    $('.cl-s-order-cancel .cl-s-form-group').on('click',function(e) {
                        if($(e.target).hasClass('cl-s-form-group')) {
                            $(e.target).find('.cl-s-form-control:not([type=hidden])').focus();
                        }
                    });

                    $('#cancel-reason').on({
                        'show.bs.select': function (e) {
                            $(this).closest('.cl-s-form-selector').addClass('active');
                        },
                        'hidden.bs.select': function(e) {
                            $(this).closest('.cl-s-form-selector').removeClass('active');

                            if($('#cancel-reason').prop('value') == '') {
                                $(this).closest('.cl-s-form-selector').addClass('empty');
                            } else {
                                $(this).closest('.cl-s-form-selector').removeClass('empty');
                            }
                        },
                        'changed.bs.select': function (e, clickedIndex, newValue, oldValue) {
                            // console.log(this.value, clickedIndex, newValue, oldValue);
                        }
                    });

                    $('.cl-s-order-cancel .control-textarea').on({
                        focus: function(e) {
                            $(this).closest('.cl-s-form-wrap').addClass('active');
                        },
                        blur: function(e) {
                            var val = $(this).val().trim();

                            $(this).closest('.cl-s-form-wrap').removeClass('active');
                            if(val.length == 0) {
                                $(this).closest('.cl-s-form-wrap').removeClass('error').addClass('empty');
                                $(this).closest('.cl-s-form-wrap').find('.cl-s-control-label.error').remove();
                                return false;
                            } else {
                                $(this).closest('.cl-s-form-wrap').removeClass('empty');
                                var error_str = '';
                                if(checkEmojis(val)) error_str = $.lang[LANG]['config.unable.emoji'];
                                else if(val.length < 5) error_str = $.lang[LANG]['customsite.validate.message.minlengthto5'];

                                if(error_str.length > 0) {
                                    $(this).closest('.cl-s-form-wrap').addClass('error');
                                    if($(this).parent().find('.cl-s-control-label.error').length > 0) {
                                        $(this).parent().find('.cl-s-control-label.error').html(error_str);
                                    } else {
                                        $(this).after('<label for="input" class="cl-s-control-label error">' + error_str + '</label>');
                                    }
                                    return false;
                                }
                            }

                            $(this).closest('.cl-s-form-wrap').removeClass('error').removeClass('empty');
                            $(this).closest('.cl-s-form-wrap').find('.cl-s-control-label.error').remove();
                        }
                    });

                    $('.cl-s-form-wrap .cl-s-form-control').on({
                        focus: function(e) {
                            $(this).closest('.cl-s-form-wrap').addClass('active');
                        },
                        blur: function(e) {
                            var val = $(this).val().trim();
                            
                            $(this).closest('.cl-s-form-wrap').removeClass('active');
                            if(val.length == 0) {
                                $(this).closest('.cl-s-form-wrap').removeClass('error').addClass('empty');
                                $(this).closest('.cl-s-form-wrap').find('.cl-s-control-label.error').remove();
                                return false;
                            } else {
                                $(this).closest('.cl-s-form-wrap').removeClass('empty');

                                if(checkEmojis(val)) {
                                    $(this).closest('.cl-s-form-wrap').addClass('error');
                                    if($(this).parent().find('.cl-s-control-label.error').length > 0) {
                                        $(this).parent().find('.cl-s-control-label.error').html($.lang[LANG]['config.unable.emoji']);
                                    } else {
                                        $(this).after('<label for="input" class="cl-s-control-label error">' + $.lang[LANG]['config.unable.emoji'] + '</label>');
                                    }
                                    return false;
                                }
                            }

                            $(this).closest('.cl-s-form-wrap').removeClass('error');
                            $(this).closest('.cl-s-form-wrap').find('.cl-s-control-label.error').remove();
                        }
                    });

                    if(escrow == 'Y') {
                        $('.cancel-info-data').off('change');
                    }
                
                    ocModal.find('[data-toggle="popover"]').popover();
                });

            },'json');
        },
        orderReturnExchangeModal: function(sid, pnum, onum, ognum, status, pclass) {
            if(typeof sid == 'undefined' || typeof pnum == 'undefined' || typeof onum == 'undefined') {
                alert('정보가 올바르지 않습니다');
                return false;
            }

            $.post('/_check_order', { sid:sid, pnum:pnum, onum:onum, mode:'return', ognum: ognum }, function(data) {
                var LUX = false;
                if(data.lux) LUX = data.lux;

                if(typeof data.error != 'undefined' && data.error) {
                    $(this).showModalFlat('ERROR', data.error, true, false, '', 'close');
                    return false;
                }
                var c_data = data.r, checkboxNone = '', noneAll = '', noneChecked = '', checkNoneAll = '', checkEscrowFooter = '', checkEscrowClass = '', checkEscrowExchangeFooter = '', checkDepositCancel = '';
                
                var checkEscrow = '', exchangeCheck = 'N';
                var dtl = c_data.delivery_template_list;
                var used_code_coupon = false;
                
                if (status == 'Y') {
                    checkboxNone = 'checked';
                    noneAll = ' noneAll';
                    checkNoneAll = 'fule';
                    checkEscrow = '<div class="escrow-warring top-escrow">\
                                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 13 13" width="15" height="15">\
                                        <path fill="#4789e7" d="M6.5 0C2.91 0 0 2.91 0 6.5S2.91 13 6.5 13 13 10.09 13 6.5 10.09 0 6.5 0zM6.5 12C3.47 12 1 9.53 1 6.5S3.47 1 6.5 1 12 3.47 12 6.5 9.53 12 6.5 12z"/>\
                                        <rect fill="#4789e7" x="6" y="3" width="1" height="5"/>\
                                        <rect fill="#4789e7" x="6" y="9" width="1" height="1"/>\
                                    </svg>\
                                    에스크로 결제 상품은 취소/반품 요청 시 전체선택만 가능합니다.\
                                </div>';

                    checkEscrowFooter = '<div class="escrow-warring bottom-escrow">\
                                            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 13 13" width="15" height="15">\
                                                <path fill="#4789e7" d="M6.5 0C2.91 0 0 2.91 0 6.5S2.91 13 6.5 13 13 10.09 13 6.5 10.09 0 6.5 0zM6.5 12C3.47 12 1 9.53 1 6.5S3.47 1 6.5 1 12 3.47 12 6.5 9.53 12 6.5 12z"/>\
                                                <rect fill="#4789e7" x="6" y="3" width="1" height="5"/>\
                                                <rect fill="#4789e7" x="6" y="9" width="1" height="1"/>\
                                            </svg>\
                                            에스크로 환불 안내\
                                            <div class="escrow-return-info">- 취소처리 시 구매자의 환불정산액에서 취소 수수료(330원)가 차감됩니다.</div>\
                                            <div class="escrow-return-info">- 환불정산액은 취소처리 후 1~3영업일 후에 지급됩니다.</div>\
                                        </div>';
                    checkEscrowClass = 'cl-s-escrow-info';

                    checkEscrowExchangeFooter = '\
                        <div class="escrow-warring escrow-exchange-warning bottom-escrow" style="display: none;">\
                            <div class="escrow-return-info">- 에스크로 결제 상품의 경우, 교환 요청/완료 시에는 반품이 불가능합니다.</div>\
                            <div class="escrow-return-info">- 자세한 사항은 판매자의 안내를 따라주세요.</div>\
                        </div>\
                    ';
                }

                if(c_data.pay_info.coupon_list && c_data.pay_info.coupon_list.length) {
                    $.each(c_data.pay_info.coupon_list, function(k, v) {
                        if(v.kind == 'C') {
                            used_code_coupon = true;
                        }
                    })
                }

                if(used_code_coupon) {
                    checkboxNone = 'checked';
                    noneAll = ' noneAll';
                    checkNoneAll = 'fule';
                    checkDepositCancel = '<div class="modal-comment deposit-cancel-desc codecoupon-cancel-desc">\
                                <div class="desc-box">\
                                    <div class="desc-title">코드쿠폰 사용 주문취소 안내</div>\
                                    <div class="section">- 코드쿠폰 사용 주문 건은 <span class="cl-red">전체 반품</span>만 가능합니다.</div>\
                                    <div class="section">- 전체 반품 후 구매를 원하는 상품은 다시 주문해주세요.</div>\
                                    ' + (c_data.order_status == 'W' ? '<div class="section">- 혹시나 입금을 하신 경우 별도로 문의 주시기 바랍니다.</div>' : '') + '\
                                </div>\
                            </div>\
                        ';
                        
                    checkEscrowExchangeFooter = '\
                    <div class="code-coupon-exchange-warning escrow-warring escrow-exchange-warning bottom-escrow" style="display: none;">\
                        <div class="escrow-return-info">- 코드 쿠폰이 적용된 주문건은 교환 접수 시 반품이 불가능합니다.</div>\
                        <div class="escrow-return-info">- 자세한 사항은 판매자의 안내를 따라주세요.</div>\
                    </div>\
                ';
                }
                
                var modal_str = '\
                    <form name="re_form" method="post" action="/_return_exchange">\
                        <input type="hidden" name="sid" value="' + sid + '">\
                        <input type="hidden" name="order_group" id="cancel-order-group" value="' + ognum + '">\
                        <input type="hidden" name="order_number" id="cancel-order-number" value="' + onum + '">\
                        <input type="hidden" name="m_status" value="M">\
                        <div class="cl-s-btn-group-toggle btn-group btn-group-toggle" data-toggle="buttons">\
                ';

                if(status == 'Y' && data.r.exchange_check == true) {
                    modal_str += '\
                            <label class="btn btn-secondary disable">\
                                <input type="radio" name="status" id="order-radio-return" value="R"> 반품 요청\
                            </label>\
                            <label class="btn btn-secondary active">\
                                <input type="radio" name="status" id="order-radio-exchange" value="E" checked> 교환 요청\
                            </label>\
                    ';
                } else {
                    modal_str += '\
                            <label class="btn btn-secondary active">\
                                <input type="radio" name="status" id="order-radio-return" value="R" checked> 반품 요청\
                            </label>\
                            <label class="btn btn-secondary">\
                                <input type="radio" name="status" id="order-radio-exchange" value="E"> 교환 요청\
                            </label>\
                    ';
                }

                modal_str += '\
                        </div>\
                        '+checkEscrow+'\
                        <div class="cancel-product-title">\
                            <div class="newcheckbox hand">\
                                <label>\
                                    <input type="checkbox" class="'+noneAll+'" id="product-check" '+checkboxNone+'>\
                                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16">\
                                        <path d="M13 0H3C1.3 0 0 1.3 0 3v10c0 1.7 1.3 3 3 3h10c1.7 0 3-1.3 3-3V3C16 1.3 14.7 0 13 0zM15 13c0 1.1-0.9 2-2 2H3c-1.1 0-2-0.9-2-2V3c0-1.1 0.9-2 2-2h10c1.1 0 2 0.9 2 2V13z"/>\
                                    </svg>\
                                    <svg class="active" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16">\
                                        <path d="M13 0H3C1.34 0 0 1.34 0 3v10c0 1.66 1.34 3 3 3h10c1.66 0 3-1.34 3-3V3C16 1.34 14.66 0 13 0zM13.03 6.03l-5.5 5.5C7.38 11.68 7.19 11.75 7 11.75s-0.38-0.07-0.53-0.22l-3.5-3.5c-0.29-0.29-0.29-0.77 0-1.06s0.77-0.29 1.06 0L7 9.94l4.97-4.97c0.29-0.29 0.77-0.29 1.06 0S13.32 5.74 13.03 6.03z"/>\
                                    </svg>\
                                </label>\
                            </div>\
                            반품/교환요청 상품\
                        </div>';
                        var my_point = Number(data.r.my_point);
                        var weight_template_product = {};

                        for (var i=0;i<data.r.odata.length;i++) {
                            if(c_data.odata[i].state != 'normal') return;
                            if (c_data.odata[i].exchange_check == 'Y') exchangeCheck = 'Y';
                            var dts = c_data.odata[i].state == 'normal' ? c_data.odata[i].delivery_template_seq : '';
                            if(c_data.odata[i].state == 'normal' && c_data.odata[i].mix_yn != 'Y') dts += '-' + c_data.odata[i].product_number;
                            var dt = c_data.odata[i].state == 'normal' ? c_data.odata[i].delivery_type : '';

                            if(!weight_template_product.hasOwnProperty(dts)) weight_template_product[dts] = {};
                            if(!weight_template_product[dts].hasOwnProperty(dt)) weight_template_product[dts][dt] = {};
                            if(!weight_template_product[dts][dt].hasOwnProperty(c_data.odata[i].product_number)) weight_template_product[dts][dt][c_data.odata[i].product_number] = data.r.odata[i];

                            var tooltip = '';
                            if(dtl[dts]['price_type'] == 'WEIGHT' || dtl[dts]['price_type'] == 'QUANTITY') {
                                if(dtl[dts]['price_type_detail']['method'] == 'DIFFERENTIAL') {
                                    if(dtl[dts]['price_type'] == 'QUANTITY') {
                                        tooltip += '<li class=\'title\'>수량별 배송비</li>';
                                        $(dtl[dts]['price_type_detail']['detail']).each(function(k, detail) {
                                            var d_v = Object.keys(detail)[0];
                                            var d_p = detail[d_v];
                                            tooltip += '<li class=\'item\'>' + d_v + '개 이상 ' + number_format(d_p) + '원</li>';
                                        });
                                    } else if(dtl[dts]['price_type'] == 'WEIGHT') {
                                        tooltip += '<li class=\'title\'>무게별 배송비</li>';
                                        $(dtl[dts]['price_type_detail']['detail']).each(function(k, detail) {
                                            var d_v = Object.keys(detail)[0];
                                            var d_p = detail[d_v];
                                            tooltip += '<li class=\'item\'>' + d_v + 'Kg 이상 ' + number_format(d_p) + '원</li>';
                                        });
                                    }
                                } else if(dtl[dts]['price_type_detail']['method'] == 'REPEAT') {
                                    if(dtl[dts]['price_type'] == 'QUANTITY') {
                                        tooltip += '<li class=\'title\'>수량별 배송비</li>';
                                        tooltip += '<li class=\'item\'>' + number_format(dtl[dts]['repeat_value']) + '개 구매시마다 ' + number_format(dtl[dts]['repeat_price']) + '원 반복 부과</li>';
                                    } else if(dtl[dts]['price_type'] == 'WEIGHT') {
                                        tooltip += '<li class=\'title\'>무게별 배송비</li>';
                                        tooltip += '<li class=\'item\'>' + number_format(dtl[dts]['repeat_value']) + 'Kg마다 ' + number_format(dtl[dts]['repeat_price']) + '원 반복 부과</li>';
                                    }
                                }
                                if(tooltip && (dt == 'DELIVERY' || dt == 'DIRECT'))  {
                                    if(!LUX) tooltip += '<li class=\'desc\'>추가 상품은 배송비 조건에 반영되지 않습니다.</li>';

                                    if(dtl[dts]['price_type'] == 'WEIGHT' && weight_template_product[dts][dt]) {
                                        tooltip += '<li class=\'title product-weight\'>상품별 무게</li>';
                                        $.each(weight_template_product[dts][dt], function(k, v) {
                                            tooltip += '<li class=\'item\'>' + v.product_name + ' : ' + number_format(v.product_weight) + 'kg</li>';
                                        });
                                    }

                                    tooltip = '<ul class=\'delivery-tooltip\'>' + tooltip + '</ul>';
                                    dtl[dts]['tooltip'] = tooltip;
                                }
                            }
                        }
                        
                        modal_str += '<table class="table product-table">';
                        for (var i=0;i<data.r.odata.length;i++) {
                            if (c_data.odata[i].d_status == '' || c_data.odata[i].d_status == 'CN') {
                                noneChecked = '';
                                if (!checkNoneAll) noneAll = '';
                            } else {
                                if (!checkNoneAll) noneAll = 'noneAll';
                                noneChecked = 'noneChecked';
                            }

                            var curr_point = 0;
                            var usable_point = 0;
                            var refund_point = 0;
                            var expired_point = 0;

                            if(c_data.odata[i].used_point) {
                                curr_point = Math.abs(c_data.odata[i].used_point.point);
                                usable_point = Math.abs(c_data.odata[i].used_point.usable_point);
                            }

                            // if(c_data.odata[i].refund_point) {
                            //     refund_point = c_data.odata
                            // }

                            if(c_data.odata[i].expired_point) {
                                expired_point = Math.abs(c_data.odata[i].expired_point.point);
                            }

                            var dts = c_data.odata[i].state == 'normal' ? c_data.odata[i].delivery_template_seq : '';
                            if(c_data.odata[i].state == 'normal' && c_data.odata[i].mix_yn != 'Y') dts += '-' + c_data.odata[i].product_number;
                            var dt = c_data.odata[i].state == 'normal' ? c_data.odata[i].delivery_type : '';

                            modal_str += '\
                            <tr class="cl-s-product-jumbotron clearfix">\
                                <td>\
                                <div class="newcheckbox hand">\
                                    <label>\
                                        <input type="checkbox" class="status-checkbox cancel-info-data '+noneAll+' '+noneChecked+'" data-curr_point="' + curr_point + '" data-usable_point="' + usable_point + '" data-expired_point="' + expired_point + '" data-type="'+c_data.pdata[i].state+'" name="order_number_ary[]" value="'+c_data.odata[i].order_number+'" '+checkboxNone+' data-option_type="' + c_data.pdata[i].option_type + '" data-product_number="' + c_data.odata[i].product_number + '" data-product_weight="' + (c_data.odata[i].state == 'normal' ? c_data.odata[i].product_weight : 0) + '" data-mix_yn="' + (c_data.odata[i].state == 'normal' ? c_data.odata[i].mix_yn : '') + '" data-delivery_template_seq="' + (c_data.odata[i].state == 'normal' ? dts : '') + '" data-delivery_type="' + (c_data.odata[i].state == 'normal' ? c_data.odata[i].delivery_type : '') + '" data-quantity="' + c_data.odata[i].quantity + '" data-delivery_price="'+ (c_data.odata[i].state == 'normal' && dtl[dts]['pay_type'] == 'PREPAY' ? c_data.odata[i].delivery_price : 0) +'">\
                                        <svg viewBox="0 0 16 16" width="16" height="16">\
                                            <path d="M13 0H3C1.3 0 0 1.3 0 3v10c0 1.7 1.3 3 3 3h10c1.7 0 3-1.3 3-3V3C16 1.3 14.7 0 13 0zM15 13c0 1.1-0.9 2-2 2H3c-1.1 0-2-0.9-2-2V3c0-1.1 0.9-2 2-2h10c1.1 0 2 0.9 2 2V13z"/>\
                                        </svg>\
                                        <svg class="active" viewBox="0 0 16 16" width="16" height="16">\
                                            <path d="M13 0H3C1.34 0 0 1.34 0 3v10c0 1.66 1.34 3 3 3h10c1.66 0 3-1.34 3-3V3C16 1.34 14.66 0 13 0zM13.03 6.03l-5.5 5.5C7.38 11.68 7.19 11.75 7 11.75s-0.38-0.07-0.53-0.22l-3.5-3.5c-0.29-0.29-0.29-0.77 0-1.06s0.77-0.29 1.06 0L7 9.94l4.97-4.97c0.29-0.29 0.77-0.29 1.06 0S13.32 5.74 13.03 6.03z"/>\
                                        </svg>\
                                    </label>\
                                </div>\
                                <div class="cl-s-product-thumb">\
                                    <img src="' + c_data.pdata[i].img + '" alt="' + c_data.pdata[i].name + '" class="' + c_data.pdata[i].img_align + '" />\
                                </div>\
                                <div class="cl-s-product-info">\
                                    <h5 class="cl-s-product-title">' + c_data.pdata[i].name + '</h5>\
                            ';

                            var price = c_data.odata[i].price,
                                quantity = Number(c_data.odata[i].quantity),
                                sum_price = quantity * price;
                                option_name = (typeof c_data.pdata[i].option != "undefined" && c_data.pdata[i].option) ? c_data.pdata[i].option : '',
                                option_str = '',
                                etc_str = (typeof c_data.pdata[i].etc_date != "undefined" && c_data.pdata[i].etc_date) ? '<span>선택일자: '+c_data.pdata[i].etc_date+'</span>' : '',
                                option_title = (c_data.pdata[i].option_type == 'A') ? '추가옵션: ' + (c_data.pdata[i].option_group ? c_data.pdata[i].option_group + ' : ' : '') : '옵션';
                            if(option_name) {
                                option_str = (c_data.pdata[i].option_text_str) ? '<span>' + option_title + ': '+option_name+' / '+c_data.pdata[i].option_text_str+'</span>' : '<span>' + option_title + ': '+option_name+'</span>';
                            } else {
                                option_str = (c_data.pdata[i].option_text_str) ? '<span>' + option_title + ': '+c_data.pdata[i].option_text_str+'</span>' : '';
                            }

                            modal_str += '\
                                    <div class="option-str option-check" data-optionState="" data-optionPrice="'+sum_price+'" data-deliveryPrice="'+(dtl[dts]['sel_pay_type'] == 'DELIVERED' ? 0 : c_data.odata[i].delivery_price)+'"><span>' + number_format(sum_price) + '원</span>' + option_str + etc_str + '<span>' + quantity + '개</span></div>\
                                </div>\
                            </td>';

                            if(c_data.odata[i].state == 'normal') {
                                var delivery_cnt = dtl[dts]['dtype'][dt].delivery_cnt;
                                if(!dtl[dts]['dtype'][dt].hasOwnProperty('counter')) {
                                    dtl[dts]['dtype'][dt]['counter'] = 0;
                                }

                                dtl[dts]['dtype'][dt]['counter']++;

                                if(dtl[dts]['dtype'][dt]['counter'] == 1) {
                                    modal_str +='\
                                        <td rowspan="' + delivery_cnt + '" class="delivery-price"><div>배송비</div><div class="price"><span>';
                                    if(dt == 'DELIVERY' || dt == 'DIRECT') {
                                        if(dtl[dts]['price_type'] == 'ETC') {
                                            modal_str += '별도안내</span>';
                                        } else {
                                            modal_str += number_format(dtl[dts]['dtype'][dt]['price']) + '</span> 원';    
                                        }
                                        if(dtl[dts]['pay_type'] == 'DELIVERED') modal_str += '(착불)';

                                        if(dtl[dts]['price_type'] == 'FREE_CONDITION') {
                                            modal_str += '<div class="price-desc">' + number_format(dtl[dts]['free_condition']) + '원 이상<br>배송비 무료</div>';
                                        }
                                    } else {
                                        modal_str += $.lang[LANG]['shopping.delivery.template.delivery_type.' + dt.toLowerCase()] + '</span>';
                                        if(dt == 'QUICK') modal_str += '(착불)';
                                    }
                                    if(dtl[dts]['tooltip'] && (dt == 'DELIVERY' || dt == 'DIRECT')) {
                                        modal_str += '<svg class="cm-popover-info" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 13 13" width="13" height="13" tabindex="0" data-trigger="hover" data-toggle="popover" fill="#4789e7" data-html="true" data-placement="top" data-content="' + dtl[dts]['tooltip'] + '" data-original-title="" title=""><path d="M6.5 0C2.91 0 0 2.91 0 6.5S2.91 13 6.5 13 13 10.09 13 6.5 10.09 0 6.5 0zM6.5 12C3.47 12 1 9.53 1 6.5S3.47 1 6.5 1 12 3.47 12 6.5 9.53 12 6.5 12z"></path><path d="M6.66 3.01C5.61 3.01 4.58 3.5 4.5 4.8c0 0.06-0.01 0.12 0 0.2h1.02c0-0.07 0.01-0.15 0.02-0.23 0.08-0.62 0.52-0.76 1.08-0.76 0.63 0 1.02 0.37 1.02 0.95 -0.01 0.48-0.3 0.87-0.76 1.34C6.21 6.97 6.02 7.37 6 8h0.99C7 7.66 7.04 7.37 7.67 6.75 8.17 6.27 8.7 5.68 8.7 4.87 8.7 3.85 7.89 3.01 6.66 3.01z"></path><rect x="6" y="9" width="1" height="1"></rect></svg>';
                                    }
                                    modal_str +='</div></td>\
                                    ';
                                }

                                modal_str += '\
                                </tr>';

                                if(dtl[dts]['dtype'][dt]['counter'] == dtl[dts]['dtype'][dt]['delivery_cnt']) {
                                    modal_str += '\
                                        <tr class="cl-s-product-jumbotron clearfix delivery-price delivery-price-mobile">\
                                            <td><div class="delivery-title">묶음 배송비</div><div class="delivey-price"><span>';

                                    if(dtl[dts]['tooltip'] && (dt == 'DELIVERY' || dt == 'DIRECT')) {
                                        modal_str += '<svg class="cm-popover-info" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 13 13" width="13" height="13" tabindex="0" data-trigger="hover" data-toggle="popover" fill="#4789e7" data-html="true" data-placement="top" data-content="' + dtl[dts]['tooltip'] + '" data-original-title="" title=""><path d="M6.5 0C2.91 0 0 2.91 0 6.5S2.91 13 6.5 13 13 10.09 13 6.5 10.09 0 6.5 0zM6.5 12C3.47 12 1 9.53 1 6.5S3.47 1 6.5 1 12 3.47 12 6.5 9.53 12 6.5 12z"></path><path d="M6.66 3.01C5.61 3.01 4.58 3.5 4.5 4.8c0 0.06-0.01 0.12 0 0.2h1.02c0-0.07 0.01-0.15 0.02-0.23 0.08-0.62 0.52-0.76 1.08-0.76 0.63 0 1.02 0.37 1.02 0.95 -0.01 0.48-0.3 0.87-0.76 1.34C6.21 6.97 6.02 7.37 6 8h0.99C7 7.66 7.04 7.37 7.67 6.75 8.17 6.27 8.7 5.68 8.7 4.87 8.7 3.85 7.89 3.01 6.66 3.01z"></path><rect x="6" y="9" width="1" height="1"></rect></svg>';
                                    }

                                    if(dt == 'DELIVERY' || dt == 'DIRECT') {
                                        modal_str += number_format(dtl[dts]['dtype'][dt]['price']) + '</span> 원';
                                        if(dtl[dts]['pay_type'] == 'DELIVERED') modal_str += '(착불)';
                                        if(dtl[dts]['price_type'] == 'FREE_CONDITION') {
                                            modal_str += '<div class="price-desc">' + number_format(dtl[dts]['free_condition']) + '원 이상 배송비 무료</div>';
                                        }
                                    } else {
                                        modal_str += $.lang[LANG]['shopping.delivery.template.delivery_type.' + dt.toLowerCase()] + '</span>';
                                        if(dt == 'QUICK') modal_str += '(착불)';
                                    }

                                    modal_str += '</div></td>\
                                        </tr>\
                                    ';
                                }
                            }
                        }

                        modal_str += '</table>';

                        modal_str += '<div class="order-re-content">\
                            <div class="cl-s-form-selector">\
                                <select class="selectpicker dropdown" id="re-reason" name="reason">\
                                    <option value="구매의사 취소">구매의사 취소</option>\
                                    <option value="다른 상품 잘못 주문">다른 상품 잘못 주문</option>\
                                    <option value="상품파손">상품파손</option>\
                                    <option value="배송지연">배송지연</option>\
                                    <option value="상품정보 상이">상품정보 상이</option>\
                                    <option value="오배송">오배송</option>\
                                    <option value="기타">기타</option>\
                                </select>\
                                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 8 4" width="8" height="4"><polygon points="0 0 4 4 8 0 "></polygon></svg>\
                            </div>\
                            <div class="cl-s-form-wrap">\
                                <div class="cl-s-form-group input-label-hide">\
                                    <textarea class="cl-s-form-control cl-s-form-textarea" id="re-requests" name="requests" maxlength="500" required="required"></textarea>\
                                    <label for="input" class="cl-s-control-label">자세한 내용을 적어주세요. (500자 이내)</label>\
                                </div>\
                            </div>\
                        </div>';
                        /*  반품/교환 사진 제거
                            <div class="cl-s-files re-files">\
                                <input id="re-file" type="file" name="files[]" multiple data-sid="' + sid + '" data-uid=\"' + c_data.writer.id + '\">\
                                <label class="cl-s-file-update re-file-update clearfix"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" width="20" height="20"><path d="M0 0v20h20V0H0zM19 1v11.3l-3-3 -4 4 -6-6 -5 5V1H19zM1 19v-5.3l5-5 6 6 4-4 3 3V19H1z"/><circle cx="14.5" cy="5.5" r="1.5"/></svg> <span>사진</span></label>\
                                <ul class="cl-s-files-list re-files-list clearfix">\
                                </ul>\
                            </div>\
                        */

                        modal_str += checkEscrowExchangeFooter;

                        modal_str += '<div class="order-cancel-content">\
                            <div class="cancel-info-box">\
                                <div class="cancel-info"><span class="cancel-info-title">반품상품 합계</span><span class="cancel-info-price" id="cancel-price">0원</span></div>\
                                <div class="cancel-info"><span class="cancel-info-title">반품 배송비 합계</span><span class="cancel-info-price" id="cancel-delivery-price">0원</span></div>\
                                <div class="cancel-info"><span class="cancel-info-title">적립금</span><span class="cancel-info-price" id="cancel-point-price">0원</span></div>\
                                <div class="cancel-info"><span class="cancel-info-title">쿠폰</span><span class="cancel-info-price" id="cancel-coupon-price">0원</span></div>\
                                <div class="cancel-info"><span class="cancel-info-title cancel-coupon-title"></span><span class="cancel-info-price" id="cancel-coupon-detail"></span></div>\
                                <div class="cancel-info-line"></div>\
                                <div class="return-total-info"><span class="cancel-info-title">환불 예정금액</span><span class="cancel-info-price"><span id="return-total-price">0</span>원</span></div>\
                            </div>'+checkEscrowFooter+'\
                        </div>';
                        modal_str += checkDepositCancel;
                    
                    if (pclass == '무통장 입금' || pclass == '가상계좌') {
                        var returnClass = '';
                        if (c_data.return_bank.length > 1 && c_data.return_bank.indexOf('')===-1) returnClass = 'returnDisabled';

                        modal_str += '\
                            <div id="return-modal">\
                                <div class="modal-sub-title">환불 계좌</div>\
                                <ul class="qna-writer clearfix">\
                                    <li class="">\
                                        <div class="cl-s-form-wrap '+returnClass+'">\
                                            <div class="cl-s-form-group">';
                                            if (c_data.return_bank.length > 1 && c_data.return_bank.indexOf('')===-1) modal_str += '<input type="text" class="cl-s-form-control has-value" id="no-bank" name="no_bank" readonly required="required" value="'+c_data.return_bank[1]+'">';
                                            else modal_str += '<input type="text" class="cl-s-form-control" id="no-bank" name="no_bank" required="required" value="">';
                                            modal_str += '<label for="input" class="cl-s-control-label">은행명</label>\
                                            </div>\
                                        </div>\
                                    </li>\
                                    <li>\
                                        <div class="cl-s-form-wrap '+returnClass+'">\
                                            <div class="cl-s-form-group">';
                                            if (c_data.return_bank.length > 1 && c_data.return_bank.indexOf('')===-1) modal_str += '<input type="text" class="cl-s-form-control has-value" id="no-bank-name" readonly name="no_bank_name" required="required" value="'+c_data.return_bank[2]+'">';
                                            else modal_str += '<input type="text" class="cl-s-form-control" id="no-bank-name" name="no_bank_name" required="required">';
                                            modal_str += '<label for="input" class="cl-s-control-label">예금주</label>\
                                            </div>\
                                        </div>\
                                    </li>\
                                    <li>\
                                        <div class="cl-s-form-wrap '+returnClass+'">\
                                            <div class="cl-s-form-group">';
                                            if (c_data.return_bank.length > 1 && c_data.return_bank.indexOf('')===-1) modal_str += '<input type="text" class="cl-s-form-control has-value" id="no-bank-number" name="no_bank_number" readonly data-type="email" required="required" value="'+c_data.return_bank[3]+'">';
                                            else modal_str += '<input type="text" class="cl-s-form-control" id="no-bank-number" name="no_bank_number" data-type="email" required="required" value="">';
                                            modal_str += '<label for="input" class="cl-s-control-label">계좌번호</label>\
                                            </div>\
                                        </div>\
                                    </li>\
                                </ul>\
                                <div class="modal-comment">동일 주문 내 여러 상품을 환불 요청하시는 경우, 최초 입력한 환불계좌로 일괄 환불처리됩니다.</div>\
                                <div class="modal-comment point-used-desc hide">\
                                    <div class="desc-box">\
                                        <div class="desc-title">적립금 환불 안내</div>\
                                        <div class="section">상품(들)을 구매하여 적립된 적립금 <span id="disp_used_point_total" class="point-color"></span>원이 이미 사용되거나 유효기간이 만료되었습니다.</div>\
                                        <div class="section">현재 보유 적립금이 <span class="point-color">' + addCommas(my_point) + '</span>원 으로 구매 적립된 적립금 <span id="disp_cancel_after_point" class="point-color"></span>원을 취소 처리할 수 없습니다.</div>\
                                        <div class="section">미 취소된 적립금에 대한 처리는 판매자와 협의해주세요.</div>\
                                    </div>\
                                    <div class="newcheckbox hand">\
                                        <label style="margin-left: 25px;">\
                                            <input type="checkbox" class="cancel-agree" />\
                                            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16">\
                                                <path d="M13 0H3C1.3 0 0 1.3 0 3v10c0 1.7 1.3 3 3 3h10c1.7 0 3-1.3 3-3V3C16 1.3 14.7 0 13 0zM15 13c0 1.1-0.9 2-2 2H3c-1.1 0-2-0.9-2-2V3c0-1.1 0.9-2 2-2h10c1.1 0 2 0.9 2 2V13z"></path>\
                                            </svg>\
                                            <svg class="active" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16">\
                                                <path d="M13 0H3C1.34 0 0 1.34 0 3v10c0 1.66 1.34 3 3 3h10c1.66 0 3-1.34 3-3V3C16 1.34 14.66 0 13 0zM13.03 6.03l-5.5 5.5C7.38 11.68 7.19 11.75 7 11.75s-0.38-0.07-0.53-0.22l-3.5-3.5c-0.29-0.29-0.29-0.77 0-1.06s0.77-0.29 1.06 0L7 9.94l4.97-4.97c0.29-0.29 0.77-0.29 1.06 0S13.32 5.74 13.03 6.03z"></path>\
                                            </svg>\
                                        위 내용을 확인하였습니다.</label>\
                                    </div>\
                                    <div class="point-used-cancel-agree-desc">\
                                        <svg viewBox="0 0 13 13" width="13" height="13"><path d="M6.5 0C2.91 0 0 2.91 0 6.5S2.91 13 6.5 13 13 10.09 13 6.5 10.09 0 6.5 0zM6.5 12C3.47 12 1 9.53 1 6.5S3.47 1 6.5 1 12 3.47 12 6.5 9.53 12 6.5 12z"/><rect x="6" y="3" width="1" height="5"/><rect x="6" y="9" width="1" height="1"/></svg>\
                                        적립금 환불 안내에 동의해주세요.\
                                    </div>\
                                </div>\
                            </div>\
                        ';
                    }
                    modal_str += '</form>\
                ';
                var $form = $('form[name="re_form"]');
                var oreModal = $(this).showModalFlat('반품/교환 요청', modal_str,true,true,function () {

                    var f = document.re_form;

                    if(oreModal.find('#re-reason').prop('value') == '') {
                        // $('#re-reason').selectpicker('toggle');
                        // return false;
                        $('#re-reason').closest('.cl-s-form-selector').addClass('empty');
                    }

                    oreModal.find('.cl-s-form-wrap').each(function() {
                        var check_input = $(this).find('.cl-s-form-control'),
                            val = check_input.val().trim();

                        if(val.length == 0) {
                            $(this).removeClass('error').addClass('empty');
                            $(this).find('.cl-s-control-label.error').remove();
                        } else {
                            if($(this).hasClass('error')) {
                                check_input.focus();
                            }
                        }
                    });
                    var checkCnt = 0;

                    $(".status-checkbox").each(function (i, index) {
                        if ($(this).is(":checked") === true) {
                            checkCnt++;
                        }
                    });

                    if (checkCnt < 1) {
                        alert('상품을 1개 이상 선택해 주세요');
                        return false;
                    }

                    if(oreModal.find('.cl-s-form-wrap.empty, .cl-s-form-wrap.error').length > 0) {
                        // oreModal.find('.cl-s-form-wrap.empty, .cl-s-form-wrap.error').eq(0).find('.cl-s-form-control').focus();
                        return false;
                    }


                    if(oreModal.find("input[type='checkbox'].cancel-agree:visible").length && oreModal.find("input[type='checkbox'].cancel-agree:visible").length != oreModal.find("input[type='checkbox'].cancel-agree:visible:checked").length) {
                        $(".point-used-cancel-agree-desc").show();
                        return false;
                    } else {
                        $(".point-used-cancel-agree-desc").hide();
                    }

                    $.processON();

                    f.submit();

                },'close','등록하기','cl-s-order-returnexchange cl-s-order-cancel cl-modal cl-s-btn cover ' + checkEscrowClass, false, '', function() {
                    var totalCnt = 0, totalNomalCheck = 0, nomalCheck = 0;
                    var price = 0;
                    var deliveryPrice = 0;
                    
                    var mix_yn = $(this).data('mix_yn');
                    var delivery_price = 0;

                    
                    $('.status-checkbox').each(function(i, index) {
                        if ($(this).is(":checked") === true) {
                            price += ($(this).closest('.cl-s-product-jumbotron').find('.option-check').attr('data-optionPrice') * 1);
                            totalCnt++;
                            if ($(this).attr('data-type') == 'normal') {
                                nomalCheck++;
                                var mix_yn = $(this).data('mix_yn');
                                var delivery_price = 0;
                                var delivery_template_seq = $(this).data('delivery_template_seq');
                                var delivery_type = $(this).data('delivery_type');
                                if(oreModal.find('input[name="order_number_ary[]"][data-delivery_type="' + delivery_type + '"][data-delivery_template_seq="' + delivery_template_seq + '"]').length == oreModal.find('input[name="order_number_ary[]"][data-delivery_type="' + delivery_type + '"][data-delivery_template_seq="' + delivery_template_seq + '"]:checked').length) {
                                    delivery_price = Number($(this).data('delivery_price'));
                                }
                                deliveryPrice += delivery_price;
                            }
                        }

                        if ($(this).attr('data-type') == 'normal') {
                            totalNomalCheck++;
                        }
                    });

                    var product_price = price + deliveryPrice,
                        rePayment = parseInt(c_data.pay_info.request.payment.total) - parseInt(c_data.pay_info.request.payment.coupon) - parseInt(c_data.pay_info.request.cancel.total) - parseInt(c_data.pay_info.request.return.total);

                    rePayment = (rePayment > 0) ? rePayment : 0;

                    // coupon 처리
                    var coupon = c_data.pay_info.coupon_list,
                        cancel_coupon_price = 0;
                    if(coupon.length) {
                        var checked_order_number = $('.cancel-info-data:checked').map(function(){ return this.value; }).toArray();
                        $.each(coupon, function(i,v) {
                            if(checked_order_number.indexOf(v.order_number) > -1 || v.kind == 'C') {
                                cancel_coupon_price += parseInt(v.discount_price);

                                // 환불금에서 쿠폰처리
                                if($('.coupon-detail-info[data-seq="' + v.seq + '"]').length == 0) {
                                    $('.cancel-coupon-title').append('<div class="coupon-name coupon-detail-info" data-seq="' + v.seq + '">' + v.coupon_name + '</div>');
                                    $('#cancel-coupon-detail').append('<div class="coupon-price coupon-detail-info" data-seq="' + v.seq + '">-' + number_format(parseInt(v.discount_price)) + '원</div>');
                                }
                            } else {
                                $('.coupon-detail-info[data-seq="' + v.seq + '"]').remove();
                            }
                        });
                        // 취소된 쿠폰 저장
                        
                    }
                    product_price = product_price - parseInt(cancel_coupon_price);

                    var use_point = (rePayment - product_price > 0) ? 0 : rePayment - product_price;
                    product_price = product_price + use_point;

                    $('#cancel-price').html(number_format(price)+'원');
                    $('#cancel-delivery-price').html(number_format(deliveryPrice)+'원');
                    $('#cancel-point-price').html(number_format(use_point)+'원');
                    $('#cancel-coupon-price').html(((cancel_coupon_price > 0) ? '-' + number_format(cancel_coupon_price) : '0')+'원');
                    $('#return-total-price').html(number_format(product_price));

                    $('.cancel-info-data').on('change', function () {
                        if($(this).hasClass('noneAll')) return;    
                        var cancel_after_point = my_point;
                        var disp_used_point_total = 0;
                        var deliveryPrice = 0;

                        var product_number = $(this).attr('data-product_number');
                        // console.log(product_number);
                        if($('input[name="status"]:checked').val() == 'R') { // 반품일때만 
                            if($(this).attr('data-option_type') != 'A' && !$('input[name="order_number_ary[]"][data-product_number="' + product_number + '"][data-option_type!="A"]:not(:checked)').length) {
                                $('input[name="order_number_ary[]"][data-product_number="' + product_number + '"][data-option_type="A"]').prop('checked',true);
                            } else if($(this).attr('data-option_type') == 'A' && !$('input[name="order_number_ary[]"][data-product_number="' + product_number + '"][data-option_type!="A"]:not(:checked)').length && !$(this).prop('checked')) {
                                $('input[name="order_number_ary[]"][data-product_number="' + product_number + '"][data-option_type!="A"]:last').prop('checked',false);
                            }
                        }

                        if($("input[name='order_number_ary[]']:checked").length) {
                            coupon.map(function(v,k) { coupon[k]['apply'] = '';  });
                            $("input[name='order_number_ary[]']:checked").each(function() {
                                cancel_after_point = Number(cancel_after_point) + ((Number($(this).data("expired_point"))) - Number($(this).data("curr_point")));
                                disp_used_point_total += ((Number($(this).data("expired_point"))) - Number($(this).data("curr_point")));
                                c_ord_num = $(this).val();

                                if($(this).data('type') != 'normal' || $(this).data('option_type') == 'A') return;
                                var mix_yn = $(this).data('mix_yn');
                                var delivery_price = 0;
                                var delivery_template_seq = $(this).data('delivery_template_seq');
                                var delivery_type = $(this).data('delivery_type');
                                var product_weight = $(this).data('product_weight');

                                

                                if(delivery_type != 'DELIVERY' && delivery_type != 'DIRECT') return;
                                // if(dtl[delivery_template_seq]['price_type'] != 'WEIGHT' && dtl[delivery_template_seq]['price_type'] != 'QUANTITY') {
                                if(oreModal.find('input[name="order_number_ary[]"][data-delivery_type="' + delivery_type + '"][data-delivery_template_seq="' + delivery_template_seq + '"]').length == oreModal.find('input[name="order_number_ary[]"][data-delivery_type="' + delivery_type + '"][data-delivery_template_seq="' + delivery_template_seq + '"]:checked').length) {
                                    delivery_price = Number($(this).data('delivery_price'));

                                    coupon.map(function(v,k) { if(v.order_number == c_ord_num && delivery_price > 0 && v.benefit == 'DELIVERY') coupon[k]['apply'] = '1';  });
                                } 
                                deliveryPrice += delivery_price;
                            });
                        }

                        if(cancel_after_point < 0) {
                            $(".point-used-desc #disp_cancel_after_point").html(addCommas(Math.abs(cancel_after_point)));
                            $(".point-used-desc #disp_used_point_total").html(addCommas(Math.abs(disp_used_point_total)));
                            $(".point-used-desc").removeClass("hide");
                        } else {
                            $(".point-used-desc").addClass("hide");
                            $(".point-used-desc #disp_cancel_after_point").html("");
                            $(".point-used-desc #disp_used_point_total").html("");
                        }

                        var price = 0;
                        var oLength = $('.option-check').length;
                        var totalCnt = 0, totalNomalCheck = 0, nomalCheck = 0;
                        var isReturn = $('input[name="status"]:checked').val();


                        $form.find('.order-cancel-content.extra-info').remove();

                        if ($(this).hasClass('noneAll') === true) {
                            if ($(this).hasClass('noneChecked') === true) {
                                $(this).prop('checked', false);
                            } else {
                                $(this).prop('checked', true);
                                $('.status-checkbox').each(function () {
                                    if ($(this).prop('disabled') !== true) $(this).prop('checked', true);
                                });
                            }
                        }

                        $('.status-checkbox').each(function (i, index) {
                            if ($(this).is(':checked') === true) {
                                price += ($(this).closest('.cl-s-product-jumbotron').find('.option-check').attr('data-optionPrice') * 1);
                                totalCnt++;
                                if ($(this).attr('data-type') == 'normal') {
                                    nomalCheck++;
                                }
                            }

                            if ($(this).attr('data-type') == 'normal') {
                                totalNomalCheck++;
                            }
                        });

                        var product_price = price + deliveryPrice,
                            rePayment = parseInt(c_data.pay_info.request.payment.total) - parseInt(c_data.pay_info.request.payment.coupon) - parseInt(c_data.pay_info.request.cancel.total) - parseInt(c_data.pay_info.request.return.total);

                        rePayment = (rePayment > 0) ? rePayment : 0;


                        // coupon 처리
                        var cancel_coupon_price = 0;
                        if(coupon.length) {
                            var checked_order_number = $('.cancel-info-data:checked').map(function(){ return this.value; }).toArray();
                            $.each(coupon, function(i,v) {
                                v.apply = (v.apply || v.benefit != 'DELIVERY') ? '1' : '';
                                if((checked_order_number.indexOf(v.order_number) > -1 && v.apply) || v.kind == 'C') {
                                    cancel_coupon_price += parseInt(v.discount_price);

                                    // 환불금에서 쿠폰처리
                                    if($('.coupon-detail-info[data-seq="' + v.seq + '"]').length == 0) {
                                        $('.cancel-coupon-title').append('<div class="coupon-name coupon-detail-info" data-seq="' + v.seq + '">' + v.coupon_name + '</div>');
                                        $('#cancel-coupon-detail').append('<div class="coupon-price coupon-detail-info" data-seq="' + v.seq + '">-' + number_format(parseInt(v.discount_price)) + '원</div>');
                                    }
                                } else {
                                    $('.coupon-detail-info[data-seq="' + v.seq + '"]').remove();
                                }
                            });
                            // 취소된 쿠폰 저장
                        }
                        product_price = product_price - parseInt(cancel_coupon_price);
                        
                        var use_point = (rePayment - product_price > 0) ? 0 : rePayment - product_price;
                        product_price = product_price + use_point;
                        
                        $('#cancel-price').html(number_format(price)+'원');
                        $('#cancel-delivery-price').html(number_format(deliveryPrice)+'원');
                        $('#cancel-point-price').html(number_format(use_point)+'원');
                        $('#cancel-coupon-price').html(((cancel_coupon_price > 0) ? '-' + number_format(cancel_coupon_price) : '0')+'원');
                        $('#return-total-price').html(number_format((product_price>0) ? product_price : '0'));

                        var priceSumArr = [];
                        var extra_charge_flag = {};
                        if(oreModal.find('.cancel-info-data:checked').length) {
                            oreModal.find('.cancel-info-data:checked').each(function() {
                                if($(this).data('type') != 'normal') 
                                    return;

                                var dts = $(this).data('delivery_template_seq');
                                if(dtl[dts]['price_type'] != 'FREE_CONDITION') return;
                                var dt = $(this).data('delivery_type');
                                if(dt != 'DELIVERY' && dt != 'DIRECT') return;

                                if(!priceSumArr.hasOwnProperty(dts)) {
                                    priceSumArr[dts] = [];
                                }
                                if(!priceSumArr[dts].hasOwnProperty(dt)) {
                                    priceSumArr[dts][dt] = 0;
                                }
                                // cancel_after_point = Number(cancel_after_point) + ((Number($(this).data("usable_point")) + Number($(this).data("expired_point"))) - Number($(this).data("curr_point")));
                                var selectedPrice = 0;
                                selectedPrice = Number($(this).closest('tr').find('[data-optionprice]').data('optionprice'));
                                priceSumArr[dts][dt] += selectedPrice;

                                if(dtl[dts]['dtype'][dt]['product_price'] - priceSumArr[dts][dt] < dtl[dts]['free_condition'] && dtl[dts]['dtype'][dt]['product_price'] - priceSumArr[dts][dt] > 0 && dtl[dts]['dtype'][dt]['price'] == 0) {
                                    extra_charge_flag[dts + '|' + dt] = true;
                                } else {
                                    extra_charge_flag[dts + '|' + dt] = false;
                                }
                            });
                        }

                        extra_charge_info($form, 'R', Object.values(extra_charge_flag).indexOf(true) > -1 ? true : false, false);

                        if($('input[name="order_number_ary[]"]').length == $('input[name="order_number_ary[]"]:checked').length) $('#product-check').prop('checked', true);
                        else $('#product-check').prop('checked', false);
                    });

                    $(document).on('click', '#product-check', function () {
                        var price = 0;
                        var deliveryPrice = 0;
                        var totalCnt = 0,
                            isReturn = $('input[name="status"]:checked').val();
                        $form.find('.order-cancel-content.extra-info').remove();   
                        if ($(this).hasClass('noneAll') === true) {
                            $(this).prop('checked', true);
                            $(".status-checkbox").each(function () {
                                if ($(this).prop('disabled') !== true) $(this).prop('checked', true).change();
                            });
                        }
                        if ($(this).is(':checked') === true) {
                            $('.status-checkbox').each(function (i) {
                                if ($(this).prop('disabled') !== true) {
                                    $(this).prop('checked', true).change();
                                }
                            });
                        } else {
                            $(".status-checkbox").each(function () {
                                if ($(this).prop('disabled') !== true) $(this).prop('checked', false).change();
                            });

                            $('#cancel-price').html('0원');
                            $('#cancel-delivery-price').html('0원');
                            $('#cancel-point-price').html('0원');
                            $('#return-total-price').html('0');
                        }
                    });

                    /* first option setting */
                    $('.cl-s-order-returnexchange .cl-s-form-selector').each(function(e) {
                        var checkSelectOption = ($(this).find('select option').length > 0) ? true : false;
                        if(checkSelectOption) {
                            var selectId = $(this).find('select').attr('id'),
                                val = $(this).find('select').children().eq(0).val();
                            $(this).find('select').selectpicker({'val':val, dropupAuto:false});
                        }
                    });

                    $('#re-reason').on({
                        'show.bs.select': function (e) {
                            $(this).closest('.cl-s-form-selector').addClass('active');
                        },
                        'hidden.bs.select': function(e) {
                            $(this).closest('.cl-s-form-selector').removeClass('active');

                            if($('#re-reason').prop('value') == '') {
                                $(this).closest('.cl-s-form-selector').addClass('empty');
                            } else {
                                $(this).closest('.cl-s-form-selector').removeClass('empty');
                            }
                        },
                        'changed.bs.select': function (e, clickedIndex, newValue, oldValue) {
                            // console.log(this.value, clickedIndex, newValue, oldValue);
                        }
                    });


                    $('.cl-s-order-returnexchange .cl-s-form-group').on('click',function(e) {
                        if($(e.target).hasClass('cl-s-form-group')) {
                            $(e.target).find('.cl-s-form-control:not([type=hidden])').focus();
                        }
                    });


                    $('.cl-s-order-returnexchange .cl-s-form-textarea').on({
                        focus: function(e) {
                            $(this).closest('.cl-s-form-wrap').addClass('active');
                        },
                        blur: function(e) {
                            var error_str = '',
                                val = $(this).val().trim();

                            $(this).closest('.cl-s-form-wrap').removeClass('active');
                            if(val.length == 0) {
                                $(this).closest('.cl-s-form-wrap').removeClass('error').addClass('empty');
                                $(this).closest('.cl-s-form-wrap').find('.cl-s-control-label.error').remove();
                                return false;
                            } else {
                                $(this).closest('.cl-s-form-wrap').removeClass('empty');

                                if(checkEmojis(val)) error_str = $.lang[LANG]['config.unable.emoji'];
                                else if(val.length < 5) error_str = $.lang[LANG]['customsite.validate.message.minlengthto5'];

                                if(error_str.length > 0) {
                                    $(this).closest('.cl-s-form-wrap').addClass('error');
                                    if($(this).parent().find('.cl-s-control-label.error').length > 0) {
                                        $(this).parent().find('.cl-s-control-label.error').html(error_str);
                                    } else {
                                        $(this).after('<label for="input" class="cl-s-control-label error">' + error_str + '</label>');
                                    }
                                    return false;
                                }
                            }

                            $(this).closest('.cl-s-form-wrap').removeClass('error');
                            $(this).closest('.cl-s-form-wrap').find('.cl-s-control-label.error').remove();
                        }
                    });

                    $('.cl-s-form-wrap .cl-s-form-control').on({
                        focus: function(e) {
                            $(this).closest('.cl-s-form-wrap').addClass('active');
                        },
                        blur: function(e) {
                            var val = $(this).val().trim();

                            $(this).closest('.cl-s-form-wrap').removeClass('active');
                            if(val.length == 0) {
                                $(this).closest('.cl-s-form-wrap').removeClass('error').addClass('empty');
                                $(this).closest('.cl-s-form-wrap').find('.cl-s-control-label.error').remove();
                                return false;
                            } else {
                                $(this).closest('.cl-s-form-wrap').removeClass('empty');

                                if(checkEmojis(val)) {
                                    $(this).closest('.cl-s-form-wrap').addClass('error');
                                    if($(this).parent().find('.cl-s-control-label.error').length > 0) {
                                        $(this).parent().find('.cl-s-control-label.error').html($.lang[LANG]['config.unable.emoji']);
                                    } else {
                                        $(this).after('<label for="input" class="cl-s-control-label error">' + $.lang[LANG]['config.unable.emoji'] + '</label>');
                                    }
                                    return false;
                                }
                            }

                            $(this).closest('.cl-s-form-wrap').removeClass('error');
                            $(this).closest('.cl-s-form-wrap').find('.cl-s-control-label.error').remove();
                        }
                    });



                    $(document).on('click', '.cl-s-order-returnexchange .re-img-close', function() {
                        $(this).closest('li').remove();
                    })

                    $('.cl-s-order-returnexchange .re-file-update').on('click', function () {
                        $("#re-file").click();
                    });

                    $('.cl-s-order-returnexchange #re-file').on({
                        click: function () {

                            var reImageCnt = $('.re-files-list').children('li').length;
                            if (reImageCnt >= 5) {
                                alert('이미지는 최대 5개까지 등록이 가능합니다.');
                                return false;
                            }

                            var sid = $('#re-file').attr('data-sid'),
                                uid = $('#re-file').attr('data-uid');

                            $.uploadON();
                            $(this).fileupload({
                                url: '/_upload/type/re/sid/'+sid+'/uid/'+uid,
                                dataType: 'json',
                                pasteZone: null,
                                async: true,
                                sequentialUploads: true,
                                add: function(e, data) {
                                    var r = $.upload_add(e,data,'image');

                                    if(r.submit) {
                                        var jqXHR = data.submit();
                                        UPLOAD++;
                                    } else {
                                        data.context.find('.loading').html('<i class="fa fa-times error"></i>');
                                        data.context.find('.ing').addClass('error').text(r.err);
                                    }

                                    $('.uploadModal .upload-cancel .btn, .uploadModal .upload-close').off('click').on('click', function(e) {
                                        if(jqXHR != undefined) jqXHR.abort();
                                        data.context.fadeOut().remove();
                                        $('.uploadModal #file-upload-progress').css('width','0%');
                                        $.uploadOFF();
                                        UPLOAD = 0;
                                        UPLOADED = 0;
                                        PROGRESS = 0;
                                    });
                                },
                                progress: function(e, data) {
                                    $.upload_progress(e,data);
                                },                        
                                done: function(e, data) {
                                    $.upload_done(e,data);
                                    UPLOADED++;
                                    var src = (typeof data.result.magic != 'undefined') ? data.result.magic : data.result.src;
                                    var reImage = '\
                                        <li id="re-image-'+reImageCnt+'">\
                                            <img src="'+src+'" class="img-responsive" />\
                                            <input type="hidden" name="review_image[]" value="'+src+'" />\
                                            <div class="cl-s-files-img-close re-img-close"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 8 8" width="8" height="8"><path d="M4.71 4l3.15-3.15c0.2-0.2 0.2-0.51 0-0.71s-0.51-0.2-0.71 0L4 3.29 0.85 0.15c-0.2-0.2-0.51-0.2-0.71 0s-0.2 0.51 0 0.71L3.29 4 0.15 7.15c-0.2 0.2-0.2 0.51 0 0.71C0.24 7.95 0.37 8 0.5 8s0.26-0.05 0.35-0.15L4 4.71l3.15 3.15C7.24 7.95 7.37 8 7.5 8s0.26-0.05 0.35-0.15c0.2-0.2 0.2-0.51 0-0.71L4.71 4z"/></svg></div>\
                                        </li>\
                                    ';

                                    $(".cl-s-order-returnexchange .re-files-list").append(reImage);
                                    reImageCnt++;

                                    if(UPLOADED) {
                                        if(UPLOAD==UPLOADED) {
                                            setTimeout(function() {
                                                $.uploadOFF();
                                                UPLOAD = 0;
                                                UPLOADED = 0;
                                                PROGRESS = 0;
                                            },1000);
                                        }
                                    }
                                },
                                progressall: function (e, data) {
                                    $.upload_progressall(e,data);
                                },
                                start : function(e, data) {
                                    $.upload_start(e,data);
                                    progress1 = 0; progress2 = 0; PROGRESS = 0;
                                },
                                dragover : function(e, data) {
                                    e.preventDefault();
                                },
                            }).prop('disabled', !$.support.fileInput)
                                .parent().addClass($.support.fileInput ? undefined : 'disabled');
                        }
                    });
                    if(status == 'Y') {
                        $('.status-checkbox').off('change');
                    }
                    if(status == 'Y' && data.r.exchange_check == true) {
                        $('.btn-group-toggle').off('click');
                        // console.log(oreModal.find('[btn-toggle="buttons"] .btn-secondary.disable'));
                        oreModal.find('[data-toggle="buttons"] .btn-secondary.disable').on('click', function(e) {
                            e.preventDefault();
                            e.stopPropagation();
                            alert('에스크로 결제 상품은 교환 요청/완료가 있는 경우 반품 요청이 불가능합니다.\n기타 요청이 있는 경우 관리자에게 문의해 주세요.');
                            return false;
                        });
                    }
                    
                    oreModal.find('[data-toggle="popover"]').popover();
                });

                var used_code_coupon = false;
                var coupon = c_data.pay_info.coupon_list;
                if(coupon.length) {
                    $.each(coupon, function(i,v) {
                        if(v.kind == 'C') used_code_coupon = true;
                    });
                }

                $('.cl-s-order-returnexchange .cl-s-btn-group-toggle input:radio').on({
                    change: function() {
                        var order_status = $(this).val(),
                            re_reason_obj = {
                            'R' : '\
                                <option value="구매의사 취소">구매의사 취소</option>\
                                <option value="다른 상품 잘못 주문">다른 상품 잘못 주문</option>\
                                <option value="상품파손">상품파손</option>\
                                <option value="배송지연">배송지연</option>\
                                <option value="상품정보 상이">상품정보 상이</option>\
                                <option value="오배송">오배송</option>\
                                <option value="기타">기타</option>\
                            ',
                            'E' : '\
                                <option value="컬러 및 사이즈 변경">컬러 및 사이즈 변경</option>\
                                <option value="다른 상품 잘못 주문">다른 상품 잘못 주문</option>\
                                <option value="상품파손">상품파손</option>\
                                <option value="상품정보 상이">상품정보 상이</option>\
                                <option value="오배송">오배송</option>\
                                <option value="기타">기타</option>\
                            '
                        };
                        $form.find('.order-candel-content.extra-info').remove();
                        $(this).closest('.btn-group-toggle').find('.btn-secondary').removeClass('active');
                        $(this).parent('.btn-secondary').addClass('active');

                        if (order_status == 'R') {
                            if (status == 'Y' && data.r.exchange_check == true) {
                                alert('에스크로 결제 상품은 교환 요청/완료가 있는 경우 반품 요청이 불가능합니다.\n기타 요청이 있는 경우 관리자에게 문의해 주세요.');
                                setTimeout(function () {
                                    $('#order-radio-exchange').click();
                                }, 500);
                                return false;
                            } else if(used_code_coupon && data.r.exchange_check == true) {
                                alert('코드 쿠폰이 적용된 주문건은 교환 접수 시 반품이 불가능합니다.\n자세한 사항은 판매자의 안내를 따라주세요.');
                                setTimeout(function() {
                                    $('#order-radio-exchange').click();
                                });
                                return false;
                            }
                            
                            $('#return-modal').css('display', 'block');
                            $('.order-cancel-content').css('display', 'block');
                            $('#no-bank').parent().parent().addClass('cl-s-form-wrap');
                            $('#no-bank-name').parent().parent().addClass('cl-s-form-wrap');
                            $('#no-bank-number').parent().parent().addClass('cl-s-form-wrap');
                            $('.code-coupon-exchange-warning').hide();

                            if (status == 'Y') {
                                $('.status-checkbox').each(function () {
                                    $(this).prop('checked', true);
                                    $(this).addClass('noneAll');
                                });
                                $('#product-check').addClass('noneAll');
                                $('#product-check').prop('checked', true);
                                $('.escrow-warring').css({'display': 'block'});
                                $('.escrow-exchange-warning').hide();
                            } else if(used_code_coupon) {
                                $('.status-checkbox').each(function () {
                                    $(this).prop('checked', true);
                                    $(this).addClass('noneAll');
                                });
                                $('#product-check').addClass('noneAll');
                                $('#product-check').prop('checked', true);
                            }
                            var totalCnt = 0, totalNomalCheck = 0, nomalCheck = 0;
                            var price = 0;
                            var deliveryPrice = 0;
                            $(".status-checkbox").each(function (i, index) {
                                if ($(this).is(":checked") === true) {
                                    price += ($(this).closest('.cl-s-product-jumbotron').find('.option-check').attr('data-optionPrice') * 1);
                                    totalCnt++;
                                    if ($(this).attr('data-type') == 'normal') {
                                        nomalCheck++;
                                        var mix_yn = $(this).data('mix_yn');
                                        var delivery_price = 0;
                                        var delivery_template_seq = $(this).data('delivery_template_seq');
                                        var delivery_type = $(this).data('delivery_type');
                                        if(oreModal.find('input[name="order_number_ary[]"][data-delivery_type="' + delivery_type + '"][data-delivery_template_seq="' + delivery_template_seq + '"]').length == oreModal.find('input[name="order_number_ary[]"][data-delivery_type="' + delivery_type + '"][data-delivery_template_seq="' + delivery_template_seq + '"]:checked').length) {
                                            delivery_price = Number($(this).data('delivery_price'));
                                        }
                                        deliveryPrice += delivery_price;
                                    }

                                    var product_number = $(this).attr('data-product_number');
                                    if($(this).attr('data-option_type') != 'A' && !$('input[name="order_number_ary[]"][data-product_number="' + product_number + '"][data-option_type!="A"]:not(:checked)').length) {
                                        $('input[name="order_number_ary[]"][data-product_number="' + product_number + '"][data-option_type="A"]').prop('checked',true).change();
                                    } else if($(this).attr('data-option_type') == 'A' && !$('input[name="order_number_ary[]"][data-product_number="' + product_number + '"][data-option_type!="A"]:not(:checked)').length && !$(this).prop('checked')) {
                                        $('input[name="order_number_ary[]"][data-product_number="' + product_number + '"][data-option_type!="A"]:last').prop('checked',false).change();
                                    }
                                }

                                if ($(this).attr('data-type') == 'normal') {
                                    totalNomalCheck++;
                                }
                            });

                            var product_price = price + deliveryPrice,
                                rePayment = parseInt(c_data.pay_info.request.payment.total) - parseInt(c_data.pay_info.request.payment.coupon) - parseInt(c_data.pay_info.request.cancel.total) - parseInt(c_data.pay_info.request.return.total);

                            rePayment = (rePayment > 0) ? rePayment : 0;
                            
                            // coupon 처리
                            
                            var cancel_coupon_price = 0;
                            if(coupon.length) {
                                var checked_order_number = $('.cancel-info-data:checked').map(function(){ return this.value; }).toArray();
                                $.each(coupon, function(i,v) {
                                    if(checked_order_number.indexOf(v.order_number) > -1 || v.kind == 'C') {
                                        cancel_coupon_price += parseInt(v.discount_price);

                                        // 환불금에서 쿠폰처리
                                        if($('.coupon-detail-info[data-seq="' + v.seq + '"]').length == 0) {
                                            $('.cancel-coupon-title').append('<div class="coupon-name coupon-detail-info" data-seq="' + v.seq + '">' + v.coupon_name + '</div>');
                                            $('#cancel-coupon-detail').append('<div class="coupon-price coupon-detail-info" data-seq="' + v.seq + '">-' + number_format(parseInt(v.discount_price)) + '원</div>');
                                        }
                                    } else {
                                        $('.coupon-detail-info[data-seq="' + v.seq + '"]').remove();
                                    }
                                });
                                // 취소된 쿠폰 저장
                                
                            }
                            product_price = product_price - parseInt(cancel_coupon_price);
                            
                            var use_point = (rePayment - product_price > 0) ? 0 : rePayment - product_price;
                            product_price = product_price + use_point;

                            $('#cancel-price').html(number_format(price)+'원');
                            $('#cancel-delivery-price').html(number_format(deliveryPrice)+'원');
                            $('#cancel-point-price').html(number_format(use_point)+'원');
                            $('#cancel-coupon-price').html(((cancel_coupon_price > 0) ? '-' + number_format(cancel_coupon_price) : '0')+'원');
                            $('#return-total-price').html(number_format(product_price));
                            $('.codecoupon-cancel-desc').show();

                            var priceSumArr = [];
                            var extra_charge_flag = {};
                            if(oreModal.find('.cancel-info-data:checked').length) {
                                oreModal.find('.cancel-info-data:checked').each(function() {
                                    if($(this).data('type') != 'normal') 
                                        return;

                                    var dts = $(this).data('delivery_template_seq');
                                    if(dtl[dts]['price_type'] != 'FREE_CONDITION') return;
                                    var dt = $(this).data('delivery_type');
                                    if(dt != 'DELIVERY' && dt != 'DIRECT') return;

                                    if(!priceSumArr.hasOwnProperty(dts)) {
                                        priceSumArr[dts] = [];
                                    }
                                    if(!priceSumArr[dts].hasOwnProperty(dt)) {
                                        priceSumArr[dts][dt] = 0;
                                    }
                                    // cancel_after_point = Number(cancel_after_point) + ((Number($(this).data("usable_point")) + Number($(this).data("expired_point"))) - Number($(this).data("curr_point")));
                                    var selectedPrice = 0;
                                    selectedPrice = Number($(this).closest('tr').find('[data-optionprice]').data('optionprice'));
                                    priceSumArr[dts][dt] += selectedPrice;

                                    if(dtl[dts]['dtype'][dt]['product_price'] - priceSumArr[dts][dt] < dtl[dts]['free_condition'] && dtl[dts]['dtype'][dt]['product_price'] - priceSumArr[dts][dt] > 0 && dtl[dts]['dtype'][dt]['price'] == 0) {
                                        extra_charge_flag[dts + '|' + dt] = true;
                                    } else {
                                        extra_charge_flag[dts + '|' + dt] = false;
                                    }
                                });
                            }
                            
                            extra_charge_info($form, 'R', Object.values(extra_charge_flag).indexOf(true) > -1 ? true : false, false);
                        } else {

                            $form.find('.order-candel-content.extra-info').remove();
                            $('#return-modal').css('display', 'none');
                            $('.order-cancel-content').css('display', 'none');
                            $('#no-bank').parent().parent().removeClass('cl-s-form-wrap');
                            $('#no-bank-name').parent().parent().removeClass('cl-s-form-wrap');
                            $('#no-bank-number').parent().parent().removeClass('cl-s-form-wrap');
                            if (status == 'Y') {
                                $('.status-checkbox').each(function () {
                                    $(this).prop('checked', false);
                                    $(this).removeClass('noneAll');
                                });
                                $('#product-check').removeClass('noneAll');
                                $('#product-check').prop('checked', false);
                                $('.escrow-warring').css({'display': 'none'});
                                $('.escrow-exchange-warning').show();
                            } else if(used_code_coupon) {
                                $('.status-checkbox').each(function () {
                                    $(this).prop('checked', false);
                                    $(this).removeClass('noneAll');
                                });
                                $('#product-check').removeClass('noneAll');
                                $('#product-check').prop('checked', false);
                                $('.code-coupon-exchange-warning').show();
                                $('.codecoupon-cancel-desc').hide();
                            }
                        }

                        $('#re-reason').closest('.cl-s-form-selector').removeClass('empty');
                        $('#re-reason').html(re_reason_obj[order_status]).selectpicker('refresh');
                        $('#re-reason').selectpicker('val', $('#re-reason').val());
                    }
                });
                if((status == 'Y' || used_code_coupon) && data.r.exchange_check == true) { // 에스크로이고 교환건 존재
                    $('#order-radio-exchange[value="E"]').prop('checked', true).change();
                }

            },'json');

            $('.close-button-dialog').css({'display': 'block'});
        },
        writeReviewModal: function(sid, pnum, onum, type) {
            if(typeof sid == 'undefined' || typeof pnum == 'undefined' || typeof onum == 'undefined') {
                alert('정보가 올바르지 않습니다');
                return false;
            }

            $.post('/_check_order', { sid:sid, pnum:pnum, onum:onum, mode:'review' }, function(data) {
                if(typeof data.error != 'undefined' && data.error) {
                    $(this).showModalFlat('', data.error, true, false, '', 'close');
                    return false;
                }

                var c_data = data.r,
                    modal_str = '',
                    order_group = data.order_group,
                    picturePointStr = '';
                
                if(c_data.writer.status == 'A') {
                    alert('관리자는 상품 후기 작성을 사용할 수 없습니다.');
                    return false;
                }
                    if (c_data.pay_info.settings.point_data != null && c_data.pay_info.settings.point_data['point_use'] == 'Y' && c_data.writer.status != 'T') {
                        if (c_data.pay_info.settings.point_data['review_point_status'] == 'Y') {
                            if(typeof c_data.pay_info.settings.point_data != "undefined" && c_data.pay_info.settings && c_data.odata.price > 0) {  
                                var photoPoint = (c_data.pay_info.settings.point_data['review_photo_point'] > 0) ? c_data.pay_info.settings.point_data['review_photo_point'] : 0,
                                    textPoint = (c_data.pay_info.settings.point_data['review_point'] > 0) ? c_data.pay_info.settings.point_data['review_point'] : 0;
                                    picturePointStr = '\
                                        <div class="cl-s-ps">\
                                            <svg viewBox="0 0 13 13" width="13" height="13">\
                                                <path d="M6.5 0C2.91 0 0 2.91 0 6.5S2.91 13 6.5 13 13 10.09 13 6.5 10.09 0 6.5 0zM6.5 12C3.47 12 1 9.53 1 6.5S3.47 1 6.5 1 12 3.47 12 6.5 9.53 12 6.5 12z"/>\
                                                <rect x="6" y="3" width="1" height="5"/><rect x="6" y="9" width="1" height="1"/>\
                                            </svg>사진 첨부 시 <span>'+number_format(photoPoint)+'원</span>이 적립됩니다.\
                                        </div>\
                                ';
                            }
                           
                            if(c_data.odata.price > 0) {
                                modal_str += '\
                                    <div class="review-point review-icon">후기 작성 시 적립금 <span>최대 '+number_format(photoPoint)+'원</span>\
                                        <svg viewBox="0 0 13 13" width="13" height="13" class="cm-popover-info" tabindex="0" data-trigger="hover" data-toggle="popover" data-placement="bottom" data-html="true" data-content="텍스트 후기 : &nbsp; '+number_format(textPoint)+'원 <br>포토 후기 : &nbsp; '+number_format(photoPoint)+'원<br>\
                                        <p>텍스트 후기와 포토 후기 적립금은 중복지급되지 않으며, 최초 작성한 후기를 기준으로 지급됩니다.</p>">\
                                            <path d="M6.5 0C2.91 0 0 2.91 0 6.5S2.91 13 6.5 13 13 10.09 13 6.5 10.09 0 6.5 0zM6.5 12C3.47 12 1 9.53 1 6.5S3.47 1 6.5 1 12 3.47 12 6.5 9.53 12 6.5 12z"/>\
                                            <rect x="6" y="9" width="1" height="1"/>\
                                            <path d="M6.66 3.01C5.61 3.01 4.58 3.5 4.5 4.8c0 0.06-0.01 0.12 0 0.2h1.02c0-0.07 0.01-0.15 0.02-0.23 0.08-0.62 0.52-0.76 1.08-0.76 0.63 0 1.02 0.37 1.02 0.95 -0.01 0.48-0.3 0.87-0.76 1.34C6.21 6.97 6.02 7.37 6 8h0.99C7 7.66 7.04 7.37 7.67 6.75 8.17 6.27 8.7 5.68 8.7 4.87 8.7 3.85 7.89 3.01 6.66 3.01z"/>\
                                        </svg>\
                                    </div>\
                                ';
                            }
                        }
                    }

                    modal_str += '\
                    <div class="review-body review-write-body">\
                        <div class="cl-s-product-jumbotron clearfix">\
                            <div class="cl-s-product-thumb">\
                                <img src="' + c_data.pdata.img + '" alt="' + c_data.pdata.name + '" class="' + c_data.pdata.img_align + '" />\
                            </div>\
                            <div class="cl-s-product-info">\
                                <h5 class="cl-s-product-title">' + c_data.pdata.name + '</h5>\
                    ';
                    var option_title = (c_data.pdata.option_type == 'A') ? '추가옵션: ' + (c_data.pdata.option_group ? c_data.pdata.option_group + ': ' : '') : '옵션: ';
                    if(typeof c_data.pdata.option != "undefined" && c_data.pdata.option) {
                        modal_str += (c_data.pdata.option_text_str)? '\
                                <div class="option-str">' + option_title + c_data.pdata.option + ' / ' + c_data.pdata.option_text_str + '</div>\
                        ' : '\
                                <div class="option-str">' + option_title + c_data.pdata.option + '</div>\
                        ';
                    } else {
                        modal_str += (c_data.pdata.option_text_str)? '\
                                <div class="option-str">' + c_data.pdata.option_text_str + '</div>\
                        ' : '';
                    }
                    if(typeof c_data.pdata.etc_date != "undefined" && c_data.pdata.etc_date) {
                        modal_str += '\
                                <div class="option-str">선택일자: ' + c_data.pdata.etc_date + '</div>\
                        ';
                    }
                    modal_str += '\
                            </div>\
                        </div>\
                        <div class="review-star">\
                            <h5>상품이 만족스러우셨나요?</h5>\
                            <div class="star text-center">\
                                <span data-idx="1" class="active"></span>\
                                <span data-idx="2" class="active"></span>\
                                <span data-idx="3" class="active"></span>\
                                <span data-idx="4" class="active"></span>\
                                <span data-idx="5" class="active"></span>\
                            </div>\
                        </div>\
                        <div class="review-content">\
                            <h5>어떤 점이 좋았나요?</h5>\
                            <div class="cl-s-form-wrap">\
                                <div class="cl-s-form-group input-label-hide">\
                                    <textarea class="cl-s-form-control" id="review-str" name="review" maxlength="1000" required="required"></textarea>\
                                    <label for="input" class="cl-s-control-label">자세한 내용을 적어주세요. (1000자 이내)</label>\
                                </div>\
                            </div>\
                            <div class="cl-s-files review-files file-center">\
                                <input id="review-file" type="file" name="files[]" accept="image/jpeg,image/gif,image/png" multiple data-sid="' + sid + '" data-uid=\"' + c_data.writer.id + '\">\
                                <label class="cl-s-file-update review-file-update display-flex align-items-center justify-center"><svg viewBox="0 0 42 36" width="18" height="16"><path d="M36 6h-5l-3-5c0 0-0.71-1-1.99-1 -0.72 0-2.54 0-3.99 0 0 0-0.91 0-2.04 0 -1.45 0-3.27 0-3.99 0C14.71 0 14 1 14 1l-3 5H6c-3.31 0-6 2.69-6 6v18c0 3.31 2.69 6 6 6h30c3.31 0 6-2.69 6-6V12C42 8.69 39.31 6 36 6zM21 31c-5.52 0-10-4.48-10-10 0-5.52 4.48-10 10-10 5.52 0 10 4.48 10 10C31 26.52 26.52 31 21 31z"/><circle cx="21" cy="21" r="6"/></svg><span>사진 첨부하기</span></label>';
                    if(c_data.pay_info.settings.point_data != null && c_data.pay_info.settings.point_data['point_use'] == 'Y' && c_data.pay_info.settings.point_data['review_point_status'] == 'Y') modal_str += picturePointStr;
                    modal_str += '\
                                <ul class="cl-s-files-list review-files-list clearfix files-list-wrap">\
                                </ul>\
                            </div>\
                            </div>\
                        </div>\
                            ';
                
                // $('.flat-modal .modal').modal('hide');
                var wrModal = $(this).showModalFlat('후기 작성', modal_str, true, true,function () {

                    var cl_s_f_body = $('.cl-s-product-review-write .review-content');
                    cl_s_f_body.find('.cl-s-form-wrap').each(function() {
                        var check_input = $(this).find('.cl-s-form-control'),
                            val = check_input.val().trim();

                        if(val.length == 0) {
                            $(this).removeClass('error').addClass('empty');
                            $(this).find('.cl-s-control-label.error').remove();
                        } else {
                            if($(this).hasClass('error')) {
                                check_input.focus();
                            }
                        }
                    });

                    if(cl_s_f_body.find('.cl-s-form-wrap.empty, .cl-s-form-wrap.error').length > 0) {
                        cl_s_f_body.find('.cl-s-form-wrap.empty, .cl-s-form-wrap.error').eq(0).find('.cl-s-form-control').focus();
                        return false;
                    }

                    var page_mode = ($('.cl-s-mypage').length > 0) ? 'mypage' : 'no_member',
                        review = $('#review-str').val().trim(),
                        review_star = $('.cl-s-product-review-write .review-star .star .active').length,
                        review_image = new Array();
                        review_image_orig = new Array();

                    $('input[name="review_image[]"]').each(function(i) {
                        review_image[i] = $(this).val();
                    });

                    $('input[name="review_image_orig[]"]').each(function(i) {
                        review_image_orig[i] = $(this).val();
                    });

                    var review_data = {
                        status : 'S',
                        page_mode : page_mode,
                        pnum : pnum,
                        onum : onum,
                        mb_status : c_data.writer.status,
                        review : review,
                        review_count : review_star,
                        review_image : review_image,
                        review_image_orig : review_image_orig
                    };

                    if(c_data.writer.status == 'T') {
                        review_data['name'] = c_data.odata.name;
                        // review_data['order_group'] = c_data.order_data.group;
                    }

                    $('.ok-button-dialog').prop('disabled', true);

                    $.post('/_review_write', { sid:sid, order_group: order_group, data:JSON.stringify(review_data) }, function(rw_data) {
                        if(typeof rw_data.error != 'undefined' && rw_data.error) {
                            $(this).showModalFlat('ERROR', rw_data.error, true, false, '', 'close');
                            return false;
                        }

                        location.reload();
                    }, 'json');

                },'close','등록하기','cl-s-product-review-write cl-modal cl-s-btn cover', true, '', function() {

                    $('.cl-s-product-review-write .cl-s-form-group').on('click',function(e) {
                        if($(e.target).hasClass('cl-s-form-group')) {
                            $(e.target).find('.cl-s-form-control:not([type=hidden])').focus();
                        }
                    });
                    $('[data-toggle="popover"]').popover();
                    $('.cl-s-product-review-write .cl-s-form-control').on({
                        focus: function(e) {
                            $(this).closest('.cl-s-form-wrap').addClass('active');
                        },
                        blur: function(e) {
                            var val = $(this).val().trim();

                            $(this).closest('.cl-s-form-wrap').removeClass('active');
                            if(val.length == 0) {
                                $(this).closest('.cl-s-form-wrap').removeClass('error').addClass('empty');
                                $(this).closest('.cl-s-form-wrap').find('.cl-s-control-label.error').remove();
                                return false;
                            } else {
                                $(this).closest('.cl-s-form-wrap').removeClass('empty');
                                var passEmoji = ($.inArray($(this).attr('name'),['review']) > -1) ? true : false,
                                    error_str = '';
                                if(!passEmoji && checkEmojis(val)) error_str = $.lang[LANG]['config.unable.emoji'];
                                else if(val.length < 5) error_str = $.lang[LANG]['customsite.validate.message.minlengthto5'];
                                
                                if(error_str.length > 0) {
                                    $(this).closest('.cl-s-form-wrap').addClass('error');
                                    if($(this).parent().find('.cl-s-control-label.error').length > 0) {
                                        $(this).parent().find('.cl-s-control-label.error').html(error_str);
                                    } else {
                                        $(this).after('<label for="input" class="cl-s-control-label error">' + error_str + '</label>');
                                    }
                                    return false;
                                }
                            }

                            $(this).closest('.cl-s-form-wrap').removeClass('error').removeClass('empty');
                            $(this).closest('.cl-s-form-wrap').find('.cl-s-control-label.error').remove();
                        }
                    });

                    $(document).on('click', '.cl-s-product-review-write .review-img-close', {mode: 'review'}, deleteReviewQnaImg);

                    $('.cl-s-product-review-write .review-file-update').on('click', function () {
                        $("#review-file").click();
                    });

                    $('.cl-s-product-review-write #review-file').on('click', {mode: 'review'}, uploadReviewQnaImg);

                    $('.cl-s-product-review-write .review-star .star span').on('click', function() {
                        var rCount = $(this).attr('data-idx');
                        $(this).parent().children('span').removeClass('active');
                        $(this).addClass('active').prevAll('span').addClass('active');
                    });
                }, function() {
                    if($('.cl-s-product-review-write .review-img-close').length > 0){
                        $.each($('.cl-s-product-review-write .review-img-close'), function(){
                            $(this).trigger('click');
                        });
                    }
                });


            },'json');

        },
        editReviewModal: function(sid, pnum, onum, seq) {
            if(typeof sid == "undefined" || typeof pnum == "undefined" || typeof onum == "undefined") {
                alert('정보가 올바르지 않습니다');
                return false;
            }

            $.post('/_check_review', { sid:sid, seq: seq, mode:'review' }, function(data) {

                if(typeof data.error != "undefined" && data.error) {
                    $(this).showModalFlat('', data.error, true, false, '', 'close');
                    return false;
                }

                var c_data = data.r,
                    modal_str = '\
                    <div class="review-body review-write-body">\
                        <div class="cl-s-product-jumbotron clearfix">\
                            <div class="cl-s-product-thumb">\
                                <a href="' + c_data.pdata.product_url + '" target="_blank"><img src="' + c_data.pdata.img + '" alt="' + c_data.pdata.name + '" class="' + c_data.pdata.img_align + '" onerror="this.src=\'//storage.googleapis.com/i.addblock.net/img_broken_fill_500.png\'"/></a>\
                            </div>\
                            <div class="cl-s-product-info">\
                                <h5 class="cl-s-product-title"><a href="' + c_data.pdata.product_url + '" target="_blank">' + c_data.pdata.name + '</a></h5>\
                    ';
                    var option_title = (c_data.pdata.option_type == 'A') ? '추가옵션: ' + (c_data.pdata.option_group ? c_data.pdata.option_group + ': ' : '') : '옵션: ';
                    if(typeof c_data.pdata.option != "undefined" && c_data.pdata.option) {
                        modal_str += (c_data.pdata.option_text_str)? '\
                                <div class="option-str">' + option_title + c_data.pdata.option + ' / ' + c_data.pdata.option_text_str + '</div>\
                        ' : '\
                                <div class="option-str">' + option_title + c_data.pdata.option + '</div>\
                        ';
                    } else {
                        modal_str += (c_data.pdata.option_text_str)? '\
                                <div class="option-str">' + option_title + c_data.pdata.option_text_str + '</div>\
                        ' : '';
                    }
                    if(typeof c_data.pdata.etc_date != "undefined" && c_data.pdata.etc_date) {
                        modal_str += '\
                                <div class="option-str">선택일자: ' + c_data.pdata.etc_date + '</div>\
                        ';
                    }
                    var image = c_data.review.review_image.split("||").filter(function(v){return v!==''});
                    var image_orig = c_data.review.review_image_orig.split("||").filter(function(v){return v!==''});
                    var reviewImage = '';
                    if(image.length > 0) {
                        for (var i=0;i<image.length;i++) {
                            reviewImage += '\
                                <li id="review-image-'+i+'">\
                                    <img src="'+image[i]+'" class="img-responsive" />\
                                    <input type="hidden" name="review_image[]" value="'+image[i]+'" />\
                                    <input type="hidden" name="review_image_orig[]" value="'+image_orig[i]+'" />\
                                    <div class="cl-s-files-img-close review-img-close"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 8 8" width="8" height="8"><path d="M4.71 4l3.15-3.15c0.2-0.2 0.2-0.51 0-0.71s-0.51-0.2-0.71 0L4 3.29 0.85 0.15c-0.2-0.2-0.51-0.2-0.71 0s-0.2 0.51 0 0.71L3.29 4 0.15 7.15c-0.2 0.2-0.2 0.51 0 0.71C0.24 7.95 0.37 8 0.5 8s0.26-0.05 0.35-0.15L4 4.71l3.15 3.15C7.24 7.95 7.37 8 7.5 8s0.26-0.05 0.35-0.15c0.2-0.2 0.2-0.51 0-0.71L4.71 4z"/></svg></div>\
                                </li>\
                            ';
                        }
                    }
                    
                    modal_str += '\
                            </div>\
                        </div>\
                        <div class="review-star">\
                            <h5>상품이 만족스러우셨나요?</h5>\
                            <div class="star text-center">';
                            for(var i=0;i<5;i++) {
                                var rs_onof = (i < c_data.review.review_score) ? 'active' : '';
                                modal_str += '<span data-idx="'+(i+1)+'" class="'+rs_onof+'"></span>';
                            }
                            modal_str += '\
                            </div>\
                        </div>\
                        <div class="review-content">\
                            <h5>어떤 점이 좋았나요?</h5>\
                            <div class="cl-s-form-wrap">\
                                <div class="cl-s-form-group input-label-hide">\
                                    <textarea class="cl-s-form-control" id="review-str" name="review" maxlength="1000" required="required">'+c_data.review.review+'</textarea>\
                                    <label for="input" class="cl-s-control-label">자세한 내용을 적어주세요. (1000자 이내)</label>\
                                </div>\
                            </div>\
                            <div class="cl-s-files review-files">\
                                <input id="review-file" type="file" name="files[]" multiple data-sid="' + sid + '" data-uid=\"' + c_data.writer.id + '\" data-seq=\"'+seq+'\">\
                                <label class="cl-s-file-update review-file-update display-flex align-items-center justify-center"><svg viewBox="0 0 42 36" width="18" height="16"><path d="M36 6h-5l-3-5c0 0-0.71-1-1.99-1 -0.72 0-2.54 0-3.99 0 0 0-0.91 0-2.04 0 -1.45 0-3.27 0-3.99 0C14.71 0 14 1 14 1l-3 5H6c-3.31 0-6 2.69-6 6v18c0 3.31 2.69 6 6 6h30c3.31 0 6-2.69 6-6V12C42 8.69 39.31 6 36 6zM21 31c-5.52 0-10-4.48-10-10 0-5.52 4.48-10 10-10 5.52 0 10 4.48 10 10C31 26.52 26.52 31 21 31z"/><circle cx="21" cy="21" r="6"/></svg><span>사진 첨부하기</span></label>\
                                <ul class="cl-s-files-list review-files-list clearfix" >\
                                '+reviewImage+'\
                                </ul>\
                            </div>\
                        </div>\
                    </div>\
                \
                ';

                // $('.flat-modal .modal').modal('hide');
                var wrModal = $(this).showModalFlat('후기 작성', modal_str, true, true, function () {

                    var cl_s_f_body = $('.cl-s-product-review-write .review-content');
                    cl_s_f_body.find('.cl-s-form-wrap').each(function() {
                        var check_input = $(this).find('.cl-s-form-control'),
                            val = check_input.val().trim();

                        if(val.length == 0) {
                            $(this).removeClass('error').addClass('empty');
                            $(this).find('.cl-s-control-label.error').remove();
                        } else {
                            if($(this).hasClass('error')) {
                                check_input.focus();
                            }
                        }
                    });

                    if(cl_s_f_body.find('.cl-s-form-wrap.empty, .cl-s-form-wrap.error').length > 0) {
                        cl_s_f_body.find('.cl-s-form-wrap.empty, .cl-s-form-wrap.error').eq(0).find('.cl-s-form-control').focus();
                        return false;
                    }

                    var review = $('#review-str').val().trim(),
                        review_star = $('.cl-s-product-review-write .review-star .star .active').length,
                        review_image = new Array();
                        review_image_orig = new Array();
                    $('input[name="review_image[]"]').each(function(i) {
                        review_image[i] = $(this).val();
                    });
                    $('input[name="review_image_orig[]"]').each(function(i) {
                        review_image_orig[i] = $(this).val();
                    });
                    
                    var review_data = {
                        status : 'U',
                        page_mode : 'product',
                        pnum : pnum,
                        onum : onum,
                        seq : seq,
                        mb_status : c_data.writer.status,
                        review : review,
                        review_count : review_star,
                        review_image : review_image,
                        review_image_orig : review_image_orig
                    };

                    if(c_data.writer.status == 'T') {
                        review_data['name'] = c_data.odata.name;
                        // review_data['order_group'] = c_data.order_data.group;
                    }

                    $('.ok-button-dialog').prop('disabled', true);
                    
                    $.post('/_review_write', { sid:sid, data:JSON.stringify(review_data) }, function(rw_data) {
                        if(typeof rw_data.error != 'undefined' && rw_data.error) {
                            $(this).showModalFlat('ERROR', rw_data.error, true, false, '', 'close');
                            return false;
                        }

                        wrModal.modal('hide');
                        setTimeout(function () {
                            location.reload();
                        }, 200); 
                    }, 'json');



                },'close','수정하기','cl-s-product-review-write cl-modal cl-s-btn cover', true, '', function() {
                    $('.cl-s-product-review-write .cl-s-form-group').on('click',function(e) {
                        if($(e.target).hasClass('cl-s-form-group')) {
                            $(e.target).find('.cl-s-form-control:not([type=hidden])').focus();
                        }
                    });

                    $('.cl-s-product-review-write .cl-s-form-control').on({
                        focus: function(e) {
                            $(this).closest('.cl-s-form-wrap').addClass('active');
                        },
                        blur: function(e) {
                            var val = $(this).val().trim();

                            $(this).closest('.cl-s-form-wrap').removeClass('active');
                            if(val.length == 0) {
                                $(this).closest('.cl-s-form-wrap').removeClass('error').addClass('empty');
                                $(this).closest('.cl-s-form-wrap').find('.cl-s-control-label.error').remove();
                                return false;
                            } else {
                                $(this).closest('.cl-s-form-wrap').removeClass('empty');

                                var passEmoji = ($.inArray($(this).attr('name'),['review']) > -1) ? true : false,
                                    error_str = '';
                                if(!passEmoji && checkEmojis(val)) error_str =  $.lang[LANG]['config.unable.emoji'];
                                else if(val.length < 5) error_str = $.lang[LANG]['customsite.validate.message.minlengthto5'];

                                if(error_str.length > 0) {
                                    $(this).closest('.cl-s-form-wrap').addClass('error');
                                    if($(this).parent().find('.cl-s-control-label.error').length > 0) {
                                        $(this).parent().find('.cl-s-control-label.error').html(error_str);
                                    } else {
                                        $(this).after('<label for="input" class="cl-s-control-label error">' + error_str + '</label>');
                                    }
                                    return false;
                                }
                            }

                            $(this).closest('.cl-s-form-wrap').removeClass('error').removeClass('empty');
                            $(this).closest('.cl-s-form-wrap').find('.cl-s-control-label.error').remove();
                        }
                    });


                    $(document).on('click', '.cl-s-product-review-write .review-img-close', {mode: 'review'}, deleteReviewQnaImg);


                    $('.cl-s-product-review-write .review-file-update').on('click', function () {
                        $("#review-file").click();
                    });

                    $('.cl-s-product-review-write #review-file').on('click', {mode: 'review'}, uploadReviewQnaImg);

                    $('.cl-s-product-review-write .review-star .star span').on('click', function() {
                        var rCount = $(this).attr('data-idx');
                        $(this).parent().children('span').removeClass('active');
                        $(this).addClass('active').prevAll('span').addClass('active');
                    });

                });

            },'json');

        },
        viewReviewModal: function(sid, seq, page) {
            if(typeof sid == 'undefined' || typeof seq == 'undefined') {
                alert('정보가 올바르지 않습니다');
                return false;
            }

            $.post('/_check_review', { sid:sid, seq:seq }, function(data) {
                if(typeof data.error != 'undefined' && data.error) {
                    $(this).showModalFlat('', data.error, true, false, '', 'close');
                    return false;
                }

                var c_data = data.r;
                var um_id = c_data.review.um_id;
                var writer = c_data.writer.id;
                var writerName = (um_id == writer)? c_data.review.name : c_data.review.masked_name;
                    writerName = (c_data.writer.status == 'A')? c_data.review.name : writerName;
                var image = c_data.review.review_image.split("||").filter(function(v){return v!==''});
                var reviewImage = '';
                for (var i=0;i<image.length;i++) {
                    reviewImage += '<img src="'+getServeImage(image[i], '800', '')+'">';
                }
                
                var modal_str = '\
                    <div class="review-body">\
                        <div class="cl-s-product-jumbotron clearfix">\
                            <div class="cl-s-product-thumb">\
                                <a href="' + c_data.pdata.product_url + '" target="_blank"><img src="' + c_data.pdata.img + '" alt="' + c_data.pdata.name + '" class="' + c_data.pdata.img_align + '" onerror="this.src=\'//storage.googleapis.com/i.addblock.net/img_broken_fill_500.png\'"/></a>\
                            </div>\
                            <div class="cl-s-product-info">\
                                <h5 class="cl-s-product-title"><a href="' + c_data.pdata.product_url + '" target="_blank">' + c_data.pdata.name + '</a></h5>\
                            ';
                    var option_title = (c_data.pdata.option_type == 'A') ? '추가옵션: ' + (c_data.pdata.option_group ? c_data.pdata.option_group + ': ' : '') : '옵션: ';                            
                    if(typeof c_data.pdata.option != "undefined" && c_data.pdata.option) {
                        modal_str += '\
                                <div class="option-str">' + option_title + c_data.pdata.option + '</div>\
                        ';
                    }
                    if(typeof c_data.pdata.etc_date != "undefined" && c_data.pdata.etc_date) {
                        modal_str += '\
                                <div class="option-str">선택일자: ' + c_data.pdata.etc_date + '</div>\
                        ';
                    }

                    c_data.review_status = (c_data.writer.status=='T' && page=='mypayment')? 'Y':c_data.review_status;
                    modal_str += '\
                            </div>\
                        </div>\
                        <div class="review-member-info">\
                            <span>' + (c_data.review.inflow=='NAVERPAY' ? '<svg class="ico-naverpay" viewBox="0 0 24 24" width="14" height="14"><polygon points="15.2 2.8 15.2 12.1 8.9 2.8 2 2.8 2 21.2 8.8 21.2 8.8 11.9 15.2 21.2 22 21.2 22 2.8 "></polygon></svg>' : '') + writerName + '<span class="view-review-date">' + c_data.review.reg_date + '</span></span>';
                            if (c_data.review_status == 'Y' || c_data.review_status == 'A' || c_data.writer.status == 'A') {
                                modal_str += '<div class="review-edit-box" data-pnum="'+c_data.review.product_number+'" data-onum="'+c_data.review.order_number+'" data-ogroup="'+c_data.odata.order_group+'" data-seq="'+c_data.review.seq+'">';
                                if (c_data.review_status == 'Y' && c_data.review.status == 'N' && c_data.review.seq.indexOf('mlux|') == -1) {
                                    modal_str += '<button type="button" class="review-edit">수정</button>';
                                    modal_str += '<button type="button" class="review-delete">삭제</button>';
                                }
                                if (c_data.writer.status == 'A' && c_data.review.seq.indexOf('mlux|') == -1) {
                                    modal_str += '<button type="button" class="review-delete">삭제</button>';
                                }
                                modal_str += '</div>\
                                ';
                            }
                        modal_str += '\
                        </div>\
                        <div class="view-review-box">\
                            <div class="review-score">';
                            for(var i=0;i<5;i++) {
                                var rs_onof = (i < c_data.review.review_score) ? 'on' : 'off';
                                modal_str += '<span class="re_starimg star_'+ rs_onof +'"><svg viewBox="0 0 15 15" width="15" height="15"><polygon points="15 5.8 9.78 4.77 7.5 0 5.22 4.77 0 5.8 3.59 9.55 2.93 15 7.5 12.61 12.07 15 11.41 9.55 "/></svg></span>';
                            }

                            if(c_data.review.inflow=='NAVERPAY') {
                                if(c_data.review.review_image) {
                                    reviewImage = '<img src="' + c_data.review.review_image + '" />';
                                } else {
                                    reviewImage = '';
                                }
                            }

                            modal_str += '\
                            </div>\
                            <div class="review-box-content">'+nl2br(c_data.review.review)+'</div>\
                            <div class="review-box-image">'+reviewImage+'</div>\
                            ';
                            if(c_data.review.status == 'Y'){
                            modal_str += '\
                            <div class="review-box-content review-answer answer-content_'+seq+'">\
                                <div class="review-answer-info"><span>관리자<span class="view-review-date">'+c_data.review.answer_date+'</span></span></div>\
                                <div class="review-content">'+nl2br(c_data.review.answer)+'\
                            </div>'; //end review-answer-content
                            if(c_data.writer.status == 'A') {
                                modal_str += '\
                                    <div class="answer-editor-button" data-pnum="'+c_data.review.product_number+'" data-onum="'+c_data.review.order_number+'" data-seq="'+c_data.review.seq+'">\
                                        <button type="button" class="btn answer-modify-btn" data-seq="'+seq+'">수정</button>\
                                        <button type="button" class="btn answer-delete-btn" onclick="answerDelete('+seq+')">답글 삭제</button>\
                                    </div>\
                                ';
                            }
                            modal_str += '\
                            </div>'; //end review-answer
                            }          
                            
                            if(c_data.writer.status == 'A' && c_data.review.seq.indexOf('mlux|') == -1){
                            modal_str += '\
                            <div class="answer-editor answer-editor_'+seq+' answer_'+c_data.review.status+'">\
                                <div class="review-answer-info">답글</div>\
                                <textarea id="answer-'+seq+'" placeholder="답글을 작성해 주세요.">'+nl2br(c_data.review.answer)+'</textarea>\
                                <div class="answer-editor-button" data-pnum="'+c_data.review.product_number+'" data-onum="'+c_data.review.order_number+'" data-seq="'+c_data.review.seq+'">';
                            if(c_data.review.status == 'N'){
                            modal_str += '\
                                    <button type="button" class="btn answer-submit-btn">답글 등록</button>';
                            }
                            else{
                            modal_str += '\
                                    <button type="button" class="btn answer-cancel-btn">취소</button>\
                                    <button type="button" class="btn answer-submit-btn">답글 수정</button>';
                            }
                            modal_str += '\
                                </div>\
                            </div>';
                            }
                modal_str += '\
                        </div>\
                    </div>'; //end view-review-box

                // $('.flat-modal .modal').modal('hide');
                var wrModal = $(this).showModalFlat('상품 후기', modal_str, true, false, '', '','','cl-s-product-review-write cl-s-product-review-view cl-modal cl-s-btn cover', false, '', function () {
                    $(document).off('click', '.review-edit');
                    $(document).on('click', '.review-edit', function (e) {
                        e.stopPropagation();
                        var $parent = $(this).parent(),
                            pnum = $parent.attr('data-pnum'),
                            onum = $parent.attr('data-onum'),
                            seq = $parent.attr('data-seq');

                        $('.modal-backdrop').fadeOut(200);
                        $('.modal').fadeOut(200);
                        setTimeout(function () {
                            $('.modal-backdrop').remove();
                            $('.modal').remove();
                            $('button[data-dismiss="modal"]').trigger('click');
                            $.shoppingmall.editReviewModal(sid, pnum, onum, seq);
                        }, 200);
                    });

                    $(document).off('click', '.review-delete');
                    $(document).off('click', '.answer-modify-btn');
                    $(document).off('click', '.answer-cancel-btn');
                    $(document).off('click', '.answer-submit-btn');

                    $(document).on('click', '.review-delete', function () {
                    $this = $(this)
                        var $parent = $(this).parent(),                            
                            on = $parent.attr('data-onum'),
                            og = $parent.attr('data-ogroup');
                        $.ajax({
                            url: '/_review_delete_chk',
                            type: 'post',
                            data: {
                                review_og : og,
                                review_on : on 
                            },
                            success: function (data) {
                                var parsedData = JSON.parse(data);
                                if(parsedData.result == true ){
                                    if (confirm('정말로 삭제하시겠습니까?')) {
                                        var pnum = $parent.attr('data-pnum'),
                                            onum = $parent.attr('data-onum'),
                                            seq = $parent.attr('data-seq'),
                                            on = $parent.attr('data-onum'),                                            
                                            og = $parent.attr('data-ogroup');
                                        $.ajax({
                                            url: '/_review_delete',
                                            type: 'post',
                                            data: {
                                                sid: sid,
                                                seq: seq,
                                                review_og : og,
                                                review_on : on                                                 
                                            },
                                            success: function (data) {
                                                alert('삭제가 완료되었습니다.');
                                                location.reload();
                                            }
                                        });
                                    }
                                } else {
                                    console.log($(this),"2번")
                                    if($('.rv-cancel-paddingedit').length == 0) {
                                        $this.closest('.cl-s-product-review-view .modal-content').css('opacity','.5');
                                        var modal = $(this).showModalFlat('후기 삭제에 따른<br>적립금 회수 안내','후기를 삭제하시면 후기 작성 적립금이 회수됩니다.<br>후기를 삭제 하시겠습니까?',true,true,function(){                    
                                            var $parent = $this.parent(),
                                                pnum = $parent.attr('data-pnum'),
                                                onum = $parent.attr('data-onum'),
                                                seq = $parent.attr('data-seq'),
                                                on = $parent.attr('data-onum'),
                                                og = $parent.attr('data-ogroup');

                                            $.ajax({
                                                url: '/_review_delete',
                                                type: 'post',
                                                data: {
                                                    sid: sid,
                                                    seq: seq,
                                                    review_og : og,
                                                    review_on : on 
                                                },
                                                success: function (data) {
                                                    alert('삭제가 완료되었습니다.');
                                                    location.reload();
                                                }
                                            });                            
                                        },'cancel','ok','cl-cmmodal cl-s-btn w560 cl-p130 cl-p0 review-opacity rv-cancel-paddingedit','',function(){
                                            $this.closest('.cl-s-product-review-view .modal-content').css('opacity','unset'); 
                                        }, function() {
                                            $(document).on('click', '.ok-button-dialog', function (e) {
                                                $(this).prop("disabled", true);
                                            });                                        
                                            $(document).on('keydown', function(e) {
                                                if(e.keyCode == 27) modal.modal('hide');
                                            });
                                        }, function() {
                                            $this.closest('.cl-s-product-review-view .modal-content').css('opacity','unset');
                                        });
                                    }
                                }
                            }
                        });   

                    });

                    $(document).on('click', '.answer-modify-btn', function(){
                        var $parent = $(this).parent(),
                            pnum = $parent.attr('data-pnum'),
                            onum = $parent.attr('data-onum'),
                            seq = $parent.attr('data-seq');

                        $('.answer-content_'+seq).hide();
                        $('.answer-editor_'+seq).show();
                    });

                    $(document).on('click', '.answer-cancel-btn', function(){
                        var $parent = $(this).parent(),
                            pnum = $parent.attr('data-pnum'),
                            onum = $parent.attr('data-onum'),
                            seq = $parent.attr('data-seq');

                        $('.answer-content_'+seq).show();
                        $('.answer-editor_'+seq).hide();
                    });

                    $(document).on('click', '.answer-submit-btn', function(){
                        var $parent = $(this).parent(),
                            pnum = $parent.attr('data-pnum'),
                            onum = $parent.attr('data-onum'),
                            seq = $parent.attr('data-seq');

                        $.ajax({
                            url: '/_review_msg_write',
                            type: 'post',
                            data: {
                                sid: sid,
                                seq: seq,
                                review_admin_msg: $('#answer-'+seq).val()
                            },
                            success: function (data) {
                                alert('답글이 등록되었습니다.');
                                location.reload();
                            }
                        });
                    });

                    $(document).on('click', '.answer-delete-btn', function(){
                        if (confirm('정말로 삭제하시겠습니까?')) {
                            var $parent = $(this).parent(),
                                pnum = $parent.attr('data-pnum'),
                                onum = $parent.attr('data-onum'),
                                seq = $parent.attr('data-seq');

                            $.ajax({
                                url: '/_review_msg_write',
                                type: 'post',
                                data: {
                                    sid: sid,
                                    seq: seq,
                                },
                                success: function (data) {
                                    alert('답글이 삭제되었습니다.');
                                    location.reload();
                                }
                            });
                        }
                    });
                });


            },'json');

        },
        editQnAModal: function(sid, pnum, seq, onum) {
            if(typeof property == 'undefined') {
                // alert('편집모드에서 지원하지 않습니다');
                var modal = $(this).showModalFlat('','편집모드에서 지원하지 않습니다',true,false,'','ok','','cl-cmmodal cl-s-btn w560 cl-p130 cl-t80 cl-modal cl-none-title cl-close-btn','','',function() {
                    $(document).on('keydown', function(e) {
                        if(e.keyCode == 27) modal.modal('hide');
                    });
                });
                return false;
            }
            if(typeof property.LOAD != 'undefined' && property.LOAD == 'RENDER') {
                alert('미리보기에서는 지원하지 않습니다');
                return false;
            }
            if(typeof seq == 'undefined' || seq == '') seq = -1;
            var mode = (seq == -1) ? 'new' : 'edit';
            var onum = (typeof onum == 'undefined' || onum == '')? '':onum;
            
            $.ajax({
                url: '/_qna_edit',
                type: 'POST',
                dataType: 'json',
                data: { sid:sid, pnum:pnum, seq:seq, mode:mode },
                async: false,
                cache: false,
                success: function(data) {
                    if (data.result == 'fail') {
                        location.href = '/_login';
                        return false;
                    }

                    if (data.error) {
                        $(this).showModalFlat('', data.error, true, false, '', 'close');
                        return false;
                    }

                    var status = data.um_status;
                    if(status == 'A') {
                        alert('관리자는 상품문의하기를 사용할 수 없습니다.');
                        return false;
                    }

                    var qna_files_str = qna_secret_str = qna_answer_email_str = qna_answer_alimtalk_str = '';

                    if(mode == 'edit') {
                        if(data['secret'] == 'Y') qna_secret_str = 'checked';
                        if(data['answer_email'] == 'Y') qna_answer_email_str = 'checked';
                        if(data['answer_alimtalk'] == 'Y') qna_answer_alimtalk_str = 'checked';

                        if(data['qna_image']) {
                            var image = data['qna_image'].split('||').filter(function(v){return v!==''});
                            var image_orig = data['qna_image_orig'].split('||').filter(function(v){return v!==''});
                            $.each(image, function(i,v) {
                                qna_files_str += '\
                                    <li id="qna-image-' + i + '">\
                                        <img src="' + v + '" class="img-responsive" />\
                                        <input type="hidden" name="qna_image[]" value="' + v + '"/>\
                                        <input type="hidden" name="qna_image_orig[]" value="' + image_orig[i] + '"/>\
                                        <div class="cl-s-files-img-close qna-img-close"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 8 8" width="8" height="8"><path d="M4.71 4l3.15-3.15c0.2-0.2 0.2-0.51 0-0.71s-0.51-0.2-0.71 0L4 3.29 0.85 0.15c-0.2-0.2-0.51-0.2-0.71 0s-0.2 0.51 0 0.71L3.29 4 0.15 7.15c-0.2 0.2-0.2 0.51 0 0.71C0.24 7.95 0.37 8 0.5 8s0.26-0.05 0.35-0.15L4 4.71l3.15 3.15C7.24 7.95 7.37 8 7.5 8s0.26-0.05 0.35-0.15c0.2-0.2 0.2-0.51 0-0.71L4.71 4z"></path></svg></div>\
                                    </li>\
                                ';
                            });
                        }
                    }
                    data['email'] = (data['email'] !== null)? data['email']:'';
                    seq = (seq !== -1)? seq:'';
                    var qna_writer_str = (data['member']) ? '\
                        <input type="hidden" id="qna-name" class="cl-s-form-control" name="qna_name" value="' + data['name'] + '">\
                        <input type="hidden" id="qna-email" class="cl-s-form-control" name="qna_email" value="' + data['email'] + '">\
                        <input type="hidden" id="qna-tel" class="cl-s-form-control" name="qna_tel" value="' + data['tel'] + '">\
                        <input type="hidden" id="order-number" name="order_number" value="' + onum + '">\
                    ' : '\
                        <input type="hidden" id="order-number" name="order_number" value="' + onum + '">\
                            <ul class="qna-writer clearfix">\
                                <li>\
                                    <div class="cl-s-form-wrap">\
                                        <div class="cl-s-form-group">\
                                            <input type="text" class="cl-s-form-control" id="qna-name" name="qna_name" required="required" value="' + data['name'] + '">\
                                            <label for="input" class="cl-s-control-label">이름</label>\
                                        </div>\
                                    </div>\
                                </li>\
                                <li>\
                                    <div class="cl-s-form-wrap">\
                                        <div class="cl-s-form-group">\
                                            <input type="password" class="cl-s-form-control" id="qna-password" name="qna_password" required="required">\
                                            <label for="input" class="cl-s-control-label">비밀번호</label>\
                                        </div>\
                                    </div>\
                                </li>\
                            </ul>\
                        ';

                    var qna_privacy_str = '\
                            <hr class="line"/>\
                            <div class="qna-privacy">\
                    ';
                    if(!data['member']) {
                        if(data['um_qna_fin'] == 'Y') {
                            qna_privacy_str += '\
                                <div class="cl-s-checkbox">\
                                    <label class="privacy-toggle" data-view="#qna-email-input">\
                                        <input type="checkbox" id="qna-btn-email" name="answer_email" value="Y" ' + qna_answer_email_str + '>\
                                        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16"><path d="M13 0H3C1.3 0 0 1.3 0 3v10c0 1.7 1.3 3 3 3h10c1.7 0 3-1.3 3-3V3C16 1.3 14.7 0 13 0zM15 13c0 1.1-0.9 2-2 2H3c-1.1 0-2-0.9-2-2V3c0-1.1 0.9-2 2-2h10c1.1 0 2 0.9 2 2V13z"/></svg>\
                                        <svg class="active" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16"><path d="M13 0H3C1.34 0 0 1.34 0 3v10c0 1.66 1.34 3 3 3h10c1.66 0 3-1.34 3-3V3C16 1.34 14.66 0 13 0zM13.03 6.03l-5.5 5.5C7.38 11.68 7.19 11.75 7 11.75s-0.38-0.07-0.53-0.22l-3.5-3.5c-0.29-0.29-0.29-0.77 0-1.06s0.77-0.29 1.06 0L7 9.94l4.97-4.97c0.29-0.29 0.77-0.29 1.06 0S13.32 5.74 13.03 6.03z"/></svg>\
                                        이메일로 답변완료 알림 받기\
                                    </label>\
                                </div>\
                                <div class="cl-s-form-wrap" id="qna-email-input" style="display:' + ((qna_answer_email_str == 'checked')? 'block':'none') + ';">\
                                    <div class="cl-s-form-group">\
                                        <input type="text" class="cl-s-form-control" id="qna-email" name="qna_email" data-type="email" required="required" value="' + data['email'] + '">\
                                        <label for="input" class="cl-s-control-label">이메일 주소</label>\
                                    </div>\
                                </div>\
                            ';
                            if(data['talk_cnt'] > 0) { //alimtalk
                                qna_privacy_str += '\
                                <div class="cl-s-checkbox">\
                                    <label class="privacy-toggle" data-view="#qna-tel-input">\
                                        <input type="checkbox" id="qna-btn-alimtalk" name="answer_alimtalk" value="Y" ' + qna_answer_alimtalk_str + '>\
                                        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16"><path d="M13 0H3C1.3 0 0 1.3 0 3v10c0 1.7 1.3 3 3 3h10c1.7 0 3-1.3 3-3V3C16 1.3 14.7 0 13 0zM15 13c0 1.1-0.9 2-2 2H3c-1.1 0-2-0.9-2-2V3c0-1.1 0.9-2 2-2h10c1.1 0 2 0.9 2 2V13z"/></svg>\
                                        <svg class="active" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16"><path d="M13 0H3C1.34 0 0 1.34 0 3v10c0 1.66 1.34 3 3 3h10c1.66 0 3-1.34 3-3V3C16 1.34 14.66 0 13 0zM13.03 6.03l-5.5 5.5C7.38 11.68 7.19 11.75 7 11.75s-0.38-0.07-0.53-0.22l-3.5-3.5c-0.29-0.29-0.29-0.77 0-1.06s0.77-0.29 1.06 0L7 9.94l4.97-4.97c0.29-0.29 0.77-0.29 1.06 0S13.32 5.74 13.03 6.03z"/></svg>\
                                        알림톡으로 답변완료 알림 받기\
                                    </label>\
                                </div>\
                                <div class="cl-s-form-wrap" id="qna-tel-input" style="display:' + ((qna_answer_alimtalk_str == 'checked')? 'block':'none') + ';">\
                                    <div class="cl-s-form-group">\
                                        <input type="text" class="cl-s-form-control" id="qna-tel" name="qna_tel" data-type="tel" required="required" value="' + data['tel'] + '">\
                                        <label for="input" class="cl-s-control-label">전화번호</label>\
                                    </div>\
                                </div>\
                                ';
                            }
                        }
                        qna_privacy_str += '\
                                <div class="cl-s-checkbox">\
                                    <label>\
                                        <input type="checkbox" id="qna-btn-privacy" name="qna_btn_privacy">\
                                        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16"><path d="M13 0H3C1.3 0 0 1.3 0 3v10c0 1.7 1.3 3 3 3h10c1.7 0 3-1.3 3-3V3C16 1.3 14.7 0 13 0zM15 13c0 1.1-0.9 2-2 2H3c-1.1 0-2-0.9-2-2V3c0-1.1 0.9-2 2-2h10c1.1 0 2 0.9 2 2V13z"/></svg>\
                                        <svg class="active" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16"><path d="M13 0H3C1.34 0 0 1.34 0 3v10c0 1.66 1.34 3 3 3h10c1.66 0 3-1.34 3-3V3C16 1.34 14.66 0 13 0zM13.03 6.03l-5.5 5.5C7.38 11.68 7.19 11.75 7 11.75s-0.38-0.07-0.53-0.22l-3.5-3.5c-0.29-0.29-0.29-0.77 0-1.06s0.77-0.29 1.06 0L7 9.94l4.97-4.97c0.29-0.29 0.77-0.29 1.06 0S13.32 5.74 13.03 6.03z"/></svg>\
                                        <a href="javascript:;" class="qna-view-privacy privacy-toggle" data-view="#qna-privacy-textarea">개인정보 수집 및 이용</a>에 동의합니다.\
                                    </label>\
                                </div>\
                                <div class="qna-privacy-textarea hide" name="privacy_textarea" id="qna-privacy-textarea" style="display:none;">\
                                    ※ 비회원 서비스문의를 위한 개인정보 수집·이용 동의(필수)<br>\
                                    서비스 이용자의 개인정보를 수집하는 목적은 다음과 같습니다.\
                                    <table>\
                                        <colgroup>\
                                            <col width="25%">\
                                            <col width="45%">\
                                            <col width="30%">\
                                        </colgroup>\
                                        <thead>\
                                            <tr>\
                                                <th>수집목적</th>\
                                                <th>수집항목</th>\
                                                <th>이용기간</th>\
                                            </tr>\
                                        </thead>\
                                        <tbody>\
                                            <tr>\
                                                <td>문의 응대 및 서비스 개선</td>\
                                                <td>(필수) 이름, 이메일, 문의내용</td>\
                                                <td>문의 종료일로 5년</td>\
                                            </tr>\
                                        </tbody>\
                                    </table>\
                                    <br>\
                                    - 동의를 거부할 권리가 있으나, 동의거부에 따른 서비스 이용에 제한이 있을 수 있습니다.<br>\
                                    - 회사는 계약 및 서비스 이행을 위해 개인정보 처리업무를 위탁할 수 있으며, 개인정보처리방침에 그 내용을 고지합니다.<br>\
                                </div>\
                        ';
                    } else {
                        if(data['um_qna_fin'] == 'Y') {
                            qna_privacy_str += '\
                                <div class="cl-s-checkbox">\
                                    <label>\
                                        <input type="checkbox" id="qna-btn-email" name="answer_email" value="Y" ' + qna_answer_email_str + '>\
                                        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16"><path d="M13 0H3C1.3 0 0 1.3 0 3v10c0 1.7 1.3 3 3 3h10c1.7 0 3-1.3 3-3V3C16 1.3 14.7 0 13 0zM15 13c0 1.1-0.9 2-2 2H3c-1.1 0-2-0.9-2-2V3c0-1.1 0.9-2 2-2h10c1.1 0 2 0.9 2 2V13z"/></svg>\
                                        <svg class="active" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16"><path d="M13 0H3C1.34 0 0 1.34 0 3v10c0 1.66 1.34 3 3 3h10c1.66 0 3-1.34 3-3V3C16 1.34 14.66 0 13 0zM13.03 6.03l-5.5 5.5C7.38 11.68 7.19 11.75 7 11.75s-0.38-0.07-0.53-0.22l-3.5-3.5c-0.29-0.29-0.29-0.77 0-1.06s0.77-0.29 1.06 0L7 9.94l4.97-4.97c0.29-0.29 0.77-0.29 1.06 0S13.32 5.74 13.03 6.03z"/></svg>\
                                        이메일로 답변완료 알림 받기\
                                    </label>\
                                </div>\
                            ';
                            
                            if(data['talk_cnt'] > 0) { //alimtalk
                                qna_privacy_str += '\
                                <div class="cl-s-checkbox">\
                                    <label>\
                                        <input type="checkbox" id="qna-btn-alimtalk" name="answer_alimtalk" value="Y" ' + qna_answer_alimtalk_str + '>\
                                        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16"><path d="M13 0H3C1.3 0 0 1.3 0 3v10c0 1.7 1.3 3 3 3h10c1.7 0 3-1.3 3-3V3C16 1.3 14.7 0 13 0zM15 13c0 1.1-0.9 2-2 2H3c-1.1 0-2-0.9-2-2V3c0-1.1 0.9-2 2-2h10c1.1 0 2 0.9 2 2V13z"/></svg>\
                                        <svg class="active" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16"><path d="M13 0H3C1.34 0 0 1.34 0 3v10c0 1.66 1.34 3 3 3h10c1.66 0 3-1.34 3-3V3C16 1.34 14.66 0 13 0zM13.03 6.03l-5.5 5.5C7.38 11.68 7.19 11.75 7 11.75s-0.38-0.07-0.53-0.22l-3.5-3.5c-0.29-0.29-0.29-0.77 0-1.06s0.77-0.29 1.06 0L7 9.94l4.97-4.97c0.29-0.29 0.77-0.29 1.06 0S13.32 5.74 13.03 6.03z"/></svg>\
                                        알림톡으로 답변완료 알림 받기\
                                    </label>\
                                </div>\
                                ';
                            }
                        }
                    }
                    qna_privacy_str += '\
                        </div>\
                    '; //qna-privacy

                    var modal_str = '\
                        <div class="qna-body">\
                            <h5 class="product-title">' + data['ptitle'] + '</h5>\
                            ' + qna_writer_str + '\
                            <ul class="qna-content">\
                                <li>\
                                    <div class="cl-s-form-wrap">\
                                        <div class="cl-s-form-group">\
                                            <input type="text" class="cl-s-form-control" id="qna-title" name="title" required="required" maxlength="100" value="' + data['title'] + '">\
                                            <label for="input" class="cl-s-control-label">제목</label>\
                                        </div>\
                                    </div>\
                                </li>\
                                <li>\
                                    <div class="cl-s-form-wrap">\
                                        <div class="cl-s-form-group input-label-hide">\
                                            <textarea type="text" class="cl-s-form-control" id="qna-str" name="qna" maxlength="500" required="required">' + data['qna'] + '</textarea>\
                                            <label for="input" class="cl-s-control-label">자세한 내용을 적어주세요. (500자 이내)</label>\
                                        </div>\
                                    </div>\
                                </li>\
                                <li class="last clearfix">\
                                    <div class="qna-secret">\
                                        <div class="secret cl-s-checkbox">\
                                            <label>\
                                                <input type="checkbox" id="secret-checkbox" name="secret" value="Y" ' + qna_secret_str + '>\
                                                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16"><path d="M13 0H3C1.3 0 0 1.3 0 3v10c0 1.7 1.3 3 3 3h10c1.7 0 3-1.3 3-3V3C16 1.3 14.7 0 13 0zM15 13c0 1.1-0.9 2-2 2H3c-1.1 0-2-0.9-2-2V3c0-1.1 0.9-2 2-2h10c1.1 0 2 0.9 2 2V13z"/></svg>\
                                                <svg class="active" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16"><path d="M13 0H3C1.34 0 0 1.34 0 3v10c0 1.66 1.34 3 3 3h10c1.66 0 3-1.34 3-3V3C16 1.34 14.66 0 13 0zM13.03 6.03l-5.5 5.5C7.38 11.68 7.19 11.75 7 11.75s-0.38-0.07-0.53-0.22l-3.5-3.5c-0.29-0.29-0.29-0.77 0-1.06s0.77-0.29 1.06 0L7 9.94l4.97-4.97c0.29-0.29 0.77-0.29 1.06 0S13.32 5.74 13.03 6.03z"/></svg>\
                                                비밀글\
                                            </label>\
                                        </div>\
                                    </div>\
                                    <div class="cl-s-files qna-files f-left">\
                                        <input id="qna-file" type="file" name="files[]" accept="image/jpeg,image/gif,image/png" multiple data-sid="' + sid + '" data-uid=\"' + data['um_id'] + '\" data-seq=\"'+seq+'\">\
                                        <label class="cl-s-file-update qna-file-update clearfix"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" width="20" height="20"><path d="M0 0v20h20V0H0zM19 1v11.3l-3-3 -4 4 -6-6 -5 5V1H19zM1 19v-5.3l5-5 6 6 4-4 3 3V19H1z"/><circle cx="14.5" cy="5.5" r="1.5"/></svg> <span>사진</span></label>\
                                        <ul class="cl-s-files-list qna-files-list clearfix">\
                                            ' + qna_files_str + '\
                                        </ul>\
                                    </div>\
                                </li>\
                            </ul>\
                            ' + qna_privacy_str + '\
                        </div>\
                    ';


                    $('.flat-modal .modal').modal('hide');
                    var eqnaModal = $(this).showModalFlat('문의 작성', modal_str,true,true,function () {

                        var error_cnt = 0,
                            error_str = '',
                            input_data = new Object();

                        $('.cl-s-form-control').each(function(idx, v) {
                            error_str = '';
                            if($(v).val().trim().length == 0) {
                                if(!$('input[name="answer_email"]').is(':checked') && $(v).attr('name') == 'qna_email') return;
                                if(!$('input[name="answer_alimtalk"]').is(':checked') && $(v).attr('name') == 'qna_tel') return;
                                $(v).closest('.cl-s-form-wrap').addClass('empty');
                                error_str = '필수항목을 입력해주세요.';
                                error_cnt++;
                                if(error_cnt == 1) {
                                    alert(error_str);
                                    $(v).focus();
                                    return true;
                                }
                            } else {
                                $(v).closest('.cl-s-form-wrap').removeClass('empty');
                                var key = $(v).attr('name'),
                                    val = $(v).val().trim(),
                                    passEmoji = ($.inArray(key,['title','qna']) > -1) ? true : false;

                                if(!passEmoji && checkEmojis(val)) error_str = $.lang[LANG]['config.unable.emoji'];
                                // else if(typeof regexp[key] != "undefined" && !regexp[key].test(val)) error_str = $.lang[LANG]['siteum.regexp.check.'+key];

                                if(error_str && error_str.length > 0) {
                                    error_cnt ++;
                                    if(error_cnt == 1) $(v).focus();

                                    $(v).closest('.cl-s-form-wrap').addClass('error');
                                    if($(v).closest('.cl-s-form-group').find('.cl-s-control-label.error').length > 0) {
                                        $(v).closest('.cl-s-form-group').find('.cl-s-control-label.error').html(error_str);
                                    } else {
                                        $(v).closest('.cl-s-form-group input').after('<label class="cl-s-control-label error">' + error_str + '</label>');
                                    }
                                } else {
                                    $(v).closest('.cl-s-form-wrap').removeClass('error');
                                    $(v).closest('.cl-s-form-group').find('.cl-s-control-label.error').remove();
                                    input_data[key] = $(v).val().trim();
                                }
                            }

                        });


                        if(error_cnt > 0) {
                            // alert(error_str);
                            return false;
                        }
                        
                        if(status != 'U') {
                            if(!$('#qna-btn-privacy').prop('checked')) {
                                $("#qna-btn-privacy").addClass('error');
                                alert('개인정보 수집 및 이용 동의에 체크해 주세요.');
                                return false;
                            }

                            if(!$('input[name="answer_email"]').is(':checked')) {
                                input_data['qna_email'] = '';
                            } else {
                                var regexp = {
                                    qna_email : /^[a-zA-Z0-9+-\_.]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/i,
                                };
                                if(typeof regexp['qna_email'] != "undefined" && !regexp['qna_email'].test(input_data['qna_email'])) {
                                    alert($.lang[LANG]['siteum.regexp.check.email']);
                                    input_data['qna_email'] = '';
                                    $('#qna-email').closest('.cl-s-form-wrap').addClass('error');
                                    return false;
                                }
                            }

                            if(!$('input[name="answer_alimtalk"]').is(':checked')) {
                                input_data['qna_tel'] = '';
                            } else {
                                if(input_data['qna_tel'].length > 0 && (input_data['qna_tel'].length < 10 || input_data['qna_tel'].length > 15)) {
                                    alert('올바르지 않은 번호 양식입니다.\n번호를 다시 확인해 주세요.');
                                    input_data['qna_tel'] = '';
                                    $('#qna-tel').closest('.cl-s-form-wrap').addClass('error');
                                    return false;
                                }
                            }
                        }

                        if($('.qna-files-list').children('li').length > 0) {
                            var qna_files = '';
                            var qna_files_orig = '';
                            $('.qna-files-list').children('li').each(function() {
                                if(qna_files != '')  qna_files +='||';
                                qna_files += $(this).find('input[name="qna_image[]"]').val();
                                if(qna_files_orig != '')  qna_files_orig +='||';
                                qna_files_orig += $(this).find('input[name="qna_image_orig[]"]').val();
                            });
                        }
                        input_data['qna_image'] = (qna_files) ? qna_files : '';
                        input_data['qna_image_orig'] = (qna_files_orig) ? qna_files_orig : '';
                        input_data['secret'] = ($('#secret-checkbox').prop('checked')) ? 'Y' : '';
                        input_data['answer_email'] = ($('input[name="answer_email"]').prop('checked')) ? 'Y' : 'N';
                        input_data['answer_alimtalk'] = ($('input[name="answer_alimtalk"]').prop('checked')) ? 'Y' : 'N';

                        var qna_status = { new:'S', edit:'E' },
                            page_type = (property.VIEW) ? 'product' : '';
                            
                        if($('.cl-s-mypage').length > 0) page_type = 'mypage';
                        else if($('.cl-s-nonmember-payment').length > 0) page_type = 'no_member';

                        input_data['sid'] = sid;
                        input_data['page_mode'] = page_type;
                        input_data['qna_seq'] = (seq > 0) ? seq : '';
                        input_data['qna_type'] = 'P';
                        input_data['product_number'] = pnum;
                        input_data['order_number'] = onum;
                        input_data['status'] = qna_status[mode];
                        input_data['mb_status'] = status;
                        input_data['qna_page'] = (property.VIEW) ? property.PAGE : '';
                        
                        $('.ok-button-dialog').prop('disabled', true).addClass('spinner');
                        $.ajax({
                            url: '/_qna_update',
                            type: 'post',
                            data: input_data,
                            async: true,
                            cache: false,
                            success: function(data) {
                                if(typeof data.error != 'undefined') {
                                    alert(data.error);
                                    return false;
                                }
                                location.reload();
                            },
                            error: function(request,status,error) {
                                console.log('code:'+request.status+'\n'+'message:'+request.responseText+'\n'+'error:'+error);
                                return false;
                            }

                        });

                    },'close','등록하기','cl-s-product-qna-edit cl-modal cl-s-btn cover', true, '', function() {
                        $('.cl-s-product-qna-edit .cl-s-form-group').on('click',function(e) {
                            if($(e.target).hasClass('cl-s-form-group')) {
                                $(e.target).find('.cl-s-form-control:not([type=hidden])').focus();
                            }
                        });

                        $('.cl-s-product-qna-edit .cl-s-form-control').on({
                            focus: function(e) {
                                $(this).closest('.cl-s-form-wrap').addClass('active');
                            },
                            blur: function(e) {
                                var type = $(this).attr('data-type'),
                                    // regexp = {
                                    //     email : /^[a-zA-Z0-9+-\_.]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/i
                                    // },
                                    // checkRegexp = (typeof type != 'undefined' && typeof regexp[type] != 'undefined') ? true : false,
                                    passEmoji = ($.inArray($(this).attr('name'),['title','qna']) > -1) ? true : false,
                                    error_str = '',
                                    val = $(this).val().trim();

                                $(this).closest('.cl-s-form-wrap').removeClass('active');
                                if(val.length == 0) {
                                    $(this).closest('.cl-s-form-wrap').removeClass('error').addClass('empty');
                                    $(this).closest('.cl-s-form-wrap').find('.cl-s-control-label.error').remove();
                                    return false;
                                } else if(!passEmoji && checkEmojis(val)) error_str = $.lang[LANG]['config.unable.emoji'];
                                // else if(checkRegexp && !regexp[type].test(val)) error_str = $.lang[LANG]['siteum.regexp.check.'+type];

                                $(this).closest('.cl-s-form-wrap').removeClass('empty');
                                if(error_str.length > 0) {
                                    $(this).closest('.cl-s-form-wrap').addClass('error');
                                    if($(this).parent().find('.cl-s-control-label.error').length > 0) {
                                        $(this).parent().find('.cl-s-control-label.error').html(error_str);
                                    } else {
                                        $(this).after('<label for="input" class="cl-s-control-label error">'+error_str+'</label>');
                                    }
                                    return false;
                                } else {
                                    $(this).closest('.cl-s-form-wrap').removeClass('error');
                                    $(this).closest('.cl-s-form-wrap').find('.cl-s-control-label.error').remove();
                                }

                            }
                        });

                        $('.cl-s-product-qna-edit #qna-tel').on('keyup', function(e) {
                            var txt = $(this).val();
                            var match = txt.match(/[0-9]+/g);
                            $(this).val(match);
                        });

                        $('.cl-s-product-qna-edit #qna-btn-privacy').on('change', function(e) {
                            if($(this).prop('checked')) $(this).removeClass('error');
                            else $(this).addClass('error');
                        });

                        $(document).on('click', '.cl-s-product-qna-edit .qna-img-close', {mode: 'qna'}, deleteReviewQnaImg);

                        $('.cl-s-product-qna-edit .qna-file-update').on('click', function () {
                            $("#qna-file").click();
                        });

                        $('.cl-s-product-qna-edit #qna-file').on('click', {mode: 'qna'}, uploadReviewQnaImg);

                        $('label.privacy-toggle').on('change', function(e) {
                            var $toggle = $($(this).attr('data-view'));
                            if ($(this).find('input[type="checkbox"]').is(':checked')) {
                                $toggle.removeClass('hide');
                                $toggle.slideDown(300);
                            } else {
                                $toggle.slideUp(300, function() {
                                    $toggle.addClass('hide');
                                });
                            }
                        });

                        $('a.privacy-toggle').on('click', function(e) {
                            e.preventDefault();
                            var $toggle = $($(this).attr('data-view'));
                            if ($toggle.hasClass('hide')) {
                                $toggle.removeClass('hide');
                                $toggle.slideDown(300);
                            } else {
                                $toggle.slideUp(300, function() {
                                    $toggle.addClass('hide');
                                });
                            }
                        });

                    }, function(){
                        if(qna_files_str.length === 0){
                            if($('.cl-s-product-qna-edit .qna-img-close').length > 0){
                                $.each($('.cl-s-product-qna-edit .qna-img-close'), function(){
                                    $(this).trigger('click');
                                });
                            }
                        }
                    });

                },
                error: function(request,status,error) {
                    console.log('code:'+request.status+'\n'+'message:'+request.responseText+'\n'+'error:'+error);
                    return false;
                }
            });

        },
        orderReceiptModal: function(sid, ogroup, refund) { 

            $.post('/_check_receipt', { sid:sid, order_group:ogroup, mode:'default', refund : refund }, function(data) {

                if(typeof data.error != 'undefined' && data.error) {
                    $(this).showModalFlat('ERROR', data.error, true, false, '', 'ok');
                    return false;
                }

                var d_price = (typeof data.r.delivery_price != 'undefined' && data.r.delivery_price) ? data.r.delivery_price : 0,
                    d_price_str = number_format(d_price) + ' 원',
                    o_list_cnt = data.r.list.length,
                    o_org_total = 0,
                    o_total = 0;

                var orm_html = '\
                    <div class="receipt-wrap">\
                        <table>\
                            <colgroup>\
                                <col width="*" />\
                                <col width="120px" />\
                                <col width="100px" />\
                            </colgroup>\
                            \
                            <thead>\
                                <tr>\
                                    <th>상품정보</th>\
                                    <th>상품가격</th>\
                                    <th>배송비<span class="visible-xs"> ' + d_price_str + '</span></th>\
                                </tr>\
                            </thead>\
                            <tbody>\
                ';

                var refund_count = 0, list_count = 0;
                $.each(data.r.list, function(i, val) {
                    if(refund) {
                        if(val['d_status'] == 'CY' || val['d_status'] == 'RY') ;
                        else {
                            return true;
                        }
                    }

                    var option_name    = (!$.isEmptyObject(val['option_list']) && val['option_list']['option_name']) ? val['option_list']['option_name'] : '',
                        option_type = (val['option_list']['option_type']=='A') ? '추가옵션' : '옵션',
                        option_str     = '';
                    if(val['option_list']['option_type']=='A' && val['option_list']['option_group']) {
                        option_type = option_type + ' : ' + val['option_list']['option_group'];
                    }
                    if(option_name && option_name!='noneOption') {
                        option_str     = (val['option_list']['option_text_str']) ? '<span>'+option_type+' : ' + option_name + '/' + val['option_list']['option_text_str'] + '</span>' : '<span>'+option_type+' : ' + option_name + '</span>';
                    } else {
                        option_str     = (val['option_list']['option_text_str']) ? '<span>'+option_type+' : ' + val['option_list']['option_text_str'] + '</span>' : '';
                    }
                    var checkSale = (typeof val['option_list']['sale_price'] != "undefined" && val['option_list']['sale_price']) ? true : false,
                        oi_org_price = (checkSale) ? val['option_list']['sale_price'] : val['option_list']['price'],
                        oi_price     = val['option_list']['price'],
                        oi_quantity  = val['option_list']['quantity'],
                        oi_sum       = oi_price * oi_quantity,
                        rowspan = 0;

                    if(refund) {
                        rowspan = data.r.refund;
                    } else {
                        rowspan = o_list_cnt;
                    }
                    o_org_total += (oi_org_price * oi_quantity);
                    o_total += oi_sum;

                    orm_html += '\
                                <tr class="or-grid">\
                                    <td class="mp-info">\
                                        <div class="cl-s-product-jumbotron clearfix">\
                                            <div class="cl-s-product-thumb">\
                                                <img src="' + val["pimg"] + '" alt="' + val["pname"] + '" class="img-responsive"/>\
                                            </div>\
                                            <div class="cl-s-product-info">\
                                                <h5 class="cl-s-product-title">' + val["pname"] + '</h5>\
                                                <div class="option-str">\
                                                    <div>\
                                                        <span class="visible-xs option-price">' + number_format(oi_sum) + ' 원</span>\
                                                        ' + option_str + '\
                                                        <span>' + oi_quantity + '개</span>\
                                                    </div>';
                                        if(val["etc_info"]) {
                                            orm_html += '\
                                                    <div>선택일자 : '+val["etc_info"]+'</div>';
                                        }
                                        orm_html += '\
                                                </div>\
                                            </div>\
                                        </div>\
                                    </td>\
                                    <td>' + number_format(oi_sum) + ' 원</td>\
                    ';

                    if(list_count == 0) orm_html += '<td rowspan="' + ((rowspan) ? rowspan : '') + '">' + d_price_str + '</td>';
                    list_count++;

                    orm_html += '\
                                </tr>\
                    ';

                });

                orm_html += '\
                            </tbody> \
                        </table>\
                        <p class="description">현금영수증은 발급 완료된 주문건에 한해 조회 및 출력이 가능하며, 구매확정일 기준으로 발급됩니다.<br>신용카드 매출 전표는 결제완료 시 자동 발급되며, 결제완료 후 확인 및 출력이 가능합니다.\
                ';

                if(data.r.class_cd == 'PAKM') {
                    orm_html += '\
                    <br>카카오페이머니 결제 건은 카카오페이 APP에서 전표발행이 제공됩니다.\
                    ';
                }

                orm_html += '</p>\
                ';


                orm_html += '\
                        <div class="receipt-btn-box">\
                ';
                if(data.r.pay_method != '무통장 입금' && data.r.class_cd != 'PAKM' && data.r.pay_method != '포인트 결제') {
                    orm_html += '<span class="cl-s-btn cl-s-btn-12 cl-s-btn-primary btn-card-slip" data-tno="' + data.r.tno + '">카드전표</span>';
                }
                orm_html += '\
                            <span class="cl-s-btn cl-s-btn-12 cl-s-btn-primary btn-receipt-details ' + ((refund == true) ? 'refund' : '') + '">' + ((refund == true) ? '환불영수증' : '구매영수증') + '</span>\
                        </div>\
                        <span class="cl-s-btn cl-s-btn-12 cl-s-btn-default btn-order-receipt-close">닫기</span>\
                    </div">\
                ';
                var title = (refund) ? '환불 영수증 발급내역' : '영수증 발급내역';
                var orModal = $(this).showModalFlat(title, orm_html, true, false, '', 'close', '', 'cl-s-receipt cl-modal cover', false, '', function() {
                    $('.btn-order-receipt-close').on('click', function() {
                        orModal.modal('hide');
                    });

                    $('.btn-card-slip').on('click', function() {
                        var tno = $(this).data('tno');
                        if(data.r.class_cd == 'PANP') {
                            window.open('https://new-m.pay.naver.com');
                        } else if(isNaN(tno)) { // nicepay
                            window.open('https://npg.nicepay.co.kr/issue/IssueLoader.do?type=0&TID='+tno, '', 'width=800, height=700, toolbar=no, menubar=no, scrollbars=no, resizable=yes');
                        } else { // kcp
                            // window.open('https://www.kcp.co.kr/center.paysearch.do', '', 'width=1000,height=500,scrollbars=yes');
                            window.open('https://www.kcp.co.kr/viewPaymentParent/viewPayment', '', 'width=1200,height=860,scrollbars=yes');
                        }
                        
                    });

                    $('.btn-receipt-details').on('click', function() {
                        var refund = ($(this).hasClass('refund')) ? true : false;
                        $.shoppingmall.orderReceiptDetailModal(sid, ogroup, refund);
                    });

                });

            }, 'json');

        },
        orderReceiptDetailModal: function(sid, ogroup, refund) {

            $.post('/_check_receipt', { sid:sid, order_group:ogroup, mode:'detail', refund : refund }, function(data) {

                if(typeof data.error != 'undefined' && data.error) {
                    $(this).showModalFlat('ERROR', data.error, true, false, '', 'ok');
                    return false;
                }
                var ordm_html = '\
                    <div class="receipt-wrap">\
                        <table>\
                            <colgroup>\
                                <col width="25%" />\
                                <col width="75%" />\
                            </colgroup>\
                            \
                            <tbody id="receipt-list">\
                                <tr>\
                                    <td><span>주문번호</span><br>ORDER NO.</td>\
                                    <td>' + ogroup + '</td>\
                                </tr>';
                if(refund) {
                    ordm_html+= '\
                                <tr>\
                                    <td><span>환불일자</span><br>REFUND DATE</td>\
                                    <td>' + data.pay_info.reg_date + '</td>\
                                </tr>\
                    ';
                } else {
                    ordm_html+= '\
                                <tr>\
                                    <td><span>주문날짜</span><br>TRANS DATE</td>\
                                    <td>' + data.pay_info.reg_date + '</td>\
                                </tr>\
                    ';
                }
                ordm_html+= '\
                                <tr>\
                                    <td><span>상품명</span><br>DESCRIPTION</td>\
                                    <td>' + data.pay_info.product_name + '</td>\
                                </tr>\
                                <tr>\
                                    <td><span>합계</span><br>TOTAL</td>\
                                    <td><span>'+number_format(data.pay_info.payment)+'</span> 원</td>\
                                </tr>\
                                <tr>\
                                    <td><span>회사명</span><br>COMPANY NAME</td>\
                                    <td>' + data.setting.b_name + '</td>\
                                </tr>\
                                <tr>\
                                    <td><span>대표자</span><br>MASTER</td>\
                                    <td>' + data.setting.b_rep + '</td>\
                                </tr>\
                                <tr>\
                                    <td><span>사업자등록번호</span><br>BUSINESS NO.</td>\
                                    <td>' + data.setting.b_number + '</td>\
                                </tr>\
                                <tr>\
                                    <td><span>회사주소</span><br>ADDRESS</td>\
                                    <td>' + data.setting.b_addr + '</td>\
                                </tr>\
                                <tr>\
                                    <td><span>문의전화</span><br>TEL</td>\
                                    <td>' + data.setting.b_tel + '</td>\
                                </tr>\
                                <tr>\
                                    <td><span>서명</span><br>SIGNATUE</td>\
                                    <td>' + data.pay_info.buyr_name + '</td>\
                                </tr>\
                            </tbody>\
                        </table>\
                        <div class="additional-box">구매 영수증은 세금계산서 등 증빙서류로 활용할 수 없습니다.</div>\
                    </div>\
                ';
                var title = (refund) ? '환불영수증' : '구매영수증';
                var ordModal = $(this).showModalFlat(title, ordm_html, true, true, function() {

                    $.shoppingmall.printModal(".cl-s-receipt-view");

                }, 'close', '출력', 'cl-s-receipt-view cl-modal cover', false);


            }, 'json');
        },
        printModal: function(modalEL) {
            var popupWindow = window.open("", "printPopup", "_blank" );

            var style = $('#cl_shopping').attr('href');

            popupWindow.document.write('<head>');
            popupWindow.document.write($('head').html());
            popupWindow.document.write('<link rel="stylesheet" href="'+style+'">');
            popupWindow.document.write('<style>');
            popupWindow.document.write($('#el_0css').html());
            popupWindow.document.write('.close-button-dialog, .ok-button-dialog {display:none !important;}');
            popupWindow.document.write('.cl-mobile-btn, button.close {display:none !important;}');
            popupWindow.document.write('.modal-dialog {width:700px !important;max-width:700px !important;}');
            popupWindow.document.write('</style>');
            popupWindow.document.write('</head>');

            var $table = $(modalEL);
     
            popupWindow.document.write('<body>');
            popupWindow.document.write('<div style="display:block;" class="flat-modal cl-flat-modal">');
            popupWindow.document.write($table.parent().parent().html());
            popupWindow.document.write('</div></body>');

            popupWindow.document.close();

            setTimeout(function () {
                popupWindow.print();
            }, 1500);
        },
        orderDownloadModal: function(sid, pnum, onum) {

            $.post('/_check_download', { sid:sid, pnum:pnum, onum:onum }, function(data) {
                
                if(typeof data.error != "undefined" && data.error) {
                    $(this).showModalFlat('ERROR', data.error, true, false, '', 'close');
                    return false;
                }

                var cnacelBtn = $('.mp-table[data-onum='+ onum +']').find('button[data-fn="orderCancel"]');
                cnacelBtn.remove();

                var download_href = data.r.url,
                    download_name = data.r.name,
                    download_real_name = data.r.real_name,
                    download_count = data.r.count;

                var download_url = new getLocation(download_href),
                    file_name = encodeURIComponent(download_name),
                    file_real_name = encodeURIComponent(download_real_name),
                    go = '/down?n=' + file_real_name + '&s=' + (download_url.pathname).replace('/cr-resource/forum/','').replace('/','&f='),
                    temp_el = '<a href="'+go+'" target="_blank" download id="cl-download-a"></a>';

                $('body').append(temp_el);
                document.querySelector('#cl-download-a').click();
                $('#cl-download-a').remove();
                
                if(download_count > 0) {
                    $('.mp-table[data-onum=' + onum + ']').find('.download-str span').text(download_count);
                } else {
                    $('.mp-table[data-onum=' + onum + ']').find('.download-str').html('<div class="cl-red">다운로드 기한이 지났거나<br>다운로드 횟수를 모두 사용하였습니다.</div>');
                    $('.mp-table[data-onum=' + onum + ']').find('button[data-fn="orderDownload"]').addClass('disabled');
                }

            }, 'json');
        },
    }


    $.quickbasket = {
        data: {},
        dataReset: function(){
            $.quickbasket.data = {}
        },
        init: function (sid, pid, pnum) {
            $.ajax({
                url: '/_quickbasket',
                type: 'post',
                data: { 'sid':sid, 'pid':pid, 'pnum':pnum },
                async: false,
                cache: false,
                success: function (_data) {
                    var data = JSON.parse(_data);

                    if(typeof data.error != 'undefined' & data.error) {
                        var error_str = (data.error == 'error-none-unique') ? '장바구니에 담기는 도중 오류가 발생했습니다.\n잠시후 다시시도 해주세요.\n같은 현상이 지속된다면 고객센터로 문의해주세요.' : data.error;
                        $(this).showModalFlat('INFORMATION', error_str, false, false, '', '', '', 'cl-cmmodal cl-s-btn w560 cl-p0');
                        return false;
                    }

                    $.quickbasket.dataReset();
                    var quickbasket_str = '';
                    if(typeof data.option_data != 'undefined' && data.option_data) {
                        // product has options
                        // var check_options_merge = data.option_data.checkOptionsMerge,
                        var qbo_total_cnt = 0, 
                            qbo_total_price = 0,
                            qbo_select_box = '';

                        $.quickbasket.data = data.option_data;
                        $.quickbasket.data.list.normal_md5 = {};
                        if(data.option_data.checkNomalOptionMixed) {
                            $.each(data.option_data.list.normal_org, function(a,b) {
                                var md5 = '';
                                switch(data.option_data.options_type) {
                                    case '1': md5 = clmd5.hex_md5(b.option_group + ' / ' + b.option_name); break;
                                    case '2': md5 = clmd5.hex_md5(b.option_mix2 + ' / ' + b.option_name); break;
                                    case '3': md5 = clmd5.hex_md5(b.option_mix2 + ' / ' + b.option_mix3 + ' / ' + b.option_name); break;
                                    default: break;
                                }
                                $.quickbasket.data.list.normal_md5[md5] = b;
                            });
                        }

                        $.each(data.option_data.list, function(o_key, o_groups) {
                            if($.inArray(o_key, ['normal_org','normal_md5']) > -1) return true;

                            var check_empty = (o_groups.length == 1 && o_groups[0]['arr'].length == 0) ? true : false;
                            if(!check_empty) {
                                $.each(o_groups, function(og_idx, og_obj) {
                                    if(o_key == 'additional' && og_idx == 0) quickbasket_str += (data.option_data.checkFooterStatus[2] == 'false') ? '' : '<p class="option-title">추가옵션</p>';
                                    var qbo_wrap = '',
                                        qbo_box = '',
                                        qbo_noneoption_val = '';
                                    
                                    if(og_obj['arr'].length == 0 && (og_obj['value'].length == 0 || og_obj['title'] === null)) return true;
                                    $.each(og_obj['arr'], function(og_idx2,og_obj2) {
                                        var div_property = '';
                                        if(o_key != 'text'  && !og_obj2.soldout) {
                                            div_property += 'onclick="$.quickbasket.pdOptionPick(this, \'' + data.option_data.product_price + '\')" ';
                                            // div_property += 'data-status="' + data.option_data.product_state + '" ';
                                            div_property += 'data-status="normal" ';
                                            div_property += (o_key == 'additional') ? 'data-option_type="' + og_obj2.option_type + '" ' : 'data-type="' + data.option_data.options_type + '" ';
                                            div_property += 'data-idx="' + (og_idx2-1) + '" ';
                                            if(o_key == 'normal') div_property += 'data-option-index="' + og_idx + '" ';
                                            div_property += 'data-option-price="' + og_obj2.option_price + '" ';
                                        }
                                        var option_str = {
                                            'div_class': (og_obj2.soldout) ? 'class="sold-out"' : '',
                                            'div_property': div_property,
                                            'span1': (og_obj2.soldout) ? '<span class="text-d-lt">' : '',
                                            'span2': (og_obj2.soldout) ? '</span>' : '',
                                            'seq': (og_obj2.soldout) ? '' : 'data-option-seq="'+og_obj2.option_seq+'"',
                                            'soldout': (og_obj2.soldout) ? '<label>품절</label>' : '',
                                        }

                                        if(og_obj2.option_name == 'noneOption') {

                                            if(o_key == 'text') {
                                                qbo_noneoption_val = (data.option_data.checkNoneTextOption) ? og_obj2.option_group + ' / ' + og_obj2.val : '';
                                            } else if(o_key == 'additional') {
                                                // var type = '';
                                                // qbo_selectbox = $.quickbasket.pdOptionBoxHtml(data.option_data.product_price, type, data.option_data.product_state, og_obj2.option_type == null ? '' : og_obj2.option_type, o_obj.val.split('||'), '');s
                                                var val_arr = og_obj2.val.split('||');
                                                if(data.option_data.checkOptionBox) {
                                                    if(data.option_data.checkFooterStatus[1] != 'true') {
                                                        qbo_select_box = '\
                                                            <div class="option-count-box">\
                                                                <input type="hidden" name="option_price[]" value="' + data.option_data.product_price + '">\
                                                                <input type="hidden" name="option_seq[]" class="option_seq" value="'+ val_arr[3] +'">\
                                                                <input type="hidden" class="total-quantity" value="'+ val_arr[2] +'">\
                                                                <input type="hidden" name="option_name[]" value="'+ val_arr[0] +'">\
                                                                <input type="hidden" name="option_type[]" value="' + ((og_obj2.option_type == null) ? '' : og_obj2.option_type) + '">\
                                                                <input type="hidden" name="option_text[]" value="">\
                                                                <div class="box-option-row">\
                                                                    <div class="box-option-name">' + data.option_data.product_title + '</div>\
                                                                </div>\
                                                                <div class="box-option-row">\
                                                                    <div class="box-option-price"><span class="option-price">' + addCommas(data.option_data.product_price) + '</span>원</div>\
                                                                    <div class="box-option-count"><div class="form-group"><span class="min"><svg viewBox="0 0 11 11" width="11" height="11"><rect y="5" width="11" height="1"></rect></svg></span><input type="text" class="option-normal-price" value="1" numberonly="true" name="option_count[]"><span class="plus"><svg viewBox="0 0 11 11" width="11" height="11"><polygon points="6 5 6 0 5 0 5 5 0 5 0 6 5 6 5 11 6 11 6 6 11 6 11 5 "></polygon></svg></span></div></div>\
                                                                </div>\
                                                            </div>\
                                                        ';
                                                        
                                                        qbo_total_cnt++;
                                                        qbo_total_price = data.option_data.product_price;
                                                    }
                                                } else {
                                                    qbo_select_box = '<input type="hidden" class="noneoption_seq" value="'+ og_obj2.option_seq +'">';
                                                }
                                            }

                                        } else {
                                            if(o_key == 'text') {
                                                qbo_box += '\
                                                                <div class="cl-s-option-text" data-selected_option="' + ((data.option_data.options_type == 'TR') ? 'Y' : 'N') + '" data-status="' + data.option_data.product_state + '" >\
                                                                    <input type="text" placeholder="' + og_obj2.option_name + '" data-val="' + og_obj2.option_seq + '" data-status="' + data.option_data.product_state + '" data-option_type="T" maxlength="100" readonly>\
                                                                </div>\
                                                ';
                                            } else {
                                                qbo_box += '\
                                                                <div class="' + option_str.div_class + '" data-val="' + og_obj2.val + '" ' + option_str.div_property + '>\
                                                                    ' + option_str.span1 + '\
                                                                        <span class="number">' + og_obj2.option_number + '.</span>\
                                                                        <div class="option-name" ' + option_str.seq + '>' + og_obj2.option_name + option_str.soldout + '</div>\
                                                                        <span class="price">' + og_obj2.option_price_str + ' 원</span>\
                                                                    ' + option_str.span2 + '\
                                                                </div>\
                                                ';
                                            }
                                        }
                                    });

                                    var qbo_key_str = (o_key == 'additional') ? 'addt' : o_key,
                                        qbo_required = (o_key == 'normal') ? 'option-required' : '',
                                        qbo_disabled = (o_key == 'normal' && og_idx > 0) ? 'option-disabled' : '',
                                        qbo_def_index = (o_key == 'normal') ? 'data-def-index="' + og_idx + '"' : '';

                                    if(o_key == 'text') {
                                        if(data.option_data.checkFooterStatus[1] == 'true') {
                                            qbo_wrap = '\
                                                <div id="selected-product-option" data-val="' + qbo_noneoption_val + '" data-selected_option="" data-status=""></div>\
                                                <div class="text-option-box">\
                                                    ' + qbo_box + '\
                                                </div>\
                                            ';
                                            qbo_wrap += (qbo_box == '') ? '' : '\
                                                <div class="text-center text-option-btn-box">\
                                                    <div onclick="$.quickbasket.pdTextOptionPick(this, \'' + data.option_data.product_price + '\', \'' + ((data.option_data.checkOnlyTextOption) ? 'T' : '') + '\',' + data.option_data.options_type + ')" class="btn text-center hand text-option-btn disabled">입력한 옵션으로 선택</div>\
                                                </div>\
                                            ';
                                        }
                                    } else {
                                        qbo_wrap = (
                                            (o_key == 'normal' && data.option_data.checkFooterStatus[0] == 'false') ||
                                            (o_key == 'additional' && data.option_data.checkFooterStatus[2] == 'false')
                                        ) ? '' : '\
                                            <div class="select-box">\
                                                <div class="selected-option ' + ((o_key == 'normal' && og_idx > 0) ? 'ex' : '' ) + '" id="selected-product' + ((o_key == 'normal') ? '' : qbo_key_str) + '-option"  data-val="" data-selected_option="" data-status="">\
                                                    <span class="selected-option-text">' + og_obj['title'] + '</span>\
                                                    <span class="selected-option-title hide">' + og_obj['title'] + '</span>\
                                                    ' + clSVG('caret',8,4,false) + '\
                                                </div>\
                                            </div>\
                                            <div class="option-box product-option-box" style="display: none;">\
                                                ' + qbo_box + '\
                                            </div>\
                                        ';
                                    }

                                    quickbasket_str += (qbo_wrap == '') ? '' : '\
                                        <div class="cl-s-option-selector cl-s-' + qbo_key_str + '-option-selector ' + qbo_required + ' ' + qbo_disabled + '" ' + qbo_def_index + '>\
                                            ' + qbo_wrap + '\
                                        </div>\
                                    ';
                                });

                            }
                        });

                        quickbasket_str += '\
                            <div class="option-select-box">\
                                ' + qbo_select_box + '\
                            </div>\
                            <div class="total-price-box">\
                                <span class="panel-total-title">총 상품 금액</span>\
                                <span class="panel-total-cnt">총 수량 <span class="total-cnt">' + qbo_total_cnt + '</span>개 </span>\
                                <span class="panel-total-price"><span class="total-price">' + addCommas(qbo_total_price) + '</span>원</span>\
                            </div>\
                        ';

                        var quickBasketOptionModal = $(this).showModalFlat($.lang[LANG]['gallery.sh.quickbasket.option'], quickbasket_str, true, true, function() {

                            if($('.cl-modal-check-quantity').length > 0) return false;

                            var checkEmpty = false;
                            quickBasketOptionModal.find('.option-normal-price').each(function() {
                                if($(this).val() == '' || $(this).val() < 1) {
                                    checkEmpty = true;
                                    $(this).val(1);
                                }
                            });
                            if(checkEmpty) {
                                if($('.cl-modal-check-quantity').length == 0) $.quickbasket.alertModal('ERROR','최소 구매 수량은 1개 입니다.','cl-modal-check-quantity');
                                return false;
                            }

                            $.quickbasket.setKeepShopping(sid,RENDER.b.PAGE,pid,pnum);
                            var optionName = quickBasketOptionModal.find('input[name="option_name[]"]'),
                                optionPrice = quickBasketOptionModal.find('input[name="option_price[]"]'),
                                optionCount = quickBasketOptionModal.find('input[name="option_count[]"]'),
                                optionSeq = quickBasketOptionModal.find('.option_seq'),
                                optionText = quickBasketOptionModal.find('input[name="option_text[]"]'),
                                optionType = quickBasketOptionModal.find('input[name="option_type[]"]'),
                                etcStartDate = quickBasketOptionModal.find('input[name="etc_start_date[]"]'),
                                etcEndDate = quickBasketOptionModal.find('input[name="etc_end_date[]"]'),
                                oCnt = quickBasketOptionModal.find('input[name="option_name[]"]').length,
                                state = data.option_data.state,
                                deliveryType = data.option_data.delivery_type,
                                deliveryPayType = data.option_data.delivery_pay_type;

                            if (oCnt < 1) {
                                $.quickbasket.alertModal('ERROR','옵션을 선택해주세요.','cl-modal-check-select');
                                
                                // var modal = $(this).showModalFlat('','옵션을 선택해주세요.',true,false,'','ok','','cl-cmmodal cl-s-btn w560 cl-p130 cl-t80 cl-modal cl-none-title cl-close-btn','','',function() {
                                //     modal.closest('.cl-flat-modal').next('.modal-backdrop.in').attr('style', 'z-index: 1050!important');
                                //     modal.closest('.modal').css('z-index', 1051);
                                //     $(document).on('keydown', function(e) {
                                //         if(e.keyCode == 27) modal.modal('hide');
                                //     });
                                // });
                                return false;
                            }

                            if(quickBasketOptionModal.find('.cl-s-addt-option-selector').length > 0) { //추가옵션 존재
                                var optionLength = quickBasketOptionModal.find('.option-count-box:not(.additional) input[name="option_name[]"]').length;
                                if(optionLength < 1) {
                                    $.quickbasket.alertModal('ERROR','옵션을 선택해주세요.','cl-modal-check-select');
                                    return false;
                                }
                            }

                            if(quickBasketOptionModal.find('.cl-s-option-text').length > 0) { //입력형옵션 존재
                                var optionTextArr = quickBasketOptionModal.find('input[name="option_text[]"]').map(function(){
                                    if($(this).val().trim() != '') {
                                        return $(this).val().trim();
                                    }
                                }).get();
                                if(optionTextArr.length < 1) {
                                    $.quickbasket.alertModal('ERROR','옵션을 선택해주세요.','cl-modal-check-select');
                                    return false;
                                }
                            }

                            if(!quickBasketOptionModal.find('.ok-button-dialog').hasClass('active')) return false;

                            var optionNameAry = [],
                                optionPriceAry = [],
                                optionCountAry = [],
                                optionSeqAry = [],
                                optionTextAry = [],
                                optionTypeAry = [],
                                etcStartDateAry = [],
                                etcEndDateAry = [];
                            
                            for (var i=0;i<oCnt;i++) {
                                if (optionName[i].value == 'noneOption') {
                                    optionName[i].value = '';
                                }

                                if (optionName[i].value.length == 0) {
                                    if(optionText[i].value.length > 0) {
                                        optionSeqAry[i] = optionSeq[i].value;
                                    } else {
                                        optionSeqAry[i] = '';
                                    }
                                } else if (optionName[i].value.length > 0) {
                                    optionSeqAry[i] = optionSeq[i].value;
                                }

                                if($("#product_state").val() == 'download') {
                                    optionSeqAry[i] = optionSeq[i].value;   
                                }

                                optionTextAry[i] = optionText[i].value; //입력형 옵션
                                optionTypeAry[i] = optionType[i].value; //옵션 타입
                                optionNameAry[i] = optionName[i].value;
                                
                                optionPriceAry[i] = optionPrice[i].value;
                                optionCountAry[i] = optionCount[i].value;
                                
                                etcStartDateAry[i] = etcStartDate[i] ? etcStartDate[i].value : '';
                                etcEndDateAry[i] = etcEndDate[i] ? etcEndDate[i].value : '';
                            }

                            var productBasketData = {
                                'product_number': data.option_data.product_number, // 상품 번호
                                'option_name': optionNameAry,                   // 옵션명
                                'option_text': optionTextAry,
                                'option_type': optionTypeAry,                   
                                'option_price': optionPriceAry,                 // 옵션 가격
                                'option_count': optionCountAry,                 // 옵션 개수
                                'option_seq': optionSeqAry,                     // 옵션 시퀀스
                                'etc_start_date': etcStartDateAry,              // 기타무형 상품 시작 날짜
                                'etc_end_date': etcEndDateAry,                  // 기타무형 상품 종료 날짜
                                'state': state,                                 // 상품 타입 (normal: 일반상품, download: 다운로드 상품, etc: 기타무형 상품)
                                'sid': data.option_data.sid,                    // site id,
                                'delivery_type' : deliveryType,                 // 배송타입
                                'delivery_pay_type' : deliveryPayType,          // 배송비 지불 (선착불)
                            }

                            $.quickbasket.initOptions(quickBasketOptionModal, productBasketData);


                        }, 'cancel', 'gallery.sh.quickbasket.add', 'cl-cmmodal cl-s-btn w560 in-w360 cl-p0 cl-quickbasket-modal ', false, '', function() {

                            if(quickBasketOptionModal.find('.option-count-box:not(.additional)').length > 0) quickBasketOptionModal.find('.modal-footer .ok-button-dialog').addClass('active');
                            else quickBasketOptionModal.find('.modal-footer .ok-button-dialog').removeClass('active');
                            
                            if(quickBasketOptionModal.find('.option-select-box > .option-count-box').length > 0) quickBasketOptionModal.find('.total-price-box .total-cnt').text('1');
                            else quickBasketOptionModal.find('.total-price-box .total-cnt').text('0');

                            if( quickBasketOptionModal.find('.cl-s-normal-option-selector').length == 0 &&
                                quickBasketOptionModal.find('.cl-s-option-date-selector').length == 0 
                            ) {
                                quickBasketOptionModal.find('.cl-s-option-text input').prop('readonly', false);
                            }
                            quickBasketOptionModal.find('.cl-s-option-text input').on('keyup blur', function(e) {
                                var textOptionTarr = [];
                                textOptionTarr = quickBasketOptionModal.find('.cl-s-option-text input').map(function(){
                                    var input_str = ($(this).val().trim() != '') ? $(this).val().trim() : '';
                                    if(input_str != '' && checkEmojis(input_str)) {
                                        input_str = removeEmojis(input_str);
                                        $(this).val(input_str);
                                    }

                                    if(input_str != '') return input_str;
                                }).get();

                                if(quickBasketOptionModal.find('.cl-s-option-text input').length == textOptionTarr.length && quickBasketOptionModal.find('.cl-s-option-selector.option-required .selected-option[data-val=""]').length == 0) {
                                    quickBasketOptionModal.find('.text-option-btn').removeClass('disabled');
                                } else {
                                    quickBasketOptionModal.find('.text-option-btn').addClass('disabled');
                                }
                            });

                            quickBasketOptionModal.find('.cl-s-option-selector').each(function(idx, item){
                                var cnt = $('.cl-s-option-selector').length;
                                $(this).css('z-index', cnt - idx + 1);
                            });
                            quickBasketOptionModal.find('.cl-s-option-selector .selected-option').on('click', function (e) {
                                if($(this).parents('.cl-s-option-selector').hasClass('option-disabled')) return false;
                                var option_parent = $(this).closest('.cl-s-option-selector');

                                if(quickBasketOptionModal.find('.product-option-box div').length == 0) return false;
                                if ($(this).hasClass('active') === true) {
                                    option_parent.find('.product-option-box').slideUp(300);
                                    $(this).removeClass('active');
                                    $(this).parents('.cl-s-option-selector').removeClass('active');
                                } else {
                                    option_parent.find('.product-option-box').slideDown(300);
                                    $(this).addClass('active');
                                    $(this).parents('.cl-s-option-selector').addClass('active');
                                }
                            });

                            quickBasketOptionModal.on('click', function(e) {
                                var container = quickBasketOptionModal.find('.cl-s-normal-option-selector #selected-product-option');
                                if(container.has(e.target).length == 0) {
                                    quickBasketOptionModal.find('.cl-s-normal-option-selector .product-option-box').slideUp(200);
                                    container.removeClass('active');
                                    container.parents('.cl-s-option-selector').removeClass('active');
                                } else {
                                    if($(e.target).closest('.cl-s-option-selector').length > 0) {
                                        $(e.target).closest('.cl-s-option-selector').siblings('.cl-s-option-selector').find('.product-option-box').slideUp(200);
                                    }
                                }

                                if($(e.target).is('.btn')) {
                                    if(quickBasketOptionModal.find('.cl-modal-check-quantity').length > 0) {
                                        e.preventDefault(); 
                                        return false; 
                                    }
                                    var input_v = quickBasketOptionModal.find('.box-option-count input').val();
                                    if(!$(e.target).hasClass('.box-option-count') && (input_v == '' || Number(input_v) < 1)) {
                                        $.quickbasket.alertModal('ERROR','최소 구매 수량은 1개 입니다.','cl-modal-check-quantity');
                                        if(input_v) quickBasketOptionModal.find('.box-option-count input').val(1);
                                        $.quickbasket.pdTotalPriceUpdate();
                                        return false;
                                    }
                                }
                            });

                        });

                        return false;

                    } else {
                        // product none option
                        $.quickbasket.setKeepShopping(sid,RENDER.b.PAGE,pid,pnum);
                        $.quickbasket.close(true);
                        return false;
                    }

                    // var dataObj = JSON.parse(data.r);
                }
            });
        },
        initOptions: function (qbModal, pdBasketObj) {
            $.ajax({
                url: '/_basket',
                type: 'post',
                data: pdBasketObj,
                async: false,
                cache: false,
                success: function (data) {
                    if (data == 'error-none-unique') {
                        alert('장바구니에 담기는 도중 오류가 발생했습니다.\n잠시후 다시시도 해주세요.\n같은 현상이 지속된다면 고객센터로 문의해주세요.');
                        return false;
                    }

                    var dataObj = JSON.parse(data);
                    var basketConfirm = dataObj.r.basket_confirm;
                    var state = dataObj.r.state;
                    var remainQuantity = dataObj.r.remain_quantity;
                    var totalQuantity = $('.total-quantity').val();

                    if(basketConfirm.indexOf(false)>-1 && basketConfirm.indexOf(true)==-1){
                        if(state=='download'){
                            alert('장바구니에 이미 담겨있는 상품입니다.');
                        } else if(state == 'normal' && (deliveryType != dataObj.r.delivery_type || deliveryPayType != dataObj.r.delivery_pay_type)) {
                            alert('해당 상품을 장바구니에서 비우거나 배송방법을 ' + $.lang[LANG]['shopping.delivery.template.delivery_type.' + dataObj.r.delivery_type.toLowerCase()] + ', 배송비결제를 ' + $.lang[LANG]['shopping.delivery.template.pay_type.' + dataObj.r.delivery_pay_type.toLowerCase()] + '로 수정해 주세요.');
                        }
                        else{
                            $(this).blur();
                            var modal = $(this).showModalFlat('ERROR','재고 수량('+remainQuantity+'개) 이상 구매하실 수 없습니다.',true,false,'','ok','','cl-cmmodal cl-s-btn w560 cl-p130 cl-t80 cl-modal cl-none-title cl-close-btn','','',function() {
                                modal.closest('.cl-flat-modal').next('.modal-backdrop.in').attr('style', 'z-index: 1050!important');
                                modal.closest('.modal').css('z-index', 1051);
                                $(document).on('keydown', function(e) {
                                    if(e.keyCode == 27) modal.modal('hide');
                                });
                            });
                        }
                        return false;
                    }

                    var optionName = qbModal.find('input[name="option_name[]"]'),
                        optionPrice = qbModal.find('input[name="option_price[]"]'),
                        optionCount = qbModal.find('input[name="option_count[]"]'),
                        optionSeq = qbModal.find('.option_seq'),
                        optionQuantity = qbModal.find('.option-normal-price'),
                        etcStartDate = qbModal.find('input[name="etc_start_date[]"]'),
                        etcEndDate = qbModal.find('input[name="etc_end_date[]"]'),
                        oCnt = qbModal.find('input[name="option_name[]"]').length,
                        state = qbModal.find('#product_state').val();

                    var optionNameAry = [],
                        optionSeqAry = [],
                        optionQuantityAry = [],
                        optionPriceAry = [],
                        optionCountAry =   
                        etcStartDateAry = [],
                        etcEndDateAry = [],
                        prod, prodAry = [],
                        totalPrice = qbModal.find('.total-price').text().replace(/[\{\}\[\]\/?.,;:|\)*~`!^\-+<>@\#$%&\\\=\(\'\"]/gi, ""),
                        fdq_arr = [];

                    for (var i=0;i<oCnt;i++) {
                        if (optionName[i].value == 'noneOption') optionName[i].value = '';
                        optionNameAry[i] = optionName[i].value;
                        optionSeqAry[i] = optionSeq[i].value;
                        optionQuantityAry[i] = optionQuantity[i].value;
                        optionPriceAry[i] = (optionPrice[i].value * 1) * (optionQuantity[i].value * 1);
                        optionCountAry[i] = optionCount[i].value;
                        etcStartDateAry[i] = etcStartDate[i] ? etcStartDate[i].value : '';
                        etcEndDateAry[i] = etcEndDate[i] ? etcEndDate[i].value : '';
                        prod = {
                            'option_seq': optionSeq[i].value,
                            'option_name': optionName[i].value,
                            'option_quantity': optionQuantity[i].value,
                            'option_price': optionPriceAry[i],
                            'etc_option_start': etcStartDate[i] ? etcStartDate[i].value : '',
                            'etc_option_end': etcEndDate[i] ? etcEndDate[i].value : '',
                        }
                        prodAry[i] = prod;

                        var fdq_pn = qbModal.find('.product-title [data-project-title]').text(),
                            fdq_nm = (optionName[i].value) ? optionName[i].value : qbModal.find('.option-select-box .option-count-box:eq('+i+') .box-option-name').text();
                        fdq_arr.push({
                            'id': optionSeq[i].value, 
                            'name': (fdq_pn != fdq_nm) ? fdq_pn + ' ' + fdq_nm : fdq_nm,
                            'quantity': optionQuantity[i].value, 
                            'price': optionPriceAry[i], 
                        });
                    }

                    var productCart = {
                        'product_number': pdBasketObj.value,   // 상품 번호
                        'option': prodAry,                     // 옵션
                        'state': state,                        // 상품 타입 (normal: 일반상품, download: 다운로드 상품, etc: 기타무형 상품)
                        'total_price': totalPrice,             // 상품 총 가격
                        'sid': pdBasketObj.sid,                // site id
                    }
                    if(typeof productCartCallback == 'function') productCartCallback(productCart);
                    if(typeof callbackEvtAddToCart == 'function') callbackEvtAddToCart(fdq_pn,fdq_arr,totalPrice);

                    if(basketConfirm.indexOf(true) > -1) {
                        var checkFixTypeMenu = (typeof $('.el-menu header.navbar').attr('data-fixtype') != 'undefined' && $('.el-menu header.navbar').attr('data-fixtype')) ? true : false;     
                        property.CART = (checkFixTypeMenu) ? dataObj.r.cart_cnt : 'true';
                        $.shopping.makeSiteFixedCART();

                        qbModal.modal('hide');
                        $.quickbasket.close(false);
                        return false;
                    } else {
                        $.shopping.makeSiteFixedCART();
                    }
                }
            });
        },
        close: function (checkPlusCart) {
            quickbasket_str = '\
                <div class="modal-footer mt-20\">\
                    <button type="button" class="btn btn-sm btn-line">' + $.lang[LANG]['gallery.sh.quickbasket.goto'] + '</button>\
                    <button type="button" class="btn btn-sm btn-active close-button-dialog" data-dismiss="modal">' + $.lang[LANG]['gallery.sh.quickbasket.keep'] + '</button>\
                </div>\
            ';

            var quickBasketModal = $(this).showModalFlat($.lang[LANG]['gallery.sh.quickbasket.success'], quickbasket_str, false, false, '', '', '', 'cl-cmmodal cl-s-btn w560 cl-p0 cl-quickbasket-modal', false, '', function() {
                // quickBasketModal.closest('.cl-flat-modal').next('.modal-backdrop.in').attr('style', 'z-index: 1050!important');
                // quickBasketModal.closest('.modal').css('z-index', 1051);

                if(checkPlusCart) {
                    var checkFixTypeMenu = (typeof $('.el-menu header.navbar').attr('data-fixtype') != 'undefined' && $('.el-menu header.navbar').attr('data-fixtype')) ? true : false;     
                    property.CART = (checkFixTypeMenu) ? Number(property.CART) + 1 : 'true';
                    $.shopping.makeSiteFixedCART();
                }

                quickBasketModal.find('.btn-line').on('click', function(e) {
                    location.href = '/_cart';
                    quickBasketModal.modal('hide');
                });

                $(document).on('keydown', function(e) {
                    if(e.keyCode == 13) {
                        e.preventDefault();
                        return false;
                    }
                    if(e.keyCode == 27) quickBasketModal.modal('hide');
                });
            });
        },
        alertModal: function (am_header, am_content, am_modalclass) {
            var am_selector = (am_modalclass) ? '.'+am_modalclass.replace(' ',',.') : '';
            if(am_selector != '' && $(am_selector).length > 0) return false;

            var am_zindex = ($('body').width() < 768) ? 9998 : 1050;
            var am_modal = $(this).showModalFlat(am_header, am_content, true, false, '', 'ok', '', 'cl-cmmodal cl-s-btn w560 cl-p130 cl-t80 cl-modal cl-none-title cl-close-btn ' + am_modalclass, '', '', function() {
                am_modal.closest('.cl-flat-modal').next('.modal-backdrop.in').attr('style', 'z-index: '+am_zindex+'!important');
                am_modal.closest('.modal').css('z-index', am_zindex+1);

                $(document).on('keydown', function(e) {
                    if(e.keyCode == 27) am_modal.modal('hide');
                });
            });
        },
        checkQty: function (optionAry) {
            var currentOptCnt = 0;
            $('.cl-quickbasket-modal .box-option-name').each(function (idx, v) {
                var boxOptionSeq = $(v).closest('.option-count-box').find('.option_seq').val();
                var boxOptionText = $(v).closest('.option-count-box').find('input[name="option_text[]"]').val();
                if(boxOptionSeq.indexOf(optionAry[3]) > -1) {
                    currentOptCnt++
                }
            });
            if(Number(optionAry[2]) == currentOptCnt) {
                var modal = $(this).showModalFlat('ERROR','재고 수량('+optionAry[2]+'개) 이상 구매하실 수 없습니다.',true,false,'','ok','','cl-cmmodal cl-s-btn w560 cl-p130 cl-t80 cl-modal cl-none-title cl-close-btn','','',function() {
                    modal.closest('.cl-cmmodal').next('.modal-backdrop.in').attr('style', 'z-index: 1050!important');
                    modal.closest('.modal').css('z-index', 1051);

                    $(document).on('keydown', function(e) {
                        if(e.keyCode == 27) modal.modal('hide');
                    });
                });
                return false;
            } else {
                return true;
            }
        },
        pdOptionBoxHtml: function (productPrice, type, optionStatus, optionType, optionAry, textOption, textOptionObj) {
            var quickbasketModal = $('.cl-quickbasket-modal'),
                total = 0,
                dateCheckCnt = 1,
                etcStartDate = '', etcEndDate = '', etcDate = '';

            if (quickbasketModal.find('.cl-s-option-date-selector').length > 0) { //기간
                var optionStatus = 'etc';
                etcStartDate = quickbasketModal.find('#etc-start-date-option').val();
                etcEndDate = quickbasketModal.find('#etc-end-date-option').val();
                etcTime = quickbasketModal.find('#etc-time').val();
                if (etcEndDate) etcDate = etcStartDate + ' - ' + etcEndDate;
                else etcDate = etcStartDate;
                if(etcTime) {
                    var etcTimeTmp = etcTime.split(' ');
                    etcTimeTmp[0] = (etcTimeTmp[0] == 'am')? '오전 ' : '오후 ';
                    var etcTimeStr = etcTimeTmp[0] + etcTimeTmp[1];
                    etcDate += ' '+etcTimeStr;
                    etcStartDate += '|'+etcTime;
                    if(etcEndDate) etcEndDate += '|'+etcTime;
                }

                var etcStartDateAry = quickbasketModal.find('#etc-start-date-option').val().split(".");
                var etcEndDateAry = quickbasketModal.find('#etc-end-date-option').val().split(".");
                var disabledDateArr = quickbasketModal.find('#etc-exclude-date').val().split(',');
                var startDateObj = new Date(etcStartDateAry[0], (etcStartDateAry[1] * 1) - 1, etcStartDateAry[2]);
                var endDateObj = new Date(etcEndDateAry[0], (etcEndDateAry[1] * 1) - 1, etcEndDateAry[2]);
                var betweenDate = (endDateObj.getTime() - startDateObj.getTime()) / 1000 / 60 / 60 / 24;

                var dayArr = (quickbasketModal.find('#etc-term-setting').val() && JSON.parse(quickbasketModal.find('#etc-term-setting').val()).days !== undefined)? JSON.parse(quickbasketModal.find('#etc-term-setting').val()).days.split('|'):[];
                var disabledDayArr = [];
                if(dayArr.length > 0) {
                    disabledDayArr = [0, 1, 2, 3, 4, 5, 6];
                    $.each(dayArr, function(i, v){
                        enableIdx = disabledDayArr.indexOf(daysObj[v]);
                        if(enableIdx > -1) {
                            disabledDayArr.splice(enableIdx, 1);
                        }
                    });
                }

                for (var i=0;i<betweenDate;i++) {
                    var dayCheck = 0;
                    var dateCheck;
                    var dt;
 
                    dayCheck = new Date(etcStartDateAry[0], (etcStartDateAry[1] * 1) - 1, (etcStartDateAry[2] * 1) + i).getDay();
                    dt = new Date(etcStartDateAry[0], (etcStartDateAry[1] * 1) - 1, (etcStartDateAry[2] * 1) + i);
                    dateCheck = dt.getFullYear()+'.'+ String(dt.getMonth()+1).padStart(2, '0') +'.'+dt.getDate();
                    if (disabledDateArr.indexOf(dateCheck)===-1 && disabledDayArr.indexOf(dayCheck)===-1) dateCheckCnt++;
                }
            }
            var boxOptionTextStr = (textOptionObj)? textOptionObj.map(function(element, index, array){return Object.values(element);}).join(' / ') : ''; //입력옵션 텍스트값
            if (dateCheckCnt == 0) dateCheckCnt = 1;

            optionAry[0] = (optionAry[0] === undefined) ? '' : strReplace(optionAry[0], '\\quot;', "&quot;");
            optionAry[3] = (optionAry[3] === undefined) ? quickbasketModal.find('.noneoption_seq').val() : optionAry[3];
            textOption = (textOption === undefined)? '' : textOption;
            var optionPrice = (optionAry[1] === undefined)? 0 : Number(optionAry[1]);
            var boxOptionPrice = 0;
            var boxOptionName = '';
            var boxOptionNameArr = new Array();
            if(optionType == 'A') {
                boxOptionNameArr.push(optionAry[0]);
                productPrice = 0;
            } else {
                if(optionAry[0] != '' && optionAry[0] != 'undefined') { //일반옵션
                    boxOptionNameArr.push(optionAry[0]);
                }
                if(etcDate != '') { //무형-날짜
                    if(boxOptionNameArr.indexOf(etcDate) === -1) boxOptionNameArr.push(etcDate);
                }
                if(textOption!='') { //입력옵션
                    boxOptionNameArr.push(boxOptionTextStr);
                }
            }
            boxOptionName = boxOptionNameArr.join(' / '); //옵션명
            var cnt = 0;
            quickbasketModal.find('.box-option-name').each(function () {
                var boxOptionSeq = $(this).closest('.option-count-box').find('.option_seq').val();
                var boxOptionText = $(this).closest('.option-count-box').find('input[name="option_text[]"]').val();
                if (quickbasketModal.find('.cl-s-option-date-selector').length > 0) { //날짜선택옵션
                    if ($(this).text() == boxOptionName || $(this).text() == etcDate) {
                        cnt++;
                        $(this).blur();
                        $.quickbasket.alertModal('ERROR','이 옵션은 이미 선택되어 있습니다.','cl-modal-check-select');
                    }
                } else {
                    if(textOption !== undefined && textOption != '') { //입력옵션 있음
                        if(optionAry[3] !== undefined) { //일반옵션 있음
                            if (boxOptionSeq == optionAry[3] && boxOptionText == strReplace(textOption, '&quot;', '"')) {
                                cnt++;
                                $(this).blur();
                                $.quickbasket.alertModal('ERROR','이 옵션은 이미 선택되어 있습니다.','cl-modal-check-select');
                            }
                        } else { //일반옵션 없음
                            if (boxOptionText == strReplace(textOption, '&quot;', '"')) {
                                cnt++;
                                $(this).blur();
                                $.quickbasket.alertModal('ERROR','이 옵션은 이미 선택되어 있습니다.','cl-modal-check-select');
                            }
                        }
                        
                    } else { //일반옵션만
                        if (boxOptionSeq == optionAry[3]) {
                            cnt++;
                            $(this).blur();
                            $.quickbasket.alertModal('ERROR','이 옵션은 이미 선택되어 있습니다.','cl-modal-check-select');
                        }
                    }   
                }
            });

            if (cnt > 0) return false;

            var plusOptionPrice = (optionType == 'A')? optionPrice : ((productPrice * 1) + optionPrice) * dateCheckCnt;
            if(plusOptionPrice < 0) {
                alert('구매금액이 0원보다 적을 수 없습니다.\r\n판매자에게 문의하세요.');
                return false;
            }
            if(optionType == 'A' && (optionAry[0]).indexOf(' / ') > -1) {
                var tmp = (optionAry[0]).split(' / ');
                optionAry[0] = tmp[1];
            }
            var totalPriceOption = (plusOptionPrice + total);
            var html = '';

                if(optionType == 'A') html += '<div class="option-count-box additional">';
                else html += '<div class="option-count-box">';
                html += '<input type="hidden" name="option_price[]" value="'+plusOptionPrice+'">';
                html += '<input type="hidden" name="option_seq[]" class="option_seq" value="'+optionAry[3]+'">';
                html += '<input type="hidden" class="total-quantity" value="'+optionAry[2]+'">';
                if (type) html += '<input type="hidden" name="option_name[]" value="noneOption">';
                else html += '<input type="hidden" name="option_name[]" value="'+optionAry[0]+'">';
                if(optionType != '') html += '<input type="hidden" name="option_type[]" value="'+optionType+'">';
                else html += '<input type="hidden" name="option_type[]" value="">';
                html += '<input type="hidden" name="option_text[]" value="'+textOption+'">';
                html += '<div class="box-option-row">';
                if ($('.cl-s-option-date-selector').length > 0) { //기간 있음
                    if(optionType != 'A') {
                        html += '<input type="hidden" name="etc_start_date[]" value="'+etcStartDate+'">';
                        html += '<input type="hidden" name="etc_end_date[]" value="'+etcEndDate+'">';
                    } else {
                        html += '<input type="hidden" name="etc_start_date[]" value="">';
                        html += '<input type="hidden" name="etc_end_date[]" value="">';
                    }
                    if (type) html += '<div class="box-option-name">' + etcDate + '</div>';
                    else html += '<div class="box-option-name">' + boxOptionName + '</div>';
                } else { //기간 없음
                    html += '<div class="box-option-name">'+boxOptionName+'</div>';
                }
                    html += '<div class="box-option-del"><span class="box-delete"><svg viewBox="0 0 12 12" width="12" height="12"><polygon points="12 0.71 11.29 0 6 5.29 0.71 0 0 0.71 5.29 6 0 11.29 0.71 12 6 6.71 11.29 12 12 11.29 6.71 6 "/></svg></span></div>';
                html += '</div>'; //end row
                html += '<div class="box-option-row">';
                    html += '<div class="box-option-price"><span class="option-price">'+number_format(plusOptionPrice)+'</span>원</div>';
                    html += '<div class="box-option-count">';
                    html += '<div class="form-group">';
                    html += '<span class="min"><svg viewBox="0 0 11 11" width="11" height="11"><rect y="5" width="11" height="1"/></svg></span>';
                    html += '<input type="text" class="option-normal-price" value="1" numberOnly="true" name="option_count[]">';
                    html += '<span class="plus"><svg viewBox="0 0 11 11" width="11" height="11"><polygon points="6 5 6 0 5 0 5 5 0 5 0 6 5 6 5 11 6 11 6 6 11 6 11 5 "/></svg></span>';
                    html += '</div>';
                    html += '</div>';
                html += '</div>'; //end row
                html += '</div>';

            return html;
        },
        pdOptionPick: function (obj, productPrice) {
            // console.log('pdOptionPick() ----------------------------------------------');
            // console.log($.quickbasket.data);

            var quickbasketModal = $(obj).closest('.cl-quickbasket-modal'),
                type = '',
                option = obj.getAttribute('data-val'),
                optionAry = option.split('||'),
                optionStatus =  obj.getAttribute('data-status'),
                optionType = obj.getAttribute('data-option_type'),
                _idx = obj.getAttribute('data-idx'),
                total = 0,
                totalCnt = 1,
                dateCheckCnt = 1,
                submit = false,
                reSelected = false,
                parent = $(obj).closest('.cl-s-option-selector'),
                textParent = $(obj).closest('.cl-s-option-text'),
                selectedBoxTitle = parent.find('.selected-option-title').text(),
                selectedPrice = $(obj).attr('data-option-price'),
                onlySelectedText = $(obj).find('.option-name').text();

            if(quickbasketModal.find('.cl-s-normal-option-selector').length > 1 && !$.quickbasket.checkQty(optionAry)) return false; //옵션재고수량 검사

            selectedBoxTitle += (selectedBoxTitle.length > 0) ? ' / ' : '';
            if(selectedPrice != undefined) {
                selectedPrice = (selectedPrice.indexOf('-') > -1) ? '-' + number_format(selectedPrice.substring(1)) : '+' + number_format(selectedPrice);
                selectedPrice = ' (' + selectedPrice + '원)';
            } else selectedPrice = '';

            if(parent.hasClass('cl-s-normal-option-selector')) {
                var selected_option = $(obj).parents('.cl-s-normal-option-selector'),
                    selected_index = selected_option.attr('data-def-index'),
                    last_index = quickbasketModal.find('.cl-s-normal-option-selector').last().attr('data-def-index');
                if (selected_index != last_index) reSelected = true;
            }

            // 하위메뉴 리셋
            if(selected_index != undefined) {
                $.each(quickbasketModal.find('.cl-s-normal-option-selector'), function(i,v) {
                    if(i > Number(selected_index)) {
                        var otitle = $(this).find('.selected-option-title').text();
                        $(this).addClass('option-disabled');
                        $(this).find('.selected-option')
                                .attr('data-selected_option','')
                                .attr('data-val','')
                                .attr('data-status','');
                        $(this).find('.selected-option-text').text(otitle);
                    }
                });
            }

            setTimeout(function() {
                var checkSelectEmpty = (quickbasketModal.find('.cl-s-option-selector.option-required .selected-option[data-val=""]').length > 0) ? true : false,
                    checkInputEmpty = false;
                quickbasketModal.find('.text-option-box input').each(function() {
                    if($(this).val() == '' || $(this).val().trim() == '') checkInputEmpty = true;
                });

                if(!checkSelectEmpty && !checkInputEmpty) quickbasketModal.find('.text-option-btn').removeClass('disabled');
                else quickbasketModal.find('.text-option-btn').addClass('disabled');
            }, 100);

            // 추가옵션 존재
            if(quickbasketModal.find('.cl-s-option-text input').length > 0 || quickbasketModal.find('.cl-s-normal-option-selector.option-disabled').length > 0 || reSelected) {
                //셀렉트박스 선택
                var optionSelectedVal = (quickbasketModal.find('.cl-s-option-text input').length > 0) ? quickbasketModal.find('#selected-product-option').attr('data-val') : '';
                var selectedOptionName = selectedBoxTitle + onlySelectedText + selectedPrice;
                if (optionType == null) {
                    parent.find('.selected-option-text').text(selectedOptionName);
                    parent.find('.selected-option').attr('data-selected_option', onlySelectedText);
                    parent.find('.selected-option').attr('data-val', option);
                    parent.find('.selected-option').attr('data-status', optionStatus);
                }

                // console.log(obj.getAttribute('data-type'));
                if(quickbasketModal.find('.cl-s-normal-option-selector.option-disabled').length == 0) {
                    quickbasketModal.find('.cl-s-option-text input').prop('readonly', false);
                }

                if(obj.getAttribute('data-type') == '1') {
                    quickbasketModal.find('.cl-s-normal-option-selector.option-disabled').eq(0).removeClass('option-disabled');
                } else if(obj.getAttribute('data-type') == '2') {
                    var $required = quickbasketModal.find('.cl-s-normal-option-selector').eq(1),
                        $op = $required.find('.product-option-box'),
                        idx = 0;

                    $required.find('.selected-option-text').text('선택');
                    $op.empty();
                    $.each($.quickbasket.data.list.normal[_idx]['value'], function(a,b) {
                        if(b.option_status == 'H') return true;

                        var div_property = '';
                        if(!b.soldout) {
                            div_property += 'onclick="$.quickbasket.pdOptionPick(this, \'' + productPrice + '\')" ';
                            div_property += 'data-status="normal" ';
                            div_property += 'data-idx="' + a + '" ';
                            // if(o_key == 'normal') div_property += 'data-option-index="' + og_idx + '" ';
                            div_property += 'data-option-price="' + b.option_price + '" ';
                        }
                        var option_str = {
                            'div_class': (b.soldout) ? 'class="sold-out"' : '',
                            'div_property': div_property,
                            'span1': (b.soldout) ? '<span class="text-d-lt">' : '',
                            'span2': (b.soldout) ? '</span>' : '',
                            'seq': 'data-option-seq="'+b.option_seq+'"',
                            'soldout': (b.soldout) ? '<label>품절</label>' : '',
                        }

                        var s = '\
                            <div class="' + option_str.div_class + '" data-val="' + b.val + '" ' + option_str.div_property + '>\
                                ' + option_str.span1 + '\
                                    <span class="number">' + b.option_number + '.</span>\
                                    <div class="option-name" ' + option_str.seq + '>' + b.option_name + option_str.soldout + '</div>\
                                    <span class="price">' + b.option_price_str + ' 원</span>\
                                ' + option_str.span2 + '\
                            </div>\
                        ';


                        /*
                        if(soldout == true) {
                            var s = '\
                            <div class="sold-out" data-val="' + b.option_name + '||' + b.option_price + '||0">\
                                <span class="text-d-lt">\
                                    <span class="number">' + b.option_number + '.</span>\
                                    <div class="option-name" data-option-seq="' + b.option_seq + '">' + b.option_name + '<label>품절</label></div>\
                                    <span class="price">' + b.option_price_str + ' 원</span>\
                                </span>\
                            </div>\
                            ';
                        } else {
                            var s = '\
                            <div data-val="' + b.option_name + '||' + b.option_price + '||' + quantity + '||' + b.option_seq + '" onclick="$.quickbasket.pdOptionPick(this, \'' + productPrice + '\')" data-status="normal" data-idx=' + a + ' data-option-price="' + b.option_price + '">\
                                <span class="number">' + b.option_number + '.</span>\
                                <div class="option-name" data-option-seq="' + b.option_seq + '">' + b.option_name + '</div>\
                                <span class="price">' + b.option_price_str + ' 원</span>\
                            </div>\
                            ';
                        }
                        */
                        $op.append(s);
                        idx++;
                    });
                    $required.removeClass('option-disabled');
                } else if(obj.getAttribute('data-type') == '3') {

                    var option_index = obj.getAttribute('data-option-index'),
                        selected_index = Number(option_index) + 1,
                        $required = quickbasketModal.find('.cl-s-normal-option-selector').eq(selected_index),
                        $op = $required.find('.product-option-box'),
                        idx = 0;
                        $data = (option_index == '0') ? $.quickbasket.data.list.normal[_idx]['value'] : $.quickbasket.data.list.normal[_idx]['value2'];

                    if(option_index == '1') {
                        var s1 = quickbasketModal.find('.cl-s-normal-option-selector').eq(0).find('.selected-option').attr('data-selected_option'),
                            s2 = onlySelectedText,
                            result = [];
                        $.each($.quickbasket.data.list.normal_org, function(a,b) {
                            if(b['option_mix2'] == s1 && b['option_mix3'] == s2) {
                                var tmp = b;
                                tmp['option_number'] = String(result.length + 1).padStart(2, '0');
                                result.push(tmp);
                            }
                        });

                        $data = result;
                    }
                    // $required.find('.selected-option-text').text('선택');

                    $op.empty();
                    $.each($data, function(a,b) {
                        var div_property = '';
                        if(selected_index == '2' && b.soldout) {
                        } else {
                            div_property += 'onclick="$.quickbasket.pdOptionPick(this, \'' + productPrice + '\')" ';
                            // div_property += 'data-status="' + data.option_data.product_state + '" ';
                            div_property += 'data-status="normal" data-type="3" ';
                            div_property += 'data-idx="' + a + '" ';
                            div_property += 'data-option-index="' + selected_index + '" ';
                            div_property += 'data-option-price="' + b.option_price + '" ';
                        }
                        var option_val_arr = b.val.split('||');
                        option_val_arr[0] = (selected_index == '2') ? b.option_name : b.option_mix3;
                        var option_str = {
                            'div_class': (b.soldout) ? 'class="sold-out"' : '',
                            'div_property': div_property,
                            'span1': (b.soldout) ? '<span class="text-d-lt">' : '',
                            'span2': (b.soldout) ? '</span>' : '',
                            'seq': 'data-option-seq="'+b.option_seq+'"',
                            'soldout': (selected_index == '2' && b.soldout) ? '<label>품절</label>' : '',
                            'val' : option_val_arr.join('||'),
                        }

                        var s = '\
                            <div class="' + option_str.div_class + '" data-val="' + option_str.val + '" ' + option_str.div_property + '>\
                                ' + option_str.span1 + '\
                                    <span class="number">' + b.option_number + '.</span>\
                                    <div class="option-name" ' + option_str.seq + '>' + option_val_arr[0] + option_str.soldout + '</div>\
                                    <span class="price">' + b.option_price_str + ' 원</span>\
                                ' + option_str.span2 + '\
                            </div>\
                        ';



                        // var quantity = ($.quickbasket.data.product_quantity_on == 'on') ? b.option_quantity : 99999,
                        //     soldout = (quantity == 0 || b.option_status == 'O') ? true : false,
                        //     col = (selected_index == '2') ? b.option_name : b.option_mix3;
                        // if(selected_index == '2' && soldout == true) {
                        //     var s = '\
                        //     <div class="sold-out" data-val="' + b.option_name + '||' + b.option_price + '||0">\
                        //         <span class="text-d-lt">\
                        //             <span class="number">' + b.option_number + '.</span>\
                        //             <div class="option-name" data-option-seq="' + b.option_seq + '">' + col + '<label>품절</label></div>\
                        //             <span class="price">' + b.option_price_str + ' 원</span>\
                        //         </span>\
                        //     </div>\
                        //     ';
                        // } else {
                        //     var s = '\
                        //     <div data-val="' + col + '||' + b.option_price + '||' + quantity + '||' + b.option_seq + '" onclick="$.quickbasket.pdOptionPick(this, \'' + productPrice + '\')" data-status="normal" data-idx=' + _idx + ' data-type="3" data-option-index="' + selected_index + '" data-option-price="' + b.option_price + '">\
                        //         <span class="number">' + b.option_number + '.</span>\
                        //         <div class="option-name" data-option-seq="' + b.option_seq + '">' + col + '</div>\
                        //         <span class="price">' + b.option_price_str + ' 원</span>\
                        //     </div>\
                        //     ';
                        // }
                        $op.append(s);
                        idx++;
                    });
                    $required.removeClass('option-disabled');
                }
                
                optionAry = (typeof optionSelectedVal !== 'undefined' && optionSelectedVal) ? optionSelectedVal.split('||') : optionAry;
                
                if (optionType == 'A') {
                    optionAry = option.split('||');
                }
                // var boxOptionName = optionAry[0] ;
                if (optionType != 'A') {
                    parent.find(".product-option-box").slideToggle(300);

                    if (parent.find(".selected-option").hasClass('active') === true) {
                        parent.find(".selected-option").removeClass('active');
                    } else {
                        parent.find(".selected-option").addClass('active');
                    }

                    return false;
                }
            } else {
                //셀렉트박스 선택
                var selectedOptionName = selectedBoxTitle + onlySelectedText + selectedPrice;
                if (optionType == null) {
                    parent.find('.selected-option-text').text(selectedOptionName);
                    parent.find('.selected-option').attr('data-selected_option', onlySelectedText);
                    parent.find('.selected-option').attr('data-val', option);
                    parent.find('.selected-option').attr('data-status', optionStatus);
                }
                
                option = quickbasketModal.find('.selected-option:not(#selected-delivery-type)').eq(0).attr('data-val'); 
                
                if(option == undefined || option == '') {
                    submit = false;
                } else {
                    optionAry = option.split('||'); 
                    optionStatus =  quickbasketModal.find('#selected-product-option').attr('data-status');
                    optionType = quickbasketModal.find('#selected-product-option').attr('data-option_type');
                    submit = true;
                }
            }

            if($(obj).parents('.cl-s-option-selector').hasClass('cl-s-normal-option-selector')) {
                // 추가된 기본 옵션
                $.each(quickbasketModal.find('.selected-option.ex'), function(i,v) {
                    var selectedOption = $(this).attr('data-val');
                    if(selectedOption == undefined) selectedOption = '';
                    var ex_option_arry = selectedOption.split('||');
                    if(ex_option_arry[0] !== undefined) {
                        if(optionAry[0] !== undefined) optionAry[0]+=' / ' + ex_option_arry[0];
                    }
                    if(ex_option_arry[1] !== undefined) {
                        if(optionAry[1] !== undefined) optionAry[1] = Number(optionAry[1]) + Number(ex_option_arry[1]);
                    }
                    if(ex_option_arry[2] !== undefined) {
                        if(optionAry[2] !== undefined) optionAry[2] = Number(ex_option_arry[2]);
                    }
                    if(ex_option_arry[3] !== undefined) {
                        if($.quickbasket.data.options_type == '1') {
                            if(optionAry[3] !== undefined) optionAry[3]+=',' + ex_option_arry[3];
                        } else optionAry[3] = ex_option_arry[3];
                    }
                });
            }
            
            if($(obj).parents('.cl-s-option-selector').hasClass('cl-s-addt-option-selector')) {
                var option_title = selectedBoxTitle;
                option = $(obj).attr('data-val');
                optionType = $(obj).attr('data-option_type');
                optionAry = option.split('||');
                if(optionAry[0] !== undefined) optionAry[0] = option_title + optionAry[0];
                $(obj).parents('.cl-s-option-selector').removeClass('active');
            }

            //html 생성
            var html = $.quickbasket.pdOptionBoxHtml(productPrice, type, optionStatus, optionType == null ? '' : optionType, optionAry, '');
            parent.find('.product-option-box').slideToggle(300);

            if (parent.find('.selected-option').hasClass('active') === true) parent.find('.selected-option').removeClass('active');
            else parent.find('.selected-option').addClass('active');

            if(quickbasketModal.find('.cl-s-option-text').length > 0 && optionType != 'A') {
                return false;
            } else {
                quickbasketModal.find('.option-select-box').append(html);
                if(quickbasketModal.find('.option-count-box:not(.additional)').length > 0) quickbasketModal.find('.modal-footer .ok-button-dialog').addClass('active');
                else quickbasketModal.find('.modal-footer .ok-button-dialog').removeClass('active');
            }
            
            //합계
            $.quickbasket.pdTotalPriceUpdate();

            if (optionStatus === null || optionStatus=='etc') {
                var lastBox = quickbasketModal.find('.option-count-box').last();
                var totalQuantity = lastBox.find('.total-quantity').val();
                var state = quickbasketModal.find('#product_state').val();
                var optionSeq = lastBox.find('input[name="option_seq[]"]').val();
                var optionName = lastBox.find('input[name="option_name[]"]').val();
                var optionStartDate = lastBox.find('input[name="etc_start_date[]"]').val();
                var optionCount = quickbasketModal.find('input[name="option_count[]"]');
                var optionCountAry = [];
                var etcTotalCount = 0;
                
                if(optionStartDate!==undefined && optionStartDate.length > 0) { 
                    var sameOptions = (optionName!='noneOption') ? quickbasketModal.find('input[value="'+optionSeq+'"]').closest('.option-count-box').find('input[name="option_count[]"]') : quickbasketModal.find('input[value="'+optionName+'"]').closest('.option-count-box').find('input[name="option_count[]"]');
                    var sameOptionsTotal = sameOptions.find('.total-quantity').val();
                    
                    sameOptions.each(function(){
                        etcTotalCount += Number($(this).val());
                    });
                    
                    if(etcTotalCount > totalQuantity) {
                        // alert('재고 수량('+totalQuantity+'개) 이상 구매하실 수 없습니다.');
                        $(this).blur();
                        $.quickbasket.alertModal('ERROR','재고 수량('+totalQuantity+'개) 이상 구매하실 수 없습니다.','cl-modal-check-quantity');
                        lastBox.remove();
                    }
                    $.quickbasket.pdTotalPriceUpdate();
                    submit = true;
                }
            }

            if(submit) {
                // 옵션 초기화
                quickbasketModal.find('.selected-option')
                                .attr('data-selected_option','')
                                .attr('data-val','')
                                .attr('data-status','');
                    // .find('.selected-option-text').text('선택');
                $.each(quickbasketModal.find('.cl-s-option-selector'), function(i,v) {
                    var title = $(this).find('.selected-option-title').text();
                    if(title == '') title = '선택';
                    $(this).find('.selected-option-text').text(title);
                });
                $.each(quickbasketModal.find('.cl-s-normal-option-selector'), function(i,v) {
                    if(i > 0) $(this).addClass('option-disabled');
                });
                quickbasketModal.find('#etc-start-date-option, #etc-end-date-option, #etc-time, #etc-start-date-txt, #etc-end-date-txt').val('');
                quickbasketModal.find('.selected-option > span').each(function(idx, v){
                    if($(v).attr('data-default') !== undefined) {
                        $(v).text($(v).attr('data-default'));
                    }
                });
            }


            quickbasketModal.find('.option-select-box .box-option-count .plus').off('click').on('click', function(e) {
                if($('.cl-modal-check-quantity').length > 0) {
                    e.preventDefault(); 
                    return false; 
                }

                var totalQuantity = $(this).closest('.option-count-box').find('.total-quantity').val();
                var count = $(this).parent().children('input').val();
                var state = quickbasketModal.find('#product_state').val();
                var optionSeq = $(this).closest('.option-count-box').find('input[name="option_seq[]"]').val();
                var optionName = $(this).closest('.option-count-box').find('input[name="option_name[]"]').val();
                var optionStartDate = $(this).closest('.option-count-box').find('input[name="etc_start_date[]"]').val();
                var etcTotalCount = 0;

                var target = this;
                var sameCount = 0;
                quickbasketModal.find('input[name="option_seq[]"][value="' + optionSeq + '"]').each(function() {
                    if($(this).closest('.option-count-box').has(target).length === 0) {
                        sameCount += Number($(this).parent().find('input[name="option_count[]"]').val());
                    }
                });


                if (count > 1000) {
                    $(this).blur();
                    $.quickbasket.alertModal('ERROR','최대 구매 수량은 1000개 입니다.','cl-modal-check-quantity');
                    return false;
                }
                
                count = (count * 1) + 1;

                if(optionStartDate!==undefined && optionStartDate.length > 0){
                    etcTotalCount = 0;

                    var sameOptions = (optionName!='noneOption') ? quickbasketModal.find('input[value="'+optionSeq+'"]').closest('.option-count-box').find('input[name="option_count[]"]') : quickbasketModal.find('input[value="'+optionName+'"]').closest('.option-count-box').find('input[name="option_count[]"]');

                    var sameOptionsTotal = sameOptions.find('.total-quantity').val();
                    sameOptions.each(function(){
                        etcTotalCount += Number($(this).val());
                    });

                    if(etcTotalCount >= totalQuantity) {
                        $(this).blur();
                        $.quickbasket.alertModal('ERROR','재고 수량('+totalQuantity+'개) 이상 구매하실 수 없습니다.','cl-modal-check-quantity');
                        return false;
                    }
                }
                else {
                    if(count + sameCount > totalQuantity) {
                        $(this).blur();
                        $.quickbasket.alertModal('ERROR','재고 수량('+totalQuantity+'개) 이상 구매하실 수 없습니다.','cl-modal-check-quantity');
                        count = totalQuantity - sameCount;
                    }
                }


                $(this).parent().children('input').val(count);
                $.quickbasket.pdTotalPriceUpdate();
            });
            quickbasketModal.find('.option-select-box .box-option-count .min').off('click').on('click', function(e) {
                if($('.cl-modal-check-quantity').length > 0) {
                    e.preventDefault(); 
                    return false; 
                }

                var count = $(this).parent().children('input').val();
                count = (count * 1) - 1;

                if (count < 1) {
                    $(this).blur();
                    $.quickbasket.alertModal('ERROR','최소 구매 수량은 1개 입니다.','cl-modal-check-quantity');
                    e.preventDefault(); 
                    return false;
                }

                $(this).parent().children('input').val(count);
                $.quickbasket.pdTotalPriceUpdate();
            });

            quickbasketModal.find('.option-normal-price').on('keyup blur', function(e) {
                if (e.keyCode == 13 || $('.cl-modal-check-quantity').length > 0) { 
                    e.preventDefault(); 
                    return false; 
                }

                var totalQuantity = $(this).closest('.option-count-box').find('.total-quantity').val(),
                    cnt = $(this).val();
                var state = quickbasketModal.find('#product_state').val();
                var optionSeq = $(this).closest('.option-count-box').find('input[name="option_seq[]"]').val();
                var optionName = $(this).closest('.option-count-box').find('input[name="option_name[]"]').val();
                var optionStartDate = $(this).closest('.option-count-box').find('input[name="etc_start_date[]"]').val();
                var etcTotalCount = 0;
                
                cnt = (cnt) ? Number(cnt.replace(/[^0-9\.]/g,'')) : '';
                if (!cnt) {
                    // if(e.type == 'blur') {
                    //     $.quickbasket.alertModal('ERROR','최소 구매 수량은 1개 입니다.','cl-modal-check-quantity');
                    //     return false;
                    // } else {
                    //     return false;
                    // }
                    e.preventDefault(); 
                    return false;
                }
                $(this).val(cnt);
                
                if(cnt < 1) {
                    $.quickbasket.alertModal('ERROR','최소 구매 수량은 1개 입니다.','cl-modal-check-quantity');
                    $(this).val(1);
                    return false;
                }
                if(totalQuantity==99999 && cnt > 1000) {
                    $.quickbasket.alertModal('ERROR','최대 구매 수량은 1000개 입니다.','cl-modal-check-quantity');
                    cnt = 1000;
                    $(this).val(cnt);
                    return false;
                }

                var target = this;
                var sameCount = 0;
                quickbasketModal.find('input[name="option_seq[]"][value="' + optionSeq + '"]').each(function() {
                    if($(this).closest('.option-count-box').has(target).length === 0) {
                        sameCount += Number($(this).parent().find('input[name="option_count[]"]').val());
                    }
                });

                cnt += sameCount;

                if(optionStartDate!==undefined && optionStartDate.length > 0){
                    etcTotalCount = 0;

                    var sameOptions = (optionName!='noneOption')? quickbasketModal.find('input[value="'+optionSeq+'"]').closest('.option-count-box').find('input[name="option_count[]"]') : quickbasketModal.find('input[value="'+optionName+'"]').closest('.option-count-box').find('input[name="option_count[]"]');

                    var sameOptionsTotal = sameOptions.find('.total-quantity').val();
                    sameOptions.each(function(){
                        etcTotalCount += Number($(this).val());
                    });

                    if(etcTotalCount > totalQuantity) {
                        var $this = $(this).val();
                        $(this).blur();
                        $.quickbasket.alertModal('ERROR','재고 수량('+totalQuantity+'개) 이상 구매하실 수 없습니다.','cl-modal-check-quantity');
                        $(this).val($this-(etcTotalCount-totalQuantity));
                        return false;
                    }
                    
                }
                else {
                    if(cnt > totalQuantity) {
                        $(this).blur();
                        $.quickbasket.alertModal('ERROR','재고 수량('+totalQuantity+'개) 이상 구매하실 수 없습니다.','cl-modal-check-quantity');
                        $(this).val(totalQuantity - sameCount);
                        return false;
                    }
                }

                $.quickbasket.pdTotalPriceUpdate();
            });

            quickbasketModal.find('.option-select-box .box-delete').off('click').on('click', function(e) {
                var optionCountBox = $(this).closest('.option-count-box'),
                    optionName = optionCountBox.find('input[name="option_name[]"]').val();

                if(optionName == 'noneOption') {
                    if(quickbasketModal.find('.cl-s-option-text').length > 0) {
                        quickbasketModal.find('.cl-s-option-text > input').prop('readonly', false);
                        optionCountBox.find('input[name="option_text[]"]').val('');
                    }
                }
                optionCountBox.remove();
                if(quickbasketModal.find('.option-count-box:not(.additional)').length > 0) quickbasketModal.find('.modal-footer .ok-button-dialog').addClass('active');
                else quickbasketModal.find('.modal-footer .ok-button-dialog').removeClass('active');
                
                $.quickbasket.pdTotalPriceUpdate();
            });
        },
        pdTextOptionPick: function (pickBtn, productPrice, type, options_type) {
            // console.log('pdTextOptionPick() ----------------------------------------------');

            var type = (typeof type == 'undefined') ? '' : type,
                pickOption = document.querySelector('#selected-product-option'),
                option = (pickOption !== null) ? pickOption.getAttribute('data-val') : '',
                optionAry = (pickOption !== null) ? option.split('||') : [],
                optionStatus = (pickOption !== null) ? pickOption.getAttribute('data-status') : $(pickBtn).closest('.cl-s-option-text').attr('data-status'),
                optionType = (pickOption !== null) ? pickOption.getAttribute('data-option_type') : type;

            if(optionType == null) optionType = '';
                // _idx = obj.getAttribute('data-idx'),
            var stock = optionAry[2],
                cnt = 0,
                total = 0,
                totalCnt = 1,
                // dateCheckCnt = 1,
                // submit = false,
                // reSelected = false,
                quickbasketModal = $(pickBtn).closest('.cl-quickbasket-modal'),
                parent = $(pickBtn).closest('.cl-s-text-option-selector'),
                textParent = parent.find('.text-option-box'),
                textOptionT = quickbasketModal.find('.cl-s-option-text input[data-option_type="T"], .cl-s-option-text input[data-option_type="TR"]'),
                textOptionTarr = [];
                // selectedBoxTitle = parent.find('.selected-option-title').text(),
                // selectedPrice = $(obj).attr('data-option-price'),
                // onlySelectedText = $(obj).find('.option-name').text();

            // if(selectedOption !== null && typeof obj.getAttribute('data-option_type') != 'undefined') optionType = obj.getAttribute('data-option_type');
            quickbasketModal.find('input[name="option_seq[]"][value="' + optionAry[3] + '"]').each(function() {
                if(textParent.find('input[name="product_state"]').val() == 'download') cnt += 1;
                else cnt += Number($(this).parent().find('input[name="option_count[]"]').val());
            });

            if(cnt + 1 > stock) {
                $(this).blur();
                $.quickbasket.alertModal('ERROR','재고 수량('+stock+'개) 이상 구매하실 수 없습니다.','cl-modal-check-quantity');
                return false;
            }

            // 추가된 기본 옵션
            $.each(quickbasketModal.find('.selected-option.ex'), function(i,v) {
                var ex_option_arry = $(this).attr('data-val').split('||');
                if(ex_option_arry[0] !== undefined) {
                    if(optionAry[0] !== undefined) optionAry[0]+=' / ' + ex_option_arry[0];
                }
                if(ex_option_arry[1] !== undefined) {
                    if(optionAry[1] !== undefined) optionAry[1] = Number(optionAry[1]) + Number(ex_option_arry[1]);
                }
                if(ex_option_arry[3] !== undefined) {
                    if($.quickbasket.data.options_type == '1') {
                        if(optionAry[3] !== undefined) optionAry[3]+=',' + ex_option_arry[3];
                    } else optionAry[3] = ex_option_arry[3];
                }
            });

            if(options_type == 2 || options_type == 3) {
                var md5 = clmd5.hex_md5(optionAry[0]);
                if($.quickbasket.data.list.normal_md5.hasOwnProperty(md5)) {
                    var selected = $.quickbasket.data.list.normal_md5[md5];
                    optionAry[1] = selected['option_price'];
                    optionAry[2] = (optionAry[2] == '99999') ? '99999' : selected['option_quantity'];
                    optionAry[3] = selected['option_seq'];
                } else {
                    alert('옵션 선택에 오류입니다.\n 관리자에게 문의하세요');
                }
            }

            var flag;
            textOptionT.each(function(){
                if(checkEmojis($(this).val())) {
                    alert('이모지를 사용할 수 없습니다.');
                    flag = false;
                    return false;
                }
            });

            if(flag == false) {
                return false;
            }

            textOptionT.each(function(){
                if($(this).val() != "") {
                    var objKey = $(this).attr('data-val');
                    var textTempObj = {};
                    textTempObj[$(this).attr('data-val')] = $(this).val().trim();
                    textOptionTarr.push(textTempObj);
                }
            });

            var textOption = '';
            if(textOptionT.length == textOptionTarr.length) {
                textOption = strReplace(JSON.stringify(textOptionTarr), '"', '&quot;'); //JSON
            } else {
                alert('필수 입력옵션을 모두 입력해주세요.');
                return false;
            }

            // 일반옵션 없을때 처리
            if(optionAry[0] == ' / noneOption') {
                optionAry[0] = optionAry[0].replace(' / noneOption','');
            }

            var html = $.quickbasket.pdOptionBoxHtml(productPrice, type, optionStatus, optionType, optionAry, textOption, textOptionTarr);
            quickbasketModal.find('.option-select-box').append(html);
            
            if(quickbasketModal.find('.option-count-box:not(.additional)').length > 0) quickbasketModal.find('.modal-footer .ok-button-dialog').addClass('active');
            else quickbasketModal.find('.modal-footer .ok-button-dialog').removeClass('active');
            $.quickbasket.pdTotalPriceUpdate();

            if(quickbasketModal.find('.cl-s-normal-option-selector').length > 0 || quickbasketModal.find('.cl-s-option-date-selector').length > 0) textParent.find('input').val('').prop('readonly', true);
            else textParent.find('input').val('');

            quickbasketModal.find('#selected-product-option .selected-option-text').text('선택');
            quickbasketModal.find('#selected-product-option').attr('data-selected_option', '');
            quickbasketModal.find('#selected-product-option').attr('data-val', '');
            quickbasketModal.find('#selected-product-option').attr('data-status', '');
            $(pickBtn).addClass('disabled');

            // 추가된 기본 옵션 처리
            quickbasketModal.find('.selected-option.ex').attr('data-selected_option', '');
            quickbasketModal.find('.selected-option.ex').attr('data-val', '');
            quickbasketModal.find('.selected-option.ex').attr('data-status', '');
            quickbasketModal.find('.selected-option.ex').parents('.cl-s-option-selector').addClass('option-disabled');

            quickbasketModal.find('#etc-start-date-option, #etc-end-date-option, #etc-time, #etc-start-date-txt, #etc-end-date-txt').val('');
            quickbasketModal.find('.selected-option > span').each(function(idx, v){
                if($(v).attr('data-default') !== undefined) {
                    $(v).text($(v).attr('data-default'));
                }
            });

            // $.quickbasket.pdOptionPick(this, \'' + data.option_data.product_price + '\')


            quickbasketModal.find('.option-select-box .box-option-count .plus').off('click').on('click', function(e) {
                if($('.cl-modal-check-quantity').length > 0) {
                    e.preventDefault(); 
                    return false; 
                }

                var totalQuantity = $(this).closest('.option-count-box').find('.total-quantity').val();
                var count = $(this).parent().children('input').val();
                var state = quickbasketModal.find('#product_state').val();
                var optionSeq = $(this).closest('.option-count-box').find('input[name="option_seq[]"]').val();
                var optionName = $(this).closest('.option-count-box').find('input[name="option_name[]"]').val();
                var optionStartDate = $(this).closest('.option-count-box').find('input[name="etc_start_date[]"]').val();
                var etcTotalCount = 0;

                var target = this;
                var sameCount = 0;
                quickbasketModal.find('input[name="option_seq[]"][value="' + optionSeq + '"]').each(function() {
                    if($(this).closest('.option-count-box').has(target).length === 0) {
                        sameCount += Number($(this).parent().find('input[name="option_count[]"]').val());
                    }
                });


                if (count > 1000) {
                    // alert('최대 구매 수량은 1000개 입니다.');
                    $(this).blur();
                    $.quickbasket.alertModal('ERROR','최대 구매 수량은 1000개 입니다.','cl-modal-check-quantity');
                    return false;
                }
                
                count = (count * 1) + 1;

                if(optionStartDate!==undefined && optionStartDate.length > 0){
                    etcTotalCount = 0;

                    var sameOptions = (optionName!='noneOption') ? quickbasketModal.find('input[value="'+optionSeq+'"]').closest('.option-count-box').find('input[name="option_count[]"]') : quickbasketModal.find('input[value="'+optionName+'"]').closest('.option-count-box').find('input[name="option_count[]"]');

                    var sameOptionsTotal = sameOptions.find('.total-quantity').val();
                    sameOptions.each(function(){
                        etcTotalCount += Number($(this).val());
                    });

                    if(etcTotalCount >= totalQuantity) {
                        // alert('재고 수량('+totalQuantity+'개) 이상 구매하실 수 없습니다.');
                        $(this).blur();
                        $.quickbasket.alertModal('ERROR','재고 수량('+totalQuantity+'개) 이상 구매하실 수 없습니다.','cl-modal-check-quantity');
                        return false;
                    }
                }
                else {
                    if(count + sameCount > totalQuantity) {
                        // alert('재고 수량('+totalQuantity+'개) 이상 구매하실 수 없습니다.');
                        $(this).blur();
                        $.quickbasket.alertModal('ERROR','재고 수량('+totalQuantity+'개) 이상 구매하실 수 없습니다.','cl-modal-check-quantity');
                        count = totalQuantity - sameCount;
                    }
                }


                $(this).parent().children('input').val(count);
                $.quickbasket.pdTotalPriceUpdate();
            });
            quickbasketModal.find('.option-select-box .box-option-count .min').off('click').on('click', function(e) {
                if($('.cl-modal-check-quantity').length > 0) {
                    e.preventDefault(); 
                    return false; 
                }

                var count = $(this).parent().children('input').val();
                count = (count * 1) - 1;

                if (count < 1) {
                    $(this).blur();
                    $.quickbasket.alertModal('ERROR','최소 구매 수량은 1개 입니다.','cl-modal-check-quantity');
                    return false;
                }

                $(this).parent().children('input').val(count);
                $.quickbasket.pdTotalPriceUpdate();
            });
            quickbasketModal.find('.option-normal-price').on('keyup blur', function(e) {
                if (e.keyCode == 13 || $('.cl-modal-check-quantity').length > 0) { 
                    e.preventDefault(); 
                    return false; 
                }

                var totalQuantity = $(this).closest('.option-count-box').find('.total-quantity').val(),
                    cnt = $(this).val();
                var state = quickbasketModal.find('#product_state').val();
                var optionSeq = $(this).closest('.option-count-box').find('input[name="option_seq[]"]').val();
                var optionName = $(this).closest('.option-count-box').find('input[name="option_name[]"]').val();
                var optionStartDate = $(this).closest('.option-count-box').find('input[name="etc_start_date[]"]').val();
                var etcTotalCount = 0;

                cnt = (cnt) ? Number(cnt.replace(/[^0-9\.]/g,'')) : '';
                if (!cnt) {
                    // if(e.type == 'blur') {
                    //     $.quickbasket.alertModal('ERROR','최소 구매 수량은 1개 입니다.','cl-modal-check-quantity');
                    //     return false;
                    // } else {
                    //     return false;
                    // }
                    e.preventDefault(); 
                    return false;
                }
                $(this).val(cnt);
                
                if(cnt < 1) {
                    $.quickbasket.alertModal('ERROR','최소 구매 수량은 1개 입니다.','cl-modal-check-quantity');
                    $(this).val(1);
                    return false;
                }
                if(totalQuantity==99999 && cnt > 1000) {
                    $.quickbasket.alertModal('ERROR','최대 구매 수량은 1000개 입니다.','cl-modal-check-quantity');
                    cnt = 1000;
                    $(this).val(cnt);
                    return false;
                }

                var target = this;
                var sameCount = 0;
                quickbasketModal.find('input[name="option_seq[]"][value="' + optionSeq + '"]').each(function() {
                    if($(this).closest('.option-count-box').has(target).length === 0) {
                        sameCount += Number($(this).parent().find('input[name="option_count[]"]').val());
                    }
                });

                cnt += sameCount;

                if(optionStartDate!==undefined && optionStartDate.length > 0){
                    etcTotalCount = 0;

                    var sameOptions = (optionName!='noneOption')? quickbasketModal.find('input[value="'+optionSeq+'"]').closest('.option-count-box').find('input[name="option_count[]"]') : quickbasketModal.find('input[value="'+optionName+'"]').closest('.option-count-box').find('input[name="option_count[]"]');

                    var sameOptionsTotal = sameOptions.find('.total-quantity').val();
                    sameOptions.each(function(){
                        etcTotalCount += Number($(this).val());
                    });

                    if(etcTotalCount > totalQuantity) {
                        var $this = $(this).val();
                        $(this).blur();
                        $.quickbasket.alertModal('ERROR','재고 수량('+totalQuantity+'개) 이상 구매하실 수 없습니다.','cl-modal-check-quantity');
                        $(this).val($this-(etcTotalCount-totalQuantity));
                        return false;
                    }
                    
                }
                else {
                    if(cnt > totalQuantity) {
                        $(this).blur();
                        $.quickbasket.alertModal('ERROR','재고 수량('+totalQuantity+'개) 이상 구매하실 수 없습니다.','cl-modal-check-quantity');
                        $(this).val(totalQuantity - sameCount);
                        return false;
                    }
                }

                $.quickbasket.pdTotalPriceUpdate();
            });
            quickbasketModal.find('.option-select-box .box-delete').off('click').on('click', function(e) {
                var optionCountBox = $(this).closest('.option-count-box');
                var optionName = optionCountBox.find('input[name="option_name[]"]').val();
                if(optionName == 'noneOption') {
                    if(quickbasketModal.find('.cl-s-option-text').length > 0) {
                        quickbasketModal.find('.cl-s-option-text > input').prop('readonly', false);
                        optionCountBox.find('input[name="option_text[]"]').val('');
                    }
                }
                $(this).closest('.option-count-box').remove();
                if(quickbasketModal.find('.option-count-box:not(.additional)').length > 0) quickbasketModal.find('.modal-footer .ok-button-dialog').addClass('active');
                else quickbasketModal.find('.modal-footer .ok-button-dialog').removeClass('active');
                $.quickbasket.pdTotalPriceUpdate();
            });
        },
        pdTotalPriceUpdate: function () {
            var total_price = 0,
                total_cnt = 0;
            $('.cl-quickbasket-modal .option-select-box').find('.option-count-box:not(.additional)').each(function() {
                var unti_price = $(this).find('input[name="option_price[]"]').val(),
                    cnt = $(this).find('.option-normal-price').val(),
                    price = (Number(unti_price) * Number(cnt));

                total_price += price;
                total_cnt += Number(cnt);

                $(this).find('.option-price').text(number_format(price));
            });

            
            $('.cl-quickbasket-modal .option-select-box').find('.option-count-box.additional').each(function() {
                var unti_price = $(this).find('input[name="option_price[]"]').val(),
                    cnt = $(this).find('.option-normal-price').val(),
                    price = (Number(unti_price) * Number(cnt));

                total_price += price;
                total_cnt += Number(cnt);

                $(this).find('.option-price').text(number_format(price));
            });

            $('.cl-quickbasket-modal .total-price-box .total-price').text(number_format(total_price));
            $('.cl-quickbasket-modal .total-price-box .total-cnt').text(total_cnt);
        },
        setKeepShopping : function(sid,page,pid,pnum) {
            if(typeof sid == 'undefined') sid = RENDER.b.SID;
            if(typeof page == 'undefined') page = (RENDER.b.VIEW) ? RENDER.b.PARENT.ppage : RENDER.b.PAGE;
            if(typeof pid == 'undefined') pid = (RENDER.b.VIEW) ? RENDER.b.PARENT.pid : '';
            if(typeof pnum == 'undefined') pnum = (RENDER.b.VIEW) ? RENDER.b.PARENT.seq : '';

            var cookie_g = $.cookie('gallery'),
                cookie_keepsh = [];
            if(typeof cookie_g != 'undefined' && cookie_g) {
                cookie_keepsh = [page,cookie_g,$.cookie('loadmore-'+cookie_g),$.cookie('gallery-category-'+cookie_g),$.cookie('gallery-orderby-'+cookie_g),$.cookie('gallery-item')];
            } else {
                if(pid && pnum) cookie_keepsh = [page,pid,'1','','recent',pnum];
            }

            if(cookie_keepsh.length > 0) $.cookie('keep-shopping-'+sid, cookie_keepsh.toString(), { path : '/', expires: new Date(Date.now() + 1000*60*60*3) });
        },
    }

    $.products = {
        init : function() {
            $.category.init();
            var isMainImageClick = false, idx = -1, replace = false;
            $(document)
            .off('click', '.cl-p-modal')
            .on('click', '.cl-p-modal', function(e) {
                if($('#prod-category-lists').css('display') == 'block') {
                    $('.category-lists').slideUp(200, function() {
                        $('.category-wrap').removeClass('open');    
                    });
                }
                $('.option-price-status-select').slideUp(200, function() {
                    $('.option-price-status-str').removeClass('open');    
                });
                if($('.gallery-menus-wrap').css('display') == 'block') {
                    $('.choose-gallery').removeClass('open');
                    $('.gallery-menus-wrap').hide();
                }
            });

            $(document)
            .off('click','.form-label.textarea')
            .on('click','.form-label.textarea', function() { $('#prod-desc').focus(); });
            $(document)
            .off('click','.prod-modal .modal-close')
            .on('click','.prod-modal .modal-close', function() { $.products.close(); });

            $(document)
            .off('keydown, keyup', '#prod-desc')
            .on('keydown, keyup', '#prod-desc', function(){
                $('#prod-desc')[0].style.height = 'auto';
                var descHeight = $('#prod-desc').prop('scrollHeight');
                if(descHeight > 55) {
                    $('#prod-desc').css('height', descHeight+'px');
                }

                //size check
                var value = $(this).val();        
                if(value.length > 255){
                    $(this).val(value.substr(0,255).trim());
                }
            });

            $(document)
            .off('change','.switch-product')
            .on('change','.switch-product', function() {
                $('.switch-product + label').removeClass('active');
                if($(this).val() == 'off') {
                    $('#status-append').fadeOut(0);
                    $('#sale-calendar').hide();
                } else {
                    var check = $('input[name="product_state"]:checked').val();
                    var a = 0;

                    if ($('#none-option-file').length > 0) {
                        var fileBoxCnt = $('.file-box-list').length;
                        $('.file-box-list').each(function (idx, v) {
                            var downloadCnt = $(v).find('.file-name').length;
                            if (fileBoxCnt > 1) {
                                if (a == 0) a++;
                                else {
                                    if (check == 'D' && downloadCnt == 0) {
                                        alert('다운로드 상품일 경우 파일이 1개 이상 등록되어 있어야 합니다.');
                                        $('.switch-product[value="off"]').prop('checked', true);
                                        $('#status-append').fadeOut(0);
                                        $('#sale-calendar').hide();
                                        a++;
                                        return false;
                                    }
                                }
                            } else {
                                if (check == 'D' && downloadCnt == 0) {
                                    alert('다운로드 상품일 경우 파일이 1개 이상 등록되어 있어야 합니다.');
                                    $('.switch-product[value="off"]').prop('checked', true);
                                    $('#status-append').fadeOut(0);
                                    $('#sale-calendar').hide();
                                    a += 2;
                                    return false;
                                }
                            }
                        });
                        if (a <= 1) {
                            $(this).prop('checked', true);
                        }
                    } else {
                        $(this).prop('checked', true);
                    }

                    if(a <= 1) {
                        if($(this).val() == 'lim') {
                            $('#status-append').fadeIn(0);
                            $('#sale-calendar').show();
                        } else {
                            $('#status-append').fadeOut(0);
                            $('#sale-calendar').hide();
                        }
                    }
                }
            });
            $(document)
            .off('change','.switch-quantity')
            .on('change','.switch-quantity', function() { //재고관리 on
                switchQuantity();
            });
            $(document)
            .off('click','.switch-category')
            .on('click','.switch-category', function() {
                if($(this).is(':checked')) {
                    $(this).parents('.form-wrap').removeClass('disabled');
                    $(this).parents('.form-wrap').find('.category-text').removeClass('hide');
                } else {
                    $(this).parents('.form-wrap').addClass('disabled');
                    $(this).parents('.form-wrap').find('.category-text').addClass('hide');
                    $('.category-lists').slideUp(200, function() {
                        $('.category-wrap').removeClass('open');    
                    });                    
                }
            });
            $(document)
            .off('change','.switch-text-option')
            .on('change','.switch-text-option', function() {
                if($(this).is(':checked')) {
                    $(this).parents('.form-wrap').removeClass('disabled');
                    $(this).parents('.form-wrap').find('#text-option-name').removeClass('hide');
                } else {
                    $(this).parents('.form-wrap').addClass('disabled');
                    $(this).parents('.form-wrap').find('#text-option-name').addClass('hide');
                }
            });

            $(document)
            .off('click','.switch-prod-info')
            .on('click','.switch-prod-info', function() {
                if($(this).is(':checked')) {
                    $(this).parents('.form-wrap').removeClass('disabled');
                    $(this).parents('.form-wrap').find('.info-selected').removeClass('hide');
                } else {
                    $(this).parents('.form-wrap').addClass('disabled');
                    $(this).parents('.form-wrap').find('.info-selected').addClass('hide');

                }
            });

            $(document)
            .off('click','.switch-mngprd')
            .on('click','.switch-mngprd', function() {
                if($(this).is(':checked')) {
                    $('#mng-prd-info').removeClass('disabled');
                    $(this).parents('.mng-prd-wrap').find('.mng-prd-info-toggle').removeClass('hide');
                } else {
                    $('#mng-prd-info').addClass('disabled');
                    $(this).parents('.mng-prd-wrap').find('.mng-prd-info-toggle').addClass('hide');
                }
            });

            $(document)
            .off('click', '.prod-discount-unit-select:not(.disabled)')
            .on('click', '.prod-discount-unit-select:not(.disabled)', function(e) {
                $(this).find('.discount-unit-select').toggle();
            });

            $(document)
            .off('click', '.discount-unit-select > div')
            .on('click','.discount-unit-select > div', function(e) {
                var val = $(this).attr('data-value');
                var unitStr = $(this).text();

                $('#prod-discount-unit').attr('data-value', val).text(unitStr);

                if(val == 'P') {
                    var discountRate = Number($('#prod-discount-rate').val().replace(/,/g, ''));
                    if(discountRate > 100) discountRate = 100;
                    $('#prod-discount-rate').val(discountRate);
                    // $('#price-cut-btn').removeClass('hide');
                } else {
                    var discountRate = removeCommas($('#prod-discount-rate').val());
                    $('#prod-discount-rate').val(number_format(discountRate));
                    // $('#price-cut-btn').addClass('hide');
                }

                calDiscount($('#prod-discount-rate'));
            });

            $(document)
            .off('click','.switch-pccc, .switch-require-navershop')
            .on('click','.switch-pccc, .switch-require-navershop', function(e) {
                if($(this).closest('.input-switch').hasClass('editor-upgrade-popup')) {
                    e.preventDefault();
                    return false;
                }

                // 네이버쇼핑 off 시 안내팝업
                if($(this).hasClass('switch-require-navershop') && $(this).closest('.form-wrap').hasClass('use-nshop-setting')) {
                    var modal_description = 'DBURL 기능을 사용하고 있지 않습니다.<br>DBURL 기능을 사용으로 설정 후 이용할 수 있습니다.';
                    var link = (uadmin == 'um' ? '/_admin' : '') + '/shopping/setting/T';
                    var btnstr = '<div class="btn-box">\
                        <a href="' + link + '" target="_blank" style="line-height:2;">DBURL 설정하러 가기</a>\
                        <button type="button" class="btn btn-default btn-sm close-button-dialog" data-dismiss="modal">' + $.lang[LANG]['config.close'] + '</button>\
                    </div>\
                    ';
                    
                    var str = '\
                        <div class="site-upgrade-notice">\
                            <p><span class="text-centermodal">' + modal_description + '</span></p>\
                            ' + btnstr +
                        '</div>\
                    ';
                    $(this).showModalFlat('안내', str, false, false, '', '', '', 'cl-cmmodal cl-s-btn w560 cl-p0');
                    e.preventDefault();
                    return false;
                }

                if($(this).is(':checked')) {
                    $(this).parents('.form-wrap').removeClass('disabled');
                } else {
                    $(this).parents('.form-wrap').addClass('disabled');
                }
            });
            
            $(document)
            .off('click','.check-sale > .checkbox > label')
            .on('click','.check-sale > .checkbox > label', function() {
                if($(this).prev('input').is(':disabled')) {
                    alert('0원인 상품은 할인을 할 수 없습니다.');
                    return false;
                }
            });

            $(document)
            .off('click','#prod-sale-check')
            .on('click','#prod-sale-check', function() {
                if($(this).parents('.check-sale').hasClass('disabled')) {
                    alert('가격이 연동이 활성화 되어있습니다.\n가격연동을 먼저 해제하세요');
                    return false;
                }
                
                $('.form-group.discount-append + .error-msg').remove();
                if($(this).is(':checked')) {
                    var prod_price = ($('#prod-price').val()) ? $('#prod-price').val() : 0;
                    $('#prod-sale').addClass('strike');
                    $('#prod-sale').text(prod_price);
                    $('#prod-sale').show();
                    $('.discount-append').removeClass('hide');
                    // $('#prod-price').val('').attr('placeholder','할인 가격을 입력하세요').focus();
                    $('#prod-price').prop('readonly', true);
                    $('#prod-price').addClass('sale-on');
                    $('#check-sale').html('<path d="M13 0H3C1.34 0 0 1.34 0 3v10c0 1.66 1.34 3 3 3h10c1.66 0 3-1.34 3-3V3C16 1.34 14.66 0 13 0zM13.03 6.03l-5.5 5.5C7.38 11.68 7.19 11.75 7 11.75s-0.38-0.07-0.53-0.22l-3.5-3.5c-0.29-0.29-0.29-0.77 0-1.06s0.77-0.29 1.06 0L7 9.94l4.97-4.97c0.29-0.29 0.77-0.29 1.06 0S13.32 5.74 13.03 6.03z"/>');
                    $('.check-sale').removeClass('unchecked').addClass('checked');
                    calDiscount($('#prod-discount-rate'));
                } else {
                    var prod_price = ($('#prod-sale').text()) ? $('#prod-sale').text() : '';
                    $('#prod-price').val(prod_price);
                    $('#prod-price').prop('readonly', false);
                    $('#prod-price').removeClass('sale-on').focus();
                    // $('#prod-price').removeClass('sale-on').attr('placeholder','가격을 입력하세요').focus();
                    $('#prod-sale').removeClass('strike');
                    $('#prod-sale').hide();
                    $('.discount-append').addClass('hide');
                    $('#check-sale').html('<path d="M13 0H3C1.3 0 0 1.3 0 3v10c0 1.7 1.3 3 3 3h10c1.7 0 3-1.3 3-3V3C16 1.3 14.7 0 13 0zM15 13c0 1.1-0.9 2-2 2H3c-1.1 0-2-0.9-2-2V3c0-1.1 0.9-2 2-2h10c1.1 0 2 0.9 2 2V13z"/>');
                    $('.check-sale').removeClass('checked').addClass('unchecked');
                    calInputWidth($('#prod-price'));
                }
            });

            $(document)
            .off('click','#price-cut-btn')
            .on('click','#price-cut-btn', function() {
                if($(this).hasClass('disabled')) {
                    $(this).showModalFlat('','원단위 절사 버튼은 판매가 원단위가 1이상인 경우에만 사용할 수 있습니다.',true,false,'','ok','','cl-cmmodal cl-s-btn w560 cl-p130 cl-t80 cl-modal cl-none-title cl-close-btn','','',function() {
                        $(document).on('keydown', function(e) {
                            if(e.keyCode == 27) modal.modal('hide');
                        });
                    });
                    return false;
                }
                if($('#prod-discount-unit').attr('data-value') == 'P') {
                    var orgPrice = Number(removeCommas($('#prod-sale').text()));
                    var discountRate = Number($('#prod-discount-rate').val());
                    var discountPrice = orgPrice * (discountRate / 100);
                    var price = ($('#prod-price').val()) ? Number(removeCommas($('#prod-price').val())) : 0;

                    price = Math.floor(price / 10) * 10;
                    discountRate = Math.round(((orgPrice - price) / orgPrice) * 100);

                    $('#prod-price').val(number_format(price));
                    $('#prod-discount-rate').val(discountRate);

                    $(this).addClass('disabled');
                }
            });

            $(document)
            .off('input', '#prod-price')
            .on('input', '#prod-price', function () {
                var price = $(this).val().replace(/[\u3131-\u318E\uAC00-\uD7A3]/g, '');
                price = removeCommas(price);
                price = price * 1;
                var nPrice = Number(price);

                if(!nPrice || nPrice == 0) {
                    $('#prod-sale-check').prop('disabled', true);
                } else {
                    $('#prod-sale-check').prop('disabled', false);
                }

                if(nPrice > 1000000000) {
                    $(this).val('1,000,000,000');
                }

                calInputWidth($(this));
            });

            $(document)
            .off('focusout', '#prod-price')
            .on('focusout', '#prod-price', function () {
                if($(this).prop('readonly') == true) return false;
                
                var price = $(this).val().replace(/[\u3131-\u318E\uAC00-\uD7A3]/g, '');
                price = removeCommas(price);
                price = price * 1;

                var nPrice = Number(price),
                    submit = true;

                if(nPrice > 1000000000) price = 1000000000;

                // 옵션 가격 검색
                $.each($('.prod-option-price'), function(i,v) {
                    var oPrice = $(this).attr('data-option-price');
                    if(i > 0) {
                        if(nPrice + Number(oPrice) < 0) {
                            $(this).click();
                            $(this).parents('li').addClass('err');
                            submit = false;
                        }
                    }
                });

                if(submit) {                   
                    price = addCommas(price);
                    $(this).val(price);
                } else {
                    alert('판매가가 0원 아래로 적용될 수 있는 옵션 가격이 존재하여 변경할 수 없습니다.');
                    $(this).val(price);
                }

                if(!nPrice || nPrice == 0) {
                    $('#prod-sale-check').prop('disabled', true);
                } else {
                    $('#prod-sale-check').prop('disabled', false);
                }

                calInputWidth($(this));
            });

            $(document)
            .off('input', '#prod-discount-rate')
            .on('input', '#prod-discount-rate', function(){
                calDiscount($(this));
            });

            $(document)
            .off('focusout', '#prod-discount-rate')
            .on('focusout', '#prod-discount-rate', function(){
                var discountUnit = $('#prod-discount-unit').attr('data-value');
                var discountRate = $(this).val();
                $(this).removeClass('empty');
                $('.form-group.discount-append + .error-msg').remove();
                
                if(discountRate) {
                    if(discountUnit == 'P') {
                        var percentVal = Number((Math.floor(discountRate * 100) / 100).toFixed(2));
                        $(this).val(percentVal);
                    }
                } else {
                    $(this).val(0);
                }

                if($(this).val() == 0) {
                    var error_str = '<svg viewBox="0 0 13 13" width="13" height="13"><path d="M6.5 0C2.91 0 0 2.91 0 6.5S2.91 13 6.5 13 13 10.09 13 6.5 10.09 0 6.5 0zM6.5 12.13c-3.11 0-5.63-2.53-5.63-5.63S3.39 0.87 6.5 0.87s5.63 2.53 5.63 5.63S9.61 12.13 6.5 12.13z"></path><path d="M7.44 9.58c-0.1-0.02-0.18-0.05-0.25-0.1C7.12 9.44 7.07 9.37 7.03 9.28 6.98 9.19 6.96 9.07 6.96 8.92V5h-1.7v0.4h0.03c0.11 0 0.21 0.01 0.3 0.02 0.09 0.02 0.18 0.05 0.25 0.09 0.07 0.05 0.13 0.11 0.17 0.2 0.04 0.09 0.06 0.2 0.06 0.34v2.91c0 0.14-0.02 0.25-0.06 0.34C5.97 9.39 5.91 9.45 5.84 9.5 5.77 9.54 5.68 9.57 5.59 9.58 5.49 9.6 5.39 9.6 5.29 9.6H5.16v0.4h2.71V9.6H7.75C7.64 9.6 7.54 9.6 7.44 9.58z"></path><rect x="6" y="3" width="1" height="1"></rect></svg>\
                    1 이상 입력해 주세요.';
                    $('.form-group.discount-append').after('<div class="error-msg c-red">'+error_str+'</div>');
                    $(this).addClass('empty');
                }
            });

            $(document)
            .off('click','.prod-item-image-add,.prod-item-image')
            .on('click','.prod-item-image-add,.prod-item-image',function(e) {
                idx = -1;
                isMainImageClick = ($(this).hasClass('prod-item-image')) ? true : false;
                replace = (isMainImageClick && $('.prod-item-image .preview-img').length) ? true : false;
                if($(this).hasClass('.prod-item-image-add')) {
                    $('img').removeClass('replace');
                }
                if($(this).hasClass('.prod-item-image')) $(this).find('.preview-img').addClass('replace');
                $.resource.open();
            });

            $(document)
            .off('click','.prod-item-thumb img:not(.guide-img)')
            .on('click','.prod-item-thumb img:not(.guide-img)',function(e) {
                isMainImageClick = false;
                idx = $(this).parent().index();
                replace = true;
                $(this).addClass('replace');
                $(this).attr('data-idx',idx);
                $.resource.open();
            });

            $(document)
            .off('hover', '.prod-item-thumb li')
            .on('hover', '.prod-item-thumb li',function(e) {
                e.stopPropagation();
                $('.img-delete').hide();
                $(this).find('.img-delete').show();
            });

            $(document)
            .off('click','.img-delete')
            .on('click','.img-delete',function(e) {
                $(this).parent().remove();
                if($('.prod-item-thumb li').length < 11) $('.prod-item-image-add').removeClass('hide');
                if($(this).index() == 1) {
                    var src = $('.prod-item-thumb li:not(.prod-item-image-add):eq(0)').find('img:not(.guide-img)').attr('src');
                    if(typeof src != 'undefined') {
                        src = src.replace('/250/','/800/');
                        $('.prod-item-image .preview-img').css('background-image', 'url("'+ src +'")');
                    } else {
                        $('.prod-item-image').removeClass('active').find('.preview-img').remove();
                    }
                }
            });

            $(document)
            .off('click','.resource-useit')
            .on('click','.resource-useit',function(e) {
                var isLink = $(this).attr('data-property');
                if(typeof flinkChange !== 'function' && isLink == 'flink-change') {
                    setFileLink();
                    return false;
                }
                if($('.prod-modal').length == 0) return;

                var useitResourceTab = $(this).closest('.tab-pane.active'),
                    useitResourceSelected = useitResourceTab.find('.resource-selected-ul'),
                    useitResourceBtn = $(this),
                    rmode = useitResourceTab.attr('id').replace(/storage$/gi,'');

                if(useitResourceSelected.children('li').length == 0) {
                    var z_idx = ($('.flink-fileupload').length) ? 'z-1044' : 'z-1042';
                    var error_modal = $(this).showModalFlat($.lang[LANG]['config.information'], $.lang[LANG]['editor.resource.useit'], true, false, '', 'ok', '', 'cl-p130 cl-cmmodal cl-s-btn w560 cl-p0 cl-okbtn-pbt70', '', '', '', function() {
                        useitResourceBtn.removeClass('clicked');
                    });
                    error_modal.closest('.flat-modal').addClass(z_idx);
                    return;
                }

                var imgs = $.resource.selected(),
                    empty = ($('.prod-item-image').find('.preview-img').length) ? false : true;

                var url = (typeof RESOURCE == 'undefined') ? property.RESOURCE : RESOURCE,
                    site = (typeof SID == 'undefined') ? property.SID : SID,
                    folder = '', f = '';

                var thumbs = $('.prod-item-thumb li:not(.prod-item-image-add)').length,
                    remain = 10-thumbs;

                replace = ($('.replace').length) ? true : false;
                if(imgs.length > remain && !replace) imgs.length = remain;
                if(replace) imgs.length = 1;
                if(replace && imgs.length > 1) {
                    $(this).showModalFlat('INFORMATION', $.lang[LANG]['editor.resource.choose.count.1'], true, false, '', 'ok');
                    useitResourceBtn.removeClass('clicked');
                    return false;
                }
                if(rmode == 'free' && useitResourceSelected.children('li').length > 0) {
                    $.processON('Image upload to storage...');
                    var frUpload = frStorageUpload(imgs.join('|'),800);

                    frUpload.then(function(data) {
                        $.each(data.u, function(i,v) {
                            if(empty && i == 0) {
                                folder = 800;
                                f = v.path + folder + '/' + v.file;
                                var thumb = v.path + '250/' + v.file,
                                    img_src = (v.magic) ? v.magic : v.file,
                                    src_s800 = getServeImage(img_src,'800',v.path),
                                    src_s250 = getServeImage(img_src,'250',v.path);

                                $('.prod-item-image').append('<div class="preview-img" style="background-image: url(' + src_s800 + ')">').addClass('active');
                                $('.prod-item-thumb .prod-item-image-add').before('<li><img src="' + src_s250 + '"><span class="img-delete"><i class="fa fa-times-circle" aria-hidden="true"></i></span></li>');
                            } else {
                                if(isMainImageClick && i == 0) {
                                    folder = 800;
                                    f = v.path + folder + '/' + v.file;
                                    var thumb = v.path + '250/' + v.file,
                                        img_src = (v.magic) ? v.magic : v.file,
                                        src_s800 = getServeImage(img_src,'800',v.path),
                                        src_s250 = getServeImage(img_src,'250',v.path);

                                    $('.prod-item-image').addClass('active').find('.preview-img').css('background-image','url("'+ src_s800 +'")');
                                    if($('.prod-item-thumb .prod-item-image-add').before().hasClass('.prod-item-image-add')) {
                                        $('.prod-item-thumb .prod-item-image-add').before('<li><img src="' + src_s250 + '"><span class="img-delete"><i class="fa fa-times-circle" aria-hidden="true"></i></span></li>');
                                    } else {
                                        $('.prod-item-thumb li:eq(0) img').replaceWith('<img src="' + src_s250 + '">');   
                                    }
                                } else {
                                    folder = 250;
                                    f = v.path + folder + '/' + v.file;
                                    var thumb = v.path + '250/' + v.file,
                                        img_src = (v.magic) ? v.magic : v.file,
                                        src_s800 = getServeImage(img_src,'800',v.path),
                                        src_s250 = getServeImage(img_src,'250',v.path);

                                    if(idx > -1) {
                                        if(idx == 0) $('.prod-item-image .preview-img').css('background-image', 'url("' + src_s800 + '")');
                                        $('.prod-item-thumb li:eq(' + idx +') img').replaceWith('<img src="' + src_s250 + '">');
                                    } else {
                                        $('.prod-item-thumb .prod-item-image-add').before('<li><img src="' + src_s250 + '"><span class="img-delete"><i class="fa fa-times-circle" aria-hidden="true"></i></span></li>');
                                    }
                                }
                            }
                            if(imgs.length) $('.prod-item-image').removeClass('empty');
                            if($('.prod-item-thumb li').length > 10) $('.prod-item-image-add').addClass('hide');
                        });
                        $('#el-fileupload').modal('hide');
                    });
                } else {
                    $.each(imgs, function(i,v) {
                        if(empty && i == 0) {
                            p = url + '/' + site + '/';
                            var thumb = p + '250/' + v,
                                src_s800 = getServeImage(v,"800",p),
                                src_s250 = getServeImage(v,"250",p);
                            $('.prod-item-image').append('<div class="preview-img" style="background-image: url(' + src_s800 + ');">').addClass('active');
                            $('.prod-item-thumb .prod-item-image-add').before('<li><img src="' +  src_s250 + '"><span class="img-delete"><i class="fa fa-times-circle" aria-hidden="true"></i></span></li>');
                        } else {
                            if(isMainImageClick && i == 0) {
                                p = url + '/' + site + '/';
                                var thumb = p + '250/' + v,
                                    src_s800 = getServeImage(v,"800",p),
                                    src_s250 = getServeImage(v,"250",p);
                                $('.prod-item-image').addClass('active').find('.preview-img').css('background-image','url("'+ src_s800 +'")');
                                $('.prod-item-thumb li:eq(0) img').replaceWith('<img src="' + src_s250 + '">');
                            } else {
                                p = url + '/' + site + '/';
                                var thumb = p + '250/' + v,
                                    src_s800 = getServeImage(v,"800",p),
                                    src_s250 = getServeImage(v,"250",p);
                                if(idx > -1) {
                                    if(idx == 0) $('.prod-item-image .preview-img').css('background-image', 'url("' + src_s800 + '")');
                                    $('.prod-item-thumb li:eq(' + idx +') img').replaceWith('<img src="' + src_s250 + '">');
                                } else {
                                    $('.prod-item-thumb .prod-item-image-add').before('<li><img src="' + src_s250 + '"><span class="img-delete"><i class="fa fa-times-circle" aria-hidden="true"></i></span></li>');
                                }
                            }
                        }
                    });
                }
                if(imgs.length) $('.prod-item-image').removeClass('empty');
                if($('.prod-item-thumb li').length > 10) $('.prod-item-image-add').addClass('hide');
                $('#el-fileupload').modal('hide');
                useitResourceBtn.removeClass('clicked');
            });
            
            $(document)
            .off('keyup', '.option-price-number')
            .on('keyup', '.option-price-number', function(e) {
                var key = e.keyCode || e.which;
                    txt = $(this).val();
                var match;

                if($(this).closest('.prod-option').attr('data-option_mode') == 'additional') {
                    match = txt.match(/[0-9]+/g);
                } else {
                    match = txt.match(/[0-9,\-\+]+/g);
                }
                
                $(this).val(match);
                var price = removeCommas($('#prod-price').val()),
                    input = (match == null) ? 0 : removeCommas(match[0]);

                if(parseInt(price) + parseInt(input) < 0) {
                    alert('판매가가 0원 아래로 적용될 수 있는 옵션 가격입니다.');
                    $(this).val('0').focus();
                }
            });

            $(document)
            .off('keyup', '#brand')
            .on('keyup', '#brand', function (e) {
                var key = e.keyCode || e.which;
                    txt = $(this).val();
                var match = txt.match(/[a-zA-Zㄱ-ㅎㅏ-ㅣ가-힣0-9-_/:&+() ]/g);
                if (match != null) {
                    $(this).val(match.join(''));
                } else {
                    $(this).val('');
                }
            });

            $(document)
            .off('click','.choose-gallery')
            .on('click','.choose-gallery', function(e) {
                e.stopPropagation();
                var pid = $('#prod-pid').val();
                $(this).toggleClass('open');
                $('.gallery-menus-wrap').toggle();
                $('.gallery-menus-wrap .gallery-menus li').removeClass('active');
                $('.gallery-menus-wrap .gallery-menus li.gallery-name[data-gallery-id="' + pid + '"]').addClass('active');
            });

            $(document)
            .off('click','.gallery-menus-wrap .gallery-menus li')
            .on('click','.gallery-menus-wrap .gallery-menus li', function(e) {
                e.stopPropagation();
                if($(this).hasClass('gallery-name')) {
                    var pid = $(this).attr('data-gallery-id'),
                        name = $(this).html();
                    if(typeof pid == 'undefined' || pid == '') {
                        alert('블럭 오류 입니다. 관리자에게 문의하세요');
                        $('.gallery-menus-wrap').hide();
                        return false;
                    }
                    $('#prod-pid').val(pid);
                    $('.product-gallery-name').html(name);
                    $(this).parents('.form-wrap').removeClass('empty');
                    $('.choose-gallery').removeClass('open');
                    $('.gallery-menus-wrap').hide();
                }
            });
        },
        add : function(id,gpos,gcate) {
            if($('.prod-modal.cl-p-modal').length > 0) return false;

            var site = (typeof SID == 'undefined') ? property.SID : SID,
                page = ($.gallery.item_of_page) ? $.gallery.item_of_page : '',
                pid = (typeof selectID == 'undefined') ? null : selectID;
            
            if(page == '') page = $('.gallery-modal').attr('data-page');
            if(typeof page == 'undefined' || page == '')
                page = (typeof PAGE == 'undefined') ? ((typeof property == 'undefined') ? '' : property.PAGE) : PAGE;

            if(typeof page == 'undefined' || page == '') {
                alert('Undefined page!!!');
                return false;
            }
            if(typeof $.gallery.block_id != 'undefined' && $.gallery.block_id) pid = $.gallery.block_id;
            // 상품 옵션
            product_options = {};
            fileUpdateCnt = 0;
            //     pid = $('.gallery-add-items').attr('data-pid');
            // if(typeof pid == 'undefined' || pid == null) pid = $('.config-image-edit').attr('data-pid');
            // if(typeof pid == 'undefined' || pid == null) { pid = (typeof PARENT == 'undefined') ? property.PARENT.pid : PARENT.pid }
            // if(typeof pid == 'undefined' || pid == null) pid = (typeof selectID == 'string') ? selectID : null;
            // console.log(site,page,pid);
            // return false;

            if(pid.toString().toLowerCase().match(/^cl-s-product-detail,/g) !== null) {
                pid = PARENT.pid;
            }

            page = (page.indexOf(',') > -1) ? page_split(page) : page;
            if(!site || !pid || typeof pid == 'undefined' || pid == null) {
                alert('Undefined gallery'); 
                return false;
            }

            if($('.table-item[data-seq="' + id + '"]').length) pid = $('.table-item[data-seq="' + id + '"]').attr('data-pid');

            var parentDocument = $(window.parent.document),
                $detail_modal = parentDocument.find('.product-detail-modal');
            if($detail_modal.length) $detail_modal.addClass('overlap');
            
            var params = ($('.gallery-modal').length) ? getProductParams() : getSearchURL();
            $.processON();
            $.ajax({
                url: '/template/products',
                data: { type:'get', sid:site, id:id, pid:pid, params:params },
                dataType: 'json',
                type: 'POST',
                async: true,
                cache: false,
                success: function (data) {
                    $.processOFF();
                    if(data.error != 'undefined' && data.error) {
                        alert(data.error);
                        return false;
                    }
                    var i = data.item,
                        plan = i.valid_plan;

                    closeProductNumber = i.no;
                    product_options = i.prod_options_settings;
                    var prod_quantity = parseInt(i.quantity),
                        category = '';
                    if(id == -1 && $.gallery.category) {
                        category = $.gallery.category;
                    }
                    if(typeof gcate != 'undefined' && gcate) category = gcate;
                    if(!category) category = i.category;

                    if(prod_quantity < 0 || isNaN(prod_quantity)) i.quantity = 0;
                    if(!i.price) i.price = 0;

                    $m = $(data.r).hide();
                    $('body').append($m);
                    $('#sid').val(i.sid);
                    $('#prod-page').val(page);
                    $('#prod-pid').val(i.pid);
                    $('#prod-no').val(i.no);
                    $('#prod-title').val(i.title);
                    $('#prod-desc').val(i.desc);
                    $('#prod-price').val(i.price);
                    $('#prod-sale').text(i.sale);
                    $('#lux-product').val(i.lux_product);
                    
                    if(!LUX) {
                        if(i.discount_unit == 'P') {
                            $('#prod-discount-rate').val(i.discount_rate);
                            // $('#price-cut-btn').removeClass('hide');
                        } else {
                            $('#prod-discount-rate').val(number_format(i.discount_rate));
                        }
                    }

                    if(typeof i.discount_rate == 'undefined' || i.discount_rate == 0) i.discount_unit = 'W';
                    $('#prod-discount-unit').attr('data-value', i.discount_unit);
                    $('#prod-discount-unit').text($('.discount-unit-select > div[data-value="'+i.discount_unit+'"]').text());
                    
                    // 상품 세일가 hidden
                    $('#retail-price').val(i.retail_price);
                    $('#prod-quantity').val(i.quantity);
                    if(typeof gpos != 'undefined' && gpos) $('#prod-gpos').val(gpos);
                    else $('#prod-gpos').val('');
                    $('#prod-category-text').text(category);
                    $('#prod-category-lists ul').empty();
                    $('#prod-category').attr('data-category',i.category_lists.toString());


                    if(plan.type == 'SM' && plan.valid_plan == true) {
                        $('.form-wrap.culture-benefit').removeClass('plan-upgrade');
                        if(i.use_naverpay == true) {
                            $('.form-wrap.culture-benefit').removeClass('not-support');
                            if(i.culture_benefit_yn == 'Y') {
                                $('.form-wrap.culture-benefit').removeClass('disabled');
                            }
                        }

                        $('.form-wrap#pccc-yn, .form-wrap#require-navershop, .form-wrap#mng-prd-info').removeClass('plan-upgrade');
                        $('.form-wrap#pccc-yn,.form-wrap#require-navershop, .form-wrap#mng-prd-info').find('input-switch').removeClass('editor-upgrade-popup').removeAttr('data-mode');
                        
                        if(i.product_pccc_yn == 'Y') {
                            $('.form-wrap#pccc-yn').removeClass('disabled');
                        }

                        if(i.nshop_setting == 'Y') {
                            if(LUX && i.require_navershop == 'T') {
                                $('.form-wrap#require-navershop').removeClass('disabled');
                                $('.form-wrap#require-navershop').find('input').prop('checked', true);
                            }
                        } else {
                            $('.form-wrap#require-navershop').addClass('use-nshop-setting not-support');
                        }
                        if(i.mng_product_info_use == 'on') {
                            $('.form-wrap#mng-prd-info').removeClass('disabled');
                        }
                    }

                    if(i.culture_benefit_yn == 'Y') {
                        $('.form-wrap.culture-benefit').find('input').prop('checked', true);
                    }
                    if(i.product_pccc_yn == 'Y') {
                        $('.form-wrap#pccc-yn').find('input').prop('checked', true);
                    }

                    var delivery_template_str = '';
                    if(i.delivery_template) {
                        $.each(i.delivery_template, function(k, v) {
                            var template_desc = '';
                            template_desc += '(';
                            template_desc += $.lang[LANG]['shopping.delivery.template.mix_yn.' + v.mix_yn.toLowerCase()];
                            var delivery_type_arr = v.delivery_type.split(',');
                            var delivery_type_str = '';
                            $.each(delivery_type_arr, function(idx, delivery_type) {
                                if(delivery_type_str) delivery_type_str += ', ';
                                delivery_type_str += $.lang[LANG]['shopping.delivery.template.delivery_type.' + delivery_type.toLowerCase()];
                            });
                            if(delivery_type_str) 
                                template_desc += ' / ' + delivery_type_str;
                            
                            if(delivery_type_arr.indexOf('DELIVERY') > -1) {
                                template_desc += ' / ' + $.lang[LANG]['shopping.delivery.' + v.delivery_company.toLowerCase()];
                            }

                            template_desc += ' / ' + $.lang[LANG]['shopping.delivery.template.price_type.' + v.price_type.toLowerCase()];

                            if(v.price_type == 'FIX') {
                                template_desc += '(' + number_format(v.delivery_fee) + '원)';
                            } else if(v.price_type == 'QUANTITY' || v.price_type == 'WEIGHT') {
                                var price_type_detail = v.price_type_detail ? JSON.parse(v.price_type_detail) : {};
                                
                                if(price_type_detail.method == 'DIFFERENTIAL') {
                                    var detail = '';
                                    if(price_type_detail.detail) {
                                        $.each(price_type_detail.detail, function(i, j) {
                                            var value = Object.keys(j);
                                            var price = Object.values(j);

                                            if(v.price_type == 'QUANTITY') {
                                                // if(i < 2) {
                                                    if(detail) detail += ', ';
                                                    detail += value + '개 이상(' + number_format(price) + '원)';
                                                // }
                                            } else if(v.price_type == 'WEIGHT') {
                                                // if(i < 2) {
                                                    if(detail) detail += ', ';
                                                    detail += value + 'Kg 이상(' + number_format(price) + '원)';
                                                // }
                                            }
                                        });
                                    }
                                    if(template_desc) {
                                        detail = '(차등 / ' + detail + ')';
                                        template_desc += detail;
                                    }
                                } else if(price_type_detail.method == 'REPEAT') {
                                    var detail = '';
                                    var value = Object.keys(price_type_detail.detail);
                                    var price = Object.values(price_type_detail.detail);

                                    if(v.price_type == 'QUANTITY') {
                                        detail += value + '개 구매시마다 ' + number_format(price) + '원 반복 부과';
                                    } else if(v.price_type == 'WEIGHT') {
                                        detail += value + 'Kg마다 ' + number_format(price) + '원 반복 부과';
                                    }

                                    if(detail) {
                                        detail = '(반복 / ' + detail + ')';
                                        template_desc += detail;
                                    }
                                }
                            }

                            if(v.additional_yn == 'Y') {
                                template_desc += ' / 도서산간 지역 추가 배송비 (제주 ' + number_format(v.additional_jeju_price) + '원, 제주 외 도서산간 ' + number_format(v.additional_land_price) + '원)';
                            }

                            template_desc += ' / ' + $.lang[LANG]['shopping.delivery.template.pay_type.' + v.pay_type.toLowerCase()];

                            if(v.free_condition_yn == 'Y') {
                                template_desc += ' / ' + number_format(v.free_condition) + '원 이상 무료 배송';
                            }

                            if(v.make_to_order_yn == 'Y') {
                                template_desc += ' / 주문 확인 후 ' + v.due_date + '일 후 배송 예정';
                            }
                            if(v.install_fee_yn == 'Y') {
                                template_desc += ' / 별도 설치비 있음';
                            }
                            template_desc += ')';

                            delivery_template_str += '\
                            <li data-val="' + v.seq + '" data-weight="' + (v.price_type == 'WEIGHT' ? 'true' : 'false') + '">\
                                <input type="radio" id="delivery_template_seq_' + v.seq + '" name="delivery_template_seq" value="' + v.seq + '" />\
                                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 18 18" width="18" height="18"><path d="M9 0a9 9 0 1 0 .001 18.001A9 9 0 0 0 9 0zm0 17c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z"></path></svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 18 18" width="18" height="18"><path d="M9 0a9 9 0 1 0 .001 18.001A9 9 0 0 0 9 0zm0 17c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z"></path><circle cx="9" cy="9" r="6"></circle></svg>\
                                <label for="delivery_template_seq_' + v.seq + '">\
                                    <span class="template-name">' + v.name + '</span>\
                                    <span class="template-desc">' + template_desc + '</span>\
                                </label>\
                            </li>';
                        });
                    }

                    $('.option-delivery-template-select').html(delivery_template_str);

                    if(typeof i.delivery_template_seq != 'undefined' && i.delivery_template_seq) {
                        $('.option-delivery-template-select input[name="delivery_template_seq"][value="' + i.delivery_template_seq + '"]').prop('checked', true);

                        $('.option-delivery-template-str').html($('.option-delivery-template-select li[data-val="' + i.delivery_template_seq + '"] label').html());

                        if($('.option-delivery-template-select li[data-val="' + i.delivery_template_seq + '"]').data('weight') == false) {
                            $('.product-weight').hide();
                            $('#product_weight').val('');
                        } else {
                            $('#product_weight').val(number_format(i.p.product_weight) + 'kg');
                        }
                    } else {
                        $('.option-delivery-template-select input[name="delivery_template_seq"]:first').prop('checked', true).change();
                    }
                    uadmin = i.uadmin;
                    var etcAry = [];
                    if (i.etc_info) etcAry = i.etc_info.split('||');
                    $('.cl_etc_state_check').removeClass('active');
                    switch(etcAry[0]) {
                        case 'Y':
                        case 'T':
                            $('#cl_etc_state_'+etcAry[0].toLowerCase()).addClass('active');
                            
                            if(etcAry[0] == 'Y') {
                                $('.etc-setting').not('.time-setting').removeClass('hide');
                            } else {
                                $('.etc-setting').removeClass('hide');
                            }

                            if (etcAry[1] == 'S') {
                                $('#cl_etc_status_s').addClass('active');
                                $('#cl_etc_status_p').removeClass('active');
                            } else {
                                $('#cl_etc_status_s').removeClass('active');
                                $('#cl_etc_status_p').addClass('active');
                            }
                            $('#etc-date-state').val(etcAry[0]);
                            $('#etc-date-status').val(etcAry[1]);
                            $('#etc-week').val(etcAry[2]);
                            $('#etc-start-date').val(etcAry[3]);
                            $('#etc-end-date').val(etcAry[4]);
                            $('#etc-date-time').val(etcAry[5]);
                            $('#etc-exclude-date').val(etcAry[6]);
                            $('#etc-term').val(etcAry[7]);
                            $('#etc-time').val(etcAry[8]);
                            break;
                        default:
                            $('#etc-term').val(etcAry[7]);
                            $('#etc-time').val(etcAry[8]);
                            $('#cl_etc_state_n').addClass('active');
                            break;
                    }

                    
                    if(LUX) {
                        if(!id || id < 1 || id == '0' || id >= 1000000000) {
                            $('.prod-price-sync').removeClass('active').hide();
                            $('.margin-config').addClass('disabled');
                            $('#prod-price').removeAttr('readonly');
                            $('.check-sale').removeClass('disabled');
                        } else if(i.price_sync == 'F') {
                            $('.prod-price-sync').removeClass('active');
                            $('.margin-config').addClass('disabled');
                            $('#prod-price').removeAttr('readonly');
                            $('.check-sale').removeClass('disabled');
                        }

                        if(i.prod_status) {
                            $('.prod-status').removeClass('active');
                            $('.prod-status[data-val="' + i.prod_status + '"]').addClass('active');
                        }
                    }

                    var cate = (category) ? category.split(', ') : [];
                    $.each(i.category_lists, function(i,v) {
                        $li = $('<li>' + v + '</li>');
                        if($.inArray(v.trim(),cate) > -1) $li.addClass('active');
                        $('#prod-category-lists ul').append($li);
                    });

                    $('input#product_weight').on('focus', function() {
                        $(this).val($.trim($(this).val()).replace('kg', ''));
                    }).on('blur', function() {
                        $(this).val($.trim($(this).val()).replace('kg', '') + ($.trim($(this).val()).replace('kg', '') ? 'kg' : ''));
                    });
                    
                    if(LUX) {
                        $.each(i.footer, function(idx,v) {
                            if (idx == 1) return true;
                            if(idx <= 3 && v == 'true') {
                                if (idx == 2) {
                                    $('.page-options input:eq(1)').prop('checked',true);
                                } else if (idx == 3) { //photo
                                    if (v == 'true') {
                                        $('.photo-review-tab .radio-checkbox input:eq(0)').prop('checked',true);
                                    } else {
                                        $('.photo-review-tab .radio-checkbox input:eq(1)').prop('checked',true);
                                    }
                                } else {
                                    $('.page-options input:eq(' + idx + ')').prop('checked',true);
                                }
                            }
                        });
                    } else {
                        $.each(i.footer, function(idx,v) {
                            if(idx <= 3 && v == 'true') {
                                if (idx == 3) { //photo
                                    if (v == 'true') {
                                        $('.photo-review-tab .radio-checkbox input:eq(0)').prop('checked',true);
                                    } else {
                                        $('.photo-review-tab .radio-checkbox input:eq(1)').prop('checked',true);
                                    }
                                } else {
                                    $('.page-options input:eq(' + idx + ')').prop('checked',true);
                                }
                            }
                            if (idx == 1) { //review
                                if (v == 'true') {
                                    $('.photo-review-tab').css('display', 'block');
                                } else {
                                    $('.photo-review-tab').css('display', 'none');
                                }
                            }
                        });
                    }

                    if(i.imgs.length > 10) $('.prod-item-image-add').addClass('hide');
                    $.each(i.imgs, function(idx,img) {
                        if(idx > 10) return true;
                        if(img) {
                            (idx == 0) ? $('.prod-item-image').addClass('active').append('<div class="preview-img" style="background-image: url(' + img + ');">') :
                                         $('.prod-item-thumb .prod-item-image-add').before('<li><img src="' + img + '"><span class="img-delete"><i class="fa fa-times-circle" aria-hidden="true"></i></li>');
                        }
                    });

                    $('.prod-option').each(function(){
                        if($(this).data('option_mode') == 'normal' && i.options.length == 0) {
                            i.options[0] = { 
                                'seq' : '',
                                'option_name' : 'noneOption',
                                'option_price' : 0
                            } 
                        }
                    });

                    if(i.quantity_on == 'on') {
                        $('.switch-quantity').prop('checked','checked').parents('.form-wrap').removeClass('disabled');
                    }

                    setOptionlist(i.options);
                    i.footer[4] = (i.footer[4] == '' || i.footer[4] == undefined)? 'true':i.footer[4];
                    $('#normal-option').prop('checked', true);

                    $('.prod-option-tab').addClass('hide');
                    $('#normal-option').prop('checked', false);
                    $('#text-option').prop('checked', false);
                    $('#additional-option').prop('checked', false);
                    $('.prod-option-tab .prod-option').addClass('hide');
                    if(i.footer[4]=='true' && $('.prod-option[data-option_mode="normal"] .prod-option-list>li').length > 1) {
                        $('#normal-option').prop('checked', true);
                        $('.prod-option-tab').removeClass('hide');
                        $('.prod-option[data-option_mode="normal"]').removeClass('hide');
                        $('.prod-option[data-option_mode="normal"] .plus-price').removeClass('hide');
                        $('.prod-option[data-option_mode="normal"] .plus-status').removeClass('hide');
                        if(i.quantity_on == 'on') {
                            $('.prod-option[data-option_mode="normal"] .plus-quantity').removeClass('hide');
                        }
                    }
                    if(i.footer[5]=='true' && $('.prod-option[data-option_mode="text"] .prod-option-list>li').length > 0) {   
                        $('#text-option').prop('checked', true);
                        $('.prod-option-tab').removeClass('hide');
                        $('.prod-option[data-option_mode="text"]').removeClass('hide');
                        $('.prod-option[data-option_mode="text"] .plus-price').removeClass('hide');
                        $('.prod-option[data-option_mode="text"] .plus-status').removeClass('hide');
                        if(i.quantity_on == 'on') {
                            $('.prod-option[data-option_mode="text"] .plus-quantity').removeClass('hide');
                        }
                        if($('.prod-option[data-option_mode="text"] .prod-option-list>li').length >= 7) { //입력옵션 7개이상 추가X
                            $('.prod-option[data-option_mode="text"] > .prod-option-add').addClass('disabled');
                        }
                    }
                    if(i.footer[6]=='true' && $('.prod-option[data-option_mode="additional"] .prod-option-list>li').length > 0) {
                        $('#additional-option').prop('checked', true);
                        $('.prod-option-tab').removeClass('hide');
                        $('.prod-option[data-option_mode="additional"]').removeClass('hide');
                        $('.prod-option[data-option_mode="additional"] .plus-price').removeClass('hide');
                        $('.prod-option[data-option_mode="additional"] .plus-status').removeClass('hide');
                        if(i.quantity_on == 'on') {
                            $('.prod-option[data-option_mode="additional"] .plus-quantity').removeClass('hide');
                        }
                    }

                    if(i.prod_info_on == 'on') {
                        $('.switch-prod-info').prop('checked','checked').parents('.form-wrap').removeClass('disabled');
                        $('.prod-info-toggle').addClass('open');
                        $('.info-selected').removeClass('hide');
                    } else {
                        $('.switch-prod-info').prop('checked', '').parents('.form-wrap').addClass('disabled');
                        $('.prod-info-toggle').removeClass('open');
                        $('.info-selected').addClass('hide');
                    }

                    if(i.product_on) {
                        $('.switch-product[value="'+i.product_on+'"]').prop('checked', true);
                        $('.switch-product[value="'+i.product_on+'"] + label').addClass('active');

                        if(i.product_on == 'lim') {
                            $('#status-append').fadeIn(0);
                            $('#sale-calendar').show();
                        } else {
                            $('#status-append').hide();
                            $('#sale-calendar').hide();
                        }
                    } else {
                        $('.switch-product[value="on"]').prop('checked', true);
                        $('.switch-product[value="on"] + label').addClass('active');
                    }

                    if(i.sales_start && i.sales_end) {
                        $('#sale-start-datetime').val(i.sales_start);
                        $('#sale-end-datetime').val(i.sales_end);
                        var startDateTimeArr = i.sales_start.split(' ');
                        var endDateTimeArr = i.sales_end.split(' ');
                        var startTime = convertTime12(startDateTimeArr[1]);
                        var endTime = convertTime12(endDateTimeArr[1]);
                        $('.sale-setting .setting-text .content-start').text(startDateTimeArr[0].replace(/-/g, '.') + '. ' + startTime);
                        $('.sale-setting .setting-text .content-end').text(endDateTimeArr[0].replace(/-/g, '.') + '. ' + endTime);
                    }
                    
                    if(i.quantity_on == 'on') {
                        $('.switch-quantity').prop('checked','checked').parents('.form-wrap').removeClass('disabled');
                        if($('#normal-option').is(':checked') === true) {
                        // $('#prod-quantity').attr('readonly','true').removeClass('hide').attr('placeholder','옵션에서 재고 관리');
                            $('.quantity-label').addClass('on');
                            $('.plus-quantity').removeClass('hide');
                        } else if($('#normal-option').is(':checked') === false && $('#additional-option').is(':checked') === true) {
                            $('.quantity-label').removeClass('on');
                            $('#prod-quantity').removeAttr('readonly').removeClass('hide');
                            $('.plus-quantity').removeClass('hide');
                        } else {
                            $('.quantity-label').removeClass('on');
                            $('#prod-quantity').removeAttr('readonly').removeClass('hide');
                            $('.plus-quantity').addClass('hide');
                        }
                    } else {
                        $('.prod-option-quantity, .edit-option-quantity').hide();
                        $('.plus-quantity').addClass('hide');
                    }

                    if(!i.sale && i.price == 0) {
                        $('#prod-sale-check').prop('disabled', true);
                    } else {
                        $('#prod-sale-check').prop('disabled', false);
                    }

                    if(i.sale) {
                        $('#prod-price').addClass('sale-on');
                        $('#prod-price').prop('readonly', true);
                        $('#prod-sale').show().addClass('strike');
                        $('.discount-append').removeClass('hide');
                        $('#prod-sale-check').prop('checked',true);
                        $('#check-sale').html('<path d="M13 0H3C1.34 0 0 1.34 0 3v10c0 1.66 1.34 3 3 3h10c1.66 0 3-1.34 3-3V3C16 1.34 14.66 0 13 0zM13.03 6.03l-5.5 5.5C7.38 11.68 7.19 11.75 7 11.75s-0.38-0.07-0.53-0.22l-3.5-3.5c-0.29-0.29-0.29-0.77 0-1.06s0.77-0.29 1.06 0L7 9.94l4.97-4.97c0.29-0.29 0.77-0.29 1.06 0S13.32 5.74 13.03 6.03z"/>');
                        $('.check-sale').addClass('checked');

                        // if (Number(removeCommas(i.price)) % 10 == 0 || Number(removeCommas(i.price)) == 0) $('#price-cut-btn').addClass('disabled');
                        // else $('#price-cut-btn').removeClass('disabled');
                    }

                    calInputWidth($('#prod-price'));                    

                    $('.prod-option').each(function(){
                        if($(this).data('option_mode') == 'normal' && i.options.length == 0) {
                            i.options[0] = { 
                                'seq' : '',
                                'option_name' : 'noneOption',
                                'option_price' : 0
                            } 
                        }
                    });
                              
                    $m.fadeIn(300);
                    $('.prod-option-list').sortable({
                       handle : ".prod-option-move",
                       refreshPositions: true
                    });

                    if (i.product_state == 'download') {
                        $('#download-product').attr('checked', true);
                        $('.cl_product_state_check').each(function () {
                            if ($(this).attr('for') == 'download-product') {
                                $(this).find('.cl-icon').removeClass('cl_icon_check02_off').removeClass('cl_icon_check02_on').addClass('cl_icon_check02_on');
                                $(this).click();
                                $('#download-date').val(i.download_date);
                                $('#download-count').val(i.download_count);
                            } else {
                                $(this).find('.cl-icon').removeClass('cl_icon_check02_off').removeClass('cl_icon_check02_on').addClass('cl_icon_check02_off');
                            }
                        });
                        $('.delivery-template, .product-weight, .brand, .culture-benefit').hide();
                    }

                    if (i.product_state == 'normal') {
                        $('#normal-product').attr('checked', true);
                        $('.cl_product_state_check').each(function () {
                            if ($(this).attr('for') == 'normal-product') {
                                $(this).find('.cl-icon').removeClass('cl_icon_check02_off').removeClass('cl_icon_check02_on').addClass('cl_icon_check02_on');
                                $(this).click();
                            } else {
                                $(this).find('.cl-icon').removeClass('cl_icon_check02_off').removeClass('cl_icon_check02_on').addClass('cl_icon_check02_off');
                            }
                        });

                        if(!$('.delivery-template-list').find('[data-val]').find('input[name="delivery_template_seq"]:checked').length) {
                            $('.delivery-template-list').find('[data-val]:first').find('input[name="delivery_template_seq"]').prop('checked', true).change();
                        }

                        $('.delivery-template').show();
                    }

                    if (i.product_state == 'etc') {
                        $('#etc-product').attr('checked', true);
                        $('.cl_product_state_check').each(function () {
                            if ($(this).attr('for') == 'etc-product') {
                                $(this).find('.cl-icon').removeClass('cl_icon_check02_off').removeClass('cl_icon_check02_on').addClass('cl_icon_check02_on');
                                $(this).click();
                            } else {
                                $(this).find('.cl-icon').removeClass('cl_icon_check02_off').removeClass('cl_icon_check02_on').addClass('cl_icon_check02_off');
                            }
                        });
                        $('.delivery-template, .product-weight, .brand, .culture-benefit').hide();
                    }

                    taxUse = i.tax_use;
                    if (i.tax_use == 'TG03') {
                        $('#state-append').fadeIn(0);
                        $('#normal-product-state').fadeIn(0);
                        if (i.tax == 'TG01') {
                            $('#tax').attr('data-val', 'TG01');
                            $('#tax').html('과세');
                        }

                        if (i.tax == 'TG02') {
                            $('#tax').attr('data-val', 'TG02');
                            $('#tax').html('비과세');
                        }
                        $('#tax').attr('data-total-tax', 'TG03');
                    } else {
                        if (i.product_state == 'normal') $('#state-append').fadeOut(0);
                        $('#normal-product-state').fadeOut(0);
                        $('#tax').attr('data-val', 'TG01');
                        $('#tax').html('과세');
                    }
                    setAdvancedMode(product_options.advanced);

                    var descHeight = $('#prod-desc').prop('scrollHeight');
                    if(descHeight > 55) {
                        $('#prod-desc').css('height', descHeight+'px');
                    } else {
                        $('#prod-desc').removeAttr('style');
                    }
                },
                error : function(xhr, status, error) {
                    var parentDocument = $(window.parent.document),
                        $detail_modal = parentDocument.find('.product-detail-modal');
                    if($detail_modal.length) $detail_modal.removeClass('overlap');

                    $.processOFF();
                    alert("Error " + xhr.status);
                }            
            });
        },
        review : function(id,page) {
            var site = (typeof SID == 'undefined') ? property.SID : SID;

            $.ajax({
                url: '/template/products/',
                data: { type:'review', sid:site, id:id, page:page },
                dataType: 'json',
                type: 'POST',
                async: false,
                cache: false,
                success: function (data) {
                    if(data.error != 'undefined' && data.error) {
                        alert(data.error);
                        return false;
                    }
                    var $review = $(data.r).hide();
                    if(typeof property == "undefined") {
                        $lastEl = ($('.el-footer_ctrl').length) ? $('.el-footer_ctrl') : $('.add-footer-information');
                        if($('.page-bottomlist').length) $lastEl = $('.page-bottomlist');
                        if($('.fnav').length) $lastEl = $('.fnav');
                        $lastEl.before($review);
                        $review.show();
                    } else {
                        if(typeof property.ISLOCK != 'undefined' && property.ISLOCK == 'true') {
                            $review.addClass('hide');
                        }
                        if($('.el-footer').length) {
                            $lastEl = ($('.page-bottomlist').length) ? $('.page-bottomlist') : $('.el-footer');
                            if($('.fnav').length) $lastEl = $('.fnav');
                            $lastEl.before($review);
                            $review.show();

                            var reviewArr = new Array();

                            $('.s-table-review .review-content>div').each(function(idx, item){
                                reviewArr[idx] = $(this).html();
                            });

                            truncateReviewTitle(reviewArr);

                            $(window).on('resize', function(){
                                truncateReviewTitle(reviewArr)
                            });
                        } else {
                            $('.dsgn-body').append($review);
                            $review.show();
                        }
                    }
                    var cnt = ($('.review-wrap h4 > span').text()=="") ? 0 : $('.review-wrap h4 > span').text();
                    $('.review-count').text(' ' + cnt);
                }
            });
        },
        qna : function(id,page) {
            var site = (typeof SID == 'undefined') ? property.SID : SID;

            $.ajax({
                url: '/template/products/',
                data: { type:'qna', sid:site, id:id, page:page },
                dataType: 'json',
                type: 'POST',
                async: false,
                cache: false,
                success: function (data) {
                    if(data.error != 'undefined' && data.error) {
                        alert(data.error);
                        return false;
                    }
                    var $qna = $(data.r).hide();
                    if(typeof property == "undefined") {
                        $lastEl = ($('.el-footer_ctrl').length) ? $('.el-footer_ctrl') : $('.add-footer-information');
                        if($('.page-bottomlist').length) $lastEl = $('.page-bottomlist');
                        if($('.fnav').length) $lastEl = $('.fnav');
                        $lastEl.before($qna);
                        $qna.show();
                    } else {
                        if(typeof property.ISLOCK != 'undefined' && property.ISLOCK == 'true') {
                            $qna.addClass('hide');
                        }
                        if($('.el-footer').length) {
                            $lastEl = ($('.page-bottomlist').length) ? $('.page-bottomlist') : $('.el-footer');
                            if($('.fnav').length) $lastEl = $('.fnav');
                            $lastEl.before($qna);
                            $qna.show();
                        } else {
                            $('.dsgn-body').append($qna);
                            $qna.show();
                        }
                    }
                    var cnt = ($('.qna-wrap h4 > span').text()=="") ? 0 : $('.qna-wrap h4 > span').text();
                    $('.qna-count').text(' ' + cnt);
                }
            });
        },
        list : function(id, page, view, page_num, sfl, stx, scate) {
        },
        save : function(go) {
            var before_prod = {};
            $('.product-wrap form input[name="before_prod[]"]').each(function() {
                var bd_key = $(this).attr('data-key'),
                    bd_val = $(this).val();
                
                before_prod[bd_key] = bd_val;
            });

            var seq = $('#prod-no').val(),
                page = $('#prod-page').val(),
                pid = $('#prod-pid').val(),
                gpos = $('#prod-gpos').val(),
                $title = $('#prod-title'),
                $price = $('#prod-price'),
                $sale = $('#prod-sale'),
                $quantity = $('#prod-quantity'),
                $img = $('.prod-item-image'),
                $desc = $('#prod-desc'),
                $category = $('#prod-category-text'),
                $brand = $('#brand'),
                discountRate = ($('#prod-sale-check').is(':checked'))? $('#prod-discount-rate').val().trim().replace(/,/gi, '') : 0,
                discountUnit = ($('#prod-sale-check').is(':checked'))? $('#prod-discount-unit').attr('data-value') : 'W',
                // checkSaleCut = ($('#price-cut-btn').is(':checked'))? 'Y':'N',
                quantity_on = ($('.switch-quantity').is(":checked") == true) ? 'on' : 'off',
                product_on =  $('input[name="product_status"]:checked').val(),
                category_on = ($('.switch-category').is(":checked") == true) ? 'ON' : 'OFF',
                product_info_on = ($('.switch-prod-info').is(":checked") == true) ? 'on' : 'off',
                mng_product_info_use = ($('.switch-mngprd').is(":checked") == true) ? 'on' : 'off',
                mng_product_name = $('#mng-prd-name').val(),
                mng_product_code = $('#mng-prd-code').val(),
                submit = true,
                downloadDate = $('#download-date').val(),
                downloadCount = $('#download-count').val(),
                submit = true,
                productState = '',
                taxState = $('#tax').attr('data-val'),
                etcDateState = '',
                etcDateStatus = '', etcDateWeek = '',
                salesStart = '', salesEnd = '', open_out_datetime_yn = 'N',
                delete_options = $('#options-delete-list').val(),
                deliveryTemplateSeq = $('input[name="delivery_template_seq"]:checked').val(),
                productWeight = $('#product_weight').val().replace(/kg|,/gi, ''),
                culture_benefit_yn = $('.switch-culture-benefit').is(':checked') ? 'Y' : 'N',
                product_pccc_yn = $('.switch-pccc').is(':checked') ? 'Y' : 'N',
                require_navershop = $('.switch-require-navershop').is(':checked') ? 'T' : 'F',
                startDate = '', endDate = '', etcDate = '', exceptDate = '', termData = '', timeData = '',
                dayCheck = false, dayCheckLan = $('#etc-date-time').val();
                prod_info = getProductInfoList(),
                lux_product = ($('#lux-product').val() == "true") ? true : false;

            var price = $price.val();
            price = removeCommas(price);
            price = price * 1;

            var nPrice = Number(price),
                submit = true;

            // 옵션 가격 검색
            $.each($('.prod-option-price'), function(i,v) {
                var oPrice = $(v).attr('data-option-price');
                if(i > 0) {
                    if(nPrice + Number(oPrice) < 0) {
                        $(v).parents('li').addClass('err');
                        submit = false;
                    }
                }
            });
            if(submit == false) {
                // alert('옵션 가격이 올바르지 않습니다.');
                var modal = $(this).showModalFlat('','판매가가 0원 아래로 적용될 수 있는 옵션 가격이 존재하여 저장할 수 없습니다.',true,false,'','ok','','cl-cmmodal cl-s-btn w560 cl-p130 cl-t80 cl-modal cl-none-title cl-close-btn','','',function() {
                    $(document).on('keydown', function(e) {
                        if(e.keyCode == 27) modal.modal('hide');
                    });
                });
                return false;
            }

            if(product_on == 'lim') {
                if($('#sale-start-datetime').val() && $('#sale-end-datetime').val()) {
                    salesStart = $('#sale-start-datetime').val();
                    salesEnd = $('#sale-end-datetime').val();
                    open_out_datetime_yn = $('input[name="open_out_datetime_yn"]:checked').val();
                } else {
                    submit = false;
                    var modal = $(this).showModalFlat('','판매 시작, 판매 종료 날짜/시간을 모두 입력해주세요.',true,false,'','ok','','cl-cmmodal cl-s-btn w560 cl-p130 cl-t80 cl-modal cl-none-title cl-close-btn','','',function() {
                        $(document).on('keydown', function(e) {
                            if(e.keyCode == 27) modal.modal('hide');
                        });
                    });
                    return false;
                }

            }

            if ($('#download-product').is(":checked") == true) productState = 'download';
            if ($('#normal-product').is(":checked") == true) productState = 'normal';
            if ($('#etc-product').is(":checked") == true) {
                productState = 'etc';
                etcDateState = $('#etc-date-state').val();
                if (etcDateState == 'Y' || etcDateState == 'T') {
                    etcDateStatus = $('#etc-date-status').val();
                    etcDateWeek = $('#etc-week').val();
                    startDate = $('#etc-start-date').val();
                    endDate = $('#etc-end-date').val();
                    exceptDate = $('#etc-exclude-date').val();
                    termData = $('#etc-term').val();
                    timeData = $('#etc-time').val();
                    
                    // var checkStartDate = startDate.split('.');
                    // var checkEndDate = endDate.split('.');
                    // var checkStart = new Date(checkStartDate[0], (checkStartDate[1] * 1) - 1, checkStartDate[2]);
                    // var checkEnd = new Date(checkEndDate[0], (checkEndDate[1] * 1) - 1, checkEndDate[2]);
                    // if (checkStart.getTime() > checkEnd.getTime()) {
                    //     alert('시작일이 종료일보다 큽니다.');
                    //     return false;
                    // }
                    if($('input.select-terms:checked').val() == 'Y' && (!startDate || !endDate)) {
                        alert('날짜 기간을 선택해주세요.');
                        return false;
                    }
                }

                etcDate = etcDateState+'||'+etcDateStatus+'||'+etcDateWeek+'||'+startDate+'||'+endDate;
                etcDate += (dayCheckLan)? '||' + dayCheckLan : '||';
                etcDate += (exceptDate)? '||' + exceptDate : '||';
                etcDate += (termData)? '||' + termData : '||';
                etcDate += (timeData)? '||' + timeData : '||';
            }
            // 빈 갤러리 처리
            if(pid == '-1') {
                $('.choose-gallery').parent().addClass('empty');
                submit = false;                
            } else $('.choose-gallery').parent().removeClass('empty');

            if($img.find('.preview-img').length == 0) {
                $img.addClass('empty');
                submit = false;
            } else $img.removeClass('.empty');

            if(!$title.val().trim()) {
                $title.focus().parents('.form-wrap').addClass('empty');
                submit = false;
            } else $title.parents('.form-wrap').removeClass('empty');
            if(!$price.val().trim()) {
                $price.focus().parents('.form-wrap').addClass('empty');
                submit = false;
            } else $price.parents('.form-wrap').removeClass('empty');

            var item_quantity = (typeof $quantity.val() == 'undefined') ? 0 : parseInt($quantity.val().trim().replace(/\,/g, ''), 10),
                item_price = ($price.val().trim()) ? parseInt($price.val().trim().replace(/\,/g, ''), 10) : 0;
            if(item_quantity > 9999) {
                $quantity.focus().parents('.form-wrap').addClass('empty');
                alert('최대 수량은 9,999개입니다');
                return false;
            }
            if(item_price > 1000000000) {
                $price.focus().parents('.form-wrap').addClass('empty');
                alert('최대상품가격은 10억입니다');
                return false;
            }

            if($('#prod-sale-check').is(':checked') && discountRate == 0) {
                var error_str = '<svg viewBox="0 0 13 13" width="13" height="13"><path d="M6.5 0C2.91 0 0 2.91 0 6.5S2.91 13 6.5 13 13 10.09 13 6.5 10.09 0 6.5 0zM6.5 12.13c-3.11 0-5.63-2.53-5.63-5.63S3.39 0.87 6.5 0.87s5.63 2.53 5.63 5.63S9.61 12.13 6.5 12.13z"></path><path d="M7.44 9.58c-0.1-0.02-0.18-0.05-0.25-0.1C7.12 9.44 7.07 9.37 7.03 9.28 6.98 9.19 6.96 9.07 6.96 8.92V5h-1.7v0.4h0.03c0.11 0 0.21 0.01 0.3 0.02 0.09 0.02 0.18 0.05 0.25 0.09 0.07 0.05 0.13 0.11 0.17 0.2 0.04 0.09 0.06 0.2 0.06 0.34v2.91c0 0.14-0.02 0.25-0.06 0.34C5.97 9.39 5.91 9.45 5.84 9.5 5.77 9.54 5.68 9.57 5.59 9.58 5.49 9.6 5.39 9.6 5.29 9.6H5.16v0.4h2.71V9.6H7.75C7.64 9.6 7.54 9.6 7.44 9.58z"></path><rect x="6" y="3" width="1" height="1"></rect></svg>\
                1 이상 입력해 주세요.';
                $('.form-group.discount-append + .error-msg').remove();
                $('.form-group.discount-append').after('<div class="error-msg c-red">'+error_str+'</div>');
                $('#prod-discount-rate').addClass('empty');
                submit = false;
            } else {
                $('.form-group.discount-append + .error-msg').remove();
                $('#prod-discount-rate').remove('empty');
            }

            var delivery_template_weight = $('input[name="delivery_template_seq"]:checked').parent().data('weight');
            var product_weight = $.trim($('#product_weight').val()).replace(/kg/gi, '');
            if((lux_product || $('#normal-product').is(":checked") == true) && delivery_template_weight == true && (product_weight == '' || product_weight == 0)) {
                $('#product_weight').closest('.form-wrap.product-weight').addClass('empty');
                alert('상품 무게를 입력해 주세요.');
                return false;
            } else {
                $('#product_weight').closest('.form-wrap.product-weight').removeClass('empty');
            }

            var emptyval ='\
                <div class="value-empty">\
                    <svg viewBox="0 0 13 13" width="13" height="13"><path d="M6.5 0C2.91 0 0 2.91 0 6.5S2.91 13 6.5 13 13 10.09 13 6.5 10.09 0 6.5 0zM6.5 12C3.47 12 1 9.53 1 6.5S3.47 1 6.5 1 12 3.47 12 6.5 9.53 12 6.5 12z"/><rect x="6" y="3" width="1" height="5"/><rect x="6" y="9" width="1" height="1"/></svg>필수 입력 항목 입니다.\
                </div>\
            ';

            if(product_info_on=='on') {
                if(prod_info.cate_null) {
                    $('.prod-info-notice').addClass('empty');
                    return false;
                }
                if(prod_info.input_empty) {
                    $('.value-empty').remove();
                    $('.prod-info-notice').css('border','3px solid #ee445f');
                    var offset_idx = 0;                    

                    $.each(prod_null, function(i,v) {
                        $('.prod-input-value:eq(' + v + ')').parent('div').append(emptyval);
                        if(i==0) offset_idx = v;
                    });
                    prod_null.offset_idx = offset_idx;
                    var input_height = $('.prod-input-value:eq(' + prod_null.offset_idx + ')').offset().top;
                    if($('.prod.empty').length==0) $('.prod-modal').animate({ scrollTop: input_height*0.8 }, 500, 'easeInOutQuart');
                    return false;
                }
            }

            if(mng_product_info_use=='on') {
                $('.value-empty').remove();
                $('.mng-prd-info-toggle').removeClass('err');
                if(mng_product_code.trim()=='') {
                    var mng_prd_empty_val = (mng_product_name.trim()=='') ? 'name' : 'code';
                    if (mng_product_code.trim()=='') $('.form-mng-prd-code').after(emptyval);
                    $('.mng-prd-info-toggle').addClass('err');
                    
                    return false;
                }
            }
            
            if(lux_product) {
                if(!$('.prod-type.active').length) {
                    alert('상품유형을 선택해주세요.');
                    return false;
                }

                if(!$('#lux-category-text').find('ul').length) {
                    alert('카테고리를 하나 이상 추가해주세요.');
                    return false;
                }

                var selected_brand = $('.prod-input.prod-brand').val();
                if(selected_brand == '') {
                    alert('브랜드를 검색 후 항목에서 선택해주세요.');
                    $('#brand').focus();
                    return false;
                }

                var brand_check = brand_list.indexOf(selected_brand) > -1 ? true : false;

                if(!brand_check) {
                    alert('브랜드 목록에 없는 브랜드명입니다.\n브랜드를 검색 후 목록에서 선택해주세요.');
                    $('#brand').focus();
                    return false;
                }
            }

            if($('.prod-option-list > li').hasClass('err') == true) {
                alert('옵션 항목을 모두 작성해주세요.')
                return false;
            }

            var options = $('.prod-option-list > li').map(function(i,v) {
                if($(this).find('.prod-option-title').text().trim()) {
                    var quantity = $(this).find('.prod-option-quantity').text().trim(),
                        status = $(this).find('.option-price-status-str').attr('data-val'),
                        type = '';
                    if ($(this).closest('.prod-option').data('option_mode') == 'additional') type = 'A';
                    else if ($(this).closest('.prod-option').data('option_mode') == 'text') type = 'T';
                    
                    if(quantity == '') quantity = '0';
                    if(quantity == '0' && quantity_on == 'on') status = 'O'; 

                    var fileUrl = [],
                        fileSize = [],
                        fileStrName = [],
                        fileName = [];

                    var fileUrlCheck = $(this).find('.file-url'),
                        fileSizeCheck = $(this).find('.file-size'),
                        fileStrNameCheck = $(this).find('.file-name-detail'),
                        fileNameCheck = $(this).find('.real-file-name');

                    if (fileUrlCheck.length > 0) $(this).find('.file-url').each(function () { fileUrl.push($(this).text()); });
                    else fileUrl.push('');
                    if (fileUrlCheck.length > 0) $(this).find('.file-size').each(function () { fileSize.push($(this).text()); });
                    else fileUrl.push('');
                    if (fileUrlCheck.length > 0) $(this).find('.file-name-detail').each(function () { fileStrName.push($(this).text()); });
                    else fileUrl.push('');
                    if (fileUrlCheck.length > 0) $(this).find('.real-file-name').each(function () { fileName.push($(this).text()); });
                    else fileUrl.push('');

                    var strFileUrl = fileUrl.join('||'),
                        strFileSize = fileSize.join('||'),
                        strFileStrName = fileStrName.join('||'),
                        strFileName = fileName.join('||');

                    if(type == 'T' || type == 'A') {
                        strFileStrName = "";
                        strFileSize = "";
                        strFileName = "";
                        strFileUrl="";
                    }

                    var optionTitle = '';
                    if(product_options.advanced == 'true') {
                        if(i == 0 || type == 'T') {
                            optionTitle = $(this).find('.prod-option-title').text().trim();
                        } else {
                            var $val = $(this).find('.prod-option-title > label.owidth');
                            optionTitle = $val.map(function() {
                                return $(this).text();
                            }).get().join(' / ');

                        }
                    } else {
                        optionTitle = $(this).find('.prod-option-title').text().trim();
                    }

                    var optionPrice = (type != 'T')? $(this).find('.prod-option-price').attr('data-option-price').trim() : 0;
                    var optionGroup = '', m2 = '', m3 = '';
                    var arrTitle = optionTitle.split(" / ");
                    switch(arrTitle.length) {
                        case 1: optionTitle = arrTitle[0]; break;
                        case 2: optionTitle = arrTitle[1]; m2 = arrTitle[0]; break;
                        case 3: optionTitle = arrTitle[2]; m2 = arrTitle[0]; m3 = arrTitle[1]; break;
                    }

                    if(type == 'T') {
                        status = 'S';
                        type = 'T';
                        optionPrice = "0";
                    } else if(type == 'A') {
                        optionGroup = m2;
                        m2 = '';
                    } else if(type == '') {
                        if(product_options.type == "1") {
                            optionGroup = m2;
                            m2 = "";
                        }
                    }
                    // if(product_options.advanced == false && optionTitle != 'noneOption') {
                    //     switch(type) {
                    //         case ""  : product_options.config1[0].title = '옵션선택'; break;
                    //         case "A" : product_options.config3[0].title = '추가옵션'; break;
                    //     }                        
                    // }
                    return { 
                        s : $(this).find('.prod-option-title').attr('data-seq'),
                        m2 : m2,
                        m3 : m3,
                        o : optionTitle, 
                        v : optionPrice,
                        fn : strFileName,
                        fdn : strFileStrName,
                        fs : strFileSize,
                        fu : strFileUrl,
                        q : quantity,
                        t : status,
                        g : optionGroup,
                        a : i,
                        ty: type
                    }
                 }
            }).get();

            if(options.length==0 && $('.prod-option-tab .prod-option.hide').length < 3) {
                $('.prod-option-add').addClass('empty');
                submit = false;
            }

            var optionsAry = division(options, 300);
            // console.log(optionsAry);
            var price1 = removeCommas($price.val().trim()), //할인가
                price2 = removeCommas($sale.text().trim()); //정가

            if($sale.css('display') == 'none') {
                $sale.text('');
                price2 = 0;
            }
            
            if(lux_product == false) {
                if($('#prod-sale-check').is(':checked') && (parseInt(price1) - parseInt(price2) >= 0)) {
                // alert('할인 가격은 정가보다 높거나 동일할 수 없습니다');
                    var modal = $(this).showModalFlat('','할인 가격은 정가보다 높거나 동일할 수 없습니다',true,false,'','ok','','cl-cmmodal cl-s-btn w560 cl-p130 cl-t80 cl-modal cl-none-title cl-close-btn','','',function() {
                        $(document).on('keydown', function(e) {
                            if(e.keyCode == 27) modal.modal('hide');
                        });
                    });
                    if(price2 == 0) $price.val('');
                    submit = false;
                    return;
                }
            } else {
                if($('#prod-sale-check').is(':checked') && (parseInt(price1) - parseInt(price2) > 0)) {
                    var modal = $(this).showModalFlat('','할인 가격은 정가보다 높을 수 없습니다',true,false,'','ok','','cl-cmmodal cl-s-btn w560 cl-p130 cl-t80 cl-modal cl-none-title cl-close-btn','','',function() {
                        $(document).on('keydown', function(e) {
                            if(e.keyCode == 27) modal.modal('hide');
                        });
                    });
                    if(price2 == 0) $price.val('');
                    submit = false;
                    return;
                }
            }
/*
            if(nPrice > 0 && nPrice < 10) {
                $('#prod-price').focus();
                $('.prod-item-price1').addClass('err')
                // alert('상품 가격을 10원 이상 입력해주세요.');
                var modal = $(this).showModalFlat('','상품 가격을 10원 이상 입력해주세요.',true,false,'','ok','','cl-cmmodal cl-s-btn w560 cl-p130 cl-t80 cl-modal cl-none-title cl-close-btn','','',function() {
                    $(document).on('keydown', function(e) {
                        if(e.keyCode == 27) modal.modal('hide');
                    });
                });
                submit = false;
            } else {
                $('.prod-item-price1').removeClass('err');
            }
*/
            var imgs = [];
            if(submit) {
                $('.prod-item-thumb li').each(function(i,v) {
                    var s = $(this).find('img:not(.guide-img)').attr('src');
                    if($(this).hasClass('prod-item-image-add')) return true;
                    imgs.push(s);
                });

                
                $.processON('상품을 등록중입니다...');
                
                var func = new Array();
                func[0] = true;
                func[1] = $('#review-checkbox').is(":checked"); // 리뷰사용
                func[2] = $('#qna-checkbox').is(":checked"); // QNA 사용
                func[3] = $('#photo-review').is(":checked"); // 포토리뷰 사용
                 
                func[4] = ($('#normal-option').is(':checked'))? true : false; //일반옵션 활성화
                func[5] = ($('#text-option').is(':checked'))? true : false; //입력옵션 활성화
                func[6] = ($('#additional-option').is(':checked'))? true : false; //추가옵션 활성화
                
                var cate = ($category.text().trim()) ? $category.text().trim().split(',') : '',
                    brand = ($brand.val().trim())? $brand.val().trim():'',
                    //재고수량
                    quantity_val = (func[4] == 'true' || func[6] == 'true')? 0 : item_quantity,
                    options_config = product_options;

                var prod_user_margin = (typeof $('.prod-user-margin').val() == 'undefined') ? 0 : $('.prod-user-margin').val().trim(),
                    prod_user_price = (typeof $('.prod-user-price').val() == 'undefined') ? 0 : $('.prod-user-price').val().trim(),
                    prod_price_sync = ($('.prod-price-sync').hasClass('active')) ? 'T' : 'F',
                    prod_status = $('.prod-status.active').attr('data-val'),
                    prod_type = $('.prod-type.active').attr('data-val'),
                    prod_brand = $('.prod-brand').val(),
                    prod_category = [];
                
                if(lux_product) {
                    if(seq < 1 || seq >= 1000000000) {
                        if(prod_status == 'T' && $('.prod-option-quantity').not(':first').length == $('.prod-option-quantity').not(':first').map(function(k, v) { if($(v).text() == 0 ) return v;}).length) {
                            prod_status = 'F';
                        } else if(prod_status == 'T' && $('.prod-option-status').not(':first').length == $('.prod-option-status').not(':first').map(function(k, v) { if($(v).attr('data-val') == 'O') return v;}).length) {
                            prod_status = 'F';
                        }
                        var invenCheck = false;
                        
                        $.each(optionsAry[0], function(idx, v) {
                            if(prod_status != 'T' || (idx > 0 && v.t != 'O')) {
                                invenCheck = true;
                            }
                        });

                        if(!invenCheck) prod_status = 'F';
                    }
                }

                if($('#lux-category-text').length) {
                    $.each($('#lux-category-text ul'),function(i,v) { 
                        prod_category[i] = {
                          'sid' : $(this).attr('data-sid'),
                          'no' : $(this).attr('data-no'),
                          'category' : [],
                          'category_name' : [],
                          'update' : []
                        }
                        $.each($(this).find('li'),function(a,b) {
                            prod_category[i]['category'].push($(this).attr('data-category-no'));
                            var seq = (typeof $(this).attr('data-seq') != 'undefined' && $(this).attr('data-seq') != '') ? $(this).attr('data-seq') : '';
                            prod_category[i]['update'].push(seq);
                            prod_category[i]['category_name'].push($(this).text().trim());
                        });
                    });
                }

                setTimeout(function() {
                    for (var optionCnt=0;optionCnt<optionsAry.length;optionCnt++) {
                        var prod = {
                            'seq' : seq,
                            'page' : page,
                            'pid' : pid,
                            'gpos'  : gpos,
                            'title' : $title.val().trim(),
                            'price' : $price.val().trim(),
                            'sale' : $sale.text().trim(),
                            'discount_rate' : discountRate,
                            'discount_unit' : discountUnit,
                            // 'check_sale_cut' : checkSaleCut,
                            'product_on' : product_on,
                            'product_info_on' : product_info_on,
                            'mng_product_info_use' : mng_product_info_use,
                            'mng_product_name' : mng_product_name,
                            'mng_product_code' : mng_product_code,
                            'quantity' : quantity_val,
                            'quantity_on' : quantity_on,
                            'desc' : $desc.val().trim(),
                            'category' : cate,
                            'category_on' : category_on,
                            'brand' : brand,
                            'imgs' : imgs,
                            'func' : func,
                            'product_state' : productState,
                            'tax' : taxState,
                            'download_date' : downloadDate,
                            'download_count' : downloadCount,
                            'etc_data' : etcDate,
                            'options' : JSON.stringify(optionsAry[optionCnt]),
                            'prod_info' : prod_info,
                            'options_config' : options_config,
                            'delete_options' : delete_options,
                            'before_prod' : JSON.stringify(before_prod),
                            'delivery_template_seq' : deliveryTemplateSeq,
                            'product_weight' : productWeight,
                            'culture_benefit_yn' : culture_benefit_yn,
                            'lux' : lux_product,
                            'prod_user_margin' : prod_user_margin,
                            'prod_user_price' : prod_user_price,
                            'prod_price_sync' : prod_price_sync,
                            'prod_status' : prod_status,
                            'prod_type' : prod_type,
                            'prod_category' : prod_category,
                            'prod_brand' : prod_brand,
                            'category_deleted' : ($('#category-deleted').length) ? $('#category-deleted').val() : '',
                            'product_pccc_yn' : product_pccc_yn,
                            'require_navershop' : require_navershop,
                            'sales_start': salesStart,
                            'sales_end': salesEnd,
                            'open_out_datetime_yn': open_out_datetime_yn,
                        }

                        $.post('/template/products', { sid: SID, type : 'add', s: prod, lux : lux_product }, function (data) {
                            // checkError(data);
                            if(data.error) {
                                $.processOFF();
                                if(data.price) $('#prod-price').val('');
                                var modal = $(this).showModalFlat('',data.error,true,false,'','ok','','cl-cmmodal cl-s-btn w560 cl-p130 cl-t80 cl-modal cl-none-title cl-close-btn','','',function() {
                                    $(document).on('keydown', function(e) {
                                        if(e.keyCode == 27) modal.modal('hide');
                                    });
                                });
                                return false;
                            }

                            // control panel
                            if (optionsAry.length == (optionCnt + 1)) {
                                $('img.galleryItemEdit[data-seq="' + data.r.id + '"]').attr('src',data.r.imgs[0].path+'/60/'+data.r.imgs[0].file);
                                $('.image-title.galleryItemEdit[data-seq="' + data.r.id + '"]').text(data.r.title);

                                PRODINFO = (product_info_on=='on') ? prod_info : '';
                                PRODSETTING = 'on';

                                    // dashboard
                                    if(typeof MODE == 'undefined') {
                                        $.processOFF();
                                        $.products.close();
                                        if($('.gallery-modal').length) {
                                            var now_page = getStorageItem('gallery-product-page');
                                            $.gallery.show($.gallery.block_id,now_page,$.gallery.category);
                                        }

                                    } else {
                                        if(go) {
                                            var block = ($('.el_1').length) ? '.el_1' : '.default_project_contents',
                                                menuPage = PAGE.split(',');
                                            if(LUX) menuPage[0] = '_product';
                                            $.cookie('product-detail', true, { expires: 60*60, path : '/' });
                                            location.href = '/'+CONFIG_URL+'config/page/'+menuPage[0]+'/view/'+data.r.id;

                                        } else {
                                            showPageCallback(showPage);
                                            $.processOFF();
                                            $.products.close();
                                            if($('.gallery-modal').length) {
                                                var now_page = getStorageItem('gallery-product-page');
                                                $.gallery.show($.gallery.block_id,now_page,$.gallery.category);
                                            }
                                        }
                                    }
                            }
                        }, 'json');
                    }
                });
            }
        },
        display_info : function() {
            var prodObj = (typeof property == "undefined") ? PRODINFO : property.PRODINFO;
            var s = '\
            <div class="cl-s-product-info-notice element el_000">\
                <div class="container">\
                <span class="prod-info-notice">상품정보 제공고시</span>\
                <table>\
                    <colgroup>\
                        <col width="">\
                        <col width="*">\
                    </colgroup>\
                    <tbody>\
            ';

            $.each(prodObj.content, function(i,v) {
                s = s + '\
                    <tr>\
                        <td class="prod-info-title">' + v.title + '</td>\
                        <td>' + v.content + '</td>\
                    </tr>\
                    ';
            });
            s = s + '\
                    </tbody>\
                </table>\
                </div>\
            </div>\
            ';

            if(typeof property == "undefined") {
                $lastEl = ($('.el-footer_ctrl').length) ? $('.el-footer_ctrl') : $('.add-footer-information');
                if($('.page-bottomlist').length) $lastEl = $('.page-bottomlist');
                if($('.fnav').length) $lastEl = $('.fnav');
                $lastEl.before(s);
            } else {
                if($('.el-footer').length) {
                    $lastEl = ($('.page-bottomlist').length) ? $('.page-bottomlist') : $('.el-footer');
                    if($('.fnav').length) $lastEl = $('.fnav');
                    $lastEl.before(s);
                } else {
                    $('.dsgn-body').append($s);
                }
            }
        },
        close : function() {
            var parentDocument = $(window.parent.document),
                $detail_modal = parentDocument.find('.product-detail-modal');
            if($detail_modal.length) $detail_modal.removeClass('overlap');

            if($('.prod-modal').length) {
                $('.prod-modal').fadeOut(300, function() {
                    $(this).remove();
                });
            }
        }
    }

    var clicking = false;
    $.gallery = {
        mode : '',
        SMENU : '',
        SFOLDER : '',
        valid_plan : '',
        valid_type : '',
        service : '',
        one : '',
        block_id : '',
        block_name : '',
        block_el : '',
        blocks : [],
        pages : [],
        seqs : [],
        copy : [],
        move : [],
        delete : [],
        ex_id : [],
        view_item : 30,
        update : false,
        unlink : false,
        category : '',
        cates : '',
        drag : '',
        last : '',
        site_settings : '',
        item_of_page : '',
        sort_icon_checked : '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-check2-square" viewBox="0 0 16 16"><path d="M3 14.5A1.5 1.5 0 0 1 1.5 13V3A1.5 1.5 0 0 1 3 1.5h8a.5.5 0 0 1 0 1H3a.5.5 0 0 0-.5.5v10a.5.5 0 0 0 .5.5h10a.5.5 0 0 0 .5-.5V8a.5.5 0 0 1 1 0v5a1.5 1.5 0 0 1-1.5 1.5z"/><path d="m8.354 10.354 7-7a.5.5 0 0 0-.708-.708L8 9.293 5.354 6.646a.5.5 0 1 0-.708.708l3 3a.5.5 0 0 0 .708 0"/></svg>',
        sort_icon_desc : '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="down" viewBox="0 0 16 16"><path d="M3.5 2.5a.5.5 0 0 0-1 0v8.793l-1.146-1.147a.5.5 0 0 0-.708.708l2 1.999.007.007a.497.497 0 0 0 .7-.006l2-2a.5.5 0 0 0-.707-.708L3.5 11.293zm3.5 1a.5.5 0 0 1 .5-.5h7a.5.5 0 0 1 0 1h-7a.5.5 0 0 1-.5-.5M7.5 6a.5.5 0 0 0 0 1h5a.5.5 0 0 0 0-1zm0 3a.5.5 0 0 0 0 1h3a.5.5 0 0 0 0-1zm0 3a.5.5 0 0 0 0 1h1a.5.5 0 0 0 0-1z"/></svg>',
        sort_icon_asc : '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="up" viewBox="0 0 16 16"><path d="M3.5 3.5a.5.5 0 0 0-1 0v8.793l-1.146-1.147a.5.5 0 0 0-.708.708l2 1.999.007.007a.497.497 0 0 0 .7-.006l2-2a.5.5 0 0 0-.707-.708L3.5 12.293zm4 .5a.5.5 0 0 1 0-1h1a.5.5 0 0 1 0 1zm0 3a.5.5 0 0 1 0-1h3a.5.5 0 0 1 0 1zm0 3a.5.5 0 0 1 0-1h5a.5.5 0 0 1 0 1zM7 12.5a.5.5 0 0 0 .5.5h7a.5.5 0 0 0 0-1h-7a.5.5 0 0 0-.5.5"/></svg>',
        edit_icon : '<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 16 16"><path d="M15.41 0.76l-0.17-0.17C14.85 0.2 14.34 0 13.83 0s-1.02 0.2-1.41 0.59L1 12l-1 4 4-1L15.41 3.59C16.2 2.8 16.2 1.54 15.41 0.76zM3.49 14.1l-2.11 0.53 0.53-2.11 8.95-8.95 1.59 1.59L3.49 14.1zM14.71 2.88l-1.56 1.56 -1.59-1.59 1.56-1.56C13.31 1.1 13.56 1 13.83 1s0.52 0.1 0.71 0.29l0.17 0.17C15.1 1.85 15.1 2.49 14.71 2.88z"></path></svg>',
        close_icon : '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-x-lg" viewBox="0 0 16 16"><path d="M2.146 2.854a.5.5 0 1 1 .708-.708L8 7.293l5.146-5.147a.5.5 0 0 1 .708.708L8.707 8l5.147 5.146a.5.5 0 0 1-.708.708L8 8.707l-5.146 5.147a.5.5 0 0 1-.708-.708L7.293 8z"/></svg>',
        conf_icon : '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-gear-fill" viewBox="0 0 16 16"><path d="M9.405 1.05c-.413-1.4-2.397-1.4-2.81 0l-.1.34a1.464 1.464 0 0 1-2.105.872l-.31-.17c-1.283-.698-2.686.705-1.987 1.987l.169.311c.446.82.023 1.841-.872 2.105l-.34.1c-1.4.413-1.4 2.397 0 2.81l.34.1a1.464 1.464 0 0 1 .872 2.105l-.17.31c-.698 1.283.705 2.686 1.987 1.987l.311-.169a1.464 1.464 0 0 1 2.105.872l.1.34c.413 1.4 2.397 1.4 2.81 0l.1-.34a1.464 1.464 0 0 1 2.105-.872l.31.17c1.283.698 2.686-.705 1.987-1.987l-.169-.311a1.464 1.464 0 0 1 .872-2.105l.34-.1c1.4-.413 1.4-2.397 0-2.81l-.34-.1a1.464 1.464 0 0 1-.872-2.105l.17-.31c.698-1.283-.705-2.686-1.987-1.987l-.311.169a1.464 1.464 0 0 1-2.105-.872zM8 10.93a2.929 2.929 0 1 1 0-5.86 2.929 2.929 0 0 1 0 5.858z"/></svg>',
        info_icon_option_true : '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-info-circle" viewBox="0 0 16 16" data-toggle="tooltip" data-placement="top" title="전체 또는 일부 상품들 재고가 5개 이하입니다"><path d="M8 15A7 7 0 1 1 8 1a7 7 0 0 1 0 14m0 1A8 8 0 1 0 8 0a8 8 0 0 0 0 16"/><path d="m8.93 6.588-2.29.287-.082.38.45.083c.294.07.352.176.288.469l-.738 3.468c-.194.897.105 1.319.808 1.319.545 0 1.178-.252 1.465-.598l.088-.416c-.2.176-.492.246-.686.246-.275 0-.375-.193-.304-.533zM9 4.5a1 1 0 1 1-2 0 1 1 0 0 1 2 0"/></svg>',
        info_icon_option_false : '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-info-circle" viewBox="0 0 16 16" data-toggle="tooltip" data-placement="top" title="현재 재고가 5개 이하입니다"><path d="M8 15A7 7 0 1 1 8 1a7 7 0 0 1 0 14m0 1A8 8 0 1 0 8 0a8 8 0 0 0 0 16"/><path d="m8.93 6.588-2.29.287-.082.38.45.083c.294.07.352.176.288.469l-.738 3.468c-.194.897.105 1.319.808 1.319.545 0 1.178-.252 1.465-.598l.088-.416c-.2.176-.492.246-.686.246-.275 0-.375-.193-.304-.533zM9 4.5a1 1 0 1 1-2 0 1 1 0 0 1 2 0"/></svg>',
        reset : function() { $.gallery.move = []; $.gallery.copy = []; $.gallery.seqs = []; },
        init : function() {
            var clearLocalStorage = function() {
                window.localStorage.removeItem('gallery-product-page');
                window.localStorage.removeItem('gallery-product-name');
                window.localStorage.removeItem('gallery-product-filter');
                window.localStorage.removeItem('gallery-product-sort');
                window.localStorage.removeItem('gallery-product-by');
            }
            clearLocalStorage();
            var galleryMoveItem = function(block_id,seq,page,callback) {
                if(CANCEL) return true;
                var seqs = [];
                seqs.push(seq);
                $.ajax({
                    url: '/template/gallery/move',
                    data: { s: seqs, sid : SID, page : page, block_id : block_id },
                    dataType: 'json',
                    type: 'POST',
                    async: true,
                    cache: false,
                    success: function(data) {
                        checkError(data);
                        if(typeof callback == 'function') {
                            callback();
                        }
                    }
                });
            }
            var reloadItems = function(items) {

            }
            var updateItem = function(item) {
            
            }
            var getSearchProduct = function(product_name) {
                if(typeof product_name == 'undefined' || (product_name.length > 0 && product_name.length < 2)) {
                    alert('최소 2자이상 검색어를 입력하세요');
                    $('.gallery-list-search-text').focus();
                    return false;
                }
                window.localStorage.setItem('gallery-product-name',product_name);
                $.gallery.show($.gallery.block_id,1,$.gallery.category);
            }
            var setQuantity = function(seqs) {
                if(typeof seqs == 'undefined') {
                    var product_number_arr = $('[name="item_check[]"]:checked').map(function() { return $(this).closest('.table-item').attr('data-seq'); }).toArray();    
                } else {
                    var product_number_arr = seqs;
                }
                var route = (CONFIG_URL) ? '/_admin' : '';
                $.ajax({
                    url: route + '/shopping/stock_use_check',
                    type:'post',
                    dataType:'json',
                    async: true,
                    data:{
                        'sid' : SID,
                        'product_number' : product_number_arr
                    },
                    success:function(data) {
                        var valid_data = data.filter(function(v){ if(v.product_quantity_on == 'on') return v; });
                        var invalid_data = data.filter(function(v){ if(v.product_quantity_on != 'on') return v; });
                        if(valid_data.length > 0 && valid_data.length <= product_number_arr.length) {
                            var invalid_products = invalid_data.map(function(v) { return v.title; }).join('<br>');
                            var showProductList = function() {
                                $.ajax({
                                    url: route + '/shopping/batch_stock_list',
                                    type:'post',
                                    dataType:'html',
                                    data: {
                                        'sid' : SID,
                                        'product_number' : valid_data.map(function(v) { return v.product_number; })
                                    },
                                    success:function(data) {
                                        var modal = $(this).showModalFlat($.lang[LANG]['editor.block.gallery.product.stock'] + $.lang[LANG]['editor.block.gallery.product.price'], data, false, true, function() { //confirm

                                            var dataSet = [];

                                            modal.find('.setting_product_list [data-product_number]').each(function() {
                                                var product_number = $(this).attr('data-product_number');
                                                var option_seq = $(this).attr('data-option_seq');
                                                var pre_quantity = Number(removeCommas($(this).find('.input-stock[data-quantity]').attr('data-pre_quantity')));
                                                var quantity = Number(removeCommas($(this).find('.input-stock[data-quantity]').attr('data-quantity')));
                                                var option_status = $(this).find('.input-stock[data-quantity]').attr('data-option_status');
                                                var product_name = $(this).find('.product_title').text();
                                                var option_name = $(this).find('.option_name').text();
                                                var option_value = $(this).find('.option_value').text();
                                                var option_type = $(this).find('.input-stock[data-quantity]').attr('data-option_type');

                                                var arr = {'product_number': product_number, 'option_seq': option_seq, 'pre_quantity': pre_quantity, 'quantity': quantity, 'option_status' : option_status, 'product_name' : product_name, 'option_name' : option_name, 'option_value' : option_value, 'option_type' : option_type };
                                                dataSet.push(arr);
                                            });

                                            $.ajax({
                                                url : route + '/shopping/batch_stock_set',
                                                type:'post',
                                                dataType:'json',
                                                data: {
                                                    'sid' : SID,
                                                    'datalist' : dataSet
                                                },
                                                success: function(data) {
                                                    // if(data.result == true) $.gallery.show($.gallery.block_id);
                                                }, error: function() {

                                                }, complete: function() {
                                                    // showPageCallback(showPage)
                                                    var page = getStorageItem('gallery-product-page');
                                                    $.gallery.show($.gallery.block_id,page,$.gallery.category);
                                                }
                                            });

                                            modal.modal('hide');
                                        } ,'cancel', 'config.change', 'cl-cmmodal cl-s-btn cl-p0 w900 cl-edit-discount modal-product-discount site-popup-discount cl-product-setting cover fullcover-modal fixed', '', '', function() { //show
                                        }, function(){ //hide
                                        },true);
                                    }
                                });

                            };
                            if(!invalid_products) {
                                showProductList();
                                return false;
                            }

                            $(this).showModalFlat('안내', '<div>재고 일괄 관리는 상품정보 <span style="color:#4789e7;">설정페이지 &gt; 재고관리 옵션</span>이<br><span style="color:#4789e7;">사용</span>으로 설정된 상품만 가능합니다.<br><br>아래 상품들은 재고 관리 옵션이 <span style="color:#4789e7;">사용안함</span>으로 설정 되어 있습니다.<br>이 상품들을 제외하고 재고 설정 페이지로 이동합니다.<br>(재고관리 옵션은 각 상품들의 상품정보 설정 페이지에서 설정할 수 있습니다.)</div><div class="title">상품명</div><div class="scroll">' + invalid_products + '</div>', true, false, function() {
                                // ok callback
                                // showProductList();
                            }, 'ok', '', 'cl-cmmodal cl-s-btn w700 cl-p70 cl-t80 cl-close-btn cover cover-inner-scroll', false, function() {
                                // close callback
                                // showProductList();
                            }, function() {
                                // show callback
                            }, function() {
                                // hide callback
                                showProductList();
                            });
                        } else if(valid_data.length == 0) {
                            var modal = $(this).showModalFlat('안내', '<div>재고 일괄 관리는 상품정보 <span style="color:#4789e7;">설정페이지 &gt; 재고관리 옵션</span>이<br><span style="color:#4789e7;">사용</span>으로 설정된 상품만 가능합니다.</div>', true, false, function() {
                                // ok callback
                                modal.modal('hide');
                            }, 'ok', '', 'cl-cmmodal cl-s-btn w700 cl-p70 cl-t80 cl-close-btn', false, function() {
                                // close callback
                            }, function() {
                                // show callback
                            }, function() {
                                // hide callback
                            });
                        }
                    }
                });
            }
            var checkUserEdit = function(v,type) {
                console.log(v,type);
                switch(type) {
                    case 'sale':
                        if(!isNaN(parseFloat(v)) && isFinite(v) && parseFloat(v) >= 0 && parseFloat(v) <= 1000000000) return true;
                        break;
                    case 'org':
                        if(!isNaN(parseFloat(v)) && isFinite(v) && parseFloat(v) >= 0 && parseFloat(v) <= 1000000000) return true;
                        break;
                    case 'disc':
                        if(!isNaN(parseFloat(v)) && isFinite(v) && parseFloat(v) <= 100) return true;
                        break;
                    case 'quantity':
                        if(!isNaN(parseFloat(v)) && isFinite(v) && parseFloat(v) < 10000) return true;
                        break;
                    default: return false;
                }

                return false;
            }
            var getEditType = function($o) {
                var type = '';
                if($o.parent().hasClass('td-orig-price')) type = 'org';
                if($o.parent().hasClass('td-price')) type = 'sale';
                if($o.parent().hasClass('td-discount')) type = 'disc';
                if($o.parent().hasClass('td-quantity')) type = 'quantity';
                if(type == '') {
                    alert('Invalid type');
                    return false;
                }
                return type;
            }
            $(document).on('click','.gallery-modal .gallery-block-select', function(e) {
                $('.gallery-modal .gallery-blocks.mobile').toggle();
            })
            $(document).on('click','.item-header .product-sort, .table-toolbar li .product-sort',function(e) {
                var sort = $(this).attr('data-sort'),
                    by = $(this).attr('data-by');

                if(by == '') by = 'desc';
                else {
                    by = (by == 'desc') ? 'asc' : 'desc';
                }
                window.localStorage.setItem('gallery-product-sort',sort);
                window.localStorage.setItem('gallery-product-by',by);
                $.gallery.show($.gallery.block_id,1,$.gallery.category);
            });
            $(document).on('click','.item-header .product-sort-checked, .table-toolbar li .product-sort-checked',function(e) {
                window.localStorage.removeItem('gallery-product-sort');
                window.localStorage.removeItem('gallery-product-by');
                $.gallery.show($.gallery.block_id,1,$.gallery.category);
            });
            $(document).on('click','.gallery-blocks .all-items', function(e) {
                clearLocalStorage();
                $.gallery.show('',1);
            });
            $(document).on('click','.table-item .td-status', function(e) {
                var is_product = $(this).parent().attr('data-product');
                if(typeof is_product == 'undefined' || is_product == 'false') {
                    $(this).showModalFlat($.lang[LANG]["config.information"], '상품 정보를 입력한 후에 이용 가능합니다.<br>상품 설정을 완료해주세요', true, false, '', 'ok','','cl-p130 cl-cmmodal cl-s-btn w560 cl-p0 cl-okbtn-pbt70');
                    return false;
                }
                e.stopPropagation();
                if($(this).hasClass('open')) {
                    $(this).removeClass('open').find('.table-item-status').hide();
                    return false;
                }
                $(this).toggleClass('open');
                $('.table-item-status').hide();
                var $status = $(this).find('.table-item-status');
                ($(this).hasClass('open')) ? $status.show() : $status.hide().removeClass('open');
            });
            $(document).on('click','.table-item .table-item-status li', function(e) {
                e.preventDefault();
                var product_number = $(this).parent().attr('data-seq'),
                    status = $(this).attr('data-val');
                $(this).parent().find('li').removeClass('active');
                $(this).addClass('active');

                $.processON();
                var route = (CONFIG_URL) ? '/_admin' : '';
                $.ajax({
                    url: route + '/shopping/setProductStatus',
                    type: 'post',
                    data: { sid : SID, product_number : product_number, status : status },
                    async: true,
                    cache: false,
                    dataType: 'json',
                    success: function(data) {
                        $.processOFF();
                        if(typeof data.error != 'undefined' && data.error) {
                            $p.find('.prev-value').text(t);
                            alert(data.error);
                            return false;
                        }
                        var page = getStorageItem('gallery-product-page');
                        $.gallery.show($.gallery.block_id,page,$.gallery.category);
                        $.gallery.update = true;
                        $.gallery.reset();
                    },
                    error: function(request,status,error) {
                        $.processOFF();
                        alert('code:'+request.status+'\n'+'message:'+request.responseText+'\n'+'error:'+error);
                        return false;
                    }
                });
            });
            $(document).on('keyup','.gallery-list-search-text', function(e) {
                var product_name = $(this).val().trim();
                // if(product_name.length == 0) return false;
                if(e.key === 'Enter') {
                    getSearchProduct(product_name);
                }
            });
            $(document).on('click','.gallery-list-search-submit', function(e) {
                var product_name = $('.gallery-list-search-text').val().trim();
                // if(product_name.length == 0) return false;
                getSearchProduct(product_name);
            });
            $(document).on('click','.gallery-list-search-cancel',function(e) {
                // $(this).hide();
                $('.gallery-list-search-submit').show();
                $('.gallery-list-search-text').val('');
                window.localStorage.removeItem('gallery-product-name');
                $.gallery.show($.gallery.block_id,1,$.gallery.category);
            });
            $(document).on('click','.gallery-list-filter ul li', function(e) {
                $('.gallery-list-filter ul li').removeClass('active');
                $(this).addClass('active');
                var filter = $(this).attr('data-val');
                window.localStorage.setItem('gallery-product-filter',filter);
                $.gallery.show($.gallery.block_id,1,$.gallery.category);
            });
            var isClose = false;
            $(document).on('click','.table-item .edit-button',function(e) {
                isClose = false;
                if($(this).hasClass('conf')) {
                    var $parent = $(this).parents('.table-item'),
                        seq = $parent.attr('data-seq'),
                        seqs = [seq];
                    setQuantity(seqs);
                    return false;
                }
                var s = $(this).parent().find('.prev-value').text(),
                    type = getEditType($(this));
                $('#user-edit').remove();
                $('.close-button').hide();
                $(this).parents('.table-item').find('.edit-button').show();
                $(this).hide();
                if($(this).parent().find('input').length == 0) {
                    $(this).parent().append('<input type="text" class="' + type + '" id="user-edit" value="' + s + '" numberOnly>');
                    $('#user-edit').focus();
                    $(this).parent().find('.close-button').show();
                    $('.edit-button').hide();
                }
            });
            $(document).on('mousedown','.close-button',function(e) {
                e.preventDefault();
            });
            $(document).on('click','.close-button', function(e) { 
                var s = $(this).attr('data-val'),
                    $this = $(this);
                isClose = true;
                $(this).removeClass('err not').hide();
                $(this).parent().find('.prev-value').text(s);
                $(this).parent().find('input').remove();
                $(this).parents('.table-item').find('.edit-button').show();
            });
            $(document).on('blur','#user-edit',function(e) {
                if(isClose) return false;
                var s = $(this).val().trim(),
                    $p = $(this).parent(),
                    $this = $(this),
                    type = getEditType($(this)),
                    $parent = $this.parents('.table-item'),
                    pid = $parent.attr('data-pid'),
                    seq = $parent.attr('data-seq'),
                    t = $this.parent().find('.prev-value').text(),
                    p_orig = $parent.find('.td-orig-price').find('.prev-value').text(),
                    p_price = $parent.find('.td-price').find('.prev-value').text(),
                    p_discount = $parent.find('.td-discount').find('.prev-value').text(),
                    p_quantity = $parent.find('.td-quantity').find('.prev-value').text();

                $this.parents('.table-item').find('.close-button').removeClass('err not');
                if(!checkUserEdit(uncomma(s),type) || s.length == 0) {
                    $this.parent().find('.close-button').show().addClass('err');
                    // setTimeout(function() { $this.focus(); },0);
                    return false;
                }
                var submit = false;
                if(type == 'org' || type == 'sale') {
                    var orig = (type == 'org') ? parseFloat(uncomma(s)) : parseFloat(uncomma(p_orig)),
                        price = (type == 'org') ? parseFloat(uncomma(p_price)) : parseFloat(uncomma(s));
                    if(orig < price) {
                        $this.parent().find('.close-button').show().addClass('err not');
                        // setTimeout(function() { $this.focus(); },0);
                        return false;
                    }
                }

                $('.close-button').hide();
                $this.parent().find('.close-button').attr('data-val',s).removeClass('err not').hide();
                $this.parent().find('.prev-value').text(s); 
                $this.parents('.table-item').find('.edit-button').show();
                $this.remove();

                if(s == t) return false;
                $.processON();

                var paramData = { sid : SID, pid : pid, seqs : [seq], type : type, mark : 'change', v : s, p : t, fx : 'disc', c : 's'};
                if(type == 'quantity') paramData['t'] = $parent.find('.item-title-str').text();
                
                var route = (CONFIG_URL) ? '/_admin' : '';
                $.ajax({
                    url: route + '/shopping/setProduct',
                    type: 'post',
                    data: paramData,
                    async: true,
                    cache: false,
                    dataType: 'json',
                    success: function(data) {
                        $.processOFF();
                        if(typeof data.error != 'undefined' && data.error) {
                            $p.find('.prev-value').text(t);
                            alert(data.error);
                            return false;
                        }
                        var page = getStorageItem('gallery-product-page');
                        $.gallery.show($.gallery.block_id,page,$.gallery.category);
                        $.gallery.update = true;
                        $.gallery.reset();
                        var cmd = '';
                        switch(type) {
                            case "org":     cmd = "org-price"; break;
                            case "sale":    cmd = "sale-price"; break;
                            case "disc":    cmd = "disc-price"; break;
                        }
                        if(cmd) setLogs('ELEM','product.'+cmd +'.modify','modify','ELEM','product-manager','el');
                    },
                    error: function(request,status,error) {
                        $.processOFF();
                        alert('code:'+request.status+'\n'+'message:'+request.responseText+'\n'+'error:'+error);
                        return false;
                    }
                });
            });
            $(document).on('keyup','#user-edit',function(e) {
                if(e.key === 'Enter') {
                    $(this).parents('.table-item').find('.close-button').removeClass('err not');
                    $(this).blur(); 
                }
            });
            $(document).on('click','#section-top-menu .product-manager', function(e) { 
                clearLocalStorage();
                $.gallery.show('',1);
            });
            $(window).resize(function(e) { 
                if($('.gallery-items').length == 0) return;
                shoppingGalleryResize();
                // resizeGalleryModal();
            });
            $(document).on('click','.product-gallery-list-toggle',function(e) {
                var $list = $('.product-gallery-list'),
                    $category = $('.gallery-category'),
                    $more = $('.gallery-items-loadmore'),
                    $items = $('.gallery-items'),
                    $toggle = $('.product-gallery-list-toggle'),
                    $pagination = $('.pagination-wrap'),
                    $filter = $('.gallery-list-filter'),
                    $name = $('.selected-gallery-name'),
                    $lux_filter = $('.shop-filter-header'),
                    svg_open = '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-chevron-right" viewBox="0 0 16 16"><path fill-rule="evenodd" d="M4.646 1.646a.5.5 0 0 1 .708 0l6 6a.5.5 0 0 1 0 .708l-6 6a.5.5 0 0 1-.708-.708L10.293 8 4.646 2.354a.5.5 0 0 1 0-.708z"/></svg>',
                    svg_close = '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-chevron-left" viewBox="0 0 16 16"><path fill-rule="evenodd" d="M11.354 1.646a.5.5 0 0 1 0 .708L5.707 8l5.647 5.646a.5.5 0 0 1-.708.708l-6-6a.5.5 0 0 1 0-.708l6-6a.5.5 0 0 1 .708 0"/></svg>';
                $toggle.toggleClass('open');
                $list.toggleClass('open');
                $category.toggleClass('open');
                $more.toggleClass('open');
                $items.toggleClass('open');
                $pagination.toggleClass('open');
                $filter.toggleClass('open');
                $name.toggleClass('open');
                $lux_filter.toggleClass('open');
                if($toggle.hasClass('open')) {
                    $toggle.html(svg_open);
                } else {
                    $toggle.html(svg_close);
                }

                ($('.product-gallery-list-toggle').hasClass('open')) ? 
                    window.localStorage.setItem('product-gallery-closed',false):
                    window.localStorage.setItem('product-gallery-closed',true);
            });
            $(document).bind('cut', '.gallery-modal', function(e) {
                if($('.cl-change-badge-design').length > 0) return;
                $.gallery.move = $.gallery.seqs;
                $.gallery.seqs = [];
                $.each($.gallery.move, function(i,v) {
                    $('.gallery-items .item[data-seq="' + v + '"]').removeClass('copy').addClass('move');
                    $('.gallery-toolbar.mod-gallery').remove();
                });
            });
            $(document).bind('copy', '.gallery-modal', function(e) {
                if($.gallery.block_id == -1 || $('.cl-common-modal').length) return;
                if($('.cl-change-badge-design').length > 0) return;
                $.gallery.copy = $.gallery.seqs;
                $.gallery.seqs = [];
                $.each($.gallery.copy, function(i,v) {
                    $('.gallery-items .item[data-seq="' + v + '"]').removeClass('move').addClass('copy');
                    $('.gallery-toolbar.mod-gallery').remove();

                    $('.table-item .td-check input[type="checkbox"]').prop('checked',false); 
                    $('.table-item').removeClass('ui-selected return');
                    $('.table-toolbar .toolbar-cmd').addClass('hide');
                    $('.table-toolbar .toolbar-cmd i[data-glseq]').attr('data-glseq','');
                    $('.table-toolbar .toolbar-cmd i[data-cmd="link"]').attr('data-glink','').attr('data-glink-target','');
                    $('.table-toolbar .toolbar-cmd i[data-cmd="visible"]').attr('data-visible','0').text($.lang[LANG]['editor.gallery.icon.visible.off']);
                    $('.gallery-toolbar').removeClass('hide_col');
                    $('.gallery-toolbar').addClass('hide');
                    $('.gallery-items .item-header').removeClass('hide');
                    $('.check-all').prop('checked',false);
                    $.toast({'title' : ($.gallery.copy).length + '개의 데이터가 복사 되었습니다'});
                });
            });
            $(document).bind('paste', '.gallery-modal', function(e) {
                if($('.gallery-modal').length == 0 || $('.galleryController').length || $('.prod-modal').length || $('.cl-product-setting').length) return;
                if($('.edit-link-Content').length) return;
                if($('.cl-change-badge-design').length > 0) return;

                if(($.gallery.copy).length) $.gallery.cp();
                if(($.gallery.move).length) $.gallery.mv();
            });
            $(document).bind('keydown', 'ctrl+a', function(e) {
                if( e.ctrlKey && 
                    !$(e.target).is('input:not([type="checkbox"])') &&
                    !$(e.target).is('textarea') &&
                    !$(e.target).is('.pace-disable.modal-open') &&
                    $('.prod-modal').length == 0 && 
                    $('.galleryController').length == 0 && 
                    $('.cl-category-modal.category-modal').length == 0
                ) {
                    if(e.keyCode == 65 || e.keyCode == 85) {
                        $.gallery.seqs = [];

                        var item_selector = ($('.table-item').length) ? '.table-item' : '.gallery-items .item',
                            visible_button = false;
                        $(item_selector).find('.td-check input[type="checkbox"]').prop('checked',true);
                        $(item_selector).addClass('ui-selected');
                        $.each($(item_selector), function(i,v) {
                            $.gallery.seqs.push($(this).attr('data-seq'));
                            if($(this).attr('data-out-datetime') == "1") visible_button = true;
                        });

                        if(item_selector == '.table-item') {
                            var firstItem = $('.gallery-items '+item_selector+'.ui-selected').eq(0),
                                first_seq = firstItem.attr('data-seq'),
                                link = firstItem.attr('data-link'),
                                target = firstItem.attr('data-target'),
                                visible = firstItem.attr('data-visible'),
                                vstr = (visible == '1') ? $.lang[LANG]['editor.gallery.icon.visible.on'] : $.lang[LANG]['editor.gallery.icon.visible.off'];

                            if(visible_button) {
                                $('.table-toolbar .toolbar-cmd.toolbar-visible').addClass('disabled');
                            } else $('.table-toolbar .toolbar-cmd.toolbar-visible').removeClass('disabled');
                            if($.gallery.block_id == -1) {
                                $('.table-toolbar .toolbar-cmd.toolbar-copy').addClass('disabled');
                            }
                            $('.table-toolbar .toolbar-cmd').removeClass('hide');
                            $('.table-toolbar .toolbar-cmd i[data-glseq]').attr('data-glseq',first_seq);
                            $('.table-toolbar .toolbar-cmd i[data-cmd="link"]').attr('data-glink',link).attr('data-glink-target',target);
                            $('.table-toolbar .toolbar-cmd i[data-cmd="visible"]').attr('data-visible',visible).text(vstr);
                            $('.gallery-toolbar').addClass('hide_col');
                            $('.check-all').prop('checked',true);
                            $.gallery.setNumber();
                            $('.gallery-toolbar').removeClass('hide');
                            $('.gallery-items .item-header').addClass('hide');
                            stickyToolbar();
                        } else {
                            $.gallery.toolbar();
                            stickyToolbar();
                        }
                    }
                }
            });
            $(document).on('click','.gallery-category > .category-text', function(e) {
                var s = $(this).text().trim(),
                    pid = $('.gallery-modal').attr('data-pid');
                $.gallery.show(pid,1,s);
            });
            $(document).on('click', '.gallery-modal', function(e) {
                $('.table-item-status').hide();
                $('.status-change').removeClass('open');
                $(this).find('.gallery-toolbar.mod-gallery').remove();
                if($.gallery.mode == 'shopping') {
                    if(typeof e.target.className != 'object') {
                        if(e.target.className.indexOf('ui-selectable') === -1) {
                            $.gallery.seqs = [];
                            $('.gallery-items .table-item > div').removeClass('hide-text');
                            $('.gallery-items .table-item input').prop('checked',false);
                            $('.gallery-items .check-all').prop('checked',false);
                            $('.gallery-items .table-item').removeClass('ui-selected return');
                            $('.table-toolbar > li').removeClass('open');
                            $('.table-toolbar .toolbar-cmd').addClass('hide');
                            $('.table-toolbar .toolbar-cmd i[data-glseq]').attr('data-glseq','');
                            $('.table-toolbar .toolbar-cmd i[data-cmd="link"]').attr('data-glink','').attr('data-glink-target','');
                            $('.table-toolbar .toolbar-cmd i[data-cmd="visible"]').attr('data-visible','0').text($.lang[LANG]['editor.gallery.icon.visible.off']);
                            $('.gallery-toolbar').removeClass('hide_col');
                            $('.col-check > input[type="checkbox"]').prop('checked',false);
                            $('.gallery-toolbar').addClass('hide');   
                            $('.gallery-items .item-header').removeClass('hide');
                        }
                    }
                } else {
                    if(typeof e.target.className == 'string' && e.target.className.indexOf('item') === -1) { 
                        $.gallery.seqs = [];
                        $('.gallery-items .item').removeClass('ui-selected return');    
                        $('.gallery-toolbar').empty();
                    } else {
                    }
                }
                $('.toolbar-sort').removeClass('open');
                $('.gallery-view-count').removeClass('open').find('.view-submenu').hide();
                // $('.table-toolbar > li').addClass('disabled').removeClass('open');
                $('.gallery-blocks .btn-group').removeClass('open');
            });
            $(document).on('mousemove', '.gallery-modal', function(e) {
                if($(".item-title").is(':focus') || clicking === false) return;
                if($('.gallery-modal .clone-item').length) {
                    $('.gallery-modal .clone-item').css({
                        'left' : e.pageX+10,
                        'top' : e.pageY+10
                    }).attr('data-count',($.gallery.seqs).length).find('input').remove();
                    if(($.gallery.seqs).length >1) $('.gallery-modal .clone-item').addClass('multi');
                    $('.gallery-items .table-item').removeClass('prev last');
                    if(window.innerHeight-80 < e.pageY) $('.gallery-modal').scrollTop($('.gallery-modal').scrollTop() + 30);
                    if(e.pageY < 80) $('.gallery-modal').scrollTop($('.gallery-modal').scrollTop() - 30);
                }
                if($('.ui-selectable-helper').length == 0) return;
                if(e.target.className.match(/(gallery-items ui-selectable|item-ctrl|img-responsive|ui-selected|ui-selectee|item-title|table-item|td-handle|item-handle|td-check|td-input|td-check|td-number|td-title|td-edit|td-img|info-link|td-edut|td-category|td-price|td-quantity)/)) { 
                    $('.gallery-modal, .gallery-items-loadmore, .gallery-category, .gallery-category li, .checkbox label, .gallery-toolbar .toolbar li, .btn, .gallery-button li').removeClass('not-allowed');
                } else { 
                    $('.gallery-modal, .gallery-items-loadmore, .gallery-category, .gallery-category li, .checkbox label, .gallery-toolbar .toolbar li, .btn, .gallery-button li').addClass('not-allowed');
                }
            }).on('mouseup', function(e) {
                if($('.gallery-modal .clone-item').length) {
                    $('.gallery-modal .clone-item').remove();
                    $('.gallery-items .item').removeClass('prev last drag');
                    $('.gallery-items .table-item').removeClass('prev last drag');
                    clicking = false;
                }
                // $('.gallery-items').selectable('enable');
                $('.gallery-modal, .gallery-items-loadmore, .gallery-category, .gallery-category li, .checkbox label, .gallery-toolbar .toolbar li, .btn, .gallery-button li').removeClass('not-allowed');
                stickyToolbar();
            });
            $(document).on('mousedown','.gallery-items',function(e) {
                if(typeof e.target.className == 'string' && typeof e.target.className != 'undefined' && e.target.className.indexOf('gallery-items') > -1) {
                    $.each($('.item-title'), function(i,v) {
                        if($(this).is(':focus')) {
                            $(this).blur();
                        }
                    });
                }
            });
            $(document).on('mouseup','.gallery-items',function(e) {
                $('.table-item-status').hide();
                $('.status-change').removeClass('open');
                var group = ($('.table-item').length) ? '.table-item' : '.gallery-items .item';
                if($(group + '.ui-selected').length == 0 && $(group).length) {
                    if($.gallery.mode == 'shopping') {
                        $('.gallery-items .table-item').removeClass('ui-selected return');
                        $('.table-toolbar > li').removeClass('open').find('.item-submenu').hide();
                        $('.gallery-view-count').removeClass('open').find('.view-submenu').hide();
                        $('.gallery-items .table-item > div').removeClass('hide-text');
                        $('.gallery-items .table-item input').prop('checked',false);
                        $('.table-toolbar .toolbar-cmd').addClass('hide');
                        $('.table-toolbar .toolbar-cmd i[data-glseq]').attr('data-glseq','');
                        $('.table-toolbar .toolbar-cmd i[data-cmd="link"]').attr('data-glink','').attr('data-glink-target','');
                        $('.table-toolbar .toolbar-cmd i[data-cmd="visible"]').attr('data-visible','0').text($.lang[LANG]['editor.gallery.icon.visible.off']);
                        $('.gallery-toolbar').removeClass('hide_col');
                        $('.col-check > input[type="checkbox"]').prop('checked',false);
                        $('.gallery-toolbar').addClass('hide'); 
                        $('.gallery-items .item-header').removeClass('hide');
                    } else {
                        $.gallery.seqs = [];
                        $('.gallery-items .item').removeClass('ui-selected return');    
                        $('.gallery-toolbar').empty();
                        $('.gallery-toolbar').addClass('hide');
                        $('.gallery-items .item-header').removeClass('hide');
                    }
                }
                $('.ui-selectable-helper').removeClass('hide');
                // $(".gallery-items").selectable("enable");
                if($.gallery.seqs.length && ($('.gallery-items .item').hasClass('prev') || $('.gallery-items .item').hasClass('last'))) {
                    if($('.gallery-items .item.last').length) {
                        if($('.gallery-items .item.last').next().length) {
                            $.gallery.drag = $('.gallery-items .item.last').next().attr('data-seq');
                        } else {
                            $.gallery.drag = $('.gallery-items .item.last').attr('data-seq');
                            $.gallery.last = '-1';
                        }
                    } else if($('.gallery-items .item.prev').length) {
                        $.gallery.drag = $('.gallery-items .item.prev').attr('data-seq');
                    }
                    $('.gallery-modal .clone-item').remove();
                    $('.gallery-items .item').removeClass('prev drag last');

                    $.gallery.move = $.gallery.seqs;
                    $.gallery.mv();
                }
                if(typeof e.target.className == 'string' && e.target.className.indexOf('gallery-items') > -1) {
                    $.each($('.item-title'), function(i,v) {
                        if($(this).is(':focus')) {
                            $(this).blur();
                        }
                    });
                }
            });
            var isDragging = false;
            var startingPos = [];
            $(document).on('mousedown','.gallery-items .table-item',function(e) {
                isDragging = false;
                clicking = true;
                startingPos = [e.pageX, e.pageY];
                if(e.shiftKey) {
                    var seq_start = $('.gallery-items .table-item[data-seq="' + $.gallery.seqs[0] + '"]').index(),
                        seq_end = $(this).index();
                    $.gallery.seqs = [];
                    $('.gallery-items .item').removeClass('ui-selected return');

                    // header, sticky 요소 추가로 -2
                    seq_start = seq_start - 2;
                    seq_end = seq_end - 2;
                    var start = 0, end = 0;
                    if(seq_start<seq_end) {
                        for(var i=seq_start; i<=seq_end; i++) {
                            var $shifted_item = $('.gallery-items .table-item');
                            $shifted_item.eq(i).addClass('ui-selected');
                            // $.gallery.seqs.push($shifted_item.eq(i).attr('data-seq'));
                        }
                    } else {
                        for(var i=seq_start; i>=seq_end; i--) {
                            var $shifted_item = $('.gallery-items .table-item');
                            $shifted_item.eq(i).addClass('ui-selected');
                            // $.gallery.seqs.push($shifted_item.eq(i).attr('data-seq'));
                        }
                    }
                    $('.gallery-toolbar').removeClass('hide');
                    $('.gallery-items .item-header').addClass('hide');
                    stickyToolbar();
                }
            });
            $(document).on('mousedown','.gallery-items .item',function(e) {
                if($('.item-title').is(':focus')) return;
                isDragging = false;
                clicking = true;
                startingPos = [e.pageX, e.pageY];
                $('.gallery-modal .clone-item').remove();
                if(e.target.className.indexOf('item') === 0) {
                    $(".ui-selectable-helper").addClass('hide');
                    $(".gallery-items").selectable("disable");
                }

                $('.gallery-blocks .btn-group').removeClass('open');
                var key = e.keyCode || e.which,
                    seq = $(this).attr('data-seq'),
                    seq_idx = ($.gallery.seqs).indexOf(seq);

                if(e.ctrlKey) {
                    if(seq_idx > -1) {
                        $(this).removeClass('ui-selected return');
                        // ($.gallery.seqs).splice(seq_idx,1);
                    } else {
                        $(this).addClass('ui-selected');
                        // $.gallery.seqs.push(seq);
                    }
                    $.gallery.selected();
                    stickyToolbar();
                } else if(e.shiftKey) {
                    if(($.gallery.seqs).length > 0) {
                        var seq_start = $('.gallery-items .item[data-seq="' + $.gallery.seqs[0] + '"]').index(),
                            seq_end = $(this).index();
                        $.gallery.seqs = [];
                        $('.gallery-items .item').removeClass('ui-selected return');
                        // console.log(seq_start,seq_end);
                        // header, sticky 요소 추가로 -2
                        seq_start = seq_start - 1;
                        seq_end = seq_end - 1;
                            var start = 0, end = 0;
                        if(seq_start<seq_end) {
                            for(var i=seq_start; i<=seq_end; i++) {
                                var $shifted_item = $('.gallery-items .item');
                                $shifted_item.eq(i).addClass('ui-selected');
                                // $.gallery.seqs.push($shifted_item.eq(i).attr('data-seq'));
                            }
                        } else {
                            for(var i=seq_start; i>=seq_end; i--) {
                                var $shifted_item = $('.gallery-items .item');
                                $shifted_item.eq(i).addClass('ui-selected');
                                // $.gallery.seqs.push($shifted_item.eq(i).attr('data-seq'));
                            }
                        }
                        $.gallery.selected();
                        stickyToolbar();
                    }
                } else {
                    if(!$(this).hasClass('ui-selected')) {
                        $.gallery.seqs = []; 
                        $.gallery.seqs.push(seq);
                        $('.gallery-items .item').removeClass('ui-selected return');
                        // $(this).parent().removeClass('move').removeClass('copy');
                        $(this).addClass('ui-selected');
                        stickyToolbar();

                        // cut, copy remove
                        var i = ($.gallery.copy).indexOf(seq);
                        if(i !== -1) ($.gallery.copy).splice(i,1);

                        var i = ($.gallery.move).indexOf(seq);
                        if(i !== -1) ($.gallery.move).splice(i,1);
                    }
                }
            });
            $(document).on('mousedown','.gallery-items .td-handle',function(e) {
                // if($('.gallery-items .table-item.ui-selected').length == 0) {
                if($(this).parent().hasClass('ui-selected') == false) {
                    $(this).parent().addClass('ui-selected').find('.td-check input[type="checkbox"]').prop('checked',true);
                    $.gallery.seqs.push($(this).parent().attr('data-seq'));
                }
            });
            $(document).on('mousemove','.gallery-items .table-item',function(e) {
                if(clicking === false) return;
                $('.gallery-items .table-item').removeClass('prev');

                if($('.gallery-modal .clone-item').length) {
                    var $clone = $('.gallery-modal .clone-item');
                    $clone.css({
                        'position' : 'fixed',
                        'cursor' : 'move',
                        'z-index' : '1090'
                    });
                    $clone.css({
                        'left' : e.pageX+5,
                        'top' : e.pageY-25
                    }).attr('data-count',($.gallery.seqs).length).find('input').remove();
                    if(($.gallery.seqs).length >1) $clone.addClass('multi');

                    var this_top = e.pageY - $(this).offset().top;
                    if($(this).is(':last-child') && this_top > 45) {
                        $(this).removeClass('prev').addClass('last');
                    } else $(this).removeClass('last').addClass('prev');
                    if(window.innerHeight-80 < e.pageY) $('.gallery-modal').scrollTop($('.gallery-modal').scrollTop() + 30);
                    if(e.pageY < 80) $('.gallery-modal').scrollTop($('.gallery-modal').scrollTop() - 30);
                    e.stopPropagation();
                } 
            });
            $(document).on('mouseenter','.gallery-items .table-item',function(e) {
                if($('#user-edit').length == 0) { 
                    $('.edit-button').hide();
                    if($(this).hasClass('yet')) return;
                    $(this).find('.edit-button').show();
                } else $('.edit-button').hide();
            }).on('mouseleave','.gallery-items .table-item',function(e) {
                $('.edit-button').hide();
            });
            $(document).on('mouseenter','.gallery-items .td-category', function(e) {
                var cate_arr = $(this).text().trim().split(',');
                if(cate_arr.length < 2) return;

                var cate_str = '';
                $.each(cate_arr, function(i,v) {
                    cate_str += '<li>' + v.trim() + '</li>';
                });

                var gcate_tooltip_place = ($('.gallery-modal').height() <= $(this).closest('.table-item').offset().top + $(this).closest('.table-item').outerHeight()) ? 'top' : 'bottom'; 
                var gcate_tooltip_css = (gcate_tooltip_place == 'top') ? {
                    'top': (Math.floor($('.gallery-modal').scrollTop() + $(this).offset().top - (100 + ((cate_arr.length-2) * 20)))) + 'px',
                    'left': (Math.floor($(this).offset().left) -30) + 'px',
                } : {
                    'top': (Math.floor($('.gallery-modal').scrollTop() + $(this).offset().top + $(this).outerHeight()) - 7) + 'px',
                    'left': (Math.floor($(this).offset().left) -30) + 'px',
                }

                $('.gcategory-tooltip ul').empty().html(cate_str);
                $('.gcategory-tooltip').attr('data-place',gcate_tooltip_place).css(gcate_tooltip_css).show();
            });
            $(document).on('mouseleave', '.gallery-items .td-category', function(e) {
                if($('.gcategory-tooltip').css('display') === 'none') return;
                $('.gcategory-tooltip').hide().removeAttr('style');
                $('.gcategory-tooltip ul').empty();
            });
            $(document).on('mousemove','.gallery-items .td-handle',function(e) {
                if($('.gallery-modal').attr('data-pid') == undefined) {
                    return false;
                }
                if(clicking === false || $('.gallery-items .table-item.ui-selected').length == 0) return;
                $('.td-edit .item-edit').css('display','none');
                if ((e.pageX  < startingPos[0]-10 || e.pageX  > startingPos[0]+10) ||
                    (e.pageY  < startingPos[1]-10 || e.pageY  > startingPos[1]+10)) {
                    $('.gallery-items .table-item.ui-selected').addClass('drag');
                    if($('.gallery-modal .clone-item').length == 0 && !LUX) {
                        var $clone = $(this).parent().clone();
                        $clone.css({
                            'position' : 'fixed',
                            'cursor' : 'move',
                            'z-index' : '1090'
                        }).addClass('clone-item').attr('data-count',($.gallery.seqs).length).find('input').remove();
                        $('.gallery-modal').append($clone);

                        $clone.css({
                            'left' : e.pageX+10,
                            'top' : e.pageY+10
                        });
                        if(($.gallery.seqs).length >1) $clone.addClass('multi');
                    } 
                    isDragging = true;
                    // var parentOffset = $(this).parent().offset(); 
                    // var relX = e.pageX - parentOffset.left;
                    // var relY = e.pageY - parentOffset.top;
                    // $('.gallery-items .item').removeClass('prev last');
                    // var this_top = $(this).position().top,
                    //     next_top = ($(this).next().length) ? $(this).next().position() : -1;
                    // console.log(parentOffset);
                    // if(this_top == next_top) {
                    //     (relX - $(this).position().left < 62) ? $(this).addClass('prev') : $(this).next().addClass('prev');
                    // } else {
                    //     (relX - $(this).position().left < 62) ? $(this).addClass('prev') : $(this).addClass('last');
                    // }
                }
            });
            $(document).on('mousemove','.gallery-items .item',function(e) {
                if(clicking === false || $('.item-title').is(':focus')) return;
                if ((e.pageX  < startingPos[0]-10 || e.pageX  > startingPos[0]+10) ||
                    (e.pageY  < startingPos[1]-10 || e.pageY  > startingPos[1]+10)) {
                    $('.gallery-items .item.ui-selected').addClass('drag');
                    if($('.gallery-modal .clone-item').length == 0 && !LUX) {
                        var $clone = $(this).clone();
                        $clone.css({
                            'position' : 'fixed'
                        }).addClass('clone-item').attr('data-count',($.gallery.seqs).length).find('input').remove();
                        $('.gallery-modal').append($clone);
                        if(($.gallery.seqs).length >1) $clone.addClass('multi');
                    } 
                    isDragging = true;
                    var parentOffset = $(this).parent().offset(); 
                    var relX = e.pageX - parentOffset.left;
                    var relY = e.pageY - parentOffset.top;
                    $('.gallery-items .item').removeClass('prev last');
                    var this_top = $(this).position().top,
                        next_top = ($(this).next().length) ? $(this).next().position() : -1;
                    if(this_top == next_top) {
                        (relX - $(this).position().left < 62) ? $(this).addClass('prev') : $(this).next().addClass('prev');
                    } else {
                        (relX - $(this).position().left < 62) ? $(this).addClass('prev') : $(this).addClass('last');
                    }
                }
            });
            $(document).on('mouseup','.gallery-items .table-item',function(e) {
                clicking = false;
                if (isDragging) {
                    if($.gallery.seqs.length && $('.gallery-modal .clone-item').length) {
                        if($('.gallery-items .table-item.last').length) {
                            if($('.gallery-items .table-item.last').next().length) {
                                $.gallery.drag = $('.gallery-items .table-item.last').next().attr('data-seq');
                            } else {
                                $.gallery.drag = $('.gallery-items .table-item.last').attr('data-seq');
                                $.gallery.last = '-1';
                            }
                        } else if($('.gallery-items .table-item.prev').length) {
                            $.gallery.drag = $('.gallery-items .table-item.prev').attr('data-seq');
                        }
                        $('.gallery-modal .clone-table-item').remove();
                        $('.gallery-items .table-item').removeClass('prev drag last');

                        $.gallery.move = $.gallery.seqs;
                        $.gallery.mv();
                    }
                } else {
                    $('.gallery-items .table-item.ui-selecting').removeClass('active').addClass('ui-selected');
                    $('.check-all').prop('checked',false);
                    stickyToolbar();
                }
                isDragging = false;
                startingPos = [];

                var l = ($(this).index()%7 > 3) ? 'right' : '',
                    mode = $('.gallery-add-items').attr('data-mode');

                if(typeof mode == 'undefined' || !mode) {
                    alert('Undefined gallery mode');
                    return false;
                }                        
                $.gallery.setNumber();     
                $('.ui-selectable-helper').removeClass('hide');
                if($('.gallery-modal').attr('data-pid') != undefined) {
                    $('.gallery-items').selectable('enable');    
                }
            });
            $(document).on('mouseup','.gallery-items .item',function(e) {
                e.preventDefault();
                clicking = false;
                if (isDragging) {
                    if($.gallery.seqs.length && $('.gallery-modal .clone-item').length) {
                        if($('.gallery-items .item.last').length) {
                            if($('.gallery-items .item.last').next().length) {
                                $.gallery.drag = $('.gallery-items .item.last').next().attr('data-seq');
                            } else {
                                $.gallery.drag = $('.gallery-items .item.last').attr('data-seq');
                                $.gallery.last = '-1';
                            }
                        } else if($('.gallery-items .item.prev').length) {
                            $.gallery.drag = $('.gallery-items .item.prev').attr('data-seq');
                        }
                        $('.gallery-modal .clone-item').remove();
                        $('.gallery-items .item').removeClass('prev drag last');

                        $.gallery.move = $.gallery.seqs;
                        $.gallery.mv();
                    }
                } else {
                    var parentOffset = $(this).parent().offset(),
                        relX = e.pageX - parentOffset.left,
                        relY = e.pageY - parentOffset.top;
                    $('.gallery-items .item.ui-selecting').removeClass('active').addClass('ui-selected');
                    stickyToolbar();
                }
                isDragging = false;
                startingPos = [];

                var l = ($(this).index()%7 > 3) ? 'right' : '',
                    mode = $('.gallery-add-items').attr('data-mode');

                if(typeof mode == 'undefined' || !mode) {
                    alert('Undefined gallery mode');
                    return false;
                }                        
                // $.gallery.toolbar();
                
                $.gallery.setNumber();     
                $('.ui-selectable-helper').removeClass('hide');
                $('.gallery-items').selectable('enable');
            });
            $(document).on('click','.toolbar-cmd.null', function(e) {
                e.stopPropagation();
                $.gallery.seqs = [];
                $('.gallery-toolbar').addClass('hide');   
                $('.gallery-items .item-header').removeClass('hide');
                setTimeout(()=> {
                    $('.gallery-items .table-item input').prop('checked',false);
                    $('.gallery-items .table-item').removeClass('ui-selected ui-selecting');
                },100);
            }); 
            $(document).on('click','.gallery-controller',function(e) { 
                $.gallery.show($.gallery.block_id);
            });
            $(document).on('click','.gallery-all',function(e) { 
                $.gallery.show($.gallery.block_id);
            });
            $(document).on('click','.gallery-button .modal-close', function(e) {
                $.gallery.close();
            });
            $(document).on('keyup','.item-title', function(e) {
                if(e.keyCode == 13) $('#empty-text').focus().blur();
            });
            $(document).on('focus','.item-title', function(e) {
                $.gallery.seqs = [];
                var seq = $(this).parent().attr('data-seq');
                $.gallery.seqs.push(seq);
                $('.gallery-items .item').removeClass('ui-selected');
                $(this).parent().addClass('ui-selected');
            });
            $(document).on('mouseenter', '.gallery-items .item > img', function(e) {
                // e.stopPropagation();
                $('.gallery-items .item .gallery-paste-icon').remove();
                var s = '<div class="item-ctrl"></div>',
                    $ctrl = $(s);
                if($(this).parent().find('.item-ctrl').length == 0)
                    $(this).parent().append($ctrl);
            });
            $(document).on('mouseleave', '.gallery-items .item', function(e) {
                $(this).find('.item-ctrl').remove();
                $('.gallery-paste-icon').remove();
            });
            $(document).on('click','.gallery-items .item .gallery-paste-icon', function(e) {
                e.stopPropagation();
                ($.gallery.seqs).push($(this).parents('.item').attr('data-seq'));
                if(($.gallery.copy).length) $.gallery.cp();
                if(($.gallery.move).length) $.gallery.mv();
            });
            $(document).on('click', '.gallery-items .item input', function(e) {
                e.stopPropagation();
                $('.gallery-toolbar.mod-gallery').remove();
            });
            $(document).on('keypress click', '.gallery-items .item .item-ctrl', function(e) {
                $('.gallery-blocks .btn-group').removeClass('open');
                var key = e.keyCode || e.which,
                    seq = $(this).parent().attr('data-seq'),
                    seq_idx = ($.gallery.seqs).indexOf(seq);
                if(e.ctrlKey) {
                    if(seq_idx > -1) {
                        $(this).parents().removeClass('ui-selected');
                        ($.gallery.seqs).splice(seq_idx,1);
                    } else {
                        $(this).parent().addClass('ui-selected');
                        $.gallery.seqs.push(seq);
                    }
                } else if(e.shiftKey) {
                    if(($.gallery.seqs).length > 0) {
                        var seq_start = $('.gallery-items .item[data-seq="' + $.gallery.seqs[0] + '"]').index(),
                            seq_end = $(this).parent().index();
                        $.gallery.seqs = [];
                        $('.gallery-items .item').removeClass('ui-selected');
                        // console.log(seq_start,seq_end);
                        var start = 0, end = 0;
                        if(seq_start<seq_end) {
                            for(var i=seq_start; i<=seq_end; i++) {
                                var $shifted_item = $('.gallery-items .item');
                                $shifted_item.eq(i).addClass('ui-selected');
                                $.gallery.seqs.push($shifted_item.eq(i).attr('data-seq'));
                            }
                        } else {
                            for(var i=seq_start; i>=seq_end; i--) {
                                var $shifted_item = $('.gallery-items .item');
                                $shifted_item.eq(i).addClass('ui-selected');
                                $.gallery.seqs.push($shifted_item.eq(i).attr('data-seq'));
                            }
                        }
                    }
                } else {
                    $.gallery.seqs = []; 
                    $.gallery.seqs.push(seq);
                    $('.gallery-items .item').removeClass('ui-selected return');
                    // $(this).parent().removeClass('move').removeClass('copy');
                    $(this).parent().addClass('ui-selected');

                    // cut, copy remove
                    var i = ($.gallery.copy).indexOf(seq);
                    if(i !== -1) ($.gallery.copy).splice(i,1);

                    var i = ($.gallery.move).indexOf(seq);
                    if(i !== -1) ($.gallery.move).splice(i,1);
                }
                var l = ($(this).index()%7 > 3) ? 'right' : '',
                    mode = $('.gallery-add-items').attr('data-mode');

                if(typeof mode == 'undefined' || !mode) {
                    alert('Undefined gallery mode');
                    return false;
                }
                $(this).parents('.gallery-items').find('.toolbar.mod-gallery').remove();
                // var str = '', cmd = '';
                // if(($.gallery.move).length || ($.gallery.copy).length) {
                //     str = '붙여넣기'; cmd = 'paste';
                // } else {
                //     str = '잘라내기'; cmd = 'move';
                // }

                var seq = $(this).parent().attr('data-seq'),
                    pid = $(this).parent().attr('data-pid'),
                    link = $(this).parent().attr('data-link'),
                    target = $(this).parent().attr('data-target'),
                    visible = $(this).parent().attr('data-visible');

                var vstr = (visible == '1') ? $.lang[LANG]["editor.gallery.icon.visible.on"] : $.lang[LANG]["editor.gallery.icon.visible.off"],
                    vicon = (visible == '1') ? 'cl_icon_hide02' : 'cl_icon_show',
                    edit_name = ($.gallery.mode == 'gallery') ? $.lang[LANG]['editor.block.gallery.item.edit.image'] : $.lang[LANG]['editor.block.gallery.item.edit'];
                var outDatetime = $(this).parent().attr('data-out-datetime');
                if(outDatetime !== 'off') {
                    visible = outDatetime;
                    if(outDatetime == 1) vstr = $.lang[LANG]['editor.gallery.icon.visible.on'];
                }
                var s = '\
                    <ul>\
                        <li class="active gallery-item-edit">\
                            <i class="" data-glseq="' + seq + '" data-cmd="edit"></i>' + edit_name + '\
                        </li>\
                    ';
                s = s + '<li><i class="" data-glseq="' + seq + '" data-cmd="copy"></i>' + $.lang[LANG]['editor.gallery.icon.clone'] + '</li>';

                s = s + '<li class="toolbar-sort item-sort">' + $.lang[LANG]['editor.gallery.icon.order'] + ' <i class="fa fa-caret-down" aria-hidden="true" data-glseq="" data-cmd="item-sort"></i>\
                            <ul class="item-submenu">\
                                <li class="sort-top">' + $.lang[LANG]['editor.gallery.icon.order.front'] + '</li>\
                                <li class="sort-bottom">' + $.lang[LANG]['editor.gallery.icon.order.end'] + '</li>\
                            </ul>\
                        </li>';
                s = s + '<li class="toolbar-category"><i class="" data-glseq="" data-cmd="category"></i>' + $.lang[LANG]['editor.block.gallery.category.change'] + ' <i class="fa fa-caret-down" aria-hidden="true"></i>';
                s = s + '<ul class="item-submenu">' + $.gallery.cates + '</ul>';
                s = s + '</li>';
                
                s = s + '\
                        <li><i class="" data-glseq="' + seq + '" data-glink="' + link + '" data-glink-target="' + target + '" data-cmd="link"></i>' + $.lang[LANG]['editor.gallery.icon.link'] + '</li>\
                ';
                        
                s = s + '\
                        <li><i class="" data-glseq="' + seq + '" data-visible="' + visible + '" data-cmd="visible">' + vstr + '</i></li>\
                        <li><i class="" data-glseq="' + seq + '" data-cmd="delete"></i>' + $.lang[LANG]['editor.gallery.icon.delete'] + '</li>\
                    </ul>\
                ';
                var $tool_back = $('<div class="toolbar mod-gallery ' + l + '">' + s + '</div>');
                $(this).parents('.container').find('.gallery-toolbar').empty();
                $(this).parents('.container').find('.gallery-toolbar').append($tool_back);
                
                // $(this).parent().prev().append($tool_back);
                $.gallery.selected();
                stickyToolbar();
                $.gallery.setNumber();
            });
            $(document).on('click','.gallery-modal .check-all', function(e) {
                e.stopPropagation();
                var check = $(this).prop('checked'),
                    disabled = false,
                    visible_button = false;
                if(check) {
                    $('.table-item .td-check input[type="checkbox"]').prop('checked',true);
                    $('.table-item').addClass('ui-selected');
                    $.each($('.table-item'), function(i,v) {
                        if($.gallery.seqs.indexOf($(this).attr('data-seq')) == -1) $.gallery.seqs.push($(this).attr('data-seq'));
                    });

                    $.each($('.gallery-items .table-item.ui-selected'), function(i,v) {
                        if($(this).attr('data-product') == "false") disabled = true;
                        if($(this).attr('data-out-datetime') == "1") visible_button = true;
                    });
                    var firstItem = $('.gallery-items .table-item.ui-selected').eq(0),
                        first_seq = firstItem.attr('data-seq'),
                        link = firstItem.attr('data-link'),
                        target = firstItem.attr('data-target'),
                        visible = firstItem.attr('data-visible'),
                        vstr = (visible == '1') ? $.lang[LANG]['editor.gallery.icon.visible.on'] : $.lang[LANG]['editor.gallery.icon.visible.off'];
                    if(visible_button) {
                        $('.table-toolbar .toolbar-cmd.toolbar-visible').addClass('disabled');
                    } else $('.table-toolbar .toolbar-cmd.toolbar-visible').removeClass('disabled');
                    if($.gallery.block_id == -1) {
                        $('.table-toolbar .toolbar-cmd.toolbar-copy').addClass('disabled');
                    }
                    $('.table-toolbar .toolbar-cmd').removeClass('hide');
                    $('.table-toolbar .toolbar-cmd i[data-glseq]').attr('data-glseq',first_seq);
                    $('.table-toolbar .toolbar-cmd i[data-cmd="link"]').attr('data-glink',link).attr('data-glink-target',target);
                    $('.table-toolbar .toolbar-cmd i[data-cmd="visible"]').attr('data-visible',visible).text(vstr);
                    $('.gallery-toolbar').addClass('hide_col');
                    $('.gallery-toolbar').removeClass('hide');
                    $('.gallery-items .item-header').addClass('hide');
                    $('.checkbox-cmd .check-all').prop('checked',true);
                    stickyToolbar();
                } else {
                    $('.table-item .td-check input[type="checkbox"]').prop('checked',false);   
                    $('.table-item').removeClass('ui-selected return');
                    $('.table-toolbar .toolbar-cmd').addClass('hide');
                    $('.table-toolbar .toolbar-cmd i[data-glseq]').attr('data-glseq','');
                    $('.table-toolbar .toolbar-cmd i[data-cmd="link"]').attr('data-glink','').attr('data-glink-target','');
                    $('.table-toolbar .toolbar-cmd i[data-cmd="visible"]').attr('data-visible','0').text($.lang[LANG]['editor.gallery.icon.visible.off']);
                    $('.gallery-toolbar').removeClass('hide_col');
                    $('.gallery-toolbar').addClass('hide');
                    $('.gallery-items .item-header').removeClass('hide');
                    $('.check-all').prop('checked',false);
                    $.gallery.seqs = [];
                }
                (disabled) ? $('.product-cmd').addClass('disabled') : $('.product-cmd').removeClass('disabled');
                if($('.gallery-modal').attr('data-pid') == undefined) {
                    $('.toolbar-sort.item-sort').addClass('disabled');
                }

                $.gallery.setNumber();
            });
            $(document).on('click','.gallery-view-count', function(e) {
                e.stopPropagation();
                $(this).toggleClass('open');
                if($(this).hasClass('open')) {
                    $(this).find('.view-submenu').show();
                } else $(this).find('.view-submenu').hide();
            });
            $(document).on('click','.gallery-view-count li', function(e) {
                $('.gallery-view-count li').removeClass('active');
                $(this).addClass('active');
            });
            $(document).on('click','.gallery-move:not(.disabled)', function(e) {
                $('.gallery-move-list').removeClass('not-selected');
                $('.move-alert').text('');
                $('.gallery-move').removeClass('active');
                $(this).toggleClass('active');

                var block_id = $(this).attr('data-gallery-id'),
                    first_title = '';
                $.gallery.ex_id = [];

                // 선택된 상품 같은 갤러리 이동시 처리
                $.each($.gallery.move, function(i,v) {
                    var $product = $('.table-item[data-seq="' + v + '"]'),
                        product_pid = $product.attr('data-pid'),
                        product_title = $product.find('.td-title .item-title-str').text();
                    if(block_id == product_pid) {
                        if(first_title == '') first_title = "'" + product_title + "'";
                        $.gallery.ex_id.push(v);
                    }
                });
                if($.gallery.ex_id.length) {
                    $('.move-alert').append('<p>' + first_title + (($.gallery.ex_id.length == 1) ? ' 상품은<br>이미 갤러리에 존재하여 이동에서 제외됩니다.' : ' 외 ' + $.gallery.ex_id.length + '개 상품들은<br>이미 갤러리에 존재하여 이동에서 제외됩니다.</p>'));
                }
                ($.gallery.ex_id.length == $.gallery.move.length) ?
                    $('.ok-button-dialog').addClass('disabled') :
                    $('.ok-button-dialog').removeClass('disabled');
            });
            $(document).on('click', '.gallery-modal .toolbar li', function(e) {
                var check_disabled = ($(this).hasClass('product-cmd') && ($(this).hasClass('disabled') || $(this).hasClass('no_price'))) ? true : false;
                        
                if(check_disabled) {
                    var modal_str = ($(this).hasClass('disabled')) ? '상품 정보를 입력한 후에 이용 가능합니다.<br>상품 설정을 완료해주세요.' : '정가가 1원 이상이어야만 [할인] 및 [판매가] 설정이 가능합니다';
                    $(this).showModalFlat($.lang[LANG]["config.information"], modal_str, true, false, '', 'ok','','cl-p130 cl-cmmodal cl-s-btn w560 cl-p0 cl-okbtn-pbt70');
                    return false;
                }

                if($(this).hasClass('toolbar-visible') && $(this).hasClass('disabled')) {
                    $(this).showModalFlat($.lang[LANG]["config.information"], '판매예정/판매종료인 기간한정판매 상품은 숨김/보이기 옵션을 이용할 수 없습니다.', true, false, '', 'ok','','cl-p130 cl-cmmodal cl-s-btn w560 cl-p0 cl-okbtn-pbt70');
                    return false;
                }

                if($(this).hasClass('toolbar-copy') && $(this).hasClass('disabled')) {
                    $(this).showModalFlat($.lang[LANG]["config.information"], '상품 복제는 화면 좌측의 갤러리 목록에서 갤러리 선택 후 사용 가능합니다.', true, false, '', 'ok','','cl-p130 cl-cmmodal cl-s-btn w560 cl-p0 cl-okbtn-pbt70');
                    return false;
                }

                if($(this).hasClass('toolbar-sort') && $(this).hasClass('disabled')) {
                    $(this).showModalFlat($.lang[LANG]["config.information"], '상품 순서 변경은 화면 좌측의 갤러리 목록에서 갤러리 선택 후 사용 가능합니다.', true, false, '', 'ok','','cl-p130 cl-cmmodal cl-s-btn w560 cl-p0 cl-okbtn-pbt70');
                    return false;
                }

                $('.ui-selectable-helper').remove();
                e.stopPropagation();
                var cmd = $(this).find('i').attr('data-cmd'),
                    mode = $('.gallery-add-items').attr('data-mode'),
                    seq = $(this).find('i').attr('data-glseq'),
                    sub = ($(this).parent().hasClass('item-submenu')) ? true : false,
                    $this = $(this);

                if(typeof cmd == 'undefined' && sub == false && !$(this).hasClass('disabled')) {
                    $('.item-submenu').hide();
                    $('.submenu').removeClass('open');
                    var $submenu = $(this).find('.item-submenu'),
                        display = $submenu.css('display');
                    (display == 'none') ? $submenu.css('display','block') : $submenu.css('display','none');
                    return;
                }
                if($(this).hasClass('disabled')) {
                    if($(this).hasClass('gallery-item-edit')) {
                        $(this).showModalFlat($.lang[LANG]["config.information"], $.lang[LANG]['editor.gallery.select.items.info'], true, false, '', 'ok','','cl-p130 cl-cmmodal cl-s-btn w560 cl-p0 cl-okbtn-pbt70');
                    }
                    return false;
                }
                if(($.gallery.seqs).length == 0 && cmd != 'checkall') {
                    $(this).showModalFlat($.lang[LANG]["config.information"], $.lang[LANG]["editor.gallery.select.item"], true, false,'','ok', '', 'cl-p130 cl-cmmodal cl-s-btn w560 cl-p0 cl-okbtn-pbt70');
                    return false;
                }
                switch(cmd) {
                    case "item-sort":
                        $(this).toggleClass('open');
                        $('.item-submenu').hide();
                        if($(this).hasClass('open')) {
                            $(this).find('.item-submenu').show();
                        }
                        $('.toolbar-category').removeClass('open');
                        $('.toolbar-category .item-submenu').hide();
                        break;
                    case "category":
                        $(this).toggleClass('open');
                        $('.item-submenu').hide();
                        $('.toolbar-category .item-submenu li').removeClass('active');
                        if($(this).hasClass('open')) {
                            $(this).find('.item-submenu').show();
                        }
                        $('.toolbar-sort').removeClass('open');
                        $('.toolbar-sort .item-submenu').hide();
                        if(($.gallery.seqs).length == 1) {
                            var s = ($('.table-item').length) ? $('.table-item[data-seq="' + $.gallery.seqs[0] + '"]').attr('data-category') : $('.gallery-items .item[data-seq="' + $.gallery.seqs[0] + '"]').attr('data-category');
                            if(s) {
                                var c = s.substring(1, s.length-1),
                                    a = c.split('|,|');
                                if(a.length) {
                                    $.each(a, function(i,v) {
                                        $('.toolbar-category .item-submenu li:contains("' + v + '")').each(function() {
                                            if($(this).text().trim() == v) $(this).addClass('active');
                                        });
                                        // $('.toolbar-category .item-submenu li:contains("' + v + '")').addClass('active');
                                    });
                                }
                            }
                        } else {
                            var category_active_text = $('.gallery-category-menu.active').text();
                            $('.toolbar-category .item-submenu li:contains("'+category_active_text+'")').addClass('active');
                        }
                        break;
                    case "checkall": 
                        var check = $(this).find('input').prop('checked');
                        if(check) {
                            $('.table-item input').prop('checked',true);
                            $('.table-item').addClass('ui-selected');
                            $.each($('.table-item'), function(i,v) {
                                $.gallery.seqs.push($(this).attr('data-seq'));
                            });
                            stickyToolbar();
                        } else {
                            $('.table-item input').prop('checked',false);   
                            $('.table-item').removeClass('ui-selected return');
                            $.gallery.seqs = [];
                        }
                        break;
                    case "edit": 
                        ($.gallery.mode == 'shopping') ? $.products.add(seq) : galleryItemController(seq); break;
                    case "copy": 
                        $.gallery.copy = $.gallery.seqs; $.gallery.move = []; $.gallery.delete = []; // $.gallery.seqs = [];
                        $('.gallery-items .item').removeClass('move');
                        $('.gallery-toolbar.mod-gallery').remove();
                        $.gallery.cp();
                        break;
                    case "move":
                        $.gallery.move = $.gallery.seqs; $.gallery.copy = []; $.gallery.delete = []; $.gallery.seqs = []; $.gallery.ex_id = [];
                        $('.gallery-items .item').removeClass('copy');
                        $('.gallery-toolbar.mod-gallery').remove();
                        var content = '<ul class="gallery-move-list ui-sortable">',
                            gallery_count = 0;

                        $.each($.gallery.blocks, function(i,v) {
                            $.each(v, function(m, s) {
                                if(s.length) {
                                    $.each(s, function(k,n) {
                                        if(n.id == $.gallery.block_id && s.length == 1) {
                                            return true;
                                        }
                                        if(k == 0) {
                                            content+= '<li><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 4 8"><path d="m-.05-.06 4 4-4 4v-8z"/></svg> ' + m + '</li>';
                                        }
                                        if(n.id != $.gallery.block_id) {
                                            switch(n.mode) {
                                                case 'shopping': icon = '<svg class="shopping" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 13 14"><path d="M9.82 2C9.4 0.84 8.3 0 7 0H6C4.7 0 3.6 0.84 3.18 2H0v12h13V2H9.82zM6 1h1c0.74 0 1.37 0.41 1.72 1H4.28C4.63 1.41 5.26 1 6 1zM12 13H1V3h2v3h1V3h5v3h1V3h2V13z"/></svg>　'; break;
                                                case 'project' : icon = '<svg class="project" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path d="M13 0H3v3H0v13h13v-3h3V3L13 0zM13 1.41L14.59 3H13V1.41zM1 15V4h8v3h3v8H1zM10 4.41L11.59 6H10V4.41zM15 12h-2V6l-3-3H4V1h8v3h3V12z"/><rect x="3" y="9" width="7" height="1"/><rect x="3" y="12" width="7" height="1"/></svg>　'; break;
                                                case 'gallery' : icon = '<svg class="gallery" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 13 13"><path d="M0 0v13h13V0H0zM12 1v7.29l-2-2 -2 2 -4-4 -3 3V1H12zM1 12V8.71l3-3 4 4 2-2 2 2V12H1z"/><circle cx="10" cy="3" r="1"/></svg>　'; break;
                                            }
                                            icon = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 4 8"><path d="m-.05-.06 4 4-4 4v-8z"/></svg>';
                                            var move_disabled = (n.isActive) ? '' : 'disabled';
                                            if(LUX && n.mode == 'shopping') move_disabled = 'disabled';
                                            content+= '<li class="gallery-move ' + move_disabled + '" data-gallery-id="' + ((move_disabled == '') ? n.id : '') + '"><span class="gallery-block-name">' + n.name + '</span><span class="f-right gallery-name-edit"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path d="M15.41 0.76l-0.17-0.17C14.85 0.2 14.34 0 13.83 0s-1.02 0.2-1.41 0.59L1 12l-1 4 4-1L15.41 3.59C16.2 2.8 16.2 1.54 15.41 0.76zM3.49 14.1l-2.11 0.53 0.53-2.11 8.95-8.95 1.59 1.59L3.49 14.1zM14.71 2.88l-1.56 1.56 -1.59-1.59 1.56-1.56C13.31 1.1 13.56 1 13.83 1s0.52 0.1 0.71 0.29l0.17 0.17C15.1 1.85 15.1 2.49 14.71 2.88z"/></svg></span></li>';
                                            gallery_count++;
                                        }
                                    });
                                }
                            });
                        });
                        if(gallery_count == 0) {
                            content+= "<li>" + $.lang[LANG]['editor.block.gallery.item.move.none'] + "</li>";
                        }
                        content+= "</ul><div class='move-alert error'></div>";

                        if(gallery_count) {
                            content+= '\
                            <div class="gallery-confirm-str">' + $.lang[LANG]['editor.block.gallery.item.move.after'] + '</div>\
                            <div class="gallery-confirm-select">\
                                <div class="gallery-move-select radio">\
                                  <label><input type="radio" name="gallery_move_info" class="gallery-move-info" value="stay" checked>' + $.lang[LANG]['editor.block.gallery.item.move.after.1'] + '</label>\
                                </div>\
                                <div class="gallery-move-select radio">\
                                  <label><input type="radio" name="gallery_move_info" class="gallery-move-info" value="move">' + $.lang[LANG]['editor.block.gallery.item.move.after.2'] + '</label>\
                                </div>\
                            </div>\
                            ';
                        }

                        var moveModal = $(this).showModalFlat($.lang[LANG]['editor.block.gallery.item.move.title'], $.lang[LANG]['editor.block.gallery.item.move.select.1'] + ($.gallery.move).length + $.lang[LANG]['editor.block.gallery.item.move.select.2'] + content, true, true, function() {
                            $('.gallery-move-list').removeClass('not-selected');
                            $('.move-alert').text('');

                            var $active = $('.gallery-move.active:not(.disabled)');
                            if($active.length == 0 && gallery_count > 0) {
                                $('.gallery-move-list').addClass('not-selected');
                                $('.move-alert').text($.lang[LANG]['editor.block.gallery.item.move.error']);
                                return false;
                            }
                            var block_id = $active.attr('data-gallery-id'),
                                isMove = $("input.gallery-move-info:checked").val();
                            if(typeof block_id == "undefined") {
                                $('.move-alert').text($.lang[LANG]['editor.block.gallery.error']);
                                return false;
                            }

                            if($.gallery.ex_id.length) {
                                $.gallery.move = $.gallery.move.filter(item => !$.gallery.ex_id.includes(item));
                            }
                            moveModal.modal('hide');
                            var move_block_id = (isMove == "stay") ? $.gallery.block_id : block_id;
                            $.progressON($.lang[LANG]['editor.block.gallery.moving.str.1']);
                            var total = ($.gallery.move).length, 
                                moving = $.lang[LANG]['editor.block.gallery.moving.str.2'], 
                                progress = 0,
                                loading = '<i class="fa fa-circle-o-notch fa-spin fa-3x fa-fw"></i> ',
                                done = 0,
                                group = ($('.table-item').length) ? '.table-item' : '.gallery-items .item',
                                item = $(group).length,
                                cpage = Math.ceil(item/30),
                                spos = $('.gallery-modal').scrollTop();
                                seqs = $.gallery.move;

                            $('.progressModal .info1').html(loading + moving);
                            $.each($.gallery.move,function(i,v) {
                                var t = setTimeout(function() {
                                    if(CANCEL) {
                                        if(ABORT) {
                                            // 리스트 갱신 작업
                                            $.gallery.show($.gallery.block_id,cpage,$.gallery.category, function() {
                                                setTimeout(function() { 
                                                    $.gallery.move = [];
                                                    $('.gallery-modal').scrollTop(spos); 
                                                    $.processOFF();
                                                    $.gallery.update = true;
                                                }, 500);
                                            });
                                            ABORT = false;
                                            $.progressOFF();
                                        }
                                        i=0; return false;
                                    }
                                    galleryMoveItem(block_id,v,$.gallery.pages[block_id],function() {
                                        done++;
                                        progress = parseInt((done / total) * 100,10);
                                        $('.file-upload-progress .progress-bar').css('width',progress + "%");
                                        $('.progressModal .info2').text(done.toString() + ' / ' + total.toString());
                                        if(typeof VIEW == 'undefined') {
                                            $.gallery.unlink = true;
                                        } else if(v==VIEW) $.gallery.unlink = true;
                                        if(total == done) {
                                            $.gallery.show(move_block_id,1,$.gallery.category, function() {
                                                var group = ($('.table-item').length) ? '.table-item' : '.gallery-items .item';
                                                $.each($.gallery.move, function(i,v) {
                                                    $(group + '[data-seq="' + v + '"]').addClass('return');
                                                });
                                                setTimeout(function() { 
                                                    $.gallery.move = [];
                                                    $('.gallery-modal').scrollTop(spos); 
                                                    $.progressOFF();
                                                    $.gallery.update = true;
                                                }, 500);
                                            });
                                        } else {
                                            moving = $(group + '[data-seq="' + seqs[i+1] + '"] .td-title .item-title-str').text();
                                            if(moving == "") moving = $.lang[LANG]['editor.block.gallery.moving.str.2'];
                                            $('.progressModal .info1').html(loading + moving);
                                        }
                                    });
                                },500*i);
                            });                            
                        },'cancel', 'ok', 'cl-cmmodal cl-s-btn w560 cl-p70 cl-p0',true,'','',function() {
                            $.gallery.seqs = $.gallery.move;
                        });

                        break;
                    case "paste":
                        if(($.gallery.copy).length) $.gallery.cp();
                        if(($.gallery.move).length) $.gallery.mv();
                        break;
                    case "delete":
                        $.gallery.delete = $.gallery.seqs; $.gallery.move = []; $.gallery.copy = [];
                        $('.gallery-toolbar.mod-gallery').remove();
                        $.gallery.del();
                        break;
                    case "visible":
                        var seq = $(this).find('i').attr('data-glseq'),
                            visible = $(this).find('i').attr('data-visible'),
                            mode = '';
                        var $this = $(this);

                        visible = (visible == 1) ? 0 : 1;

                        var limitCnt = 0;
                        if($('.table-item').length) {
                            mode = 'product';
                            $.each($.gallery.seqs, function(i,v) {
                                var outDatetime = $('.gallery-items .table-item[data-seq="' + v + '"]').attr('data-out-datetime');
                                if(visible == 0 && outDatetime == '1') {
                                    limitCnt++;
                                }
                            });
                        }

                        if(limitCnt > 0) {
                            var modal_str = '선택된 상품은 기간한정판매 상품입니다.<br>\
                            판매기간 제외 상품노출 기능이 사용으로 변경됩니다.<br>\
                            선택한 상품을 노출 시키겠습니까?';

                            if(limitCnt > 1) modal_str = '선택된 상품 중 기간한정판매 상품이 포함되어 있습니다.<br>\
                                기간한정판매 상품의 판매기간 제외 상품노출 기능이 사용으로 변경됩니다.<br>\
                                선택한 '+limitCnt+'개의 상품을 노출 시키겠습니까?';

                            var modal = $(this).showModalFlat($.lang[LANG]['config.information'], modal_str, true, true, function(){
                                $.post('/template/gallery/visible', { s: $.gallery.seqs, view: visible, mode: mode }, function (data) {
                                    checkError(data);
                                    updateItem(data.item);
                                },'json');

                                var type = 'ELEM',
                                    checked = (visible) ? false : true;
                                setLogs(type,'gallery.item.visible.'+checked,'visible-'+checked,type,'product-manager','el');

                                $.each($.gallery.seqs, function(i,v) {
                                    if($('.table-item').length) {
                                        var outDatetime = $('.gallery-items .table-item[data-seq="' + v + '"]').attr('data-out-datetime');
                                        switch (outDatetime) {
                                            case 'off':
                                                if(visible == '1') {
                                                    $('.gallery-items .table-item[data-seq="' + v + '"]').addClass('invisible').attr('data-visible','1');
                                                    // $('.gallery-items .table-item[data-seq="' + v + '"] .td-note').text('숨김');
                                                } else {
                                                    $('.gallery-items .table-item[data-seq="' + v + '"]').removeClass('invisible').attr('data-visible','0');
                                                    // $('.gallery-items .table-item[data-seq="' + v + '"] .td-note').text('');
                                                }
                                                break;
                                            case '0':
                                                if(visible == '1') {
                                                    $('.gallery-items .table-item[data-seq="' + v + '"]').addClass('invisible').attr('data-visible','1');
                                                } else {
                                                    $('.gallery-items .table-item[data-seq="' + v + '"]').removeClass('invisible').attr('data-visible','0');
                                                }
                                                break;

                                            case '1':
                                                (visible == '1') ? $('.gallery-items .table-item[data-seq="' + v + '"]').addClass('invisible').attr('data-out-datetime','1')
                                                                : $('.gallery-items .table-item[data-seq="' + v + '"]').removeClass('invisible').attr('data-out-datetime','0');
                                                break;
                                        }
                                    } else {
                                        (visible == '1') ? $('.gallery-items .item[data-seq="' + v + '"]').addClass('invisible').attr('data-visible','1')
                                                         : $('.gallery-items .item[data-seq="' + v + '"]').removeClass('invisible').attr('data-visible','0');
                                    }
                                });
                                
                                (visible == '1') ? $this.find('i').attr('data-visible','1') : $this.find('i').attr('data-visible','0');
                                (visible == '1') ? $('.gallery-modal .toolbar li > i[data-cmd="visible"]').text($.lang[LANG]["editor.gallery.icon.visible.on"])
                                                 : $('.gallery-modal .toolbar li > i[data-cmd="visible"]').text($.lang[LANG]["editor.gallery.icon.visible.off"]);
                                $.gallery.update = true;
                                $.gallery.unlink = true;
                                modal.modal('hide');
                            }, 'cancel', 'ok', 'cl-p70 cl-cmmodal cl-s-btn w560 cl-p0');

                            return false;
                        }
                        
                        $.post('/template/gallery/visible', { s: $.gallery.seqs, view: visible, mode: mode }, function (data) {
                            checkError(data);
                            updateItem(data.item);
                        },'json');
                        // showPageCallback(showPage);
                        var type = 'ELEM',
                            checked = (visible) ? false : true;
                        setLogs(type,'gallery.item.visible.'+checked,'visible-'+checked,type,'product-manager','el');

                        $.each($.gallery.seqs, function(i,v) {
                            if($('.table-item').length) {
                                var outDatetime = $('.gallery-items .table-item[data-seq="' + v + '"]').attr('data-out-datetime');
                                switch (outDatetime) {
                                    case 'off':
                                        if(visible == '1') {
                                            $('.gallery-items .table-item[data-seq="' + v + '"]').addClass('invisible').attr('data-visible','1');
                                            // $('.gallery-items .table-item[data-seq="' + v + '"] .td-note').text('숨김');
                                        } else {
                                            $('.gallery-items .table-item[data-seq="' + v + '"]').removeClass('invisible').attr('data-visible','0');
                                            // $('.gallery-items .table-item[data-seq="' + v + '"] .td-note').text('');
                                        }
                                        break;
                                    case '0':
                                        if(visible == '1') {
                                            $('.gallery-items .table-item[data-seq="' + v + '"]').addClass('invisible').attr('data-visible','1');
                                        } else {
                                            $('.gallery-items .table-item[data-seq="' + v + '"]').removeClass('invisible').attr('data-visible','0');
                                        }
                                        break;

                                    case '1':
                                        (visible == '1') ? $('.gallery-items .table-item[data-seq="' + v + '"]').addClass('invisible').attr('data-out-datetime','1')
                                                        : $('.gallery-items .table-item[data-seq="' + v + '"]').removeClass('invisible').attr('data-out-datetime','0');
                                        break;
                                }
                                // if(outDatetime != 'off') {
                                //     (visible == '1') ? $('.gallery-items .table-item[data-seq="' + v + '"]').addClass('invisible').attr('data-out-datetime','1')
                                //                     : $('.gallery-items .table-item[data-seq="' + v + '"]').removeClass('invisible').attr('data-out-datetime','0');

                                // } else {
                                //     console.log($('.gallery-items .table-item[data-seq="' + v + '"] .td-note'));
                                //     if(visible == '1') {
                                //         $('.gallery-items .table-item[data-seq="' + v + '"]').addClass('invisible').attr('data-visible','1');
                                //         $('.gallery-items .table-item[data-seq="' + v + '"] .td-note').text('숨김');
                                //     } else {
                                //         $('.gallery-items .table-item[data-seq="' + v + '"]').removeClass('invisible').attr('data-visible','0');
                                //         $('.gallery-items .table-item[data-seq="' + v + '"] .td-note').text('');
                                //     }
                                // }
                            } else {
                                (visible == '1') ? $('.gallery-items .item[data-seq="' + v + '"]').addClass('invisible').attr('data-visible','1')
                                                 : $('.gallery-items .item[data-seq="' + v + '"]').removeClass('invisible').attr('data-visible','0');
                            }
                        });

                        (visible == '1') ? $this.find('i').attr('data-visible','1') : $this.find('i').attr('data-visible','0');
                        (visible == '1') ? $('.gallery-modal .toolbar li > i[data-cmd="visible"]').text($.lang[LANG]["editor.gallery.icon.visible.on"])
                                         : $('.gallery-modal .toolbar li > i[data-cmd="visible"]').text($.lang[LANG]["editor.gallery.icon.visible.off"]);
                        // $('.gallery-toolbar').empty();
                        // galleryStatusInit();
                        $.gallery.update = true;
                        $.gallery.unlink = true;
                        // $.gallery.reset();

                        break;
                    case "link":
                        var config_icon = ($(this).hasClass('gl-item-link')) ? 'gl-item-link' : 'gallery-item-link-icon',
                            seq = $(this).find('i').attr('data-glseq'),
                            glink = $(this).find('i').attr('data-glink'),
                            is_glink_target = $(this).find('i').attr('data-glink-target'),
                            glmode = $('.gallery-modal').attr('data-mode'),
                            glpid = $('.gallery-modal').attr('data-pid'),
                            glpage = $('.gallery-modal').attr('data-page'),
                            glel = $('.' + $.gallery.block_id),
                            prev_glink = '', input_glink = '',
                            target_check = (typeof is_glink_target != 'undefined' && is_glink_target == '_blank') ? 'checked' : '',
                            link_content = '',
                            glname = $.gallery.block_name;

                        var group = ($('.table-item').length) ? '.table-item' : '.gallery-items .item';
                        $select_glink = $('.gallery-item[data-seq="'+seq+'"]').find('a');
                        if(typeof glink != 'undefined' && glink) {
                            if($select_glink.attr('data-user-link')) {
                                prev_glink = glink;
                            } else if ($select_glink.attr('attr-bookmark')) {
                                prev_glink = $select_glink.attr('href');
                            } else if ($select_glink.attr('attr-flink')) {
                                prev_glink = 'flink@' + $select_glink.attr('attr-flink');
                            } else if ($select_glink.attr('attr-link')) {
                                prev_glink = $select_glink.attr('attr-link');
                            } else {
                                prev_glink = glink;
                            }
                        }
                        var site_smenu = (typeof SMENU == 'undefined') ? $.gallery.SMENU : SMENU,
                            block_el = (typeof selectEL == 'undefined') ? $.gallery.block_el : selectEL;
                        link_content = '<ul class="link-content gallery edit-link-Content" data-type="' + glmode + '" data-name="' + glname + '">\
                                        ' + makeLinkList(site_smenu,'gallery',glname,glink);
                        link_content = link_content + '\
                            </ul>\
                            <div class="link-target">\
                                <div class="newcheckbox hand ">\
                                    <label>\
                                        <div class="newcheckboxSvg">\
                                            <input type="checkbox" class="img-link-target" id="linktarget-onoff" '+target_check+' data-el="'+block_el+'" />\
                                            <svg viewBox="0 0 16 16" width="16" height="16">\
                                                <path class="st6" d="M3 0h10c1.66 0 3 1.34 3 3v10c0 1.66-1.34 3-3 3H3c-1.66 0-3-1.34-3-3V3C0 1.34 1.34 0 3 0z"/>\
                                                <path class="st19" d="M13 1c1.1 0 2 0.9 2 2v10c0 1.1-0.9 2-2 2H3c-1.1 0-2-0.9-2-2V3c0-1.1 0.9-2 2-2H13M13 0H3C1.34 0 0 1.34 0 3v10c0 1.66 1.34 3 3 3h10c1.66 0 3-1.34 3-3V3C16 1.34 14.66 0 13 0L13 0z"/>\
                                            </svg>\
                                            <svg class="active" viewBox="0 0 16 16" width="16" height="16">\
                                                <rect x="2" y="2" class="st6" width="12" height="12"/>\
                                                <path  class="st19" d="M13 0H3C1.34 0 0 1.34 0 3v10c0 1.66 1.34 3 3 3h10c1.66 0 3-1.34 3-3V3C16 1.34 14.66 0 13 0zM13.03 6.03l-5.5 5.5C7.38 11.68 7.19 11.75 7 11.75s-0.38-0.07-0.53-0.22l-3.5-3.5c-0.29-0.29-0.29-0.77 0-1.06s0.77-0.29 1.06 0L7 9.94l4.97-4.97c0.29-0.29 0.77-0.29 1.06 0S13.32 5.74 13.03 6.03z"/>\
                                            </svg>\
                                        </div>\
                                        <span>'+ $.lang[LANG]['editor.link.open.target'] +'</span>\
                                    </label>\
                                </div>\
                            </div>\
                        \
                        ';

                        var modal = $(this).showModalFlat($.lang[LANG]['editor.link.modal.title.gallery'], link_content, true, true, function() {
                            var input_type = $('.link-content').find('.link-type.active').children().attr('class');
                            var result = getInputLink(input_type);
                                link = result[0], isOkay = result[1], isActive = result[2], 
                                target_val = '', target_change = '';

                            target_val = ($('#linktarget-onoff').prop('checked')) ? '_blank' : '';
                            target_change = (((target_check=='checked') ? 'on' : 'off') == ((target_val=='_blank') ? 'on' : 'off')) ? false : true;

                            if(isOkay) {
                                $.each($.gallery.seqs, function(i,v) {
                                    if((isActive && prev_glink==link || isActive==false && prev_glink=='') && !target_change && ($.gallery.seqs).length == 1) {
                                        modal.modal('hide'); 
                                        return true;
                                    }

                                    var gsettings = {
                                        'glink' : (checkBase64Encode(decodeURIComponent(link))) ? link : Base64.encode(link),
                                        'glink_target' : target_val
                                    }
                                    $.post('/template/settings', {sid: SID, settings: JSON.stringify(gsettings), el: 'gallery_settings', seq: v}, function(data) {
                                        checkError(data);

                                        $select_glink.removeAttr('data-gallery').removeAttr('data-user-link').removeAttr('attr-link').removeAttr('attr-bookmark').removeAttr('attr-flink');
                                        $select_glink_config = $('#el-property[data-element="'+block_el+'"] #gallery-list-config');

                                        if(link) {
                                            var gallery_link = makeLinkUrl(link, ONE, VIEW);

                                            $select_glink.attr('href',gallery_link);
                                            if($.inArray(link.replace(/ /g,'-'),MENULIST) > -1) {
                                                $select_glink.attr('data-user-link',gallery_link);
                                            } else if(link.match(/^\@/g) !== null) {
                                                $select_glink.attr('attr-bookmark',link.replace(/^\@/g,''));
                                            } else if(link.match(/^flink\@/g) !== null) {
                                                $select_glink.attr('attr-flink',link.replace(/^flink\@/g,''));
                                            }else {
                                                $select_glink.attr('attr-link',link);
                                            }

                                            $select_glink_config.find('.gl-item-link[data-glseq="'+v+'"]').attr('data-glink',link).addClass('active');
                                            if(config_icon == 'gallery-item-link-icon') $('.gallery-item-link-icon[data-glseq="'+v+'"]').attr('data-glink',link);
                                            
                                        } else {
                                            $select_glink_config.find('.gl-item-link[data-glseq="'+v+'"]').attr('data-glink',link).removeClass('active');
                                            if(config_icon == 'gallery-item-link-icon') $('.gallery-item-link-icon[data-glseq="'+v+'"]').attr('data-glink',link);
                                            var imgURL =  $('.gallery-item[data-seq="' + v + '"]').find('img').prop('src');
                                            if(glmode == 'gallery') {
                                                if((typeof imgURL=='undefined' || !imgURL) && glmode == 'gallery') {
                                                    var imgURL_popup = $('.ui-selectee[data-seq="' + v + '"]').find('img').prop('src');
                                                    imgURL = imgURL_popup.split('=')[0] + '=s0';
                                                }
                                                $select_glink.attr({'href': imgURL ,'data-gallery': '#gframe-' + glpid});
                                            } else {
                                                $select_glink.removeAttr('data-gallery');
                                                $select_glink.attr('href', '/'+CONFIG_URL+'config/page/' + glpage + '/view/' + v);
                                            }

                                        }

                                        $(group + '[data-seq="' + v + '"]').attr('data-link',Base64.decode(data.data.glink)).attr('data-target',data.data.glink_target);
                                        $('.gallery-modal .gallery-toolbar li [data-cmd="link"]').attr('data-glink',Base64.decode(data.data.glink)).attr('data-glink-target',data.data.glink_target);
                                        $('.cl_icon_link').attr('data-glink',data.data.glink).attr('data-glink-target',data.data.glink_target);

                                        if(data.data.glink == '') {
                                            $('.gallery-items .item[data-seq="' + v + '"]').find('.info').remove();
                                            $('.gallery-items .table-item[data-seq="' + v + '"]').find('.info-link').remove();
                                        }
                                        else {
                                            if($('.gallery-items .item[data-seq="' + v + '"]').find('.info-link').length == 0) {
                                                // $('.gallery-items .item[data-seq="' + v + '"]').find('.info').append('<span class="info-link"><svg class="svg" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 15 15"><path d="M6 9.85c-0.22 0-0.44-0.08-0.6-0.25 -0.33-0.33-0.33-0.87 0-1.2l3-3c0.33-0.33 0.87-0.33 1.2 0 0.33 0.33 0.33 0.87 0 1.2l-3 3C6.44 9.77 6.22 9.85 6 9.85z"/><path d="M3.85 15c-1.03 0-2-0.4-2.72-1.13C0.4 13.15 0 12.18 0 11.15s0.4-2 1.13-2.72l2-2C3.46 6.1 4 6.1 4.33 6.43c0.33 0.33 0.33 0.87 0 1.2l-2 2c-0.41 0.41-0.63 0.95-0.63 1.52s0.22 1.11 0.63 1.52c0.81 0.81 2.23 0.81 3.04 0l2-2c0.33-0.33 0.87-0.33 1.2 0 0.33 0.33 0.33 0.87 0 1.2l-2 2C5.85 14.6 4.88 15 3.85 15z"/><path d="M11.2 8.85c-0.22 0-0.44-0.08-0.6-0.25 -0.33-0.33-0.33-0.87 0-1.2l2.07-2.07c0.41-0.41 0.63-0.95 0.63-1.52s-0.22-1.11-0.63-1.52c-0.81-0.81-2.23-0.81-3.04 0L7.56 4.36c-0.33 0.33-0.87 0.33-1.2 0 -0.33-0.33-0.33-0.87 0-1.2l2.07-2.07c1.45-1.46 3.99-1.46 5.44 0C14.6 1.82 15 2.78 15 3.81s-0.4 2-1.13 2.72L11.8 8.61C11.64 8.77 11.42 8.85 11.2 8.85z"/></svg></span>');
                                                $('.gallery-items .item[data-seq="' + v + '"]').append('<div class="info"><span class="info-link"><svg class="svg" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 15 15"><path d="M6 9.85c-0.22 0-0.44-0.08-0.6-0.25 -0.33-0.33-0.33-0.87 0-1.2l3-3c0.33-0.33 0.87-0.33 1.2 0 0.33 0.33 0.33 0.87 0 1.2l-3 3C6.44 9.77 6.22 9.85 6 9.85z"/><path d="M3.85 15c-1.03 0-2-0.4-2.72-1.13C0.4 13.15 0 12.18 0 11.15s0.4-2 1.13-2.72l2-2C3.46 6.1 4 6.1 4.33 6.43c0.33 0.33 0.33 0.87 0 1.2l-2 2c-0.41 0.41-0.63 0.95-0.63 1.52s0.22 1.11 0.63 1.52c0.81 0.81 2.23 0.81 3.04 0l2-2c0.33-0.33 0.87-0.33 1.2 0 0.33 0.33 0.33 0.87 0 1.2l-2 2C5.85 14.6 4.88 15 3.85 15z"/><path d="M11.2 8.85c-0.22 0-0.44-0.08-0.6-0.25 -0.33-0.33-0.33-0.87 0-1.2l2.07-2.07c0.41-0.41 0.63-0.95 0.63-1.52s-0.22-1.11-0.63-1.52c-0.81-0.81-2.23-0.81-3.04 0L7.56 4.36c-0.33 0.33-0.87 0.33-1.2 0 -0.33-0.33-0.33-0.87 0-1.2l2.07-2.07c1.45-1.46 3.99-1.46 5.44 0C14.6 1.82 15 2.78 15 3.81s-0.4 2-1.13 2.72L11.8 8.61C11.64 8.77 11.42 8.85 11.2 8.85z"/></svg></span></div>');
                                            }
                                            if($('.gallery-items .table-item[data-seq="' + v + '"] .td-img .info-link').length == 0) {
                                                $('.gallery-items .table-item[data-seq="' + v + '"]').find('.td-img').append('<span class="info-link"><svg class="svg" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 15 15"><path d="M6 9.85c-0.22 0-0.44-0.08-0.6-0.25 -0.33-0.33-0.33-0.87 0-1.2l3-3c0.33-0.33 0.87-0.33 1.2 0 0.33 0.33 0.33 0.87 0 1.2l-3 3C6.44 9.77 6.22 9.85 6 9.85z"/><path d="M3.85 15c-1.03 0-2-0.4-2.72-1.13C0.4 13.15 0 12.18 0 11.15s0.4-2 1.13-2.72l2-2C3.46 6.1 4 6.1 4.33 6.43c0.33 0.33 0.33 0.87 0 1.2l-2 2c-0.41 0.41-0.63 0.95-0.63 1.52s0.22 1.11 0.63 1.52c0.81 0.81 2.23 0.81 3.04 0l2-2c0.33-0.33 0.87-0.33 1.2 0 0.33 0.33 0.33 0.87 0 1.2l-2 2C5.85 14.6 4.88 15 3.85 15z"/><path d="M11.2 8.85c-0.22 0-0.44-0.08-0.6-0.25 -0.33-0.33-0.33-0.87 0-1.2l2.07-2.07c0.41-0.41 0.63-0.95 0.63-1.52s-0.22-1.11-0.63-1.52c-0.81-0.81-2.23-0.81-3.04 0L7.56 4.36c-0.33 0.33-0.87 0.33-1.2 0 -0.33-0.33-0.33-0.87 0-1.2l2.07-2.07c1.45-1.46 3.99-1.46 5.44 0C14.6 1.82 15 2.78 15 3.81s-0.4 2-1.13 2.72L11.8 8.61C11.64 8.77 11.42 8.85 11.2 8.85z"/></svg></span>');
                                            }
                                        }

                                        if(target_val == '_blank') $select_glink.attr('target','_blank');
                                        else $select_glink.removeAttr('target');
                                        
                                        // if(target_change) {
                                        //     if(target_val) $select_glink.attr('target',target_val);
                                        //     else $select_glink.removeAttr('target');
                                        //     // $select_glink_config.find('.gl-item-link[data-glseq="'+seq+'"]').attr('data-glink-target',target_val);
                                        //     // if(config_icon == 'gallery-item-link-icon') $('.gallery-item-link-icon[data-glseq="'+seq+'"]').attr('data-glink-target',target_val);
                                        // }

                                        var log_text = (isActive || !isActive && target_change) ? 'active' : 'broken',
                                            type = getElementType();
                                        setLogs(type,'gallery.link.'+log_text,'link-'+log_text,type,'product-manager','el');

                                        // galleryStatusInit();
                                    }, 'json');
                                });

                                modal.modal('hide');
                            }
                        } ,'cancel', 'ok', 'cl-cmmodal cl-s-btn w560 cl-p70 cl-p0 cl-edit-link modal-portfolio-link site-popup-link cover fullcover-modal',true,'',function(){
                            $('[data-toggle="popover"]').popover();
                        });
                        break;
                    case "org-price":
                    case "disc-price":
                    case "sale-price":
                        if($this.hasClass('disabled')) return;
                        var price_type = cmd.replace('-price','');
                            selectedProduct_html = getSelectedProductList(SID,price_type,$.gallery.seqs),
                            config_icon = ($(this).hasClass('gl-item-discount')) ? 'gl-item-discount' : 'gallery-item-discount-icon',
                            seq = $(this).find('i').attr('data-glseq'),
                            discount = $(this).find('i').attr('data-discount'),
                            is_discount_target = $(this).find('i').attr('data-discount-target'),
                            glmode = $('.gallery-modal').attr('data-mode'),
                            glpid = $('.gallery-modal').attr('data-pid'),
                            glpage = $('.gallery-modal').attr('data-page'),
                            glel = $('.'+ $.gallery.block_id),
                            prev_discount = '', input_discount = '',
                            target_check = (typeof is_discount_target != 'undefined' && is_discount_target == '_blank') ? 'checked' : '';
                            
                        var price_content = '';

                        price_content += '<div class="price_setting_box modal-contents-box">'+ selectedProduct_html + '</div>';                       

                        var modal = $(this).showModalFlat($.lang[LANG]['editor.block.gallery.product.'+price_type] + $.lang[LANG]['editor.block.gallery.product.price'], price_content, false, true, function() { //confirm
                            var useDiscount = $('input[name="use_discount"]:checked').val(),
                                discountRate = Number(removeCommas($('#prod-price-rate').val())),
                                discountUnit = $('#prod-price-unit').attr('data-value');                 

                            if($('.price_setting_box').find('.error_text').length > 0) return false;

                            var category_type = $('.price_setting_input_box').attr('data-category'), 
                                price_input_val = Number(removeCommas($('#prod-price-rate').val())),
                                price_unit = $('#prod-price-unit').attr('data-value'),
                                price_mark = $('#price-setting-mark-select').attr('data-value'),
                                price_fixtype = (category_type=='org') ? $('input[name="pr_detail_fix_type"][checked="checked"]').attr('data-fix') : '',
                                ch_val = (price_mark=='change') ? price_input_val : (price_mark=='raise' ? price_input_val : -price_input_val);

                            if(!$('.setting_product_list').hasClass('change_price')) {
                                modal.modal('hide');
                                return false;
                            }

                            var route = (CONFIG_URL) ? '/_admin' : '';
                            // $.processON();
                            // $.ajax({
                            //     type: 'POST',
                            //     url : route + '/shopping/setProduct',
                            //     data :  unit_obj,
                            //     dataType : 'json',
                            //     async: true,
                            //     cache: false,
                            //     success : function(data) {
                            //         checkError(data);
                            //         var page = getStorageItem('gallery-product-page');
                            //         $.gallery.show($.gallery.block_id,page,$.gallery.cateogry);
                            //         $.gallery.update = true;
                            //         $.gallery.reset();
                            //         $.processOFF();
                            //         modal.modal('hide');
                            //     },
                            //     error : function(xhr, status, error) {
                            //         $.processOFF();
                            //         alert("Error " + xhr.status + " : 관리자에게 문의");
                            //     }
                            // });

                            var list_html = ``;
                            var list_items = modal.find('.setting_product_list ul[data-gseq]').map(function(){ return {'seq' : $(this).data('gseq'),'pname':$(this).find('.product_title').text()}}).toArray();
                            $(list_items).each(function(k, v) {
                                list_html += `
                                <div class="process" data-seq="${v.seq}">
                                    <div class="bar">
                                        <div class="progressbar"></div>
                                    </div>
                                    <div class="desc">
                                        <span class="name" style="">${v.pname}</span>
                                        <div class="status">변경 중</div>
                                    </div>
                                </div>
                                `;
                            });

                            var html = `
                            <div>
                                <div class="main-progress">
                                    <div class="bar">
                                        <div></div>
                                    </div>
                                    <div class="spin">
                                        <span><i class="fa fa-circle-o-notch fa-spin fa-3x fa-fw"></i></span>
                                        <div class="counter"><span>0</span>/${list_items.length}</div>
                                    </div>
                                </div>
                                <div class="detail-progress">
                                    ${list_html}
                                </div>
                            </div>
                            `;

                            var total_cnt = list_items.length;
                            var cur_cnt = 0;
                            var ajaxController;
                            var cancelFlag = false;

                            var product_modal = $(this).showModalFlat('정가를 변경 중입니다.', html, true, true, function() {
                                product_modal.modal('hide');
                            },'cancel', 'ok', 'cl-cmmodal cl-product-price-setting cl-s-btn cl-p0 w700 zindex1045 cover fullcover-modal', true, function() {
                                // close callback
                                console.log('중간에 꺼버림')
                                if(ajaxController) ajaxController.abort();
                                cancelFlag = true;
                            },'',function(){
                                modal.modal('hide');
                                var page = getStorageItem('gallery-product-page');
                                $.gallery.show($.gallery.block_id,page,$.gallery.cateogry);
                                $.gallery.update = true;
                                $.gallery.reset();
                            });

                            product_modal.find('.ok-button-dialog').hide();

                            function ajaxRequest(item) {
                                return new Promise((resolve) => {
                                    if(cancelFlag) reject();
                                    ajaxController = $.ajax({
                                        url : route + '/shopping/setProduct',
                                        async:false,
                                        dataType:'json',
                                        type:'post',
                                        data: {
                                            sid: SID, 
                                            seqs: item.seq,
                                            type: category_type, 
                                            mark : price_mark, 
                                            v : ch_val, 
                                            unit : price_unit,
                                            fx : category_type == 'org' ? price_fixtype : '',
                                        },
                                        success: function(response) {
                                            // AJAX 성공 시 애니메이션 효과 추가
                                            product_modal.find(`.process[data-seq="${item.seq}"]`).find('.progressbar').css('width', '100%');
                                            if(!response.error) {
                                                setTimeout(function() {
                                                    product_modal.find(`.process[data-seq="${item.seq}"]`).find('.status').addClass('info').text('변경 완료')
                                                },500);
                                            } else {
                                                setTimeout(function() {
                                                    product_modal.find(`.process[data-seq="${item.seq}"]`).find('.progressbar').addClass('danger');
                                                    product_modal.find(`.process[data-seq="${item.seq}"]`).find('.status').addClass('danger').text('변경 실패');
                                                    product_modal.find(`.process[data-seq="${item.seq}"]`).append(
                                                        `
                                                        <div class="desc">
                                                            <span class="error">
                                                                <svg viewBox="0 0 13 13" width="13" height="13"><path d="M6.5 0C2.91 0 0 2.91 0 6.5S2.91 13 6.5 13 13 10.09 13 6.5 10.09 0 6.5 0zM6.5 12C3.47 12 1 9.53 1 6.5S3.47 1 6.5 1 12 3.47 12 6.5 9.53 12 6.5 12z"></path><rect x="6" y="3" width="1" height="5"></rect><rect x="6" y="9" width="1" height="1"></rect></svg>
                                                                ${response.error}
                                                            </span>
                                                        </div>
                                                        `
                                                    );
                                                }, 500);
                                            }
                                        },
                                        error: function(error) {
                                            console.log(error);
                                            if(error.statusText === 'abort') {
                                                reject();
                                            }
                                        },
                                        complete:function() {
                                            cur_cnt++;
                                            product_modal.find(`.main-progress .bar`).find('div').css('width', (cur_cnt/total_cnt*100) + '%');
                                            product_modal.find(`.main-progress .counter span`).text(cur_cnt)
                                            setTimeout(function() {
                                                resolve();
                                            },600);
                                        }
                                    });
                                });
                            }
                            async function runAjaxRequests(items) {
                                try {
                                    for (var item of items) {
                                        await ajaxRequest(item); // 각 요청이 완료될 때까지 기다림
                                    }
                                } catch (error) {
                                    console.log('중지시켜버림')
                                }
                            }

                            setTimeout(function() {
                                runAjaxRequests(list_items).then(function() {
                                    product_modal.find('.ok-button-dialog').show();
                                    product_modal.find('.close-button-dialog').hide();
                                });
                            },1100)
                        } ,'cancel', 'config.change', 'cl-cmmodal cl-s-btn cl-p0 w900 cl-edit-discount modal-product-discount site-popup-discount cl-product-setting cover fullcover-modal fixed', true, '',function(){
                            
                            var scrollHeight = document.querySelector('.product_contents').scrollHeight,
                                clientHeight = document.querySelector('.product_contents').clientHeight;
                                
                            if(scrollHeight > clientHeight) $('.product_contents').addClass('pr_scroll');
                            else $('.product_contents').removeClass('pr_scroll');

                        }, function(){ //hide
                            // $('[data-toggle="popover"]').popover();
                        },true);
                        break;
                    case "badge":
                        var badgeInput = 'change';
                        var badgeArr = ['new', 'best', 'md', 'free', 'hot'];
                        var product_list = '';
                        var badge_head = '';
                        var badge_settings = $.parseJSON(localStorage.getItem('badge_settings'));

                        $.each(badgeArr, function(idx, type) {
                            var bsettings = (typeof badge_settings[type] != 'undefined')? badge_settings[type] : {};
                            var badgeType = (typeof bsettings.type != 'undefined' && bsettings.type)? bsettings.type : 'edit';
                            var badgeStyle = (typeof bsettings.style != 'undefined' && bsettings.style)? bsettings.style : 'default-1 small';
                            var badgeText = (typeof bsettings.badge_text != 'undefined' && bsettings.badge_text)? bsettings.badge_text : $.lang[LANG]['gallery.shopping.badge.'+type];
                            var badgeBorderColor = (typeof bsettings.border_color != 'undefined' && bsettings.border_color)? bsettings.border_color : '';
                            var badgeBackgroundColor = (typeof bsettings.background_color != 'undefined' && bsettings.background_color)? bsettings.background_color : '';
                            var badgeFontColor = (typeof bsettings.font_color != 'undefined' && bsettings.font_color)? bsettings.font_color : '';
                            var badgeImgSrc = (typeof bsettings.image_src != 'undefined' && bsettings.image_src)? bsettings.image_src : '';
                            var $badge = (badgeType == 'edit')? $('<span class="change-badge-design hand product-badge ' + badgeStyle + '" data-type="'+type+'" data-style="' + badgeStyle + '" data-border_color="' + bsettings.border_color + '" data-background_color="' + bsettings.background_color + '" data-font_color="' + bsettings.font_color + '">' + badgeText + '</span>') : $('<span class="change-badge-design hand product-badge" data-type="'+type+'"><img src="' + bsettings.image_src + '"></span>');
                            var badgeCnt = $('.table-item.ui-selected .product-badge[data-type="'+type+'"]').length;
                            var checkedAll = '';
                            if(badgeBorderColor) $badge.css('border-color', badgeBorderColor);
                            if(badgeBackgroundColor) $badge.css('background-color', badgeBackgroundColor);
                            if(badgeFontColor) $badge.css('color', badgeFontColor);

                            if($.gallery.seqs.length == badgeCnt) {
                                checkedAll = 'checked';
                            }

                            badge_head += '\
                                    <div class="divTableHead">\
                                        <div class="badge-view">' + $badge[0].outerHTML + '</div>\
                                        <div class="newcheckbox">\
                                            <label>\
                                                <input type="checkbox" class="check-all" data-type="' + type + '" '+checkedAll+'>\
                                                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16">\
                                                    <path d="M13 0H3C1.3 0 0 1.3 0 3v10c0 1.7 1.3 3 3 3h10c1.7 0 3-1.3 3-3V3C16 1.3 14.7 0 13 0zM15 13c0 1.1-0.9 2-2 2H3c-1.1 0-2-0.9-2-2V3c0-1.1 0.9-2 2-2h10c1.1 0 2 0.9 2 2V13z"/>\
                                                </svg>\
                                                <svg class="active" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16">\
                                                    <path d="M13 0H3C1.34 0 0 1.34 0 3v10c0 1.66 1.34 3 3 3h10c1.66 0 3-1.34 3-3V3C16 1.34 14.66 0 13 0zM13.03 6.03l-5.5 5.5C7.38 11.68 7.19 11.75 7 11.75s-0.38-0.07-0.53-0.22l-3.5-3.5c-0.29-0.29-0.29-0.77 0-1.06s0.77-0.29 1.06 0L7 9.94l4.97-4.97c0.29-0.29 0.77-0.29 1.06 0S13.32 5.74 13.03 6.03z"/>\
                                                </svg>\
                                            </label>\
                                        </div>\
                                    </div>\
                            ';
                        });
                        $.each($.gallery.seqs, function(i,v) {
                            var badge_list = '';

                            $.each(badgeArr, function(idx, type) {
                                var $badge = $('.table-item[data-seq="'+v+'"] .product-badge[data-type="'+type+'"]');
                                badge_list += '\
                                    <div class="divTableCell product-badge-item" data-seq="'+v+'">\
                                        <div class="newcheckbox">\
                                            <label>\
                                                <input type="checkbox" class="product-badge badge-' + type + '" data-type="' + type + '" '+ (($badge.length > 0)? 'checked' : '') +'>\
                                                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16">\
                                                    <path d="M13 0H3C1.3 0 0 1.3 0 3v10c0 1.7 1.3 3 3 3h10c1.7 0 3-1.3 3-3V3C16 1.3 14.7 0 13 0zM15 13c0 1.1-0.9 2-2 2H3c-1.1 0-2-0.9-2-2V3c0-1.1 0.9-2 2-2h10c1.1 0 2 0.9 2 2V13z"/>\
                                                </svg>\
                                                <svg class="active" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16">\
                                                    <path d="M13 0H3C1.34 0 0 1.34 0 3v10c0 1.66 1.34 3 3 3h10c1.66 0 3-1.34 3-3V3C16 1.34 14.66 0 13 0zM13.03 6.03l-5.5 5.5C7.38 11.68 7.19 11.75 7 11.75s-0.38-0.07-0.53-0.22l-3.5-3.5c-0.29-0.29-0.29-0.77 0-1.06s0.77-0.29 1.06 0L7 9.94l4.97-4.97c0.29-0.29 0.77-0.29 1.06 0S13.32 5.74 13.03 6.03z"/>\
                                                </svg>\
                                            </label>\
                                        </div>\
                                    </div>\
                                ';
                            });
                            var num = i + 1;
                            product_list += '<div class="divTableRow display-flex space-between align-items-center" data-seq="' + v + '">\
                                <div class="divTableCell row-num">' + ((num < 10)? '0' + num : num) + '</div>\
                                <div class="divTableCell product-title">' + $('.table-item[data-seq="'+v+'"] .td-title .item-title-str').text() + '</div>\
                            ' + badge_list + '</div>';
                        });
                        var badge_content = '\
                            <div class="badge-setting-header display-flex space-between align-items-center">\
                                <h2>' + $.lang[LANG]['editor.block.gallery.product.badge'] + '</h2>\
                                <ul class="badge-setting-button">\
                                    <li class="modal-close">취소</li>\
                                    <li class="modal-save ok-button-dialog">저장</li>\
                                </ul>\
                            </div>\
                            <div class="badge-setting-table thin-scroll-bar">\
                                <div class="badge-setting-top display-flex space-between align-items-center">\
                                    <div class="row-cnt">선택목록<span>' + ($.gallery.seqs.length) + '개</span></div>\
                                    <button class="change-badge-design"><svg viewBox="0 0 12 12" width="13" height="12"><path d="M11.56 0.57l-0.13-0.13C11.14 0.15 10.76 0 10.37 0 9.99 0 9.6 0.15 9.31 0.44L0.75 9 0 12l3-0.75 8.56-8.56C12.15 2.1 12.15 1.15 11.56 0.57zM2.49 10.35l-1.11 0.28 0.28-1.11 6.58-6.58 0.84 0.84L2.49 10.35zM10.85 1.98L9.77 3.06 8.94 2.23l1.08-1.08C10.15 1.02 10.29 1 10.37 1s0.23 0.02 0.35 0.15l0.13 0.13C11.05 1.47 11.05 1.79 10.85 1.98z"></path></svg>뱃지 디자인 변경</button>\
                                </div>\
                                <div class="divTable">\
                                    <div class="divTableHeading display-flex space-between align-items-center">\
                                        <div class="divTableHead row-num">번호</div>\
                                        <div class="divTableHead product-title">상품</div>'
                                        + badge_head +
                                    '</div>\
                                    <div class="divTableBody">' + product_list + '</div>\
                                </div>\
                                <div class="badge-setting-bottom"></div>\
                            </div>\
                        ';

                        var badgeSettingModal = $(this).showModalFlat('', badge_content, false, true, function() { //confirm
                            var same = 0;
                            var total = $.gallery.seqs.length;
                            var spos = $('.gallery-modal').scrollTop();

                            var useBadge_obj = {};
                            var before_useBadge_obj = {};
                            var update_obj = {};
                            $.each($.gallery.seqs, function(i,v) {
                                var productName = $('.table-item[data-seq="'+v+'"] .td-title .item-title-str').text();
                                var useBadge = [];
                                var beforeUseBadge = [];
                                $('.product-badge-item[data-seq="'+v+'"]').each(function(idx, badge){
                                    var badgeType = $(badge).find('input.product-badge:checked').attr('data-type');
                                    if(typeof badgeType != 'undefined' && badgeType) useBadge.push(badgeType);
                                });
                                
                                $.each(badgeArr, function(idx, type) {
                                    var $badge = $('.table-item[data-seq="'+v+'"] .product-badge[data-type="'+type+'"]');
                                    if ($badge.length > 0) beforeUseBadge.push(type);
                                });

                                if (JSON.stringify(useBadge) === JSON.stringify(beforeUseBadge)) {
                                    same ++;    
                                } else {
                                    update_obj[v] = useBadge;
                                    useBadge_obj[v] = {'pname': productName, 'use_badge': useBadge};
                                    before_useBadge_obj[v] = {'pname': productName, 'use_badge': beforeUseBadge};
                                }
                                
                            });

                            if(total <= same) {
                                if($('.modal-product-badge').eq(0).hasClass('design-update')) {
                                    var p = $.gallery.pages;
                                    $.gallery.show($.gallery.block_id, p.page, '', function() {
                                        setTimeout(function() { 
                                            $('.gallery-modal').scrollTop(spos); 
                                        }, 200);
                                    });

                                    $.gallery.update = true;
                                    $.gallery.reset();
                                }

                                badgeSettingModal.modal('hide');
                                return false;
                            }
                            
                            $.progressON('뱃지 설정 적용중입니다...', '', '', true);

                            var done = 0;
                            var progress = 0;
                            var route = (CONFIG_URL) ? '/_admin' : '';
                            total = Object.keys(update_obj).length;
                            $.each(update_obj, function(seq, useBadge) {
                                var gsettings = {'use_badge' : useBadge};
                                setTimeout(function(){
                                    $.ajax({
                                        type: 'POST',
                                        url: '/template/settings',
                                        data: {sid: SID, settings: JSON.stringify(gsettings),  el: 'gallery_settings', seq: seq, screenupdate: 'directupload'},
                                        dataType: 'json',
                                        async: true,
                                        success: function(data) {
                                            checkError(data);
                                            done++;
                                            progress = parseInt((done / total) * 100,10);
                                            $('.progressModal .progress-bar').css('width', progress+'%');
                                            $('.progressModal .info2').html('<span class="progressCnt">' + done + '</span>' + ' / ' + total);

                                            if(total == done) {
                                                $.ajax({
                                                    type: 'POST',
                                                    url: route + '/shopping/badge_design',
                                                    data: {sid: SID, type: 'use_badge_slog', slog: JSON.stringify(useBadge_obj), before_slog: JSON.stringify(before_useBadge_obj)},
                                                    dataType: 'json',
                                                    async: true,
                                                    success: function(data) {
                                                    }
                                                });

                                                var p = $.gallery.pages;
                                                setTimeout(function(){
                                                    $.gallery.show($.gallery.block_id, p.page, '', function() {
                                                        setTimeout(function() { 
                                                            $('.gallery-modal').scrollTop(spos); 
                                                        }, 200);
                                                    });

                                                    $.gallery.update = true;
                                                    $.gallery.reset();
                                                    $.progressOFF();

                                                    badgeSettingModal.modal('hide');
                                                }, 400);
                                            }
                                        }
                                    });
                                }, 200*done);
                            });
                        }, '', '', 'cl-cmmodal cover cl-s-btn cl-p70 cl-p0 cl-edit-badge modal-product-badge', true, '', function() { //show

                            $(document).on('change', '.modal-product-badge-wrap .divTableHead .check-all', function() {
                                var type = $(this).attr('data-type');
                                if($(this).prop('checked') == true) {
                                    // $('input.check-all').prop('checked', true);
                                    $('.modal-product-badge-wrap input[data-type="'+type+'"]').prop('checked', true);
                                } else {
                                    $('.modal-product-badge-wrap input[data-type="'+type+'"]').prop('checked', false);
                                }
                            });
                            
                            $(document).on('change', '.modal-product-badge-wrap .product-badge-item input[type="checkbox"]', function() {
                                var type = $(this).attr('data-type');
                                if($(this).prop('checked') == true && ($.gallery.seqs.length == $('.modal-product-badge-wrap .product-badge-item input[type="checkbox"][data-type="'+type+'"]:checked').length)) {
                                    $('.modal-product-badge-wrap .divTableHead .check-all[data-type="'+type+'"]').prop('checked', true);
                                } else {
                                    $('.modal-product-badge-wrap .divTableHead .check-all[data-type="'+type+'"]').prop('checked', false);
                                }
                            });

                            var chBadgeDsgnContent = '\
                            <div class="badge-setting-header display-flex space-between align-items-center">\
                                <h2>뱃지 디자인 변경</h2>\
                                <ul class="badge-setting-button">\
                                    <li class="modal-close">취소</li>\
                                    <li class="modal-save ok-button-dialog">저장</li>\
                                </ul>\
                            </div>\
                            <div class="badge-setting-top display-flex space-between">\
                                <div class="return-default-design hand"><svg viewBox="0 0 20 20" width="20" height="20"><path d="M11.18 3C7.54 3 4.55 5.78 4.21 9.33L2.53 7.65l-.71.7 2.85 2.85 2.85-2.85-.7-.7-1.59 1.59C5.61 6.29 8.13 4 11.18 4c3.31 0 6 2.69 6 6s-2.69 6-6 6c-1.66 0-3.17-.68-4.26-1.78l-.71.71A6.981 6.981 0 0 0 11.18 17c3.87 0 7-3.13 7-7s-3.14-7-7-7z"></path></svg>뱃지 디자인 초기화</div>\
                            </div>\
                            <div class="divTable">\
                                <div class="divTableHeading display-flex space-between align-items-center">\
                                    <div class="divTableHead">뱃지</div>\
                                    <div class="divTableHead">스타일</div>\
                                    <div class="divTableHead">문구</div>\
                                    <div class="divTableHead">선</div>\
                                    <div class="divTableHead">배경</div>\
                                    <div class="divTableHead">텍스트</div>\
                                </div>\
                                <div class="divTableBody">\
                                </div>\
                            </div>\
                            \
                            ';

                            // $('.modal-product-badge-wrap .return-prev-setting').on('click', function(){
                            //     $('.divTableCell.product-badge-item input[type="checkbox"]').prop('checked', false);
                            //     $.each($.gallery.seqs, function(i,v) {
                            //         $.each(badgeArr, function(idx, type) {
                            //             var $badge = $('.table-item[data-seq="'+v+'"] .product-badge[data-type="'+type+'"]');
                            //             var checked = ($badge.length > 0)? 'checked' : '';
                            //             $('.divTableCell.product-badge-item[data-seq="'+v+'"] input.product-badge[data-type="'+type+'"]').prop('checked', checked);

                            //             var badgeCnt = $('.table-item.ui-selected .product-badge[data-type="'+type+'"]').length;
                            //             if($.gallery.seqs.length == badgeCnt) {
                            //                 $('.check-all[data-type="'+type+'"]').prop('checked', checked);
                            //             }
                            //         });
                            //     });

                            //     var settings = localStorage.getItem('badge_settings');
                            //     var before_settings = localStorage.getItem('before_badge_settings');
                            //     $('.modal-product-badge').eq(0).addClass('return-prev');
                            //     localStorage.setItem('badge_settings', before_settings);
                            //     $.badgeSettings.init($.parseJSON(before_settings));

                            //     // $.ajax({
                            //     //     type: 'POST',
                            //     //     url: '/shopping/badge_design',
                            //     //     data: { sid: SID, type: 'add', settings: before_settings, before_settings: settings },
                            //     //     dataType: 'json',                    
                            //     //     async: true,
                            //     //     success: function(data) {
                            //     //         localStorage.setItem('badge_settings', before_settings);
                            //     //         $.badgeSettings.init($.parseJSON(before_settings));
                            //     //     }
                            //     // });
                            // });

                            $(document).off('click', '.modal-product-badge-wrap .change-badge-design');
                            $(document).on('click', '.modal-product-badge-wrap .change-badge-design', function(e){
                                e.stopPropagation();
                                if($('.cl-change-badge-design').length > 0) return false;
                                var chBadgeModal = $(this).showModalFlat('', chBadgeDsgnContent, false, true, function(){ //confirm
                                    var before_settings = localStorage.getItem('before_badge_settings');
                                    var input_data = new Object();
                                    $('.badge-option-row').each(function(idx, v) {
                                        var key = $(v).attr('data-default');
                                        input_data[key] = {
                                            'type': $(v).find('input[name="type"]').val(),
                                            'style': ($(v).find('input[name="type"]').val() == 'edit')? $(v).find('input[name="style"]').val() : '',
                                            'badge_text': $(v).find('input[name="badge_text"]').val(),
                                            'border_color': $(v).find('input[name="border_color"]').val(),
                                            'background_color': $(v).find('input[name="background_color"]').val(),
                                            'font_color': $(v).find('input[name="font_color"]').val(),
                                            'image_src': $(v).find('input[name="image_src"]').val(),
                                            'image_name': $(v).find('input[name="image_name"]').val(),
                                        };
                                    });
                                    var isReset = $('.cl-change-badge-design').hasClass('reset-design');
                                    var route = (CONFIG_URL) ? '/_admin' : '';
                                    $.ajax({
                                        type: 'POST',
                                        url: route + '/shopping/badge_design',
                                        data: { sid: SID, type: 'add', settings: JSON.stringify(input_data), before_settings: before_settings, is_reset: isReset},
                                        dataType: 'json',                    
                                        async: true,
                                        success: function(data) {
                                            if(Object.keys(data).length > 0) {
                                                // console.log(data);
                                                var badge_settings = data;
                                                $.badgeSettings.init(badge_settings);
                                                localStorage.setItem('badge_settings', JSON.stringify(badge_settings));
                                                $('.modal-product-badge').eq(0).addClass('design-update');
                                                $.gallery.update = true;
                                            }

                                            chBadgeModal.modal('hide');
                                        }
                                    });
                                }, '', '', 'cl-cmmodal cover cl-s-btn cl-p70 cl-p0 cl-edit-badge cl-change-badge-design modal-product-badge', true, '', function() { //show
                                    var badge_settings = $.parseJSON(localStorage.getItem('badge_settings'));
                                    var changeBadgeDsgnRow = $.badgeSettings.initDesign(badgeArr, badge_settings);
                                    $('.cl-change-badge-design .divTableBody').html(changeBadgeDsgnRow);
                                    $('.cl-change-badge-design .divTable').after('<div class="text-right">※ 뱃지 디자인 변경 시, 모든 갤러리 블럭의 뱃지 디자인에 반영됩니다.</div>');

                                    $('.cl-change-badge-design').closest('.modal-default').css('z-index', 1043);
                                    // $('.cl-change-badge-design').closest('.cl-common-modal').next('.modal-backdrop.fade.in').css('z-index', 1044);

                                    $('.badge-option-row').each(function(idx, v){
                                        if($(v).find('input[name="type"]').val() == 'edit') {
                                            var $badge = $(v).find('.product-badge');
                                            var badgeBorderColor = style.getHex($badge.css('border-color'));
                                            var badgeBackgroundColor = style.getHex($badge.css('background-color'));
                                            var badgetextColor = style.getHex($badge.css('color'));
                                            
                                            $(v).find('.color-picker-badge[pn="border-color"]').css('background-color', badgeBorderColor);
                                            $(v).find('.color-picker-badge[pn="background-color"]').css('background-color', badgeBackgroundColor);
                                            $(v).find('.color-picker-badge[pn="color"]').css('background-color', badgetextColor);
                                        }
                                    });

                                    $('input[name="badge_text"]').on({
                                        focusout: function(){
                                            $('.cl-change-badge-design').removeClass('reset-design');
                                            // $('.modal-product-badge').eq(0).removeClass('return-prev');

                                            var badgeText = $(this).val().trim();
                                            if(badgeText) $(this).closest('.badge-option-row').find('.product-badge').text(badgeText);
                                        },
                                        keyup: function(e){
                                            if(e.keyCode == 13) {
                                                $('.cl-change-badge-design').removeClass('reset-design');
                                                // $('.modal-product-badge').eq(0).removeClass('return-prev');

                                                var badgeText = $(this).val().trim();
                                                if(badgeText) $(this).closest('.badge-option-row').find('.product-badge').text(badgeText);
                                            }
                                        }
                                    });

                                    setBadgeColorPicker();

                                    //뱃지 스타일 변경
                                    $(document).off('click', '.modal-product-badge-wrap .cl-change-badge-design .select-style-btn');
                                    $(document).on('click', '.modal-product-badge-wrap .cl-change-badge-design .select-style-btn', function(){
                                        var uploadedImgs = '';
                                        if(localStorage.getItem('badge_imgs')) {
                                            var uploadedImgsArr = localStorage.getItem('badge_imgs').split('||');
                                            // console.log(uploadedImgsArr);
                                            $.each(uploadedImgsArr, function(idx, v){
                                                var img = v.split('::');
                                                var src = (typeof img[1] != 'undefined') ? img[1] : img[0];
                                                uploadedImgs += '\
                                                <div class="select-badge user-upload hand">\
                                                    <span class="product-badge"><img src="'+src+'" alt="'+img[0]+'"></span>\
                                                    <span class="delete-badge"><svg viewBox="0 0 12 13" width="12" height="13" data-idx="0"><path d="M12 2h-1H9V0H3.02v2H1 0v1h1v8c0 1.1 0.9 2 2 2h6c1.1 0 2-0.9 2-2V3h1V2zM4.02 1H8v1H4.02V1zM10 11c0 0.55-0.45 1-1 1H3c-0.55 0-1-0.45-1-1V3h1.02H9h1V11z"></path><rect x="4" y="4" width="1" height="7"></rect><rect x="7" y="4" width="1" height="7"></rect></svg></span>\
                                                </div>';
                                            });
                                        }
                                        var badgeStylePopup = '\
                                        <div class="badge-style-popup">\
                                            <div class="badge-style-header display-flex align-items-center space-between">\
                                                <div class="badge-style-title">스타일 선택</div>\
                                                <div class="modal-close hand"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16"><path d="M8.71 8l7.15-7.15c0.2-0.2 0.2-0.51 0-0.71s-0.51-0.2-0.71 0L8 7.29 0.85 0.15c-0.2-0.2-0.51-0.2-0.71 0s-0.2 0.51 0 0.71L7.29 8l-7.15 7.15c-0.2 0.2-0.2 0.51 0 0.71C0.24 15.95 0.37 16 0.5 16s0.26-0.05 0.35-0.15L8 8.71l7.15 7.15c0.1 0.1 0.23 0.15 0.35 0.15s0.26-0.05 0.35-0.15c0.2-0.2 0.2-0.51 0-0.71L8.71 8z"></path></svg></div>\
                                            </div>\
                                            <ul class="badge-type-tab display-flex align-items-center">\
                                                <li class="hand active" data-tab="edit">편집형</li>\
                                                <li class="hand" data-tab="image">이미지형</li>\
                                            </ul>\
                                            <div class="badge-type-tab-content badge-tab-edit">\
                                                <div class="badge-size-tab display-flex align-items-center">\
                                                    <span class="select-badge-size hand active" data-size="small">작은</span>\
                                                    <span>·</span>\
                                                    <span class="select-badge-size hand" data-size="medium">중간</span>\
                                                    <span>·</span>\
                                                    <span class="select-badge-size hand" data-size="large">큰</span>\
                                                </div>\
                                                <div class="select-badge-table display-flex" data-size="small">\
                                                    <div class="hand select-badge selected" data-style="default-1"><span class="product-badge default-1 small">NEW</span></div>\
                                                    <div class="hand select-badge" data-style="red-1"><span class="product-badge red-1 small">NEW</span></div>\
                                                    <div class="hand select-badge" data-style="blue-1"><span class="product-badge blue-1 small">NEW</span></div>\
                                                    <div class="hand select-badge" data-style="black-1"><span class="product-badge black-1 small">NEW</span></div>\
                                                    \
                                                    <div class="hand select-badge" data-style="default-2"><span class="product-badge default-2 small">NEW</span></div>\
                                                    <div class="hand select-badge" data-style="red-2"><span class="product-badge red-2 small">NEW</span></div>\
                                                    <div class="hand select-badge" data-style="blue-2"><span class="product-badge blue-2 small">NEW</span></div>\
                                                    <div class="hand select-badge" data-style="black-2"><span class="product-badge black-2 small">NEW</span></div>\
                                                    \
                                                    <div class="hand select-badge" data-style="default-3"><span class="product-badge default-3 small">NEW</span></div>\
                                                    <div class="hand select-badge" data-style="red-3"><span class="product-badge red-3 small">NEW</span></div>\
                                                    <div class="hand select-badge" data-style="blue-3"><span class="product-badge blue-3 small">NEW</span></div>\
                                                    <div class="hand select-badge" data-style="black-3"><span class="product-badge black-3 small">NEW</span></div>\
                                                    \
                                                    <div class="hand select-badge" data-style="default-4"><span class="product-badge default-4 small">NEW</span></div>\
                                                    <div class="hand select-badge" data-style="red-4"><span class="product-badge red-4 small">NEW</span></div>\
                                                    <div class="hand select-badge" data-style="blue-4"><span class="product-badge blue-4 small">NEW</span></div>\
                                                    <div class="hand select-badge" data-style="black-4"><span class="product-badge black-4 small">NEW</span></div>\
                                                    \
                                                    <div class="hand select-badge" data-style="default-5"><span class="product-badge default-5 small">NEW</span></div>\
                                                    <div class="hand select-badge" data-style="red-5"><span class="product-badge red-5 small">NEW</span></div>\
                                                    <div class="hand select-badge" data-style="blue-5"><span class="product-badge blue-5 small">NEW</span></div>\
                                                    <div class="hand select-badge" data-style="black-5"><span class="product-badge black-5 small">NEW</span></div>\
                                                    \
                                                    <div class="hand select-badge" data-style="default-6"><span class="product-badge default-6 small">NEW</span></div>\
                                                    <div class="hand select-badge" data-style="red-6"><span class="product-badge red-6 small">NEW</span></div>\
                                                    <div class="hand select-badge" data-style="blue-6"><span class="product-badge blue-6 small">NEW</span></div>\
                                                    <div class="hand select-badge" data-style="black-6"><span class="product-badge black-6 small">NEW</span></div>\
                                                    \
                                                    <div class="hand select-badge" data-style="red-7"><span class="product-badge red-7 small">NEW</span></div>\
                                                    <div class="hand select-badge" data-style="red-8"><span class="product-badge red-8 small">NEW</span></div>\
                                                    <div class="hand select-badge" data-style="red-9"><span class="product-badge red-9 small">NEW</span></div>\
                                                    <div class="hand select-badge" data-style="blue-7"><span class="product-badge blue-7 small">NEW</span></div>\
                                                    <div class="hand select-badge" data-style="blue-8"><span class="product-badge blue-8 small">NEW</span></div>\
                                                    <div class="hand select-badge" data-style="blue-9"><span class="product-badge blue-9 small">NEW</span></div>\
                                                </div>\
                                            </div>\
                                            <div class="badge-type-tab-content badge-tab-image hide">\
                                                <div class="select-badge-table display-flex">\
                                                    <div class="hand select-badge"><span class="product-badge"><img src="https://storage.googleapis.com/i.addblock.net/shopping_mall/badge/new.gif" alt="new.gif"></span></div>\
                                                    <div class="hand select-badge"><span class="product-badge"><img src="https://storage.googleapis.com/i.addblock.net/shopping_mall/badge/new_r.gif" alt="new_r.gif"></span></div>\
                                                    <div class="hand select-badge"><span class="product-badge"><img src="https://storage.googleapis.com/i.addblock.net/shopping_mall/badge/new_g.gif" alt="new_g.gif"></span></div>\
                                                    <div class="hand select-badge"><span class="product-badge"><img src="https://storage.googleapis.com/i.addblock.net/shopping_mall/badge/new_b.gif" alt="new_b.gif"></span></div>\
                                                    \
                                                    <div class="hand select-badge"><span class="product-badge"><img src="https://storage.googleapis.com/i.addblock.net/shopping_mall/badge/best.gif" alt="best.gif"></span></div>\
                                                    <div class="hand select-badge"><span class="product-badge"><img src="https://storage.googleapis.com/i.addblock.net/shopping_mall/badge/best_r.gif" alt="best_r.gif"></span></div>\
                                                    <div class="hand select-badge"><span class="product-badge"><img src="https://storage.googleapis.com/i.addblock.net/shopping_mall/badge/best_g.gif" alt="best_g.gif"></span></div>\
                                                    <div class="hand select-badge"><span class="product-badge"><img src="https://storage.googleapis.com/i.addblock.net/shopping_mall/badge/best_b.gif" alt="best_b.gif"></span></div>\
                                                    \
                                                    <div class="hand select-badge"><span class="product-badge"><img src="https://storage.googleapis.com/i.addblock.net/shopping_mall/badge/sale.gif" alt="sale.gif"></span></div>\
                                                    <div class="hand select-badge"><span class="product-badge"><img src="https://storage.googleapis.com/i.addblock.net/shopping_mall/badge/sale_r.gif" alt="sale_r.gif"></span></div>\
                                                    <div class="hand select-badge"><span class="product-badge"><img src="https://storage.googleapis.com/i.addblock.net/shopping_mall/badge/sale_g.gif" alt="sale_g.gif"></span></div>\
                                                    <div class="hand select-badge"><span class="product-badge"><img src="https://storage.googleapis.com/i.addblock.net/shopping_mall/badge/sale_b.gif" alt="sale_b.gif"></span></div>\
                                                    \
                                                    <div class="hand select-badge"><span class="product-badge"><img src="https://storage.googleapis.com/i.addblock.net/shopping_mall/badge/md.gif" alt="md.gif"></span></div>\
                                                    <div class="hand select-badge"><span class="product-badge"><img src="https://storage.googleapis.com/i.addblock.net/shopping_mall/badge/md_r.gif" alt="md_r.gif"></span></div>\
                                                    <div class="hand select-badge"><span class="product-badge"><img src="https://storage.googleapis.com/i.addblock.net/shopping_mall/badge/md_g.gif" alt="md_g.gif"></span></div>\
                                                    <div class="hand select-badge"><span class="product-badge"><img src="https://storage.googleapis.com/i.addblock.net/shopping_mall/badge/md_b.gif" alt="md_b.gif"></span></div>\
                                                    \
                                                    <div class="hand select-badge"><span class="product-badge"><img src="https://storage.googleapis.com/i.addblock.net/shopping_mall/badge/hot.gif" alt="hot.gif"></span></div>\
                                                    <div class="hand select-badge"><span class="product-badge"><img src="https://storage.googleapis.com/i.addblock.net/shopping_mall/badge/hot_g.gif" alt="hot_g.gif"></span></div>\
                                                    <div class="hand select-badge"><span class="product-badge"><img src="https://storage.googleapis.com/i.addblock.net/shopping_mall/badge/hot_b.gif" alt="hot_b.gif"></span></div>\
                                                    <div class="hand select-badge"><span class="product-badge"><img src="https://storage.googleapis.com/i.addblock.net/shopping_mall/badge/hit.gif" alt="hit.gif"></span></div>\
                                                    \
                                                    ' + uploadedImgs + '\
                                                </div>\
                                                <div class="upload-badge-image hand">이미지 직접 올리기<svg viewBox="0 0 12 10" width="12" height="10"><polygon points="10 6 10 8 2 8 2 6 0 6 0 10 12 10 12 6 "></polygon><polygon points="10 3 7 3 7 0 5 0 5 3 2 3 6 7 "></polygon></svg></div>\
                                            </div>\
                                            <div class="badge-style-footer display-flex align-items-center">\
                                                <span class="hide">권장 이미지 높이 : 20px 이하</span>\
                                                <ul class="display-flex align-items-center">\
                                                    <li class="modal-close hand">취소</li>\
                                                    <li class="modal-save hand">저장</li>\
                                                </ul>\
                                            </div>\
                                        </div>\
                                        ';

                                        $('.badge-style-popup').remove();
                                        $(this).toggleClass('active');
                                        if($(this).hasClass('active')) {
                                            $(this).after(badgeStylePopup);
                                            $.badgeSettings.initStylePopup($(this));
                                        }
                                    });
                                    
                                    $('.modal-product-badge-wrap .cl-change-badge-design .return-default-design').on('click', function(e) {
                                        e.stopPropagation();
                                        if($('.cl-reset-badge-design').length > 0) return false;
                                        var modal = $(this).showModalFlat('뱃지 디자인 초기화', '모든 갤러리 블록에 적용된 뱃지 디자인이 초기화됩니다.<br>정말 초기화하시겠습니까?', true, true, function(){ //confirm
                                            $('.badge-option-row').each(function(idx, v){
                                                var $badge = $(v).find('.product-badge-view > .product-badge');
                                                var defaultType = $(v).attr('data-default');
                                                $badge.attr('class', 'product-badge default-1 small');
                                                $badge.removeAttr('style');
                                                $badge.html($.lang[LANG]['gallery.shopping.badge.'+defaultType]);

                                                $(v).find('input[name="badge_text"]').prop('disabled', false);
                                                $(v).find('input[name="badge_text"]').val($.lang[LANG]['gallery.shopping.badge.'+defaultType]);
                                                $(v).find('input[name="type"]').val('edit');
                                                $(v).find('input[name="style"]').val('default-1 small');
                                                $(v).find('input[name="border_color"]').val('#bebebe');
                                                $(v).find('input[name="background_color"]').val('#ffffff');
                                                $(v).find('input[name="font_color"]').val('#000000');
                                                $(v).find('input[name="image_src"]').val('');
                                                $(v).find('input[name="image_name"]').val('');

                                                $(v).find('.color-picker-badge').removeClass('disabled');
                                                $(v).find('.color-picker-badge[pn="border-color"]').css('background-color', '#bebebe');
                                                $(v).find('.color-picker-badge[pn="background-color"]').css('background-color', '#ffffff');
                                                $(v).find('.color-picker-badge[pn="color"]').css('background-color', '#000000');
                                            });
                                            $('.cl-change-badge-design').addClass('reset-design');
                                            modal.modal('hide');
                                        }, 'cancel', 'ok', 'cl-cmmodal cl-reset-badge-design cl-s-btn w560 cl-p70 cl-p0', false, '', function(){ //show
                                            $('.cl-reset-badge-design').closest('.modal-default').css('z-index', 1046);
                                            $('.cl-reset-badge-design').closest('.cl-common-modal').next('.modal-backdrop.fade.in').css('z-index', 1045);
                                        });
                                        
                                    });

                                    $(document).off('click', '.badge-style-popup .modal-save');
                                    $(document).on('click', '.badge-style-popup .modal-save', function(){
                                        var $selectedBadge = $('.badge-style-popup .badge-type-tab-content:not(.hide) .select-badge-table .select-badge.selected');
                                        if($selectedBadge.length > 0) $.badgeSettings.handleSelection($selectedBadge);

                                        $('.select-style-btn').removeClass('active');
                                        $('.badge-style-popup').remove();
                                    });

                                    $(document).off('click', '.badge-style-popup .modal-close');
                                    $(document).on('click', '.badge-style-popup .modal-close', function(){
                                        $('.select-style-btn').removeClass('active');
                                        $('.badge-style-popup').remove();
                                    });

                                    // $('.cl-change-badge-design .modal-body').off('click');
                                    // $('.cl-change-badge-design .modal-body').on('click', function(e){
                                    //     if(!$(e.target).is('.select-style-btn') && $(e.target).closest('.badge-style-popup').length == 0) {
                                    //         $('.select-style-btn').removeClass('active');
                                    //         $('.badge-style-popup').remove();
                                    //     }
                                    // });

                                    $(document).off('click', '.badge-type-tab > li');
                                    $(document).on('click', '.badge-type-tab > li', function(){ //편집형, 이미지형 탭
                                        var optionIdx = $(this).closest('.badge-option-row').attr('data-idx');
                                        var badgeText = $('.badge-option-row[data-idx="'+optionIdx+'"] input[name="badge_text"]').val();
                                        var badgeType = $('.badge-option-row[data-idx="'+optionIdx+'"] input[name="type"]').val();
                                        var badgeStyle = $('.badge-option-row[data-idx="'+optionIdx+'"] input[name="style"]').val();
                                        var badgeStyleArr = badgeStyle.split(' ');
                                        var style = badgeStyleArr[0];
                                        var size = badgeStyleArr[1];

                                        $('.badge-type-tab > li').removeClass('active');
                                        $(this).addClass('active');
                                        $('.badge-type-tab-content').addClass('hide');
                                        $('.badge-style-popup .badge-style-footer > span').addClass('hide');

                                        $('.badge-tab-' + $(this).attr('data-tab')).removeClass('hide');
                                        if($(this).attr('data-tab') == 'edit') {
                                            if(!style) style = 'default-1';
                                            if(!size) {
                                                size = 'small';
                                                $('.badge-size-tab .select-badge-size').removeClass('active');
                                                $('.badge-size-tab .select-badge-size[data-size="'+size+'"]').addClass('active');
                                                $('.select-badge-table').attr('data-size', size);
                                            }
                                            if(!badgeText) badgeText = $.lang[LANG]['gallery.shopping.badge.'+ $(this).closest('.badge-option-row').attr('data-default')]
                                            $('.badge-style-popup .badge-tab-edit .select-badge .product-badge').html(badgeText);
                                            $('.badge-style-popup .badge-tab-edit .select-badge .product-badge').addClass(size);
                                        } else {
                                            $('.badge-style-popup .badge-style-footer > span').removeClass('hide');
                                            $('.badge-style-popup .select-badge-table .product-badge').removeClass('small medium large');
                                        }
                                    });

                                    $(document).off('click', '.badge-style-popup .badge-size-tab .select-badge-size');
                                    $(document).on('click', '.badge-style-popup .badge-size-tab .select-badge-size', function() { //뱃지 사이즈 탭
                                        $('.badge-size-tab .select-badge-size').removeClass('active');
                                        $(this).addClass('active');

                                        var badgeSize = $(this).attr('data-size');
                                        $('.select-badge-table').attr('data-size', badgeSize);
                                        $('.select-badge-table .product-badge').removeClass('small medium large');
                                        $('.select-badge-table .product-badge').addClass(badgeSize);
                                    });

                                    $(document).off('click', '.badge-style-popup .select-badge-table .select-badge');
                                    $(document).on('click', '.badge-style-popup .select-badge-table .select-badge', function() {
                                        if($(this).find('.product-badge > img').attr('src') == '//storage.googleapis.com/i.addblock.net/icon_broken_img.png') {
                                            return false;
                                        }
                                        $('.badge-style-popup .select-badge-table .select-badge').removeClass('selected');
                                        $(this).addClass('selected');

                                        // $.badgeSettings.handleSelection($(this));
                                    });

                                    $(document).off('click', '.badge-style-popup .select-badge-table .select-badge .delete-badge');
                                    $(document).on('click', '.badge-style-popup .select-badge-table .select-badge .delete-badge', function() {
                                        var $this = $(this);
                                        var modal = $(this).showModalFlat('뱃지 이미지 삭제', '선택한 이미지를 삭제하시겠습니까?', true, true, function(){ //confirm
                                            var optionIdx = Number($this.closest('.badge-option-row').attr('data-idx'));
                                            var imgSrc = $this.closest('.select-badge').find('img').attr('src');
                                            var imgName = $this.closest('.select-badge').find('img').attr('alt');
                                            var beforeImgSrcArr = $('.badge-option-row input[name="image_src"]').map(function(idx, v){
                                                return $(v).val();
                                            }).get();
                                            // console.log(optionIdx, imgSrc, beforeImgSrcArr);
                                            $this.closest('.select-badge').remove();
                                            
                                            var badgeImgsArr = new Array();
                                            $('.badge-tab-image .select-badge-table .select-badge.user-upload .product-badge img').each(function(idx, v){
                                                var imgData = (typeof $(v).attr('alt') != 'undefined' && $(v).attr('alt')) ? $(v).attr('alt') + '::' + $(v).attr('src') : $(v).attr('src');
                                                badgeImgsArr.push(imgData);
                                            });
                                            // console.log('badgeImgsArr', badgeImgsArr);
                                            var badge_imgs = (badgeImgsArr.length > 0)? badgeImgsArr.join('||') : '';
                                            var route = (CONFIG_URL) ? '/_admin' : '';
                                            $.ajax({
                                                type: 'POST',
                                                url: route + '/shopping/badge_design',
                                                data: { sid: SID, type: 'delete-image', settings: badge_imgs, file_name: imgName, },
                                                dataType: 'json',                    
                                                async: true,
                                                success: function(data) {
                                                    // console.log(data);
                                                    localStorage.setItem('badge_imgs', badge_imgs);
                                                    var imgIdx = beforeImgSrcArr.indexOf(imgSrc);

                                                    if(imgIdx > -1) {
                                                        var badgeText = $('.badge-option-row[data-idx="'+imgIdx+'"] input[name="badge_text"]').val();

                                                        if(imgIdx == optionIdx) {
                                                            $('.badge-style-popup .select-badge-table .select-badge').removeClass('selected');
                                                            $('.badge-style-popup .badge-tab-edit .select-badge-table').attr('data-size', 'small');
                                                            $('.badge-style-popup .badge-tab-edit .select-badge-table .select-badge .product-badge').addClass('small');
                                                            $('.badge-style-popup .badge-tab-edit .select-badge-table .select-badge .product-badge').html(badgeText);

                                                            var defaultBadge = $('.badge-style-popup .badge-tab-edit .select-badge-table[data-size="small"] .select-badge[data-style="default-1"]');
                                                            defaultBadge.addClass('selected');
                                                            // console.log('defaultBadge', defaultBadge);
                                                            $.badgeSettings.handleSelection(defaultBadge);
                                                        } else {
                                                            var badgeEL = $('<span class="product-badge default-1 small">' + badgeText + '</span>');
                                                            $('.badge-option-row[data-idx="'+imgIdx+'"] .product-badge-view').html(badgeEL);

                                                            $('.badge-option-row[data-idx="'+imgIdx+'"]').find('.color-picker-badge').removeClass('disabled');
                                                            $('.badge-option-row[data-idx="'+imgIdx+'"]').find('input[name="badge_text"]').prop('disabled', false);

                                                            $('.badge-option-row[data-idx="'+imgIdx+'"]').find('.color-picker-badge[pn="border-color"]').css('background-color', '#bebebe');
                                                            $('.badge-option-row[data-idx="'+imgIdx+'"]').find('.color-picker-badge[pn="background-color"]').css('background-color', '#ffffff');
                                                            $('.badge-option-row[data-idx="'+imgIdx+'"]').find('.color-picker-badge[pn="color"]').css('background-color', '#000000');

                                                            $('.badge-option-row[data-idx="'+imgIdx+'"] input[name="type"]').val('edit');
                                                            $('.badge-option-row[data-idx="'+imgIdx+'"] input[name="style"]').val('default-1 small');
                                                            $('.badge-option-row[data-idx="'+imgIdx+'"] input[name="border_color"]').val('#bebebe');
                                                            $('.badge-option-row[data-idx="'+imgIdx+'"] input[name="background_color"]').val('#ffffff');
                                                            $('.badge-option-row[data-idx="'+imgIdx+'"] input[name="font_color"]').val('#000000');
                                                            $('.badge-option-row[data-idx="'+imgIdx+'"] input[name="image_src"]').val('');
                                                            $('.badge-option-row[data-idx="'+imgIdx+'"] input[name="image_name"]').val('');
                                                        }
                                                    }
                                                }
                                            });
                                            modal.modal('hide');
                                        }, 'cancel', 'ok', 'cl-cmmodal cl-delete-badge-image cl-s-btn w560 cl-p70 cl-p0', false);
                                    });
                                    $(document).on('click', '.upload-badge-image', function(){
                                        $('.resource-useit').attr('data-property','upload-badge-image')
                                                            .attr('data-element','.product-badge')
                                                            .attr('data-replace-count',0)
                                                            .removeAttr('data-ctrl')
                                                            .removeAttr('data-idx')
                                                            .removeAttr('data-seq')
                                                            .removeAttr('data-col');
                                        $('#el-fileupload').modal('show');
                                    });
                                    
                                    
                                }, function(){ //hide
                                    $('[data-toggle="popover"]').popover();
                                });
                                
                                $('.cl-change-badge-design .badge-setting-button > .modal-close').on('click', function() { 
                                    chBadgeModal.modal('hide');
                                });
                            });
                        }, function(){ //hide
                            $('[data-toggle="popover"]').popover();
                        });

                        $('.modal-product-badge-wrap .badge-setting-header .modal-close').on('click', function() {
                            badgeSettingModal.modal('hide');
                            if($(this).closest('.modal-product-badge').hasClass('design-update')) $.gallery.show($.gallery.block_id);
                        });

                        break;
                    case "margin":
                        var route = (CONFIG_URL) ? '/_admin' : '';
                        var firstItem = $('.gallery-items .table-item.ui-selected').eq(0),
                            margin_rate = firstItem.find('.margin-info .rate').text().trim().replace(/[^0-9.]/g,'') * 1,
                            margin_add = firstItem.find('.margin-info .add').text().trim().replace(/[^0-9.]/g,'') * 1,
                            margin_seqs = $.gallery.seqs,
                            margin_html = '\
                                <ul>\
                                    <li>\
                                        <span class="title">마진율</span>\
                                        <span class="prod-margin-price cal-margin">\
                                            <svg xmlns="http://www.w3.org/2000/svg" width="17" height="17" fill="currentColor" class="bi bi-plus-lg plus" viewBox="0 0 16 16"><path fill-rule="evenodd" d="M8 2a.5.5 0 0 1 .5.5v5h5a.5.5 0 0 1 0 1h-5v5a.5.5 0 0 1-1 0v-5h-5a.5.5 0 0 1 0-1h5v-5A.5.5 0 0 1 8 2Z"/></svg>\
                                            <input type="text" class="prod-user-margin input-margin" value="'+ margin_rate +'" numberOnly>%\
                                            <svg xmlns="http://www.w3.org/2000/svg" width="17" height="17" fill="currentColor" class="bi bi-dash-lg minus" viewBox="0 0 16 16"><path fill-rule="evenodd" d="M2 8a.5.5 0 0 1 .5-.5h11a.5.5 0 0 1 0 1h-11A.5.5 0 0 1 2 8Z"/></svg>\
                                        </span>\
                                    </li>\
                                    <li>\
                                        <span class="title">마진값</span>\
                                        <span class="prod-margin-price cal-price">\
                                            <svg xmlns="http://www.w3.org/2000/svg" width="17" height="17" fill="currentColor" class="bi bi-plus-lg plus" viewBox="0 0 16 16"><path fill-rule="evenodd" d="M8 2a.5.5 0 0 1 .5.5v5h5a.5.5 0 0 1 0 1h-5v5a.5.5 0 0 1-1 0v-5h-5a.5.5 0 0 1 0-1h5v-5A.5.5 0 0 1 8 2Z"/></svg>\
                                            <input type="text" class="prod-user-price input-margin" value="'+ addCommas(margin_add) +'" numberOnly>원\
                                            <svg xmlns="http://www.w3.org/2000/svg" width="17" height="17" fill="currentColor" class="bi bi-dash-lg minus" viewBox="0 0 16 16"><path fill-rule="evenodd" d="M2 8a.5.5 0 0 1 .5-.5h11a.5.5 0 0 1 0 1h-11A.5.5 0 0 1 2 8Z"/></svg>\
                                        </span>\
                                    </li>\
                                </ul>\
                            ';

                        var marginModal = $(this).showModalFlat('마진 설정', margin_html, true, true, function() {
                            var new_mrate = marginModal.find('.prod-user-margin').val().trim().replace(/[^0-9.]/g,'') * 1,
                                new_madd = marginModal.find('.prod-user-price').val().trim().replace(/[^0-9.]/g,'') * 1;
                            $.processON();
                            setTimeout(function() {
                                $.post(route + '/shopping/setMargin', {sid: SID, seqs: margin_seqs, rate: new_mrate, val: new_madd}, function(data) {
                                    if(typeof data.error != 'undefined' && data.error) {
                                        var marginError = $(this).showModalFlat('ERROR','실패',true,false,'','close','','cl-cmmodal cl-s-btn w560 cl-p130 cl-p0');
                                        marginModal.modal('hide');
                                        return false;
                                    }

                                    var changed_seqs = margin_seqs;
                                    $('.gallery-modal .table-item.ui-selected').each(function() {
                                        // if($.inArray($(this).attr('data-seq'), margin_seqs.i) > -1 || $.inArray($(this).attr('data-seq'), margin_seqs.u) > -1) {
                                        if($.inArray($(this).attr('data-seq'), data.list.edit) > -1) {
                                            var p_retail = $(this).find('.td-title .add-info .sale-rate').attr('data-retail').trim() * 1,
                                                p_supply = $(this).find('.td-title .add-info .margin-info .price').attr('data-supply').trim() * 1,
                                                tmp_cal = p_supply * (new_mrate/100),
                                                tmp_five = (tmp_cal - Math.floor(tmp_cal) == 0.5) ? true : false,
                                                tmp_r = (tmp_five) ? Math.floor(tmp_cal) : Math.round(tmp_cal),
                                                new_margin = tmp_r + new_madd,
                                                new_price = p_supply + new_margin,
                                                new_srate = (p_retail - new_price > 0) ? Math.floor((p_retail - new_price) / p_retail  * 100) : 0;

                                            var new_price_span = (new_price > 0) ? '<span class="price-val">' + addCommas(new_price) + '원</span>' : '<span class="price-val">-</span>',
                                                new_srate_span = (new_price < p_retail) ? '할인율 <span class="rate">' + new_srate + '</span>%' : '',
                                                new_sale_span = (new_price < p_retail) ? '<span class="price-sale">' + addCommas(p_retail) + '원</span>' : '';

                                            var p_name = $(this).find('.td-title .item-title-str').text().trim(),
                                                p_seq = $(this).attr('data-seq'),
                                                pid = $(this).closest('.gallery-modal').attr('data-pid'),
                                                before_margin = '미지정',
                                                after_margin = '마진율 : ' + new_mrate + '% / 마진값 : ' + addCommas(new_madd) + '원';
                                            
                                            if($(this).find('.margin-info .rate').length > 0) {
                                                var old_mrate = $(this).find('.margin-info .rate').text().trim().replace(/[^0-9.]/g,'') * 1,
                                                    old_madd = $(this).find('.margin-info .add').text().trim().replace(/[^0-9.]/g,'') * 1,
                                                    before_margin = '마진율 : ' + old_mrate + '% / 마진값 : ' + addCommas(old_madd) + '원';
                                            }
                                            var slog_obj = {'pname':p_name, 'seq':p_seq, 'pid':pid, 'supply_price': addCommas(p_supply)+'원', 'before_margin':before_margin, 'margin':after_margin};
                                            setSiteLogs('sh.product.edit','margin',slog_obj,'sh.config',p_seq);

                                            $(this).attr('data-pcase','M');
                                            $(this).find('.td-title .add-info .sale-rate').html(new_srate_span);
                                            $(this).find('.td-title .add-info .margin-info .rate').text(new_mrate);
                                            $(this).find('.td-title .add-info .margin-info .add').text(addCommas(new_madd));
                                            $(this).find('.td-title .add-info .margin-info .price').text(addCommas(new_margin));
                                            $(this).find('.td-price').html(new_price_span + new_sale_span);
                                        }

                                    });

                                    $.processOFF();
                                    marginModal.modal('hide');

                                    if(typeof data.list.error != 'undefined' && data.list.error.length > 0) {
                                        var error_msg = '판매가가 10억이 넘게 적용되는 일부 상품(들)이 존재합니다.<br>마진 설정은 최종 판매가가 10억 이하의 상품들에만 적용되고,<br>10억이 넘는 상품들은 가격 또는 마진 설정을 재 검토해 주세요.';
                                        // var error_msg = (data.list.error.length == $.gallery.seqs.length) ? '문구요청1. 선택 상품 마진 변경 불가. 금액 10억 이상 이라서' : '문구요청1. 선택 상품 중 일부 상품 마진 변경 불가. 금액 10억 이상 이라서';
                                        $(this).showModalFlat('마진 설정', error_msg, true, false, '', 'ok', '', 'cl-cmmodal cl-s-btn w560 cl-p70 cl-p0 cl-shopping-margin-error');
                                    }

                                }, 'json');
                            });
                        } ,'cancel', 'ok', 'cl-cmmodal cl-s-btn w560 cl-p70 cl-p0 cl-shopping-margin','','',function(){

                            $('.cl-shopping-margin .prod-margin-price > svg.bi').off('click').on({
                                click: function(e) {
                                    var margin_type = ($(this).closest('.prod-margin-price').hasClass('cal-margin')) ? 'margin' : 'price',
                                        marginInput = $(this).closest('.prod-margin-price').find('.prod-user-'+margin_type),
                                        isPlus = (($(this).attr('class')).indexOf('plus') > -1) ? true : false,
                                        margin = marginInput.val().trim(),
                                        r = Number(margin.replace(/[^0-9.]/g,''));
                                    if(margin_type == 'margin') {
                                        r = (isPlus) ? r + 1 : r - 1;
                                        if(r < 0) r = 0;
                                        if(r > 100) r = 100;
                                    } else {
                                        r = (isPlus) ? r + 10000 : r - 10000;
                                        if(r < 0) r = 0;
                                        r = addCommas(r);
                                    }
                                    marginInput.val(r);
                                }
                            });

                            $('.cl-shopping-margin .prod-user-margin, .cl-shopping-margin .prod-user-price').off('blur').on({
                                blur: function(e) {
                                    if($(this).val().trim() == '') $(this).val('0');
                                    if($(this).hasClass('prod-user-margin')) {
                                        if(Number(removeCommas($('.prod-user-margin').val())) > 100) $(this).val('100');
                                    }
                                    if($(this).hasClass('prod-user-price')) {
                                        if(Number(removeCommas($('.prod-user-price').val())) > 1000000000) $(this).val('1,000,000,000');
                                    }
                                }
                            });

                        });
                        break;
                    case "stock" :
                        setQuantity();
                        break;
                    default:
                        break;
                }
            });
            $(document).on('click','.gallery-add-items', function(e) {
                if($(this).hasClass('disabled')) {
                    ($(this).hasClass('gallery-need')) 
                    ? $(this).showModalFlat('안내', '화면 좌측의 갤러리 목록에서 갤러리 선택 후 상품을 추가할 수 있습니다.', true, false, '', 'ok','','cl-cmmodal cl-s-btn w560 cl-p130 cl-p0 cl-okbtn-pbt70')
                    : $(this).showModalFlat('안내', '상품관리를 사용하려면 쇼핑갤러리가 필요합니다.<br><a href="/config" style="text-decoration:underline;color:#4789e7;font-weight:600;">[편집모드]</a>에서 쇼핑 갤러리를 먼저 생성하세요', true, false, '', 'ok','','cl-cmmodal cl-s-btn w560 cl-p130 cl-p0 cl-okbtn-pbt70');
                    return false;
                }

                var mode = $(this).attr('data-mode');
                if(typeof mode == 'undefined' || !mode) {
                    alert('Undefined gallery mode');
                    return false;
                }
                switch(mode) {
                    case 'shopping' : $.products.add(-1); break;
                    default:
                        $('.resource-useit')
                            .removeAttr('data-property')
                            .removeAttr('data-element')
                            .attr('data-replace-count','0');
                        selectCount = 0;
                        selectID = $('.gallery-modal').attr('data-pid');
                        $.resource.open();
                        break;
                }
            });
            $(document).on('blur','.item-title', function(e) {
                var title = $(this).val().trim(),
                    s = $(this).attr('data-title'),
                    seq = $(this).attr('data-seq'),
                    caption = $(this).attr('data-caption'),
                    hashtag = $(this).attr('data-hashtag'),
                    category = $(this).attr('data-category'),
                    datetime = $(this).attr('data-datetime'),
                    thumb = $(this).attr('data-url'),
                    file = (thumb.indexOf('googleusercontent') > -1) ? thumb : thumb.replace(/^.*[\\\/]/, ''),
                    $gitem = $('.' + $.gallery.block_id).find('.gallery-item[data-seq="'+seq+'"]'),
                    pathinfo = thumb.split('/');

                    if($gitem.length == 0) {
                    if($(this).parents('.gallery-modal').attr('data-mode')=='gallery') {
                        $gitem = $('.gallery-popup').find('.gallery-item[data-seq="'+seq+'"]');
                    }
                }

                if($('.' + $.gallery.block_id).attr('data-msny') == 'true') $.gallery.update = true;

                if(title != s && title) {
                    if(typeof seq == 'undefined' || !seq) {
                        alert('Invalid item');
                        return false;
                    }

                    $gitem.find('[data-gallery]').attr({'data-title':title});
                    if($('.gallery-items .item').length < 3) $('.gallery-popup').find('.gallery-item[data-seq="'+seq+'"]').find('[data-gallery]').attr({'data-title':title});
                    var type = 'ELEM',
                        s = '';
                    if(pathinfo[4]!= 'free') s = 'false';
                    else {
                        var p = pathinfo.slice(1,6);
                        p.unshift('');
                        p.push('');
                        s = p.join('/');
                    }

                    $.post('/template/update/type/gallery',{ s: seq, id : SID, title : title, caption : caption, datetime : datetime, hashtag : hashtag, category : category, file : file, storage : s}, function(data) {
                        var isCheck = checkError(data);
                        if(!isCheck) return false;
                        setLogs(type,'gallery.data.edit','modify',type,'product-manager','el');
                    }, 'json');    

                    (title.length>0) ? $gitem.find('h5.figure').html(title) :  $gitem.find('h5.figure').text('Title');
                    $(this).attr({'value':title,'data-title':title});
                }
                $('.gallery-items').selectable('enable');
            });
            $(document).on('click', '.prod-button .modal-save, .prod-detail-edit', function(e) {
                var hasEmoji = false;
                $('.prod-input, .prod-input-value').each(function() {
                    var passEmoji = ($.inArray($(this).attr('id'),['prod-title', 'prod-desc']) > -1) ? true : false,
                        check_val = ($(this).is('div')) ? $(this).text().trim() : $(this).val().trim();
                    
                    if(!passEmoji && checkEmojis(check_val)) {
                        hasEmoji = true;
                        return false;
                    }
                });
                if(hasEmoji) {
                    e.preventDefault();
                    errorEmojisModal();
                    return false;
                }

                var go = $(this).hasClass('prod-detail-edit') ? true : false;
                // var modal = $(this).showModalFlat('INFORMATION', '편집한 내용 저장 시 실 사이트에도 반영이 됩니다.<br>저장 하시겠습니까?', true, true, function() {
                //     modal.modal('hide');
                    $.products.save(go);
                // });
            });
            $(document).on('click', '.gallery-blocks .gallery-name[data-gallery-id]:not(.disabled)', function(e) {
                e.stopPropagation();
                var id = $(this).attr('data-gallery-id');
                if(typeof id == 'undefined') return false;
                $.gallery.block_id = id;
                $('#prod-pid').val(id);
                if(LUX) {
                    setProductParams({'category_no' : $(this).attr('data-category')});
                }
                clearLocalStorage();
                $.gallery.show($.gallery.block_id);
            });
            $(document).on('click','.gallery-items-loadmore', function(e) {
                var id = $(this).attr('data-pid'),
                    page = Number($(this).attr('data-page')),
                    cate_str = $(this).attr('data-category-str');
                page++;
                $.gallery.list(id,page,cate_str);
            });
            $(document).on('hover','.gallery-items .table-item', function(e) {
                if (e.type == "mouseenter") {
                    if(!LUX && $('.gallery-modal').attr('data-pid') != undefined) $(this).find('.item-handle').show();
                    $(this).find('.item-edit').show();
                } else { // mouseleave
                    if(!LUX) $(this).find('.item-handle').hide();
                    $(this).find('.item-edit').hide();
                    $(this).find('.item-edit').find('.item-submenu').hide();
                }
            });
            $(document).on('click', '.gallery-modal .item-edit li', function(e) {
                $('.item-submenu').hide();
                $('.submenu').removeClass('open');
                var $submenu = $(this).find('.item-submenu'),
                    display = $submenu.css('display');
                (display == 'none') ? $submenu.css('display','block') : $submenu.css('display','none');
                return;
            });
            $(document).on('click', '.gallery-modal .product-item-edit li', function(e) {
                var group = ($('.table-item').length) ? '.table-item' : '.gallery-items .item';
                var mode = $(this).attr('data-mode'),
                    seq = $(this).parent().attr('data-seq'),
                    // page = $('.gallery-modal').attr('data-page'),
                    page = $(group).attr('data-page'),
                    config_url = (CONFIG_URL) ? '_config' : 'config';
                if(typeof seq == 'undefined' || seq == '' || typeof page == 'undefined' || page == '') {
                    alert('Undefined product seq or page!');
                    return false;
                }
                page = encodeURIComponent(page);
                if(mode == 'prodInfo') {
                    $.gallery.item_of_page = $(this).parents('.table-item').attr('data-page');
                    $.products.add(seq);
                } else {
                    if(LUX) page = '_product';
                    // location.href = '/'+config_url+'/page/'+page+'/view/'+seq;
                    $.detail.open('/'+config_url+'/page/'+page+'/view/'+seq, mode);
                }
            });
            $(document).on('click', '.td-check input[type="checkbox"]', function(e) {
                e.stopPropagation();
                var seq = $(this).parents('.table-item').attr('data-seq'),
                    seq_idx = ($.gallery.seqs).indexOf(seq),
                    disabled = false, visible_button = false, no_price = false;
                    // disabled = ($(this).parents('.table-item').attr('data-product') == "false") ? true : false;

                if($(this).is(':checked')) {
                    $(this).parents('.table-item').addClass('ui-selected return');
                    if(typeof seq != 'undefined')
                        $.gallery.seqs.push(seq);
                    $('.gallery-toolbar').addClass('hide_col');
                } else {
                    if(seq_idx > -1) ($.gallery.seqs).splice(seq_idx,1);
                    $(this).parents('.table-item').removeClass('ui-selected return');
                    if($.gallery.seqs.length == 0) $('.gallery-toolbar').removeClass('hide_col');
                }
                stickyToolbar();

                $.each($('.gallery-items .table-item.ui-selected'), function(i,v) {
                    if($(this).attr('data-product') == "false") disabled = true;
                    if($(this).attr('data-out-datetime') == "1") visible_button = true;                    
                    if($(this).attr('data-pricechk') == "false") no_price = true;
                });

                $('.gallery-items .table-item > div').addClass('hide-text');
                $('.table-toolbar > li').removeClass('open').find('.item-submenu').hide();
                $('.gallery-view-count').removeClass('open').find('.view-submenu').hide();

                if($('.gallery-items .table-item.ui-selected').length == 0) {
                    $.gallery.seqs = [];
                    $('.gallery-toolbar').removeClass('hide_col');
                    $('.gallery-items .table-item > div').removeClass('hide-text');
                    $('.table-toolbar .toolbar-cmd').addClass('hide'); 
                    $('.table-toolbar .toolbar-cmd i[data-glseq]').attr('data-glseq','');
                    $('.table-toolbar .toolbar-cmd i[data-cmd="link"]').attr('data-glink','').attr('data-glink-target','');
                    $('.table-toolbar .toolbar-cmd i[data-cmd="visible"]').attr('data-visible','0').text($.lang[LANG]['editor.gallery.icon.visible.off']);
                    $('.gallery-toolbar').addClass('hide');
                    $('.gallery-items .item-header').removeClass('hide');
                } else { 
                    var firstItem = $('.gallery-items .table-item.ui-selected').eq(0),
                        first_seq = firstItem.attr('data-seq'),
                        link = firstItem.attr('data-link'),
                        target = firstItem.attr('data-target'),
                        visible = firstItem.attr('data-visible'),
                        vstr = (visible == '1') ? $.lang[LANG]['editor.gallery.icon.visible.on'] : $.lang[LANG]['editor.gallery.icon.visible.off'];
                    if(visible_button) {
                        $('.table-toolbar .toolbar-cmd.toolbar-visible').addClass('disabled');
                    } else $('.table-toolbar .toolbar-cmd.toolbar-visible').removeClass('disabled');
                    if($.gallery.block_id == -1) {
                        $('.table-toolbar .toolbar-cmd.toolbar-copy').addClass('disabled');
                    }
                    $('.table-toolbar .toolbar-cmd').removeClass('hide');
                    $('.table-toolbar .toolbar-cmd i[data-glseq]').attr('data-glseq',first_seq);
                    $('.table-toolbar .toolbar-cmd i[data-cmd="link"]').attr('data-glink',link).attr('data-glink-target',target);
                    $('.table-toolbar .toolbar-cmd i[data-cmd="visible"]').attr('data-visible',visible).text(vstr);
                    $('.gallery-toolbar').removeClass('hide');
                    $('.gallery-items .item-header').addClass('hide');
                }
                (no_price) ? $('.product-cmd').not('.toolbar-org-price').not('.toolbar-stock').addClass('no_price') : $('.product-cmd').removeClass('no_price');
                (disabled) ? $('.product-cmd').addClass('disabled') : $('.product-cmd').removeClass('disabled');
                if($('.gallery-modal').attr('data-pid') == undefined) {
                    $('.toolbar-sort.item-sort').addClass('disabled');
                }
                if($('.gallery-modal .table-item').length == $('.gallery-modal .table-item .td-input:checked').length) $('.table-toolbar .check-all').prop('checked', true);
                $.gallery.setNumber();
            });
            $(document).on('change','.category-onoff-check', function(e) {
                var gc = $(this).prop('checked'),
                    g_category_onoff = (gc) ? 'ON' : 'OFF',
                    settings = {
                        category_display : g_category_onoff
                    };
                $.gallery.update = true;
                if(gc) {
                    $('.gallery-category-menu').removeClass('hide');
                    $('.category-title-str').addClass('on');
                    $('.td-category').removeClass('hide');
                } else {
                    $('.gallery-category-menu').addClass('hide');
                    $('.category-title-str').removeClass('on');
                    $('.td-category').addClass('hide');
                }
                $.post('/template/settings', {sid: SID, settings : JSON.stringify(settings), el: $.gallery.block_id}, function(data) {
                    checkError(data);
                    $.gallery.show($.gallery.block_id);
                }, 'json');
                
                var type = (typeof selectEL != 'undefined') ? getElementType() : 'ELEM';
                setLogs(type,'gallery.category.' + gc,'toggle-' + gc, type,'product-manager','el');
            });
            $(document).on('click','.toolbar-category ul.item-submenu li', function(e) {
                if(($.gallery.seqs).length) {
                    $(this).toggleClass('active');
                    var click_cate = $(this).text(),
                        cate_str = $('.toolbar-category ul.item-submenu li.active').map(function() { return $(this).text(); }).get(),
                        text_str = cate_str.join(),
                        data_str = '|' + text_str.replace(/\,/g,'|,|') + '|';

                    $.each($.gallery.seqs, function(i,v) {
                        if($('.gallery-modal').hasClass('shopping')) {
                            $('.table-item[data-seq="' + v + '"]').attr('data-category', data_str).find('.td-category').text(text_str).attr('data-original-title',text_str);
                            
                            if(text_str.indexOf(',') > -1) $('.table-item[data-seq="' + v + '"] .td-category').addClass('line');
                            else $('.table-item[data-seq="' + v + '"] .td-category').removeClass('line');
                        } else {
                            $('.gallery-items .item[data-seq="' + v + '"]').attr('data-category', data_str).find('.td-category').text(text_str);
                        }

                        $.post('/template/gallery/category', { sid : SID, s : cate_str, mode : 'gallery', seq : v }, function(r) {

                            if($('.element[data-id="' + $.gallery.block_id + '"] .gallery-category-nav li:nth-child(1)').hasClass('hide')) {
                                if($('.element[data-id="' + $.gallery.block_id + '"] .gallery-category-nav li.active a').text() == click_cate) {
                                    $.gallery.update = true;
                                }
                            }

                        }, 'json');
                    });
                }
            });
            $(document).on('click','.toolbar-sort ul.item-submenu li', function(e) {
                if(($.gallery.seqs).length) {
                    var group = ($('.table-item').length) ? '.table-item' : '.gallery-items .item';
                    $.gallery.move = $.gallery.seqs;
                    if($(this).hasClass('sort-top')) {
                        $.gallery.drag = $(group).first().attr('data-seq');
                        // $.gallery.seqs = [];
                        var modal = $(this).showModalFlat($.lang[LANG]['config.gallery.order.move'],$.lang[LANG]['editor.gallery.move'],true,true,function() {
                            modal.modal('hide');
                            // $.gallery.mv();
                            var spos = $('.gallery-modal').scrollTop();
                            $.processON('move gallery item(s)...');
                            $.ajax({
                                url: '/template/gallery/sort-top',
                                data: { sid : SID, seq : $.gallery.seqs, block_id : $.gallery.block_id },
                                dataType: 'json',
                                type: 'POST',
                                async: false,
                                cache: false,
                                success: function (data) {
                                    checkError(data);
                                    var p = $.gallery.pages;
                                    $.gallery.show($.gallery.block_id,p.page,$.gallery.category, function() {
                                        $.each(data.seqs, function(i,v) {
                                            $(group + '[data-seq="' + v + '"]').addClass('return');
                                        });
                                        setTimeout(function() { 
                                            $('.gallery-modal').scrollTop(spos); 
                                            $.processOFF();
                                        }, 500);
                                    });
                                    $.gallery.update = true;
                                    $.gallery.reset();
                                    $.processOFF();
                                }
                            });                            
                        }, 'cancel','ok','cl-cmmodal cl-s-btn w560 cl-p130 cl-p0',false, function() {
                            // cancel callback
                            $.gallery.seqs = $.gallery.move;
                        });
                    } else if($(this).hasClass('sort-bottom')) {
                        if($('.gallery-items-loadmore').length == 0) {
                            var last = $(group).last().attr('data-seq');
                            if($.gallery.seqs[0] == last) {
                                var s = (group == '.gallery-items .item') ? $.lang[LANG]['editor.gallery.select.front.last.1'] : $.lang[LANG]['editor.gallery.select.front.last.2'],
                                    contents2_str = (LANG =='ko') ? $.lang[LANG]['editor.gallery.select.contents.2'] : '';

                                $(this).showModalFlat($.lang[LANG]['config.gallery.order.move'], $.lang[LANG]['editor.gallery.select.contents.1'] + s + contents2_str, true, false, '', 'ok','','cl-cmmodal cl-s-btn w560 cl-p130 cl-p0 cl-okbtn-pbt70');
                                return false;
                            }
                        }

                        var modal = $(this).showModalFlat($.lang[LANG]['config.gallery.order.move'],$.lang[LANG]['editor.gallery.move'],true,true,function() {
                            var item = $(group).length,
                                cpage = Math.ceil(item/30),
                                spos = $('.gallery-modal').scrollTop();

                            modal.modal('hide');
                            $.processON('move gallery item(s)...');
                            $.ajax({
                                url: '/template/gallery/sort-bottom',
                                data: { sid : SID, seq : $.gallery.seqs, block_id : $.gallery.block_id },
                                dataType: 'json',
                                type: 'POST',
                                async: false,
                                cache: false,
                                success: function (data) {
                                    checkError(data);
                                    var p = $.gallery.pages;
                                    $.gallery.show($.gallery.block_id,p.page,$.gallery.category, function() {
                                        $.each(data.seqs, function(i,v) {
                                            $(group + '[data-seq="' + v + '"]').addClass('return');
                                        });
                                        setTimeout(function() { 
                                            $('.gallery-modal').scrollTop(spos); 
                                            $.processOFF();
                                        }, 500);
                                    });
                                    $.gallery.update = true;
                                    $.gallery.reset();
                                    $.processOFF();
                                }
                            });
                        }, 'cancel','ok','cl-cmmodal cl-s-btn w560 cl-p130 cl-p0', false, function() {
                            // cancel callback
                            $.gallery.seqs = $.gallery.move;
                        });
                    }
                }
            });
            $(document).on('click','.view-submenu li', function(e) {
                $.processON();

                var view = (typeof $(this).attr('data-view') != 'undefined' && $(this).attr('data-view')) ? $(this).attr('data-view') : 30;

                window.localStorage.setItem('gallery-product-view',view);
                $.gallery.show($.gallery.block_id,'',$.gallery.category,function() {
                    setTimeout(function() { 
                        $.processOFF();
                    }, 500);
                });
            });
            $(document).on('click', '.gallery-modal .edit-gallery-detail', function(e) {
                var seq = $(this).attr('data-seq'),
                    mode = $(this).attr('data-mode');
                var page = $('.gallery-modal').attr('data-page');
                var config_url = (CONFIG_URL) ? '_config' : 'config';
                if(typeof seq == 'undefined') return;
                // location.href = '/'+config_url+'/page/' + page + '/view/' + seq;
                $.detail.open('/'+config_url+'/page/' + page + '/view/' + seq, 'gallery');
            });
            $(document).on('click','.gallery-name-edit', function(e) {
                e.stopPropagation();
                $('.gallery-name-edit-input').remove();
                var v = $(this).parents('.gallery-name').text(),
                    s = '<div class="gallery-name-edit-input"><input type="text" class="gallery-name-edit-inputbox" value="' + v.trim() + '" maxlength="20"><div class="gallery-name-edit-close"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 12 12"><polygon points="12 0.71 11.29 0 6 5.29 0.71 0 0 0.71 5.29 6 0 11.29 0.71 12 6 6.71 11.29 12 12 11.29 6.71 6 "/></svg></div><div class="gallery-name-edit-save"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 15 10"><path d="M14.29 0L5.5 8.79 0.71 4 0 4.71l5.15 5.15C5.24 9.95 5.37 10 5.5 10s0.26-0.05 0.35-0.15L15 0.71 14.29 0z"/></svg></div></div>';
                $(this).parents('.gallery-name').append(s);
            });
            $(document).on('click','.gallery-name-edit-inputbox',function(e) {
                e.stopPropagation();
            });
            $(document).on('keypress', '.gallery-name-edit-inputbox', function(e) {
                var keyCode = e.keyCode,
                    blockname = $(this).val().trim();

                if(keyCode == 13) {
                    saveGalleryBlockName($(this), blockname);
                }
            });
            $(document).on('click','.gallery-name-edit-save',function(e) {
                e.stopPropagation();
                var blockname = $('.gallery-name-edit-inputbox').val().trim(),
                    $input = $('.gallery-name-edit-inputbox');

                if(checkEmojis(blockname)) {
                    e.preventDefault();
                    var open_el = $(this).closest('.gallery-blocks').find('.btn-group'),
                        focus_el = $(this).closest('.gallery-name-edit-input').find('.gallery-name-edit-inputbox');
                    errorEmojisModal('','','',function() {
                        open_el.addClass('open');
                        focus_el.focus();
                    });
                    return false;
                }
                saveGalleryBlockName($input, blockname);
            });
            $(document).on('click','.gallery-name-edit-close',function(e) {
                e.stopPropagation();
                $(this).parents('.gallery-name-edit-input').remove();
            });
        },
        cp : function() {
            var seqs = $.gallery.copy,
                page = $('.gallery-modal').attr('data-page');

            seqs = seqs.reverse();
            if(typeof seqs.length == 0 || seqs == '') {
                alert('Invalid variable');
                return false;
            }
            var modal = $(this).showModalFlat($.lang[LANG]['editor.gallery.clone.title'],($.gallery.mode == 'shopping' ? $.lang[LANG]['editor.gallery.shoppingclone' + (LUX ? '.lux' : '')] : $.lang[LANG]['editor.gallery.clone']),true,true,function() {
                var count = seqs.length;

                modal.modal('hide');
                var group = ($('.table-item').length) ? '.table-item' : '.gallery-items .item',
                    item = $(group).length,
                    cpage = Math.ceil(item/30),
                    spos = $('.gallery-modal').scrollTop();

                $.processON('copy gallery item(s)...');
                // console.log('ModalPlugin cp ');
                // console.log(seqs);
                $.ajax({
                    url: '/template/gallery/copy',
                    data: { s: seqs, sid : SID, page : page, block_id : $.gallery.block_id },
                    dataType: 'json',
                    type: 'POST',
                    async: true,
                    cache: false,
                    success: function (data) {
                        checkError(data);
                        // console.log(data);
                        galleryStatusInit();
                        $.gallery.copy = [];
                        var type = (typeof selectEL != 'undefined') ? getElementType() : 'ELEM';
                        setLogs(type,'gallery.item.clone','clone',type,'product-manager','el');

                        $.gallery.show($.gallery.block_id,cpage,$.gallery.category,function() {
                            $.each(data.r, function(i,v) {
                                // console.log(v.seq);
                                $(group + '[data-seq="' + v.seq + '"]').addClass('return');
                            });
                            setTimeout(function() { 
                                $('.gallery-modal').scrollTop(spos); 
                                $.processOFF();
                            }, 500);
                        });
    
                        $.gallery.update = true;                        
                    }
                });
            }, 'cancel','ok','cl-cmmodal cl-s-btn w560 cl-p130 cl-p0');
        },
        mv : function(func) {
            var seqs = $.gallery.move,
                page = $('.gallery-modal').attr('data-page');
            // seqs = seqs.reverse();
            if(typeof seqs.length == 0 || seqs == '') {
                alert('Invalid variable');
                return false;
            }
            clicking = false;
            var group = ($('.table-item').length) ? '.table-item' : '.gallery-items .item';

            if($.gallery.drag) {
                if(($.gallery.drag == seqs[0] || 
                    $.gallery.drag == $(group + '[data-seq="' + seqs[0] + '"]').next().attr('data-seq')) ||
                    $.gallery.drag == $(group + '[data-seq="' + seqs[0] + '"]').next().hasClass('prev')) {
                    if($('.clone-item').length) {
                        $('.clone-item').remove();
                        // $.gallery.seqs = [];
                        return false;
                    } else {
                        if($('.item-sort').hasClass('open')) {
                            var s = (group == '.gallery-items .item') ? $.lang[LANG]['editor.gallery.select.front.first.1'] : $.lang[LANG]['editor.gallery.select.front.first.2'],
                                contents2_str = (LANG =='ko') ? $.lang[LANG]['editor.gallery.select.contents.2'] : '';
                            $.gallery.seqs = $.gallery.move;
                            $(this).showModalFlat($.lang[LANG]['config.gallery.order.move'], $.lang[LANG]['editor.gallery.select.contents.1'] + s + contents2_str, true, false, '', 'ok','','cl-cmmodal cl-s-btn w560 cl-p130 cl-p0 cl-okbtn-pbt70');
                            return false;
                        }
                    }
                }
            }
            var count = seqs.length,
                selected = $.gallery.drag;

            var item = $(group).length
                cpage = Math.ceil(item/30),
                spos = $('.gallery-modal').scrollTop();

            // modal.modal('hide');
            $.processON('move gallery item(s)...');
            $.ajax({
                url: '/template/gallery/move',
                data: { s: seqs, sid : SID, page : page, block_id : $.gallery.block_id, selected : selected, last : $.gallery.last },
                dataType: 'json',
                type: 'POST',
                async: true,
                cache: false,
                success: function (data) {
                    checkError(data);
                    $.gallery.update = true;
                    $.gallery.drag = '';
                    $.gallery.last = '';
                    if(typeof func == 'function') {
                        func();
                    } else {
                        $.gallery.show($.gallery.block_id,cpage,$.gallery.category, function() {
                            $.each(data.seqs, function(i,v) {
                                $(group + '[data-seq="' + v + '"]').addClass('return');
                            });
                            setTimeout(function() { 
                                $('.gallery-modal').scrollTop(spos); 
                                $.processOFF();
                            }, 500);
                        });
                    }

                }
            });
        },
        del : function() {
            var seqs = $.gallery.delete,
                page = $('.gallery-modal').attr('data-page'),
                pid = $('.gallery-modal').attr('data-pid'),
                total = seqs.length,
                title = (LANG == 'ko') ? '갤러리 데이터를 삭제중입니다...' : 'Deleting gallery data...',
                sub_des = (LANG == 'ko') ? '데이터를 삭제중입니다' : 'Deleting',
                loading = '<i class="fa fa-circle-o-notch fa-spin fa-3x fa-fw"></i> ';

            if(typeof seqs.length == 0 || seqs == '') {
                alert('Invalid variable');
                return false;
            }   
            var modal = $(this).showModalFlat($.lang[LANG]['config.delete'],$.lang[LANG]['editor.gallery.selected.1'] + (seqs.length) + $.lang[LANG]['editor.gallery.selected.2'] + $.lang[LANG]['editor.gallery.selected.delete'],true,true, function() {
                var count = seqs.length;
                modal.modal('hide');
                $.progressON(title);

                var group = ($('.table-item').length) ? '.table-item' : '.gallery-items .item',
                    item = $(group).length,
                    item = ((item - count) < 0) ? 1 : item - count;
                    cpage = Math.ceil(item/30),
                    spos = $('.gallery-modal').scrollTop(),
                    done = 0;

                $.each(seqs, function(i,v) {
                    $(group + '[data-seq="' + v + '"]').fadeOut(100, function() { $(this).remove(); });

                    var t = setTimeout(function() {
                        if(CANCEL) {
                            if(ABORT) {
                                // 리스트 갱신 작업
                                $.gallery.show($.gallery.block_id,cpage,$.gallery.category, function() {
                                    setTimeout(function() { 
                                        $.gallery.move = [];
                                        $('.gallery-modal').scrollTop(spos); 
                                        $.processOFF();
                                    }, 500);
                                });
                                ABORT = false;
                                $.progressOFF();
                            }
                            i=0; return false;
                        }
                        galleryDeleteItem(v,function(data) {
                            done++;
                            progress = parseInt((done / total) * 100,10);
                            $('.file-upload-progress .progress-bar').css('width',progress + "%");
                            $('.progressModal .info2').text(done.toString() + ' / ' + total.toString());

                            var d = data.data;
                            $.each(d, function(i,o) {
                                blockBookmarkDelete(o.sid,o.seq);
                            });

                            glItemDelete(v,page);
                            if(v==VIEW) $.gallery.unlink = true;

                            if(total == done) {
                                var type = getElementType();
                                setLogs(type,'gallery.item.delete','delete',type,'product-manager','el');
                                $.gallery.reset();
                                $.gallery.update = true;

                                $.gallery.show($.gallery.block_id,cpage,$.gallery.category, function() {
                                    setTimeout(function() { 
                                        $.gallery.move = [];
                                        $('.gallery-modal').scrollTop(spos); 
                                        $.progressOFF();
                                    }, 500);
                                });
                            } else {
                                moving = $(group + '[data-seq="' + seqs[i+1] + '"] .td-title .item-title-str').text();
                                if(moving == "") moving = sub_des;
                                $('.progressModal .info1').html(loading + moving);
                            }
                        });
                    },500*i);
                });
            }, 'cancel', 'ok', 'cl-cmmodal cl-s-btn w560 cl-p130 cl-p0');
        },
        show : function(id,page,category,func) {
            // if(typeof id == 'undefined' || !id) {
            //     alert('Undefined gallery ID');
            //     return false;
            // }

            if(typeof page =='undefined' || !page) page = 1;
            if(typeof category =='undefined') category = '';
            if(typeof id == 'undefined') id = '';
            // var params = ($('.gallery-modal').length) ? getProductParams() : getSearchURL();

            var params = getProductParams(),
                product_name = getStorageItem('gallery-product-name'),
                product_filter = getStorageItem('gallery-product-filter'),
                product_view = getStorageItem('gallery-product-view'),
                sort = getStorageItem('gallery-product-sort'),
                by = getStorageItem('gallery-product-by'),
                manager = (id == '' || id == -1) ? SID : '';

            $.gallery.seqs = [];
            $.gallery.block_id = (id == '') ? -1 : id;
            $.gallery.category = category;
            $.processON();
            $.ajax({
                type: 'POST',
                url : '/template/gallery/show',
                data :  { mode : 'show', id : id, page : page, category : category, params : params, manager : manager, product_name : product_name, product_filter : product_filter, product_view : product_view, sort : sort, by : by },
                dataType : 'json',
                async: true,
                cache: false,
                success : function(data) {
                    $.processOFF();
                    if(LUX && data.mode == 'shopping' && params) {
                        setProductParams(params);
                    }
                    if(data.error != 'undefined' && data.error) {
                        alert(data.error);
                        return false;
                    }
                    $.gallery.site_settings = data.settings;
                    // premium block
                    if( !$('#el-blockConfig').hasClass('open') && 
                        $('.element[data-id="' + $.gallery.block_id + '"][data-type="gallery"][data-type2="premium"]').length > 0 
                    ) {
                        stopGalleryJS($('.element[data-id="' + $.gallery.block_id + '"]'));
                    }

                    $.gallery.mode = data.mode;
                    $.gallery.SMENU = data.SMENU;
                    $.gallery.SFOLDER = data.SFOLDER;
                    $.gallery.valid_plan = data.valid_plan;
                    $.gallery.valid_type = data.valid_type;
                    $.gallery.one = data.one;
                    $.gallery.service = data.service;
                    $.gallery.block_el = ($.gallery.block_id == '-1') ? 'el_prod' : data.gallerys[$.gallery.block_id].el;
                    var $backdrop = $('<div id="dummy-drop" style="position:fixed;top:0;left:0;right:0;bottom:0;background-color:#fff;z-index:1039;"></div>');
                    if($('#dummy-drop').length == 0)
                        $('body').append($backdrop);
    
                    $('.gallery-modal').hide().remove();
                    $('#gallery-style').remove();
                    $('#gallery-modal-script').remove();
                    $m = $(data.r).hide();
                    $('body').append($m);
                    
                    if($.gallery.mode != 'shopping') $('.gallery-list-filter').remove();
                    if(data.name) $('.selected-gallery-name').text(data.name);
                    if(typeof id == 'undefined' || !id || id == -1) {
                        $('.gallery-category').addClass('product-all-items');
                        $('.gallery-category .category-title-str').hide();
                        $('.gallery-category .gallery-category-onoff').hide();
                        $('.gallery-blocks .all-items').addClass('active');
                        $('.gallery-block-select, .selected-gallery-name').text('전체상품');
                        $('.gallery-add-items').addClass('disabled gallery-need');
                    } else {
                        $('.gallery-blocks .all-items').removeClass('active');  
                        $('.gallery-category').show();
                        $('.gallery-category').removeClass('product-all-items');
                        $('.gallery-add-items').removeClass('disabled gallery-need');
                    }

                    $('.gallery-modal').attr('data-page',data.page).attr('data-pid',data.pid).attr('data-mode',data.mode).attr('data-category',data.category).attr('data-total',data.total);
                    (data.mode == 'shopping') ? $('.gallery-modal').addClass('shopping') : $('.gallery-modal .gallery-items').addClass('mod-gallery');
                    if(data.mode == 'shopping' && LUX) $('.gallery-modal').addClass('lux');
                    $('#gallery-name').text(data.name);
                    $('.gallery-add-items').attr('data-mode',data.mode).attr('data-page',data.page);
                    if(data.only_category == false) $('.gallery-add-items').hide();
                    (data.mode == 'shopping') ? $('.gallery-modal-title').text($.lang[LANG]['bc.tp.gallery-contents.shopping']) : $('.gallery-modal-title').text($.lang[LANG]['editor.block.gallery.title']);
                    $('.view-submenu li[data-view="' + data.view + '"]').addClass('active');
                    $('#gallery_view').text(data.view);
                    var icon = '';
                    $.gallery.blocks = []; var idx = 0, menu_name = '';
                    $.gallery.pages = [];
                    $.each(data.lists, function(i,v) {
                        $.gallery.blocks.push(v);
                        $.each(v, function(m, menus) {
                            $('.gallery-blocks').append('<ul class="menus" data-name="' + m + '"><li><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 4 8"><path d="m-.05-.06 4 4-4 4v-8z"/></svg> ' + m + '</li>');
                            if(menus.length) {
                                menu_name = m;
                                for(var key in menus) {
                                    var value = menus[key];
                                    switch(value.mode) {
                                        case 'shopping': icon = '<svg class="shopping" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 13 14"><path d="M9.82 2C9.4 0.84 8.3 0 7 0H6C4.7 0 3.6 0.84 3.18 2H0v12h13V2H9.82zM6 1h1c0.74 0 1.37 0.41 1.72 1H4.28C4.63 1.41 5.26 1 6 1zM12 13H1V3h2v3h1V3h5v3h1V3h2V13z"/></svg>　'; break;
                                        case 'project' : icon = '<svg class="project" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path d="M13 0H3v3H0v13h13v-3h3V3L13 0zM13 1.41L14.59 3H13V1.41zM1 15V4h8v3h3v8H1zM10 4.41L11.59 6H10V4.41zM15 12h-2V6l-3-3H4V1h8v3h3V12z"/><rect x="3" y="9" width="7" height="1"/><rect x="3" y="12" width="7" height="1"/></svg>　'; break;
                                        case 'gallery' : icon = '<svg class="gallery" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 13 13"><path d="M0 0v13h13V0H0zM12 1v7.29l-2-2 -2 2 -4-4 -3 3V1H12zM1 12V8.71l3-3 4 4 2-2 2 2V12H1z"/><circle cx="10" cy="3" r="1"/></svg>　'; break;
                                    }
                                    if(value.id == id) $.gallery.block_name = value.name;
                                    var gb_li_class = (value.id == id) ? 'active' : '',
                                        gb_li_attr = '';

                                    if(gb_li_class == 'active') $('.gallery-block-select').text(value.name);

                                    if(!value.isActive) {
                                        gb_li_class += 'disabled editor-upgrade-popup';
                                        gb_li_attr = 'data-mode="gallery.primeum"';
                                    }

                                    if(LUX) {
                                        gb_li_attr += ' data-category="' + value.lux_category_no + '" ';
                                    }
    
                                    var gb_li_html = '\
                                        <li class="gallery-name ' + gb_li_class + '" data-gallery-id="' + value.id + '" ' + gb_li_attr + '>\
                                            <span class="gallery-block-name">' + value.name + '</span>\
                                            <span class="f-right gallery-name-edit"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path d="M15.41 0.76l-0.17-0.17C14.85 0.2 14.34 0 13.83 0s-1.02 0.2-1.41 0.59L1 12l-1 4 4-1L15.41 3.59C16.2 2.8 16.2 1.54 15.41 0.76zM3.49 14.1l-2.11 0.53 0.53-2.11 8.95-8.95 1.59 1.59L3.49 14.1zM14.71 2.88l-1.56 1.56 -1.59-1.59 1.56-1.56C13.31 1.1 13.56 1 13.83 1s0.52 0.1 0.71 0.29l0.17 0.17C15.1 1.85 15.1 2.49 14.71 2.88z"/></svg></span>\
                                        </li>\
                                    ';
    
                                    $('.gallery-blocks ul[data-name="' + m + '"]').append(gb_li_html);
                                    cates = cates + '<li class="gallery-name" data-gallery-id="' + value.id + '">' + value.name + '</li>';
                                    // if(value.id == id) $.gallery.blocks[idx][menu_name].splice(k,1);
                                    $.gallery.pages[value.id] = menu_name;
                                }
                            }
                        });
                        idx++;
                    });

                    if((data.lists).length == 0) $('.gallery-modal .gallery-add-items').addClass('disabled');
                    var cates = '';
                    var show = (data.cate_onoff == 'ON') ? '' : 'hide';
                    if(show) $('.gallery-cog').addClass('hide');
                    $.each(data.category, function(i,v) {
                        var active = (data.cate_str == v) ? 'active' : '';
                        $('.gallery-category .gallery-category-onoff').before('<li class="category-text gallery-category-menu ' + show + ' ' + active + '">' + v + '</li>');
                        cates = cates + '<li>' + v + '</li>';
                        if(data.cate_str == '') {
                            $('.gallery-category > li:nth-child(2)').addClass('active');
                        }
                    });
                    $.gallery.cates = cates;
                    if(data.cate_onoff == 'ON') {
                        $('.category-onoff-check').prop('checked','checked');
                        $('.category-title-str').addClass('on');
                    } else {
                        $('.category-onoff-check').prop('checked','');
                        $('.gallery-category > li:nth-child(2)').addClass('hide');
                        // $('.gallery-category > li:last-child').addClass('hide');
                    }
                    var selected_category = '',
                        $tag = $('.gallery-modal > .container');

                    // lux shopping
                    if(LUX) {
                        $('.gallery-category').hide();
                        $tag.prepend('<div class="shop-filter-header open"></div>');
                        shopHeaderDisplay($tag.find('.shop-filter-header'),data);

                        $('.gallery-list-filter').hide();
                        $('.selected-gallery-name').hide();
                        $('.gallery-category').hide();
                    } else {
                        // shopping filter
                        if(data.mode == 'shopping') {                        
                            var s = '\
                                <ul class="filter">\
                                    <li data-val="all" class="active">전체</li>\
                                    <li data-val="on">판매중</li>\
                                    <li data-val="off">판매중지</li>\
                                    <li data-val="out">품절</li>\
                                    <li data-val="hide">숨김</li>\
                                    <li data-val="wait">판매예정</li>\
                                    <li data-val="end">판매종료</li>\
                                </ul>\
                            ';
                            $('.gallery-list-filter').append(s);
                        }
                    }

                    var keys = {'title' : '', 'date' : '', 'orig' : '', 'disc' : '', 'price' : ''},
                        keys_by = {'title' : '', 'date' : '', 'orig' : '', 'disc' : '', 'price' : ''},
                        checked = {'title' : '','date' : '', 'orig' : '', 'disc' : '', 'price' : ''},
                        icons = {
                            'title' : $.gallery.sort_icon_desc,
                            'date' : $.gallery.sort_icon_desc,
                            'orig' : $.gallery.sort_icon_desc,
                            'disc' : $.gallery.sort_icon_desc,
                            'price' : $.gallery.sort_icon_desc
                        };
                    switch(sort) {
                        case '' : break;
                        default : 
                            keys[sort] = 'sorted';
                            checked[sort] = '\
                                <span class="product-sort-checked">' + 
                                $.gallery.sort_icon_checked + '</span>\
                            ';
                        break;
                    }
                    if(sort) {
                        keys_by[sort] = by;
                        icons[sort] = (by == 'desc') ? $.gallery.sort_icon_desc : $.gallery.sort_icon_asc;
                    }

                    var filter = getStorageItem('gallery-product-filter');
                    if(filter != null && filter.length) {
                        $('.gallery-list-filter .filter li').removeClass('active');
                        $('.gallery-list-filter .filter li[data-val="' + filter + '"]').addClass('active');
                    }
                    var s = '<ul class="table-toolbar">';
                    // lux shopping
                    if(LUX) {
                        s = s + '<li class="checkbox-cmd toolbar-cmd hide"><i class="" data-glseq="" data-cmd="checkall"></i> <input type="checkbox" class="check-all"></li>';
                        s = s + '<li class="toolbar-copy toolbar-cmd hide"><i class="" data-glseq="" data-cmd="copy"></i>' + $.lang[LANG]['editor.gallery.icon.clone'] + '</li>';
                        s = s + '<li class="toolbar-margin toolbar-cmd hide"><i class="" data-glseq="" data-cmd="margin"></i>마진율</li>';
                        s = s + '<li class="toolbar-delete toolbar-cmd hide"><i class="" data-glseq="" data-cmd="delete"></i>' + $.lang[LANG]['editor.gallery.icon.delete'] + '</li>';
                    } else {
                        s = s + '<li class="checkbox-cmd toolbar-cmd hide"><i class="" data-glseq="" data-cmd="checkall"></i> <input type="checkbox" class="check-all"></li>';
                        s = s + '<li class="toolbar-org-price product-cmd toolbar-cmd hide"><i class="" data-glseq="" data-discount="" data-discount-target="" data-cmd="org-price"></i>' + $.lang[LANG]['editor.gallery.icon.org.price'] + '</li>';
                        s = s + '<li class="toolbar-disc-price product-cmd toolbar-cmd hide"><i class="" data-glseq="" data-discount="" data-discount-target="" data-cmd="disc-price"></i>' + $.lang[LANG]['editor.gallery.icon.disc.price'] + '</li>';
                        s = s + '<li class="toolbar-sale-price product-cmd toolbar-cmd hide"><i class="" data-glseq="" data-discount="" data-discount-target="" data-cmd="sale-price"></i>' + $.lang[LANG]['editor.gallery.icon.sale.price'] + '</li>';
                        s = s + '<li class="toolbar-stock product-cmd toolbar-cmd hide"><i class="" data-glseq="" data-discount="" data-discount-target="" data-cmd="stock"></i>' + $.lang[LANG]['editor.gallery.icon.stock'] + '</li>';

                        if(!$('.gallery-modal .gallery-category .gallery-all').hasClass('hide')) {
                            s = s + '<li class="toolbar-category toolbar-cmd submenu hide"><i class="" data-glseq="" data-cmd="category"></i>' + $.lang[LANG]['editor.block.gallery.category.change'] + ' <i class="fa fa-caret-down" aria-hidden="true"></i>';
                            s = s + '<ul class="item-submenu">' + cates + '</ul>';
                            s = s + '</li>';
                        }                        

                        s = s + '<li class="toolbar-sort item-sort toolbar-cmd submenu hide">' + $.lang[LANG]['editor.gallery.icon.order'] + ' <i class="fa fa-caret-down" aria-hidden="true" data-glseq="" data-cmd="item-sort"></i>\
                                    <ul class="item-submenu">\
                                        <li class="sort-top">' + $.lang[LANG]['editor.gallery.icon.order.shopping.front'] + '</li>\
                                        <li class="sort-bottom">' + $.lang[LANG]['editor.gallery.icon.order.shopping.end'] + '</li>\
                                    </ul>\
                                </li>';
                        // s = s + '<li class="toolbar-discount toolbar-cmd hide"><i class="" data-glseq="" data-discount="" data-discount-target="" data-cmd="discount"></i>' + $.lang[LANG]['editor.gallery.icon.discount'] + '</li>';

                        s = s + '<li class="toolbar-badge toolbar-cmd hide"><i class="" data-glseq="" data-badge="" data-badge-target="" data-cmd="badge"></i>' + $.lang[LANG]['editor.gallery.icon.badge'] + '</li>';
                                               
                        s = s + '\
                                <li class="toolbar-visible toolbar-cmd hide"><i class="" data-glseq="" data-visible="" data-cmd="visible">' + $.lang[LANG]['editor.gallery.icon.visible.off'] + '</i></li>\
                                <li class="toolbar-move toolbar-cmd hide"><i class="" data-glseq="" data-visible="" data-cmd="move">' + $.lang[LANG]['editor.block.gallery.item.move'] + '</i></li>\
                                <li class="toolbar-link toolbar-cmd hide"><i class="" data-glseq="" data-glink="" data-glink-target="" data-cmd="link"></i>' + $.lang[LANG]['editor.gallery.icon.link'] + '</li>\
                                <li class="toolbar-copy toolbar-cmd hide"><i class="" data-glseq="" data-cmd="copy"></i>' + $.lang[LANG]['editor.gallery.icon.clone'] + '</li>\
                                <li class="toolbar-delete toolbar-cmd hide"><i class="" data-glseq="" data-cmd="delete"></i>' + $.lang[LANG]['editor.gallery.icon.delete'] + '</li>\
                        ';
                        if(id == '') {
                            s = s + '<li class="dummy dm-gallery all">갤러리</li><li class="dummy dm-date all">등록일<span class="product-sort ' + keys['date'] + '" data-sort="date" data-by="' + keys_by['date'] + '">' + icons['date'] + '</span>' + checked['date'] + '</li><li class="dummy dm-category">카테고리</li>';
                        } else {
                            s = s + ((data.cate_onoff == 'ON' || !id || id == -1) ? 
                                '<li class="dummy dm-date select">등록일<span class="product-sort ' + keys['date'] + '" data-sort="date" data-by="' + keys_by['date'] + '">' + icons['date'] + '</span>' + checked['date'] + '</li><li class="dummy dm-category">카테고리</li>' : 
                                '<li class="dummy dm-date">등록일<span class="product-sort ' + keys['date'] + '" data-sort="date" data-by="' + keys_by['date'] + '">' + icons['date'] + '</span>' + checked['date'] + '</li>');
                        }
                        s = s + '\
                                <li class="dummy dm-orig-price">정가<span class="product-sort ' + keys['orig'] + '" data-sort="orig" data-by="' + keys_by['orig'] + '">' + icons['orig'] + '</span>' + checked['orig'] + '</li>\
                                <li class="dummy dm-discount">할인율<span class="product-sort ' + keys['disc'] + '" data-sort="disc" data-by="' + keys_by['disc'] + '">' + icons['disc'] + '</span>' + checked['disc'] + '</li>\
                                <li class="dummy dm-price">판매가<span class="product-sort ' + keys['price'] + '" data-sort="price" data-by="' + keys_by['price'] + '">' + icons['price'] + '</span>' + checked['price'] + '</li>\
                                <li class="dummy dm-quantity">재고</li>\
                                <li class="dummy dm-status">상태</li>\
                            </ul>\
                        ';
                    }
                    var $tool_back = $('<div class="toolbar sort-disabled sticky">' + s + '</div>');
                    if(data.mode == 'shopping') {
                        $('.gallery-toolbar').append($tool_back).addClass('hide');
                    }

                    var badge_settings = (data.badge_settings !== undefined && data.badge_settings)? JSON.stringify(data.badge_settings) : '{}';
                    var badge_imgs = (data.badge_imgs !== undefined && data.badge_imgs)? data.badge_imgs : '';
                    localStorage.setItem('badge_settings', badge_settings);
                    localStorage.setItem('badge_imgs', badge_imgs);
                    localStorage.setItem('before_badge_settings', badge_settings);

                    var num = (page > 1) ? data.total : data.total - ((page-1) * data.view);
                    if((data.items).length && data.mode == 'shopping') {
                        var item_header = '\
                        <div class="item-header sticky">\
                            <div class="td-handle"></div>\
                            <div class="td-check"><input type="checkbox" class="check-all"></div>\
                            <div class="td-number">번호</div>\
                            <div class="td-img"></div>\
                            <div class="td-title">제목<span class="product-sort ' + keys['title'] + '" data-sort="title" data-by="' + keys_by['title'] + '">' + icons['title'] + '</span>' + checked['title'] + '\
                            </div>\
                        ';

                        item_header+= (typeof id == 'undefined' || !id || id == -1) ? '<div class="td-gallery">갤러리</div>' : '';
                        item_header+='\
                            <div class="td-date">등록일<span class="product-sort ' + keys['date'] + '" data-sort="date" data-by="' + keys_by['date'] + '">' + icons['date'] + '</span>' + checked['date'] + '</div>\
                        ';
                        item_header+= (data.cate_onoff == 'ON' || !id || id == -1) ? '<div class="td-category">카테고리</div>' : '';
                        item_header+= '\
                            <div class="td-orig-price">정가<span class="product-sort ' + keys['orig'] + '" data-sort="orig" data-by="' + keys_by['orig'] + '">' + icons['orig'] + '</span>' + checked['orig'] + '</div>\
                            <div class="td-discount">할인율<span class="product-sort ' + keys['disc'] + '" data-sort="disc" data-by="' + keys_by['disc'] + '">' + icons['disc'] + '</span>' + checked['disc'] + '</div>\
                            <div class="td-price">판매가<span class="product-sort ' + keys['price'] + '" data-sort="price" data-by="' + keys_by['price'] + '">' + icons['price'] + '</span>' + checked['price'] + '</div>\
                            <div class="td-quantity">재고</div>\
                            <div class="td-status">상태</div>\
                        </div>\
                        ';
                        $('.gallery-items').append(item_header);
                    }

                    if(window.localStorage.getItem('product-gallery-closed') == 'true' || $(document).width() < 1440) {
                        var $list = $('.product-gallery-list'),
                            $category = $('.gallery-category'),
                            $more = $('.gallery-items-loadmore'),
                            $items = $('.gallery-items'),
                            $toggle = $('.product-gallery-list-toggle'),
                            $pagination = $('.pagination-wrap'),
                            $filter = $('.gallery-list-filter'),
                            $name = $('.selected-gallery-name'),
                            $lux_filter = $('.shop-filter-header');
                        $list.removeClass('open');
                        $category.removeClass('open');
                        $more.removeClass('open');
                        $items.removeClass('open');
                        $toggle.removeClass('open');
                        $pagination.removeClass('open');
                        $filter.removeClass('open');
                        $name.removeClass('open');
                        $lux_filter.removeClass('open');
                    }
                    $.each(data.items, function(i,v) {
                        var settings = (v.gsettings) ? $.parseJSON(v.gsettings) : {},
                            link = (typeof settings.glink != 'undefined') ? settings.glink : '',
                            link_icon = (typeof settings.glink != 'undefined' && settings.glink) ? clSVG('gallery-link','20','20',true,'info-link') : '',
                            target = (typeof settings.glink_target != 'undefined') ? settings.glink_target : '',
                            cp_class = ($.inArray(v.seq,$.gallery.copy) > -1) ? ' active copy' : '',
                            mv_class = ($.inArray(v.seq,$.gallery.move) > -1) ? ' active move' : '',
                            invisible = (v.visible == '1') ? true : false;
                            // file = ((v.image).indexOf('googleusercontent') > -1) ? v.image : v.url
                            imgPATH = (typeof settings.storage == 'undefined') ? RPATH : settings.storage,
                            // src_s250 = getServeImage(v.image,'250',imgPATH);
                            src_s250 = v.url;

                        link = Base64.decode(link);
                        if(data.mode == 'shopping') {
                            var yet = (v.price == null) ? 'yet' : '';
                            $table = $('<div class="table-item ' + yet + '" data-page="' + v.page + '" data-product="' + v.is_product + '" data-pos="' + v.pos + '" data-page="' + v.page + '" data-pid="' + v.pid + '" data-seq="' + v.seq + '" data-link="' + link + '" data-target="' + target + '" data-visible="' + v.visible + '" data-category="' + v.category + '" data-out-datetime="off" data-pricechk="' + v.price_check + '">');
                            // lux
                            if(LUX) {
                                v.sale = (v.price < v.sale) ? v.sale : '';
                                if(v.prod_case) $table.attr('data-pcase',v.prod_case);
                            }

                            var title = (v.title) ? v.title : '상품명을 입력하세요',
                                price = (v.price != null && v.price !== '') ? addCommas(v.price) : '-',
                                sale = (v.sale != null && v.sale !== '') ? addCommas(v.sale) : '-',
                                soldout = '',
                            
                            quantity = (v.quantity_on == 'on' && v.quantity) ? addCommas(v.quantity) : 0;
                            var discount_settings = (settings.discount)? settings.discount : '';
                            var discount_rate = (discount_settings.rate !== undefined && discount_settings.rate)? discount_settings.rate : '';
                            var discount_unit = (discount_settings.unit !== undefined && discount_settings.unit)? discount_settings.unit : '';

                            var discount = addCommas(discount_rate) + discount_unit;
                            var use_badge = (settings.use_badge)? settings.use_badge : '';
                            var status = '';

                            if(invisible) $table.addClass('invisible');

                            var is_soldout = false,
                                is_soldout_label = false,
                                saleStatus = '',
                                badgeList = '';

                            quantity = (v.quantity_on == 'off' || v.quantity_on == null)  ? '-' : quantity;

                            if(LUX) {
                                if(v.soldout) is_soldout = is_soldout_label = true;
                            } else {
                                if(v.quantity_on == 'off' || v.quantity_on == null || v.quantity_on == '') {
                                    if(v.status == 'off' || v.status == '') is_soldout = true;
                                } else {
                                    if(v.status == 'off' || v.status == '') is_soldout = true;
                                    if(v.quantity == 0) is_soldout = is_soldout_label = true;
                                }
                                if(v.status == 'lim') {
                                    saleStatus = '<span class="item-limit" data-toggle="tooltip" data-placement="top" data-original-title="' + v.sales_start + ' ~ ' + v.sales_end + '">기간한정판매</span>';
                                    $table.attr('data-out-datetime', (v.sale_now) ? '0' : '1');
                                }

                                if(use_badge) {
                                    var badge_settings = $.parseJSON(localStorage.getItem('badge_settings'));
                                    badgeList = drawBadgeList(use_badge, badge_settings);
                                }
                            }
                            if(is_soldout) {
                                $table.addClass('soldout');
                                if(is_soldout_label) soldout = '<span class="item-soldout">품절</span>';
                            }

                            switch(v.status) {
                                case "on": status = "판매중"; break;
                                case "off": status = "판매중지"; break;
                                default: status = "판매중지"; break;
                            }
                            // if(v.quantity_on == 'on' && v.quantity == 0) status = "품절";
                            if(sale == '') sale = price;
                            if(price == 0 && sale == 0) {
                                v.sale_per = 0;
                                sale = price;
                            }
                            if(invisible) $table.addClass('invisible');

                            if(LUX) {
                                var margin_str = (v.prod_case == 'O' || v.price_sync == 'F') ? '' : '<span class="margin-info">마진율 <span class="rate">' + v.margin.rate + '</span>% + <span class="add">' + addCommas(v.margin.value) + '</span> = 마진금액 <span class="price" data-supply="' + v.supply_price + '">' + addCommas(v.margin_price) + '</span>원</span/>',
                                    add_info = '\
                                <div class="add-info">\
                                    <span class="brand">' + v.brand_name + '</span/>\
                                    <span class="sale-rate" data-retail="' + v.retail_price + '">' + ((v.price < v.sale) ? '할인율 <span class="rate">' + v.sale_rate + '</span>%' : '') + '</span/>\
                                    '+ margin_str + '\
                                </div>';
                                soldout += add_info;
                            }
    
                            var empty_title = (v.title == '' || price == '-') ? ' empty' : '';
                            var s = '\
                                <div class="td-handle"><div class="item-handle"><img src="https://storage.googleapis.com/i.addblock.net/handle.png"></div></div>\
                                <div class="td-check"><input type="checkbox" name="item_check[]" class="td-input" data-ownproduct="' + (LUX && v.seq >= 1000000000 ? 'Y' : 'N') + '"></div>\
                                <div class="td-number">' + (num - i) + '</div>\
                                <div class="td-img"><img src="' + src_s250 + '" class="img-responsive">' + link_icon + '</div>\
                                <div class="td-title' + empty_title + '"><span class="item-title-str">' + title + '</span>' + saleStatus + badgeList + soldout +'\
                                    <ul class="product-item-edit" data-seq="' + v.seq + '">\
                                        <li class="edit-gallery-item" data-mode="prodDetail">'+ $.lang[LANG]['editor.block.gallery.product.detail'] +'</li>\
                                        <li class="edit-gallery-item" data-mode="prodInfo">'+ $.lang[LANG]['editor.block.gallery.product.info'] +'</li>\
                                    </ul>\
                                </div>\
                                ';
                            if(typeof id == 'undefined' || !id || id == -1)
                                if(typeof data.gallerys[v.pid] != 'undefined')
                                    s+= '<div class="td-gallery"><span title="' + data.gallerys[v.pid].title + '" alt="' + data.gallerys[v.pid].title + '">' + data.gallerys[v.pid].title + '</span></div>';
                                else 
                                    s+= '<div class="td-gallery"></div>';

                            s+= '<div class="td-date">' + v.datetime2 + '</div>';
                            if(LUX) {
                                s+= '\
                                <div class="td-category">' + v.category_name + '</div>\
                                ';
                            } else {
                                if(typeof data.gallerys[v.pid] != 'undefined') {
                                    s+= '\
                                    <div class="td-category' + empty_title + ((data.cate_onoff == 'OFF') ? ' hide' : '') + ((v.item_category.indexOf(',') > -1) ? ' line' : '') + '">' + ((data.gallerys[v.pid].cate_onoff == 'ON') ? v.item_category : '') + '</div>\
                                    ';
                                } else {
                                    s+= '\
                                    <div class="td-category' + empty_title + ((data.cate_onoff == 'OFF') ? ' hide' : '') + ((v.item_category.indexOf(',') > -1) ? ' line' : '') + '"></div>\
                                    ';
                                }
                            }
                            var edit_button = '', str_quantity = '', hint_quantity = '';
                                quantity_need = (v.quantity_on == 'on' && (parseInt(uncomma(quantity)) < 6 || parseInt(uncomma(v.quantity_add_op)) < 6)) ? '<span class="need">' + ((v.add_options == true) ? $.gallery.info_icon_option_true : $.gallery.info_icon_option_false) + '</span>' : '';
                            if(v.quantity_on == 'on') {
                                if(v.normal_options == false && v.add_options == false) {
                                    edit_button = '<div class="edit-button">' + $.gallery.edit_icon + '</div><div class="close-button" data-val="' + quantity + '">' + $.gallery.close_icon + '</div>';
                                } else {
                                    edit_button = '<div class="edit-button conf">' + $.gallery.edit_icon + '</div>';
                                }
                            }

                            str_quantity = (v.add_options == true && v.quantity_on == "on") ? quantity + '|' + addCommas(v.quantity_add_op) : addCommas(quantity);
                            hint_quantity = (v.add_options == true && v.quantity_on == "on") ? ' data-toggle="tooltip" data-html="true" data-placement="top" data-original-title="일반 재고 옵션 : ' + quantity + '<br>추가 옵션 재고 : ' + addCommas(v.quantity_add_op) + '"' : '';
                            var product_status = status;
                            if(v.status == 'lim') {
                                product_status = ((v.sale_now) ? '판매중' : (v.sale_fin) ? '판매종료' : '판매예정'); 
                                if(v.sale_now) product_status = '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-clock" viewBox="0 0 16 16"><path d="M8 3.5a.5.5 0 0 0-1 0V9a.5.5 0 0 0 .252.434l3.5 2a.5.5 0 0 0 .496-.868L8 8.71z"/><path d="M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16m7-8A7 7 0 1 1 1 8a7 7 0 0 1 14 0"/></svg> ' + product_status;
                            }
                            var status_select = changeStatus(v.status, v.seq);
                            if(LUX) {
                                s+= '\
                                    <div class="td-orig-price' + empty_title + '">' + sale + '</div>\
                                    <div class="td-discount' + empty_title + '">' + (LUX ? v.sale_rate : v.sale_per) + '</div>\
                                    <div class="td-price' + empty_title + '">' + price + '</div>\
                                    <div class="td-quantity' + empty_title + '">' + quantity_need  + str_quantity + '</div>\
                                    <div class="td-status">' + product_status + '</div>\
                                ';
                            } else {
                                var sale_per = (v.sale_per) ? v.sale_per : ((typeof v.sale_per === 'number') ? 0 : '-');
                                s+= '\
                                    <div class="td-orig-price' + empty_title + '"><span class="prev-value">' + sale + '</span><div class="edit-button">' + $.gallery.edit_icon + '</div><div class="close-button" data-val="' + sale + '">' + $.gallery.close_icon + '</div></div>\
                                    <div class="td-discount' + empty_title + '"><span class="prev-value">' + sale_per + '</span><div class="edit-button">' + $.gallery.edit_icon + '</div><div class="close-button" data-val="' + (LUX ? v.sale_rate : sale_per) + '">' + $.gallery.close_icon + '</div></div>\
                                    <div class="td-price' + empty_title + '"><span class="prev-value">' + price + '</span><div class="edit-button">' + $.gallery.edit_icon + '</div><div class="close-button" data-val="' + price + '">' + $.gallery.close_icon + '</div></div>\
                                    <div class="td-quantity' + empty_title + '">' + quantity_need + '<span class="prev-value" ' + hint_quantity + '>' + str_quantity + '</span>' + edit_button + '</div>\
                                    <div class="td-status">' + product_status + status_select + '</div>\
                                ';
                            }
    
                            $table.append(s);
                            
                            if ($table.find('.td-title > span').length > 4) {
                                $table.find('.td-title .item-title-str').addClass('fw-title-block')
                            }

                            $('.gallery-items').append($table);
                        } else {
                            var $info = $('<div class="info"></div>'),
                                $item = $('<div class="item" data-pos="' + v.pos + '" data-page="' + v.page + '" data-pid="' + v.pid + '" data-seq="' + v.seq + '" data-link="' + link + '" data-target="' + target + '" data-visible="' + v.visible + '" data-category="' + v.category + '"><img src="' + src_s250 + '" class="img-responsive"><input type="text" name="item_name" class="item-title" value="' + v.title + '" placeholder="' + $.lang[LANG]['board.enter-title'] + '" data-seq="' + v.seq + '" data-title="' + v.title + '" data-caption="' + v.content + '" data-category="' + v.category + '" data-date="' + v.datetime2 + '" data-hash="' + v.hashtag + '" data-url="' + src_s250 + '"></div>');
    
                            // if(mv_class) $item.addClass('active move');
                            // if(cp_class) $item.addClass('active copy');
                            $info.empty();
                            if(invisible) $item.addClass('invisible');
                            if(typeof settings.glink != 'undefined' && settings.glink) {
                                $info.append(link_icon);
                                $item.append($info);
                            }
    
                            $('.gallery-items').append($item);
                        }
                    });
                    
                    $('.gallery-items-loadmore').remove();
                    if(data.mode == 'shopping') {
                        if($('.gallery-modal').find('.pagination-wrap').length == 0 && data.total > 0) {
                            $('.gallery-items').after('<div class="pagination-wrap open"><ul class="pagination" id="product-pagination"></ul></div>');
                            var totalPage = (data.total > 0) ? Math.ceil(data.total/data.view) : 1;
                            $.jqPaginator('#product-pagination', {
                                totalPages: totalPage,
                                totalCounts: data.total,
                                currentPage: 1,
                                visiblePages: 10,
                                onPageChange: function (num, type) {
                                    if(type == 'change') {
                                        $.gallery.list($.gallery.block_id,num,$.gallery.category,'list');   
                                        $.gallery.update = true;
                                    }
                                    window.localStorage.setItem('gallery-product-page',num);
                                }
                            });
                        }
                        if(data.total == 0) {
                            var msg = (data.mode == 'shopping') ? $.lang[LANG]['editor.gallery.product.empty'] : $.lang[LANG]['editor.gallery.list.empty'];
                            msg = (data.search) ? '결과가 없습니다' : msg;
                            $('.gallery-items').append('<p class="text-center sort-disabled category-empty"> ' + msg + '</p>');
                        }
                    } else {
                        if((data.items).length == 0) {
                            var msg = (data.mode == 'shopping') ? $.lang[LANG]['editor.gallery.product.empty'] : $.lang[LANG]['editor.gallery.list.empty'];
                            msg = (data.search) ? '결과가 없습니다' : msg;
                            $('.gallery-items').append('<p class="text-center sort-disabled category-empty"> ' + msg + '</p>');
                        } else {
                            if((data.items).length < data.total) {
                                var count = (data.mode == 'shopping') ? $('.gallery-items .table-item').length : $('.gallery-items .item').length;
                                $('.gallery-items').after('<div class="gallery-items-loadmore open" data-pid="' + data.pid + '" data-category-str="' + data.cate_str + '" data-page="1">' + $.lang[LANG]['data.loadmore'] + ' (' + count + ' / ' + number_format(data.total) + ')</div>');
                            }
                        }
                    }
                    if(product_name != null && product_name.length) {
                        $('.gallery-list-search-text').val(product_name);
                        // $('.gallery-list-search-submit').hide();
                        // $('.gallery-list-search-cancel').show();
                    }
                    $('.gallery-ctrl-category').attr('data-category',data.category.toString()).attr('data-pid',data.pid);
    
                    var handle = (data.mode == 'shopping') ? '.td-handle' : '.item-ctrl';
                    var $item = $('.gallery-items .item');
                    
                    var gallery_items_handle = (LUX) ? '' : ', .td-handle';
                    $('.gallery-items').selectable({
                        // distance: 3,
                        filter : '.table-item,.item',
                        cancel : '.gallery-toolbar, .td-orig-price, .td-discount, .td-price, .td-quantity, .item-edit, .product-item-edit, .item.ui-selected, .table-item-status, .td-check, .td-status, .item-title, .item .info, svg'+gallery_items_handle,
                        stop : function(event,ui) {
                            if($('#user-edit').length) $('#user-edit').blur(); 
                            $.gallery.selected(event,ui);
                        }
                    });
                    $('.item-header').removeClass('ui-selectee');
    
                    $m.fadeIn(300, function() {
                        if(typeof func == 'function') func();
                        $('#dummy-drop').remove();
                    });
    
                    $('.gallery-modal').off('scroll').on('scroll', function(e) {
                        if($('.gallery-blocks').length && $(this).scrollTop() < 65) {
                            $('.product-gallery-list').css('top','93px'); 
                        } else $('.product-gallery-list').css('top','0px'); 
                        stickyToolbar();
                    });
                    // resizeGalleryModal();
                    setLanguage(LANG);

                    if(typeof GALLERY_MODE != 'undefined') {
                        GALLERY_MODE.push({
                            seq : data.pid,
                            mode : data.mode
                        });
                    }
                    
                    if(data.gallery_mode != 'shopping' || LUX) {
                        $('.gallery-blocks .all-items').addClass('hide');
                        if(data.pid) {
                            $('.gallery-blocks .menus li[data-gallery-id="' + data.pid +'"]').addClass('active');
                            $.gallery.block_id = data.pid;
                        }
                    }
                },
                error : function(xhr, status, error) {
                    $.processOFF();
                    alert("Error " + xhr.status + " : 관리자에게 문의");
                }
            });
        },
        list : function(id, page, category, type) {
            // if(typeof id == 'undefined' || !id) {
            //     alert('Undefined gallery ID');
            //     return false;
            // }
            $.gallery.seqs = [];
            if(typeof page =='undefined') page = 1;
            if(typeof category =='undefined') category = '';
            if(typeof type == 'undefined') type = 'load';
            // $('.gallery-items-loadmore').addClass('spinner');
            var params = ($('.gallery-modal').length) ? getProductParams() : getSearchURL(),
                product_name = getStorageItem('gallery-product-name'),
                product_filter = getStorageItem('gallery-product-filter'),
                product_view = getStorageItem('gallery-product-view'),
                sort = getStorageItem('gallery-product-sort'),
                by = getStorageItem('gallery-product-by'),
                manager = (id == '' || id == -1) ? SID : '';

            $.processON();                
            $.ajax({
                type: 'POST',
                url : '/template/gallery/show',
                data :  { mode : 'list', id : id, page : page, category : category, params : params, manager : manager, product_name : product_name, product_filter : product_filter, product_view : product_view, sort : sort, by : by },
                dataType : 'json',
                async: true,
                cache: false,
                success : function(data) {
                    $.processOFF();
                    if(data.error != 'undefined' && data.error) {
                        alert(data.error);
                        return false;
                    }
                    (typeof id == 'undefined' || !id) ? $('.gallery-category').hide() : $('.gallery-category').show();
                    if(LUX) {
                        $('.gallery-list-filter').hide();
                        $('.selected-gallery-name').hide();
                        $('.gallery-category').hide();
                    }
                    if(type == 'list') $('.gallery-items').find('.table-item').remove();
                    var num = data.total - ((page-1) * data.view);
                    $.each(data.items, function(i,v) {
                        var settings = (v.gsettings) ? $.parseJSON(v.gsettings) : {},
                            link = (typeof settings.glink != 'undefined') ? settings.glink : '',
                            link_icon = (typeof settings.glink != 'undefined' && settings.glink) ? clSVG('gallery-link','16','16',true,'info-link') : '',
                            target = (typeof settings.glink_target != 'undefined') ? settings.glink_target : '',
                            cp_class = ($.inArray(v.seq,$.gallery.copy) > -1) ? ' active copy' : '',
                            mv_class = ($.inArray(v.seq,$.gallery.move) > -1) ? ' active move' : '',
                            invisible = (v.visible == '1') ? true : false;
                            // file = ((v.image).indexOf('googleusercontent') > -1) ? v.image : v.url
                            imgPATH = (typeof settings.storage == 'undefined') ? RPATH : settings.storage,
                            // src_s250 = getServeImage(v.image,'250',imgPATH);
                            src_s250 = v.url;

                        link = Base64.decode(link);
                        if(data.mode == 'shopping') {
                            var yet = (v.price == null) ? 'yet' : '';
                            $table = $('<div class="table-item ' + yet + '" data-product="' + v.is_product + '" data-pos="' + v.pos + '" data-page="' + v.page + '" data-pid="' + v.pid + '" data-seq="' + v.seq + '" data-link="' + link + '" data-target="' + target + '" data-visible="' + v.visible + '" data-category="' + v.category + '" data-out-datetime="off"  data-pricechk="' + v.price_check + '">');
                            // lux
                            if(LUX) {
                                v.sale = (v.price < v.sale) ? v.sale : '';
                                if(v.prod_case) $table.attr('data-pcase',v.prod_case);
                            }

                            var title = (v.title) ? v.title : '상품명을 입력하세요',
                                price = (v.price != null && v.price !== '') ? addCommas(v.price) : 0,
                                sale = (v.sale != null && v.sale !== '') ? addCommas(v.sale) : 0,
                                soldout = '',
                                quantity = (v.quantity_on == 'on' && v.quantity) ? addCommas(v.quantity) : '-';
                            var discount_settings = (settings.discount)? settings.discount : '';
                            var discount_rate = (discount_settings.rate !== undefined && discount_settings.rate)? discount_settings.rate : '';
                            var discount_unit = (discount_settings.unit !== undefined && discount_settings.unit)? discount_settings.unit : '';
                            var discount = addCommas(discount_rate) + discount_unit;

                            var use_badge = (settings.use_badge)? settings.use_badge : '';
                            // console.log('use_badge', use_badge);
                            if(invisible) $table.addClass('invisible');

                            var is_soldout = false,
                                is_soldout_label = false,
                                saleStatus = '',
                                badgeList = '';

                            quantity = (v.quantity_on == 'off' || v.quantity_on == null)  ? '-' : quantity;
                            if(LUX) {
                                if(v.soldout) is_soldout = is_soldout_label = true;
                            } else {
                                if(v.quantity_on == 'off' || v.quantity_on == null || v.quantity_on == '') {
                                    if(v.status == 'off' || v.status == '') is_soldout = true;
                                } else {
                                    if(v.status == 'off' || v.status == '') is_soldout = true;
                                    if(v.quantity == 0) is_soldout = is_soldout_label = true;
                                }
                                if(v.status == 'lim') {
                                    saleStatus = '<span class="item-limit" data-toggle="tooltip" data-placement="top" data-original-title="' + v.sales_start + ' ~ ' + v.sales_end + '">기간한정판매</span>';
                                    $table.attr('data-out-datetime', (v.sale_now) ? '0' : '1');
                                }

                                if(use_badge) {
                                    var badge_settings = $.parseJSON(localStorage.getItem('badge_settings'));
                                    badgeList = drawBadgeList(use_badge, badge_settings);
                                }
                            }
                            if(is_soldout) {
                                $table.addClass('soldout');
                                if(is_soldout_label) soldout = '<span class="item-soldout">품절</span>';
                            }

                            switch(v.status) {
                                case "on": status = "판매중"; break;
                                case "off": status = "판매중지"; break;
                                default: status = "판매중지"; break;
                            }
                            // if(v.quantity_on == 'on' && v.quantity == 0) status = "품절";
                            if(sale == '') sale = price;
                            if(price == 0 && sale == 0) {
                                v.sale_per = 0;
                                sale = price
                            }
                            if(invisible) $table.addClass('invisible');

                            if(LUX) {
                                var margin_str = (v.prod_case == 'O' || v.price_sync == 'F') ? '' : '<span class="margin-info">마진율 <span class="rate">' +  v.margin.rate + '</span>% + <span class="add">' + addCommas(v.margin.value) + '</span> = 마진금액 <span class="price" data-supply="' + v.supply_price + '">' + addCommas(v.margin_price) + '</span>원</span/>',
                                    add_info = '\
                                <div class="add-info">\
                                    <span class="brand">' + v.brand_name + '</span/>\
                                    <span class="sale-rate" data-retail="' + v.retail_price + '>' + ((v.price < v.sale) ? '할인율 <span class="rate">' + v.sale_rate + '</span>%' : '') + '</span/>\
                                    ' + margin_str + '\
                                </div>';
                                soldout += add_info;
                            }
    
                            var empty_title = (v.title == '' || price == '-') ? ' empty' : '';
                            var s = '\
                                <div class="td-handle"><div class="item-handle"><img src="https://storage.googleapis.com/i.addblock.net/handle.png"></div></div>\
                                <div class="td-check"><input type="checkbox" name="item_check[]" class="td-input" data-ownproduct="' + (LUX && v.seq >= 1000000000 ? 'Y' : 'N') + '"></div>\
                                <div class="td-number">' + (num - i) + '</div>\
                                <div class="td-img"><img src="' + src_s250 + '" class="img-responsive">' + link_icon + '</div>\
                                <div class="td-title' + empty_title + '"><span class="item-title-str">' + title + '</span>' + saleStatus + badgeList + soldout + '\
                                    <ul class="product-item-edit" data-seq="' + v.seq + '">\
                                        <li class="edit-gallery-item" data-mode="prodDetail">상세페이지</li>\
                                        <li class="edit-gallery-item" data-mode="prodInfo">상품설정</li>\
                                    </ul>\
                                </div>\
                            ';
                                // <!--<div class="td-edit' + empty_title + '"><div class="item-edit" data-seq="' + v.seq + '"><span class="cl-icon cl_icon_edit04"></span>&nbsp;&nbsp;' + $.lang[LANG]['editor.block.gallery.item.edit'] + '</div></div>-->\
                            s+= '<div class="td-date">' + v.datetime2 + '</div>';
                            if(LUX) {
                                s+= '\
                                <div class="td-category">' + v.category_name + '</div>\
                                ';
                            } else {
                                s+= '\
                                <div class="td-category' + empty_title + ((data.cate_onoff == 'OFF') ? ' hide' : '') + ((v.item_category.indexOf(',') > -1) ? ' line' : '') + '">' + ((data.gallerys[v.pid].cate_onoff == 'ON') ? v.item_category : '') + '</div>\
                                ';
                            }
                            var edit_button = '', str_quantity = '', hint_quantity = '';
                                quantity_need = (v.quantity_on == 'on' && (parseInt(uncomma(quantity)) < 6 || parseInt(uncomma(v.quantity_add_op)) < 6)) ? '<span class="need">' + ((v.add_options == true) ? $.gallery.info_icon_option_true : $.gallery.info_icon_option_false) + '</span>' : '';
                            if(v.quantity_on == 'on') {
                                if(v.normal_options == false && v.add_options == false) {
                                    edit_button = '<div class="edit-button">' + $.gallery.edit_icon + '</div><div class="close-button" data-val="' + quantity + '">' + $.gallery.close_icon + '</div>';
                                } else {
                                    edit_button = '<div class="edit-button conf">' + $.gallery.edit_icon + '</div>';
                                }
                            }

                            str_quantity = (v.add_options == true && v.quantity_on == "on") ? addCommas(quantity) + '|' + addCommas(v.quantity_add_op) : addCommas(quantity);
                            hint_quantity = (v.add_options == true && v.quantity_on == "on") ? ' data-toggle="tooltip" data-html="true" data-placement="top" data-original-title="일반 재고 옵션 : ' + quantity + '<br>추가 옵션 재고 : ' + addCommas(v.quantity_add_op) + '"' : '';
                            var product_status = status;
                            if(v.status == 'lim') {
                                product_status = ((v.sale_now) ? '판매중' : (v.sale_fin) ? '판매종료' : '판매예정');
                                if(v.sale_now) product_status = '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-clock" viewBox="0 0 16 16"><path d="M8 3.5a.5.5 0 0 0-1 0V9a.5.5 0 0 0 .252.434l3.5 2a.5.5 0 0 0 .496-.868L8 8.71z"/><path d="M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16m7-8A7 7 0 1 1 1 8a7 7 0 0 1 14 0"/></svg> ' + product_status;
                            }
                            var status_select = changeStatus(v.status, v.seq);
                            if(LUX) {
                                s+= '\
                                    <div class="td-orig-price' + empty_title + '">' + sale + '</div>\
                                    <div class="td-discount' + empty_title + '">' + (LUX ? v.sale_rate : v.sale_per) + '</div>\
                                    <div class="td-price' + empty_title + '">' + price + '</div>\
                                    <div class="td-quantity' + empty_title + '">' + quantity_need  + str_quantity + '</div>\
                                    <div class="td-status">' + product_status + '</div>\
                                ';
                            } else {
                                var sale_per = (v.sale_per) ? v.sale_per : ((typeof v.sale_per === 'number') ? 0 : '-');
                                s+= '\
                                    <div class="td-orig-price' + empty_title + '"><span class="prev-value">' + sale + '</span><div class="edit-button">' + $.gallery.edit_icon + '</div><div class="close-button" data-val="' + sale + '">' + $.gallery.close_icon + '</div></div>\
                                    <div class="td-discount' + empty_title + '"><span class="prev-value">' + sale_per + '</span><div class="edit-button">' + $.gallery.edit_icon + '</div><div class="close-button" data-val="' + (LUX ? v.sale_rate : sale_per) + '">' + $.gallery.close_icon + '</div></div>\
                                    <div class="td-price' + empty_title + '"><span class="prev-value">' + price + '</span><div class="edit-button">' + $.gallery.edit_icon + '</div><div class="close-button" data-val="' + price + '">' + $.gallery.close_icon + '</div></div>\
                                    <div class="td-quantity' + empty_title + '">' + quantity_need + '<span class="prev-value" ' + hint_quantity + '>' + str_quantity + '</span>' + edit_button + '</div>\
                                    <div class="td-status">' + product_status + status_select + '</div>\
                                ';
                                /*                                
                                s+= '\
                                    <div class="td-orig-price' + empty_title + '"><span class="prev-value">' + sale + '</span><div class="edit-button">' + $.gallery.edit_icon + '</div><div class="close-button" data-val="' + sale + '">' + $.gallery.close_icon + '</div></div>\
                                    <div class="td-discount' + empty_title + '"><span class="prev-value">' + (LUX ? v.sale_rate : v.sale_per) + '</span><div class="edit-button">' + $.gallery.edit_icon + '</div><div class="close-button" data-val="' + (LUX ? v.sale_rate : v.sale_per) + '">' + $.gallery.close_icon + '</div></div>\
                                    <div class="td-price' + empty_title + '"><span class="prev-value">' + price + '</span><div class="edit-button">' + $.gallery.edit_icon + '</div><div class="close-button" data-val="' + price + '">' + $.gallery.close_icon + '</div></div>\
                                    <div class="td-quantity' + empty_title + '">' + quantity_need + '<span class="prev-value">' + str_quantity + '</span>' + edit_button + '</div>\
                                    <div class="td-status">' + product_status + status_select + '</div>\
                                ';
                                */
                            }

                            $table.append(s);
                            $('.gallery-items').append($table);
                        } else {
                            var $info = $('<div class="info"></div>'),
                                $item = $('<div class="item" data-pos="' + v.pos + '" data-pid="' + v.pid + '" data-seq="' + v.seq + '" data-link="' + link + '" data-target="' + target + '" data-visible="' + v.visible + '" data-category="' + v.category + '"><img src="' + src_s250 + '" class="img-responsive"><input type="text" name="item_name" class="item-title" value="' + v.title + '" placeholder="' + $.lang[LANG]['board.enter-title'] + '" data-seq="' + v.seq + '" data-title="' + v.title + '" data-caption="' + v.content + '" data-category="' + v.category + '" data-date="' + v.datetime2 + '" data-hash="' + v.hashtag + '" data-url="' + src_s250 + '"></div>');
    
                            $info.empty();
                            if(invisible) $item.addClass('invisible');
                            if(typeof settings.glink != 'undefined' && settings.glink) {
                                $info.append(link_icon);
                                $item.append($info);
                            }
    
                            $('.gallery-items').append($item);
                        }
                    });
                    
                    $('.gallery-toolbar').addClass('hide');
                    if(product_name != null && product_name.length) {
                        $('.gallery-list-search-text').val(product_name);
                        // $('.gallery-list-search-submit').hide();
                        // $('.gallery-list-search-cancel').show();
                    }

                    if(type == 'load') {
                        $('.gallery-items-loadmore').remove();
                        var itemCheck = (data.mode == 'shopping') ? '.table-item' : '.item';
        
                        if($('.gallery-items ' + itemCheck).length < data.total) {
                            $('.gallery-items').after('<div class="gallery-items-loadmore" data-pid="' + data.pid + '" data-category-str="' + data.cate_str + '" data-page="' + data.page_num + '">' + $.lang[LANG]['data.loadmore'] + ' (' + $('.gallery-items ' + itemCheck).length + ' / ' + number_format(data.total) + ')</div>');
                        }
                    }
    
                    // $('.gallery-items').sortable('refresh');                
                },
                error : function(xhr, status, error) {
                    $.processOFF();
                    alert("Error " + xhr.status + " : 관리자에게 문의");
                }
            });
        },
        setNumber: function() {
            var items = $.gallery.seqs;
            if(items.length) {
                var group = ($('.table-item').length) ? '.table-item' : '.gallery-items .item';
                $.each(items, function(i,v) {
                    $(group+'[data-seq="' + v + '"]').attr('data-index',(i+1));
                });
            }

            if(LUX) {
                if($.gallery.seqs.length > 0) {
                    var checkDefault = ($('.gallery-items .table-item.ui-selected:not([data-pcase="O"])').length > 0) ? true : false,
                        checkPcaseO = ($('.gallery-items .table-item.ui-selected[data-pcase="O"]').length > 0) ? true : false,
                        checkMargin = ($('.gallery-items .table-item.ui-selected:not([data-pcase="O"])').length == $('.gallery-items .table-item.ui-selected:not([data-pcase="O"]) .margin-info').length) ? true : false;

                    if(checkPcaseO && !checkDefault) $('.table-toolbar .toolbar-delete').removeClass('hide');
                    else $('.table-toolbar .toolbar-delete').addClass('hide');

                    if(!checkPcaseO && checkDefault && checkMargin) $('.table-toolbar .toolbar-margin').removeClass('hide');
                    else $('.table-toolbar .toolbar-margin').addClass('hide');

                    if($('.gallery-items .table-item.ui-selected').length == $('.gallery-items .table-item').length) $('.checkbox-cmd > input[type="checkbox"]').prop('checked',true);
                    else $('.checkbox-cmd > input[type="checkbox"]').prop('checked',false);
                } else {
                    $('.gallery-toolbar').removeClass('hide_col');
                    $('.table-toolbar .toolbar-cmd').addClass('hide');
                    $('.table-toolbar .toolbar-cmd i[data-glseq]').attr('data-glseq','');
                    $('.table-toolbar .toolbar-cmd i[data-cmd="link"]').attr('data-glink','').attr('data-glink-target','');
                    $('.table-toolbar .toolbar-cmd i[data-cmd="visible"]').attr('data-visible','0').text($.lang[LANG]['editor.gallery.icon.visible.off']);
                    $('.checkbox-cmd > input[type="checkbox"], .col-check > input[type="checkbox"]').prop('checked',false);
                    $('.gallery-toolbar').addClass('hide');
                    $('.gallery-items .item-header').removeClass('hide');
                }
            }
        },
        selected: function(e,ui) {
            $.gallery.seqs = [];
            var disabled = false, visible_button = false; no_price = false;
            if($.gallery.mode == 'shopping') {
                $('.table-item .td-check > input[type="checkbox"]').prop('checked',false);
                $.each($('.gallery-items .table-item.ui-selected'), function(i,v) {
                    if($(this).attr('data-product') == "false") disabled = true;
                    if($(this).attr('data-out-datetime') == "1") visible_button = true;
                    if($(this).attr('data-pricechk') == "false") no_price = true;
                    $(this).find('.td-check > input[type="checkbox"]').prop('checked',true);
                    ($.gallery.seqs).push($(v).attr('data-seq'));
                });

                if($.gallery.seqs.length > 0) {
                    if($('.gallery-items .table-item.ui-selected').length && $('.gallery-items .table-item').length) {
                        $('.table-toolbar li').removeClass('hide open');
                        $('.gallery-toolbar').addClass('hide_col');
                    }
                    var firstItem = $('.gallery-items .table-item.ui-selected').eq(0),
                        first_seq = firstItem.attr('data-seq'),
                        seq = firstItem.attr('data-seq'),
                        pid = firstItem.attr('data-pid'),
                        link = firstItem.attr('data-link'),
                        target = firstItem.attr('data-target'),
                        visible = firstItem.attr('data-visible'),
                        vstr = (visible == '1') ? $.lang[LANG]['editor.gallery.icon.visible.on'] : $.lang[LANG]['editor.gallery.icon.visible.off'];
                    if(visible_button) {
                        $('.table-toolbar .toolbar-cmd.toolbar-visible').addClass('disabled');
                    } else $('.table-toolbar .toolbar-cmd.toolbar-visible').removeClass('disabled');
                    if($.gallery.block_id == -1) {
                        $('.table-toolbar .toolbar-cmd.toolbar-copy').addClass('disabled');
                    }
                    $('.table-toolbar .toolbar-cmd').removeClass('hide');
                    $('.table-toolbar .toolbar-cmd i[data-glseq]').attr('data-glseq',first_seq);
                    $('.table-toolbar .toolbar-cmd i[data-cmd="link"]').attr('data-glink',link).attr('data-glink-target',target);
                    $('.table-toolbar .toolbar-cmd i[data-cmd="visible"]').attr('data-visible',visible).text(vstr);
                    $('.gallery-toolbar').removeClass('hide');
                    $('.gallery-items .item-header').addClass('hide');
                    stickyToolbar();
                    $.gallery.setNumber();
                } else {
                    $('.gallery-items .table-item > div').removeClass('hide-text');
                    $('.table-toolbar .toolbar-cmd').addClass('hide');
                    $('.table-toolbar .toolbar-cmd i[data-glseq]').attr('data-glseq','');
                    $('.table-toolbar .toolbar-cmd i[data-cmd="link"]').attr('data-glink','').attr('data-glink-target','');
                    $('.table-toolbar .toolbar-cmd i[data-cmd="visible"]').attr('data-visible','0').text($.lang[LANG]['editor.gallery.icon.visible.off']);
                    $('.gallery-toolbar').addClass('hide');
                    $('.gallery-items .item-header').removeClass('hide');
                }
            } else {
                $.each($('.gallery-items .item.ui-selected'), function(i,v) {
                    ($.gallery.seqs).push($(v).attr('data-seq'));
                });
                $.gallery.toolbar();
                stickyToolbar();
            }

            (no_price) ? $('.product-cmd').not('.toolbar-org-price').not('.toolbar-stock').addClass('no_price') : $('.product-cmd').removeClass('no_price');
            (disabled) ? $('.product-cmd').addClass('disabled') : $('.product-cmd').removeClass('disabled');
            if($('.gallery-modal').attr('data-pid') == undefined) {
                $('.toolbar-sort.item-sort').addClass('disabled');
            }

            $('.item-submenu, .view-submenu').hide();
            $('.toolbar-sort, .gallery-view-count').removeClass('open');
            $('.gallery-blocks .btn-group').removeClass('open');
        },
        toolbar : function() {
            $('.gallery-list-filter').remove();
            $('.gallery-items').find('.toolbar.mod-gallery').remove();
            if($.gallery.seqs.length == 0) return false;
            var $s = $('.gallery-items .item[data-seq="' + $.gallery.seqs[0] + '"]'),
                seq = $s.attr('data-seq'),
                pid = $s.attr('data-pid'),
                link = $s.attr('data-link'),
                target = $s.attr('data-target'),
                visible = $s.attr('data-visible'),
                edit_name = ($.gallery.mode == 'gallery') ? $.lang[LANG]['editor.block.gallery.item.edit.image'] : $.lang[LANG]['editor.block.gallery.item.edit'];

            var l = ($s.index()%7 > 3) ? 'right' : '',
                mode = $('.gallery-add-items').attr('data-mode');

            var vstr = (visible == "1") ? $.lang[LANG]["editor.gallery.icon.visible.on"] : $.lang[LANG]["editor.gallery.icon.visible.off"],
                vicon = (visible == "1") ? 'cl_icon_hide02' : 'cl_icon_show',
                editable = ($.gallery.seqs.length > 1) ? "disabled" : "";

            var s = '\
                <ul>\
                    <li class="active gallery-item-edit submenu' + editable + ' edit-'+ $.gallery.mode +'">\
                ';
            if($.gallery.mode == 'project') {
                s = s + '\
                        ' + $.lang[LANG]['editor.block.gallery.item.edit'] + '</span> <i class="fa fa-caret-down"></i>\
                        <ul class="item-submenu">\
                            <li class="edit-gallery-item"><i class="" data-glseq="' + seq + '" data-cmd="edit">'+$.lang[LANG]["editor.gallery.icon.thumnail.config"]+'</i></li>\
                            <li class="edit-gallery-detail" data-seq="' + seq + '" >'+$.lang[LANG]["editor.gallery.icon.Project.page"]+'</li>\
                        </ul>\
                    </li>\
                ';
            } else {
                s = s + '\
                        <i class="" data-glseq="' + seq + '" data-cmd="edit"></i>' + edit_name + '\
                    </li>\
                ';
            }
            s = s + '<li><i class="" data-glseq="' + seq + '" data-cmd="copy"></i>' + $.lang[LANG]['editor.gallery.icon.clone'] + '</li>';

            s = s + '<li class="toolbar-sort item-sort submenu">' + $.lang[LANG]['editor.gallery.icon.order'] + ' <i class="fa fa-caret-down" aria-hidden="true" data-glseq="" data-cmd="item-sort"></i>\
                        <ul class="item-submenu">\
                            <li class="sort-top">' + $.lang[LANG]['editor.gallery.icon.order.front'] + '</li>\
                            <li class="sort-bottom">' + $.lang[LANG]['editor.gallery.icon.order.end'] + '</li>\
                        </ul>\
                    </li>';
            if(!$('.gallery-modal .gallery-category .gallery-all').hasClass('hide')) {
                s = s + '<li class="toolbar-category submenu"><i class="" data-glseq="" data-cmd="category"></i>' + $.lang[LANG]['editor.block.gallery.category.change'] + ' <i class="fa fa-caret-down" aria-hidden="true"></i>';
                s = s + '<ul class="item-submenu">' + $.gallery.cates + '</ul>';
                s = s + '</li>';
            }
            
            s = s + '\
                    <li><i class="" data-glseq="' + seq + '" data-glink="' + link + '" data-glink-target="' + target + '" data-cmd="link"></i>' + $.lang[LANG]['editor.gallery.icon.link'] + '</li>\
            ';
            s = s + '\
                    <li><i class="" data-glseq="' + seq + '" data-visible="' + visible + '" data-cmd="visible">' + vstr + '</i></li>\
                    <li><i class="" data-glseq="' + seq + '" data-cmd="move">' + $.lang[LANG]['editor.block.gallery.item.move'] + '</i></li>\
                    <li><i class="" data-glseq="' + seq + '" data-cmd="delete"></i>' + $.lang[LANG]['editor.gallery.icon.delete'] + '</li>\
                </ul>\
            ';
            var $tool_back = $('<div class="toolbar mod-gallery ' + l + '">' + s + '</div>');
            $('.gallery-toolbar').empty();
            $('.gallery-toolbar').append($tool_back).removeClass('hide');

            if($.gallery.seqs.length > 1) { 
                $('.gallery-toolbar .toolbar .gallery-item-edit').addClass('disabled');
            } else {
                $('.gallery-toolbar .toolbar .gallery-item-edit').removeClass('disabled');
            }
            // $('.gallery-items').selectable('disable');
        },
        pages : function() {
            var group = ($('.table-item').length) ? '.table-item' : '.gallery-items .item',
                item = $(group).length,
                cpage = Math.ceil(item/30),
                spos = $('.gallery-modal').scrollTop();
            return {
                page : cpage, pos : spos
            }
        },
        close : function() {
            $.gallery.mode = '';
            localStorage.removeItem('gallery-product-view');

            if($('.gallery-modal').hasClass('view-detail') && $.gallery.unlink) { // 상세페이지가 삭제됐을경우 리스트로 이동
                var go_url = PAGE.split(",");
                location.replace('/'+CONFIG_URL+'config/page/' + go_url[0]);
            } else {
                if($('.gallery-modal').length) {
                    localStorage.removeItem('badge_settings');
                    localStorage.removeItem('badge_imgs');
                    localStorage.removeItem('before_badge_settings');
                    $('.gallery-modal').fadeOut(300, function() {
                        $('#gallery-style').remove();
                        $('#gallery-modal-script').remove();
                        $(this).remove();
                    });
                }

                if($.gallery.update) {
                    if(typeof showPageCallback == 'function')
                        showPageCallback(showPage);
                }

                // premium block
                if( !$('#el-blockConfig').hasClass('open') && $('.element[data-id="' + $.gallery.block_id + '"][data-type="gallery"][data-type2="premium"]').length > 0) {
                    if(typeof elGalleryJS[selectID] != 'undefined') elGalleryJS[selectID] = true;
                    startGalleryJS($('.element[data-id="' + $.gallery.block_id + '"]'));
                }
            }
        }
    }

    $.detail = {
        open : function(product, mode) {
            var $detail = $('.product-detail-modal'),
                title = '';
            if($.gallery.mode) {
                title = ($.gallery.mode == 'shopping') ? '상품 상세페이지' : '상세페이지';
            } else {
                title = (mode == 'shopping') ? '상품 상세페이지' : '상세페이지';
            }
            if($detail.length == 0) {
                var s = '\
                <div class="product-detail-modal">\
                    <div class="detail-page"><iframe class="detail-iframe" src="' + product + '#detail"></iframe></div>\
                </div>\
                ';
                $('body').append(s);
                setTimeout(function() { 
                    $('.product-detail-modal').addClass('open'); 
                },50);
            }
            $(document).on('click', '.product-detail-modal .modal-close', function(e) {
                $.detail.close();
            });
        },
        close : function() {
            if($('.product-detail-modal').length) {
                $('.product-detail-modal').removeClass('open');
                setTimeout(function() { $('.product-detail-modal').remove(); },750);
            }            
        }
    }

    var setBadgeColorPicker = function() {
        // console.log('setBadgeColorPicker');
        $('.color-picker-badge').each(function(idx, v){
            $(v).colpick({
                onBeforeShow: function(picker) {
                    var this_color = style.getHex($(v).css('background-color'));
                    $(this).colpickSetColor(this_color);
                },
                onShow: function(picker) {
                    if($(v).hasClass('disabled')){
                        $(picker).colpickHide();
                        return false;
                    }
                },
                onSubmit: function(hsb, hex, rgb, root_picker) {
                    var $optionRow = $(root_picker).closest('.badge-option-row');
                    var pn = $(root_picker).attr('pn');
                    var val = '#'+hex;

                    switch(pn) {
                        case 'border-color':
                            $optionRow.find('input[name="border_color"]').val(val);
                            break;
                        case 'background-color':
                            $optionRow.find('input[name="background_color"]').val(val);
                            break;
                        case 'color':
                            $optionRow.find('input[name="font_color"]').val(val);
                            break;
                    }
                    // console.log($optionRow.find('.product-badge'), pn, val);
                    $optionRow.find('.product-badge-view > .product-badge').css(pn, val);
                    $('.cl-change-badge-design').removeClass('reset-design');
                    // $('.modal-product-badge').eq(0).removeClass('return-prev');

                    $(root_picker).css('background-color', val);
                    $(root_picker).colpickHide();
                }
            });
        });
    }
    $.badgeSettings = {
        init: function(badge_settings){
            $.each(badge_settings, function(k, v) {
                var $badge = $('.badge-view .product-badge[data-type="'+k+'"]');
                if(v.type == 'edit') {
                    var badgeType = (v.type)? v.type : 'edit';
                    var badgeStyle = (v.style)? v.style : 'default-1 small';
                    var badgeText = (v.badge_text)? v.badge_text : $.lang[LANG]['gallery.shopping.badge.'+k]
                    var badgeBorderColor = (v.border_color)? v.border_color : '';
                    var badgeBackgroundColor = (v.background_color)? v.background_color : '';
                    var badgeFontColor = (v.font_color)? v.font_color : '';

                    $badge.attr('class', 'change-badge-design hand product-badge '+badgeStyle);
                    if(badgeBorderColor) $badge.css('border-color', badgeBorderColor);
                    if(badgeBackgroundColor) $badge.css('background-color', badgeBackgroundColor);
                    if(badgeFontColor) $badge.css('color', badgeFontColor);
                    $badge.html(badgeText);
                } else {
                    // console.log('img',v.image_src);
                    $badge.attr('class', 'change-badge-design hand product-badge');
                    $badge.removeAttr('style');
                    $badge.html('<img src="'+v.image_src+'">');
                }
            });
        },
        initDesign: function(badgeArr, badge_settings) {
            var changeBadgeDsgnRow = '';
            $.each(badgeArr, function(idx, type) {
                var bsettings = (typeof badge_settings[type] != 'undefined')? badge_settings[type] : {};
                        
                var badgeType = (typeof bsettings.type != 'undefined' && bsettings.type)? bsettings.type : 'edit';
                var badgeStyle = (typeof bsettings.style != 'undefined' && bsettings.style)? bsettings.style : 'default-1 small';
                var badgeText = (typeof bsettings.badge_text != 'undefined' && bsettings.badge_text)? bsettings.badge_text : $.lang[LANG]['gallery.shopping.badge.'+type];
                var badgeBorderColor = (typeof bsettings.border_color != 'undefined' && bsettings.border_color)? bsettings.border_color : '';
                var badgeBackgroundColor = (typeof bsettings.background_color != 'undefined' && bsettings.background_color)? bsettings.background_color : '';
                var badgeFontColor = (typeof bsettings.font_color != 'undefined' && bsettings.font_color)? bsettings.font_color : '';
                var badgeImgSrc = (typeof bsettings.image_src != 'undefined' && bsettings.image_src)? bsettings.image_src : '';
                var badgeImgName = (typeof bsettings.image_name != 'undefined' && bsettings.image_name)? bsettings.image_name : '';
                var $badge = (badgeType == 'edit')? $('<span class="product-badge ' + badgeStyle + '" data-style="' + badgeStyle + '" data-border_color="' + bsettings.border_color + '" data-background_color="' + bsettings.background_color + '" data-font_color="' + bsettings.font_color + '">' + badgeText + '</span>')
                                                : $('<span class="product-badge"><img src="'+badgeImgSrc+'"></span>');
                if(badgeBorderColor) $badge.css('border-color', badgeBorderColor);
                if(badgeBackgroundColor) $badge.css('background-color', badgeBackgroundColor);
                if(badgeFontColor) $badge.css('color', badgeFontColor);
                var disabled = (badgeType == 'image')? 'disabled' : '';

                changeBadgeDsgnRow += '\
                    <div class="divTableRow badge-option-row" data-idx="' + idx + '" data-default="' + type + '">\
                        <div class="divTableCell product-badge-view">'+ $badge[0].outerHTML +'</div>\
                        <div class="divTableCell product-badge-option">\
                            <div class="select-style-btn hand">선택</div>\
                        </div>\
                        <div class="divTableCell product-badge-option">\
                            <input type="text" name="badge_text" value="'+ badgeText +'" maxlength="7" ' + disabled + '>\
                        </div>\
                        <div class="divTableCell product-badge-option">\
                            <span class="color tooltips color-picker-badge '+disabled+'" el=".product-badge" pn="border-color" data-toggle="tooltip" data-placement="top" title="" style="" data-original-title="color"></span>\
                        </div>\
                        <div class="divTableCell product-badge-option">\
                            <span class="color tooltips color-picker-badge '+disabled+'" el=".product-badge" pn="background-color" data-toggle="tooltip" data-placement="top" title="" style="" data-original-title="color"></span>\
                        </div>\
                        <div class="divTableCell product-badge-option">\
                            <span class="color tooltips color-picker-badge '+disabled+'" el=".product-badge" pn="color" data-toggle="tooltip" data-placement="top" title="" style="" data-original-title="color"></span>\
                        </div>\
                        <input type="hidden" name="type" value="' + badgeType + '">\
                        <input type="hidden" name="style" value="' + badgeStyle + '">\
                        <input type="hidden" name="border_color" value="' + badgeBorderColor + '">\
                        <input type="hidden" name="background_color" value="' + badgeBackgroundColor + '">\
                        <input type="hidden" name="font_color" value="' + badgeFontColor + '">\
                        <input type="hidden" name="image_src" value="'+badgeImgSrc+'">\
                        <input type="hidden" name="image_name" value="'+badgeImgName+'">\
                    </div>\
                ';
            });

            return changeBadgeDsgnRow;
        },
        initStylePopup: function($selection) {
            var optionIdx = $selection.closest('.badge-option-row').attr('data-idx');
            var badgeText = $('.badge-option-row[data-idx="'+optionIdx+'"] input[name="badge_text"]').val();
            var badgeType = $('.badge-option-row[data-idx="'+optionIdx+'"] input[name="type"]').val();
            var badgeStyle = $('.badge-option-row[data-idx="'+optionIdx+'"] input[name="style"]').val();
            var badgeImgSrc = (badgeType == 'image')? $('.badge-option-row[data-idx="'+optionIdx+'"] input[name="image_src"]').val() : '';

            if(!badgeText) badgeText = $.lang[LANG]['gallery.shopping.badge.'+$selection.closest('.badge-option-row').attr('data-default')]
            $('.badge-style-popup .badge-tab-edit .select-badge .product-badge').html(badgeText);

            if(badgeType) {
                $('.badge-type-tab li').removeClass('active');
                $('.badge-type-tab li[data-tab="'+badgeType+'"]').addClass('active');
            }
            // console.log('initStylePopup', localStorage.getItem('badge_imgs'))

            var popoverObj = {
                trigger: 'hover',
                container: '.cl-change-badge-design',
                placement: 'top',
                html: true,
                content: '이미지가 삭제되었습니다.'
            };

            $('.badge-style-popup .select-badge-table img').each(function(idx, v){
                // console.log($(v).attr('src'));
                $(v).error(function(){
                    $(this).attr('src', '//storage.googleapis.com/i.addblock.net/icon_broken_img.png');
                    $(this).closest('.product-badge').popover(popoverObj);
                });

                if($(v).attr('src').indexOf('//storage.googleapis.com/i.addblock.net/icon_broken_img.png') > -1) {
                    $(v).closest('.product-badge').popover(popoverObj);
                }

                if(badgeType == 'image' && badgeImgSrc == $(v).attr('src') && !$('.badge-style-popup .badge-tab-image .select-badge').hasClass('selected')) {
                    $(v).closest('.select-badge').addClass('selected');
                }
            });

            if(badgeType == 'edit') {
                $('.badge-type-tab > li').removeClass('active');
                $('.badge-type-tab > li[data-tab="edit"]').addClass('active');
                $('.badge-type-tab-content').addClass('hide');
                $('.badge-style-popup .badge-style-footer > span').addClass('hide');
                $('.badge-tab-edit').removeClass('hide');

                var badgeStyleArr = badgeStyle.split(' ');
                var style = badgeStyleArr[0];
                var size = badgeStyleArr[1];
                // console.log(style, size);
                $('.badge-style-popup .badge-size-tab > span').removeClass('active');
                $('.badge-style-popup .select-badge-table .product-badge').removeClass('small medium large');
                $('.badge-style-popup .select-badge-table .select-badge').removeClass('selected');
                
                $('.badge-style-popup .badge-size-tab > span[data-size="'+size+'"]').addClass('active');
                $('.badge-style-popup .select-badge-table').attr('data-size', size);
                $('.badge-style-popup .select-badge-table .product-badge').addClass(size);
                $('.badge-style-popup .select-badge-table .select-badge').removeClass('selected');
                $('.badge-style-popup .select-badge-table .select-badge[data-style="'+style+'"]').addClass('selected');
            } else { //이미지형
                $('.badge-type-tab > li').removeClass('active');
                $('.badge-type-tab > li[data-tab="image"]').addClass('active');
                $('.badge-type-tab-content').addClass('hide');
                $('.badge-tab-image').removeClass('hide');
                $('.badge-style-popup .badge-style-footer > span').removeClass('hide');
            }
        },
        handleSelection: function($selection, idx){
            var optionIdx = $selection.closest('.badge-option-row').attr('data-idx');
            var badgeTab = $selection.closest('.badge-type-tab-content');
            var badgeEL = $selection.find('.product-badge').clone();

            $('.badge-option-row[data-idx="'+optionIdx+'"] .product-badge-view > .product-badge').attr('class', 'product-badge');
            $('.cl-change-badge-design').removeClass('reset-design');
            // $('.modal-product-badge').eq(0).removeClass('return-prev');

            if($selection.closest('.badge-type-tab-content').hasClass('badge-tab-edit')) { //편집형
                var $selectedBadge = $selection.find('.product-badge');
                var badgeStyle = $selectedBadge.attr('class').replace('product-badge ', '');

                var badgeBorderColor = style.getHex($selectedBadge.css('border-color'));
                var badgeBackgroundColor = style.getHex($selectedBadge.css('background-color'));
                var badgetextColor = style.getHex($selectedBadge.css('color'));

                $('.badge-option-row[data-idx="'+optionIdx+'"] .product-badge-view').html(badgeEL);

                $('.badge-option-row[data-idx="'+optionIdx+'"]').find('.color-picker-badge').removeClass('disabled');
                $('.badge-option-row[data-idx="'+optionIdx+'"]').find('input[name="badge_text"]').prop('disabled', false);

                $('.badge-option-row[data-idx="'+optionIdx+'"]').find('.color-picker-badge[pn="border-color"]').css('background-color', badgeBorderColor);
                $('.badge-option-row[data-idx="'+optionIdx+'"]').find('.color-picker-badge[pn="background-color"]').css('background-color', badgeBackgroundColor);
                $('.badge-option-row[data-idx="'+optionIdx+'"]').find('.color-picker-badge[pn="color"]').css('background-color', badgetextColor);

                $('.badge-option-row[data-idx="'+optionIdx+'"] input[name="type"]').val('edit');
                $('.badge-option-row[data-idx="'+optionIdx+'"] input[name="style"]').val(badgeStyle.trim());
                $('.badge-option-row[data-idx="'+optionIdx+'"] input[name="border_color"]').val(badgeBorderColor);
                $('.badge-option-row[data-idx="'+optionIdx+'"] input[name="background_color"]').val(badgeBackgroundColor);
                $('.badge-option-row[data-idx="'+optionIdx+'"] input[name="font_color"]').val(badgetextColor);
                $('.badge-option-row[data-idx="'+optionIdx+'"] input[name="image_src"]').val('');
                $('.badge-option-row[data-idx="'+optionIdx+'"] input[name="image_name"]').val('');
            } else { //이미지형
                var imgSrc = $selection.find('.product-badge > img').attr('src');
                var imgName = $selection.find('.product-badge > img').attr('alt');
                if(imgSrc == '//storage.googleapis.com/i.addblock.net/icon_broken_img.png') {
                    return false;
                }
                
                $('.badge-option-row[data-idx="'+optionIdx+'"] .product-badge-view').html(badgeEL);

                $('.badge-option-row[data-idx="'+optionIdx+'"]').find('.color-picker-badge').addClass('disabled');
                // $('.badge-option-row[data-idx="'+optionIdx+'"]').find('input[name="badge_text"]').val('');
                $('.badge-option-row[data-idx="'+optionIdx+'"]').find('input[name="badge_text"]').prop('disabled', true);

                $('.badge-option-row[data-idx="'+optionIdx+'"] input[name="type"]').val('image');
                $('.badge-option-row[data-idx="'+optionIdx+'"] input[name="style"]').val('');
                $('.badge-option-row[data-idx="'+optionIdx+'"] input[name="border_color"]').val('');
                $('.badge-option-row[data-idx="'+optionIdx+'"] input[name="background_color"]').val('');
                $('.badge-option-row[data-idx="'+optionIdx+'"] input[name="font_color"]').val('');
                $('.badge-option-row[data-idx="'+optionIdx+'"] input[name="image_src"]').val(imgSrc);
                $('.badge-option-row[data-idx="'+optionIdx+'"] input[name="image_name"]').val(imgName);
            }

            setBadgeColorPicker();
        }
    }    
})(jQuery);

var getSelectedProductList = function(sid, cmd, gallery_seqs) {
    var returnHtml = '';
    var route = (CONFIG_URL) ? '/_admin' : '';
    $.ajax({
        url: route  + '/shopping/productListInfo',
        type: 'post',
        data: { sid : sid, cmd : cmd, gseqs : JSON.stringify(gallery_seqs) },
        dataType: 'html',
        success: function (list_html) {
            // $('.order-list-area').html(list_html);
            returnHtml += list_html;
        }, error: function () {

        }, complete: function () {
            // $.processOFF();
        }
    });
   
    return returnHtml;
}

var SFOLDER_ACTIVE = '';
var updateOutputFolder = function (e) {
    var list = e.length ? e : $(e.target),
        output = list.data('output');

    if (window.JSON && list.attr('class') == 'dd') {
        output.val(window.JSON.stringify(list.nestable('serialize')));
    } else {
        if (typeof output != 'undefined') output.val('JSON browser support required');
    }

    if (SID) {
        SFOLDER = JSON.parse($('#nestableFolder-output').val());
        $.ajaxSetup({ async : false });
        $.post('/template/update/type/folder', { s: $('#nestableFolder-output').val(), id: SID }, function (data) {
            checkError(data);
        }, 'json');
    }
}

var setResourceSelectedBox = function(mode) {
    var setResourceTab = $('.modal-resourcebox #'+mode+'storage'),
        setResourceSelectedInfo = setResourceTab.find('.resource-ctrl-selectedinfo'),
        setResourceSelected = setResourceTab.find('.resource-selected-ul');
    setResourceTab.find('.resource-ctrl-btns').removeClass('active');
    setResourceSelected.find('.selected-hover').popover('destroy');
    if(setResourceSelected.children('li').length > 0) {
        if(mode == 'my') {
            setResourceTab.find('.resource-ctrl-btns').addClass('active');
            var size = 0; 
            setResourceSelected.children('li').map(function() { return $(this).data('size')}).each(function(){ size += this;});
            setResourceSelectedInfo.find('.size').text('('+formatFileSize(size,2,'str')+')');

        }
        setResourceTab.find('.resource-useit').addClass('active');
        setResourceSelectedInfo.find('.count').text(setResourceSelected.children('li').length);
        setResourceSelectedInfo.find('label').show();

        setResourceSelected.find('.selected-hover').popover({
            container: 'body',
            trigger: 'hover',
            html: true,
            content: $.lang[LANG]['editor.resource.selected.cancel'],
            placement: function(context, source) {
                $(context).addClass('resource-selected-cancel-popover');
                return 'auto top';
            }
        });

    } else {
        setResourceTab.find('.resource-useit').removeClass('active');
        if(setResourceSelectedInfo.length > 0) {
            setResourceSelectedInfo.find('label').hide()
            setResourceSelectedInfo.find('.count').text('0');
        }
    }
}

var resourceGetPage = function(page,ffolder,fsort,fsearch) {
    if(typeof fsort == 'undefined') fsort = 'date_desc';
    if(typeof fsearch == 'undefined') fsearch = '';

    var property = $('.resource-useit').eq(0).attr('data-property'),
        checkFileLink = (property == 'flink-change') ? true : false,
        // checkGabia = (HOST.indexOf('gabia') > -1 || SERVICE.indexOf('gabia') > -1) ? true : false,
        checkGabia = (window.getServiceHost().indexOf('gabia') > -1) ? true : false,
        sfl = 'default';
    var thisResourceTab = (checkFileLink) ?  $('#filestorage') : $('#mystorage'),
        thisResourceFiles = thisResourceTab.find('ul.files'),
        thisResourceSelected = thisResourceTab.find('.resource-selected-ul');

    thisResourceFiles.removeClass('empty');
    ffolder = (typeof ffolder == 'undefined') ? SFOLDER_ACTIVE : ffolder;
    if(checkFileLink) {
        ffolder = 'flink@';
        if(thisResourceFiles.find('.fitem.selected').length == 0) thisResourceTab.find('.resource-useit').removeClass('active');
        if(thisResourceTab.find('#flink-sfl').length > 0) sfl = thisResourceTab.find('#flink-sfl option:selected').val();
    } else {
        if(thisResourceTab.find('#nestableFolder .fln-group').length > 0) thisResourceTab.find('#nestableFolder .fln-group .btn-fln-cancel').click();
    }

    $.ajax({
        type : 'post',
        url: '/template/resource/files/page/' + page + '/sfl/' + sfl + '/ffolder/' + ffolder,
        data: { fsort: fsort, fsearch: fsearch },
        dataType: 'json',
        async: false,
        success: function (data) {
            if (typeof(data.error) != 'undefined' && data.error) {
                checkError(data);
                $.resource.modalFilesEmpty(thisResourceFiles, 'No files uploaded');
            } else {
                if(page == 1) thisResourceFiles.empty();

                cTotal = (!checkFileLink) ? $.resource.getMystorageFlc() : data.total;
                if(cTotal < 0) cTotal = data.total;
                var path = data.path;

                if(checkFileLink) {
                    var checkPlan = (typeof property.VALIDPLAN == 'undefined') ? ((typeof VALIDPLAN == 'undefined') ? $.gallery.valid_plan : VALIDPLAN) : property.VALIDPLAN,
                        checkPType = (typeof property.VALIDTYPE == 'undefined') ? ((typeof VALIDTYPE == 'undefined') ? $.gallery.valid_type : VALIDTYPE) : property.VALIDTYPE,
                        flink_max = (checkPlan) ? 15 : 0;

                    if(checkPType == 'BN') flink_max = 100;
                    else if(checkPType == 'SM') flink_max = $.lang[LANG]['editor.link.file.unlimited'];
    
                    thisResourceTab.find('.flink-capacity .flink-cnt').text(cTotal);
                    thisResourceTab.find('.flink-capacity .flink-max').text(flink_max);
    
                    if(cTotal >= flink_max) thisResourceTab.find('.flink-fileinput').addClass('flink-disabled');
                    else thisResourceTab.find('.flink-fileinput').removeClass('flink-disabled');
    
                    if(cTotal > page * 100) {
                        thisResourceTab.find('.resource-row.bottom').addClass('active');
                        thisResourceTab.find('.resource-loadmore').attr('onclick', 'resourceGetPage(' + (page+1) + ')');
                    } else {
                        thisResourceTab.find('.resource-row.bottom').removeClass('active');
                        thisResourceTab.find('.resource-loadmore').removeAttr('onclick');
                    }
    
                    if(data.file.length == 0) $.resource.modalFilesEmpty(thisResourceFiles, $.lang[LANG]['editor.link.file.list.empty']);
                    $.each(data.file, function (idx, val) {

                        var file_s = (/^[0-9.]*$/.test(val.filesize)) ? val.filesize * 1 : 0,
                            fsize_obj = formatFileSize(file_s, 2, 'obj'),
                            tag = '\
                                    <li class="fitem">\
                                        <div class="fitem-wrap">\
                                            <p class="fitem-name" data-seq="' + val.seq + '" data-source="' + val.filename + '">' + val.origname + '</p>\
                                            <p class="fitem-size"><span class="size" data-size="' +file_s +'" data-unit="' + fsize_obj['unit'] + '">' + fsize_obj['val'] + '</span></p>\
                                            <span class="fitem-ctrl-del" data-page="' + page + '"><svg viewBox="0 0 12 12" width="12" height="12"><path d="M11 2H9V0H3v2H1 0v1h1v7c0 1.1 0.9 2 2 2h6c1.1 0 2-0.9 2-2V3h1V2H11zM4 1H8v1H4V1zM10 10c0 0.6-0.4 1-1 1H3c-0.5 0-1-0.4-1-1V3h1H9h1V10z"></path><rect x="4" y="4" width="1" height="6"></rect><rect x="7" y="4" width="1" height="6"></rect></svg></span>\
                                        </div>\
                                    </li>\
                        ';

                        thisResourceFiles.append(tag);
                    });
    
                } else {
                    if(fsort != thisResourceTab.find('.resource-ctrl-sort select').val()) thisResourceTab.find('.resource-ctrl-sort select').val(fsort).change();
                    if(fsearch != thisResourceTab.find('.resource-search-stx').val()) thisResourceTab.find('.resource-search-stx').val(fsearch);

                    if(thisResourceTab.find('#nestableFolder').hasClass('ready')) {
                        $.resource.setMystorageFolder('set_fll');
                        if(ffolder && thisResourceTab.find('#nestableFolder .fli[data-id="' + ffolder + '"]').length > 0) thisResourceTab.find('#nestableFolder .fli[data-id="' + ffolder + '"]').addClass('active').siblings().removeClass('active');
                        else thisResourceTab.find('#nestableFolder .fli[data-id="all"]').addClass('active').siblings().removeClass('active');
                    }
                    
                    var selected = new Array();
                    thisResourceSelected.children('li').each(function() {
                        selected.push($(this).attr('data-seq'));
                    });
    
                    page = (data.file.length < 2) ? page-1 : page;
                    page = (page) ? page : 1;
    
                    thisResourceFiles.removeClass('empty');
                    thisResourceFiles.find('.resource-empty-area').remove();
                    $.each(data.file, function (idx, val) {
                        var tag = resourceFileTag(val.filename, val.seq, path, selected, val.ffolder, page, val.origname, val.filesize, val.w, val.h, val.magic, val.date);
                        thisResourceFiles.append(tag);
                    });
    
                    if(cTotal==0) {
                        var empty_msg = (fsearch) ? $.lang[LANG]['editor.resource.files.empty'] : $.lang[LANG]['editor.resource.notice.text.top'] + '<br>' + $.lang[LANG]['editor.resource.notice.text.bottom'];
                        $.resource.modalFilesEmpty(thisResourceFiles, empty_msg);
                    } else {
                        var upgrade_link = (checkGabia) ? 'https://www.gabia.com/mygabia/service' : '/upgrade/site/' + SID,
                            load_btn = '\
                                    <img src="https://storage.googleapis.com/i.addblock.net/image-upload.gif">&nbsp;&nbsp;\
                                    <span class="resource-info"><span data-lang="config.file.browse">' + $.lang[LANG]["config.file.browse"] + '</span></span>\
                                    <input id="mystorageUploadBtn" class="upload-resource-button" type="file" name="files[]" multiple>\
                            ',
                            upgrade_btn = '\
                                <a href="' + upgrade_link + '" style="color: #fff; text-decoration:none;">\
                                    <i class="fa fa-level-up" aria-hidden="true" style="margin-right: 5px;"></i>\
                                    <span class="resource-info">' + $.lang[LANG]["plan.upgrade"] + '</span>\
                                </a>\
                            ';
    
                        if(typeof thisResourceTab.find('.fileinput-button').attr('data-limit') == 'undefined') {
                            var check_langs = (typeof SLANG != 'undefined' && !$.isEmptyObject(SLANG.lists) && SLANG.lists.length > 1) ? true : false;
                            var str = (data.is_limit) ? upgrade_btn : load_btn,
                                css_str = (data.is_limit) ? { 'background-color':'#4889e7', 'margin-left':'5px' } : {}, 
                                max_str = (data.is_limit) ? '<span class="error">' + $.lang[LANG]['plan.disk-space.limit.info'] + '</span> ' : '';
                            if(data.is_limit && check_langs) max_str = '<span class="error" style=" line-height: 1.4; display: inline-block; text-align: right;">' + $.lang[LANG]['plan.disk-space.limit.info.lang'] + '</span>';

                            thisResourceTab.find('.fileinput-button').attr('data-limit',data.is_limit).html(str).css(css_str);
                            thisResourceTab.find('.upload-max-size').html(max_str);
                        }
                        thisResourceTab.find('.resource-search-btn').removeClass('clicked');
                    }
                
                }
                if(thisResourceFiles.data('uiSelectableScroll')) thisResourceFiles.data('uiSelectableScroll').refresh();
            }
            thisResourceFiles.removeClass('ready');
            thisResourceFiles.find('.listprogress').remove();
        }
    });

    cPage = page;
    setResourceSelectedBox('my');
}

var resourcePaging = function(page,total,ffolder) {
    view = RVIEW;
    $('.modal-resourcebox .resource-paging').empty();

    page_view = 10;
    start = Math.floor((page-1) / page_view) * page_view;
    pages = Math.ceil(total/view);
    end = (Math.floor((page-1) / page_view) + 1) * page_view;
    end = (end>pages) ? pages : end;

    prev = (start > 0) ? start : 1;
    next = ((end+1) > pages) ? pages : end+1;

    ffolder = (ffolder) ? 'ffolder' : 'all';

    var str = '\
    <ul class="pagination pagination-sm" data-pages="'+pages+'">\
        <li><a href="javascript:;" onclick="resourceGetPage(' + prev + ')">&laquo;</a></li>\
    ';
    for(i=start;i<end;i++) {
        active = ((i+1)==page) ? 'active' : '';
        str = str + '\
        <li class="' + active + '"><a href="javascript:;" onclick="resourceGetPage(' + (i+1) + ')">' + (i+1) + '</a></li>\
        ';
    }
    str = str + '\
        <li><a href="javascript:;" onclick="resourceGetPage(' + next+ ')">&raquo;</a></li>\
    </ul>\
    ';

    if(total) $('.modal-resourcebox .resource-paging').append(str);
}

function formatFileSize(bytes,decimalPoint,return_style) {
    if(typeof return_style == 'undefined' || !return_style)  return_style = 'str';

    var return_val = {'val': 0, 'unit': 'Bytes'};
    
    if(bytes == 0) {
        return (return_style == 'obj') ? return_val : '0 KB';
    }

    var k = 1024,
        dm = decimalPoint || 2,
        sizes = ['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
        i = Math.floor(Math.log(bytes) / Math.log(k));

    return_val['val'] = parseFloat((bytes / Math.pow(k, i)).toFixed(dm));
    return_val['unit'] = sizes[i];

    if(return_style == 'obj') return return_val
    else return return_val['val'] + ' ' + return_val['unit'];
}

var resourceFileTag = function (source, seq, path, selected, ffolder, page, origname, filesize, file_w, file_h, magic, date) {

    filesize = (/^[0-9.]*$/.test(filesize)) ? filesize * 1 : 0;
    file_w = (/^[0-9.]*$/.test(file_w)) ? file_w * 1 : 0;
    file_h = (/^[0-9.]*$/.test(file_h)) ? file_h * 1 : 0;

    var active = ($.inArray(seq,selected)>-1) ? ' ui-selected' : '',
        blank = (magic == '') ? path + '/' + source : getServeImage(magic,'0','');
        image = (magic == '') ? path + '/800/' + source : magic,
        fsize_obj = formatFileSize(filesize, 2, 'obj');
    
    var ftag_str = '\
        <li class="fitem' + active + '">\
            <div class="fitem-wrap">\
                <div class="fitem-visual">\
                    <div class="fitem-thumb">\
                        <div class="fitem-mold"><img src="https://storage.googleapis.com/i.addblock.net/sample/sns_cm_1.png"/></div>\
                        <img class="fitem-img" src="' + image + '" alt="' + source + '">\
                    </div>\
                    <div class="fitem-name visible-layout-list"><span>'+origname+'</span></div>\
                    <div class="fitem-ctrl">\
                        <ul data-ffolder="'+ffolder+'" data-page="'+page+'" data-source="'+source+'" data-seq="'+seq+'" data-fsize="'+filesize+'">\
                            <li class="hover">\
                                <a class="fitem-ctrl-imgview" data-url="' + blank + '" data-img-original="ON">\
                                    <svg viewBox="0 0 13 13" width="13" height="13"><path d="M5.14 1c2.28 0 4.14 1.86 4.14 4.14 0 2.28-1.86 4.14-4.14 4.14S1 7.43 1 5.14C1 2.86 2.86 1 5.14 1m0-1C2.3 0 0 2.3 0 5.14s2.3 5.14 5.14 5.14 5.14-2.3 5.14-5.14S7.98 0 5.14 0z"/><path d="M12.5 13a.47.47 0 0 1-.35-.15L8.22 8.92c-.2-.2-.2-.51 0-.71s.51-.2.71 0l3.93 3.93c.2.2.2.51 0 .71-.1.1-.23.15-.36.15z"/></svg>\
                                </a>\
                            </li>\
                            <li class="hover">\
                                <a class="fitem-ctrl-down" href="/down/fetchimg?s=' + blank + '" alt="' + source + '" download="' + origname + '" target="_self">\
                                    <svg viewBox="0 0 13 13" width="13" height="13"><path d="M6.46 7.59 2.71 3.83 2 4.54l3.76 3.75.7.71.71-.71 3.76-3.75-.71-.71z"/><path d="M6 8V0h1v8z"/><path d="M12 12V7h1v5z"/><path d="M0 12V7h1v5z"/><path d="M13 13H0v-1h13z"/></svg>\
                                </a>\
                            </li>\
                            <li class="hover">\
                                <span class="fitem-ctrl-del">\
                                    <svg viewBox="0 0 12 13" width="12" height="13"><path d="M12 2H9V0H3.02v2H0v1h1v8c0 1.1.9 2 2 2h6c1.1 0 2-.9 2-2V3h1V2zM4.02 1H8v1H4.02V1zM10 11c0 .55-.45 1-1 1H3c-.55 0-1-.45-1-1V3h8v8z"></path><path d="M4 4h1v7H4z"></path><path d="M7 4h1v7H7z"></path></svg>\
                                </span>\
                            </li>\
                            <li class="visible-layout-list w132"><span class="fitem-date">' + date + '</span></li>\
                            <li class="visible-layout-list w85"><span class="fitem-size2">' + file_w + 'x' + file_h + '</span></li>\
                            <li class="visible-layout-list w82"><span class="fitem-size3" data-unit="'+fsize_obj['unit']+'">'+fsize_obj['val']+'</span></li>\
                        </ul>\
                    </div>\
                </div>\
                <div class="fitem-content visible-layout-grid">\
                    <p class="fitem-name" data-seq="' + seq + '" data-source="' + source + '" data-magic="' + magic + '" data-toggle="tooltip" data-placement="top" data-original-title="' + origname + '">' + origname + '</p>\
                    <p class="fitem-size"><span class="size" data-size="'+filesize+'" data-unit="'+fsize_obj['unit']+'">'+fsize_obj['val']+'</span><span class="width">'+file_w+'</span><span class="height">'+file_h+'</span></p>\
                    <p class="visible-layout-grid fitem-date2">' + date + '</p>\
                </div>\
            </div>\
        </li>\
    ';

    return $(ftag_str);
}


var myStorageActive = function() {
    return ($('#mystorage').hasClass('active')) ? true : false;
}

var frStorageUpload = function(v,w,id) {
    var deferred = $.Deferred(),
        id = (typeof id != 'undefined' && id) ? id : $('li[data-source="' + v + '"]').attr('data-id');

    var ex = v.split("|"),
        s = [];
    if(ex.length>1) {
        $.each(ex, function(i,d) {
            s[i] = $('li[data-source="' + d + '"]').attr('data-id');
        });
    } else {
        s[0] = id;
    }
    var ids = s.join("|");

    setTimeout(function() {
        $.ajax({
            type : 'post',
            url: '/template/frstorage/upload',
            data: { img : v, sid : SID, w : w, ids : ids },
            dataType: 'json',
            async: false,
            success: function (data) {
                $.processOFF();
                if(data.error) { 
                    alert(data.error);
                    return false;
                }
                deferred.resolve(data);
            }
        });
    });
    return deferred.promise();
}

var uploadReviewQnaImg = function (e) {
    var mode = e.data.mode;
    if(mode != 'qna' && mode != 'review'){
        return false;
    }
    var imageCnt = $('.'+mode+'-files-list').children('li').length;
    if (imageCnt >= 5) {
        alert('이미지는 최대 5개까지 등록이 가능합니다.');
        return false;
    }

    var sid = $('#'+mode+'-file').attr('data-sid'),
        uid = $('#'+mode+'-file').attr('data-uid');

    $.uploadON();
    $(this).fileupload({
        url: '/_upload/type/'+mode+'/sid/'+sid+'/uid/'+uid,
        dataType: 'json',
        pasteZone: null,
        async: true,
        sequentialUploads: true,
        change: function(e, data) {
            var fileCount = $('.'+mode+'-files-list>li').length + data.files.length;
            if(fileCount > 5) {
                alert('이미지는 최대 5개까지 등록이 가능합니다.');
                return false;
            }

            var ext = ['gif', 'jpg', 'jpeg', 'png', 'webp'];
            var maxSize  = 1024 * 1024 * 10;
            var flag = true;
            $.each(data.fileInput[0]['files'], function(idx, item){
                var extAry = item['name'].toLowerCase().split('.');
                if (ext.indexOf(extAry[extAry.length - 1]) == -1) {
                    alert($.lang[LANG]['editor.upload.error.ext']);
                    flag = false;
                    return false;
                }

                var fileSize = item['size'];
                if (fileSize > maxSize) {
                    alert($.lang[LANG]['editor.upload.max.1'] + $.lang[LANG]['editor.upload.max.2']);
                    flag = false;
                    return false;
                }
            });
            
            if(flag === false) {
                return false;
            }
            
        },
        add: function(e, data) {
            var r = $.upload_add(e,data,'image');

            if(r.submit) {
                var jqXHR = data.submit();
                UPLOAD++;
            } else {
                data.context.find('.loading').html('<i class="fa fa-times error"></i>');
                data.context.find('.ing').addClass('error').text(r.err);
            }

            $('.uploadModal .upload-cancel .btn, .uploadModal .upload-close').off('click').on('click', function(e) {
                if(jqXHR != undefined) jqXHR.abort();
                data.context.fadeOut().remove();
                $('.uploadModal #file-upload-progress').css('width','0%');
                $.uploadOFF();
                UPLOAD = 0;
                UPLOADED = 0;
                PROGRESS = 0;
            });
        },
        progress: function(e, data) {
            $.upload_progress(e,data);
        },                        
        done: function(e, data) {
            $.upload_done(e,data);
            if(typeof data.result.error != 'undefined' && data.result.error) {
                $.processOFF();
                return false;
            }
            
            UPLOADED++;
            var src = (typeof data.result.magic != 'undefined') ? data.result.magic : data.result.src;
            var src_orig = (typeof data.result.magic != 'undefined') ? data.result.src_orig : '';
            var uploadedImg = '\
                <li id="'+mode+'-image-'+imageCnt+'">\
                    <img src="'+src+'" class="img-responsive" />\
                    <input type="hidden" name="'+mode+'_image[]" value="'+src+'" />\
                    <input type="hidden" name="'+mode+'_image_orig[]" value="'+src_orig+'" />\
                    <div class="cl-s-files-img-close '+mode+'-img-close"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 8 8" width="8" height="8"><path d="M4.71 4l3.15-3.15c0.2-0.2 0.2-0.51 0-0.71s-0.51-0.2-0.71 0L4 3.29 0.85 0.15c-0.2-0.2-0.51-0.2-0.71 0s-0.2 0.51 0 0.71L3.29 4 0.15 7.15c-0.2 0.2-0.2 0.51 0 0.71C0.24 7.95 0.37 8 0.5 8s0.26-0.05 0.35-0.15L4 4.71l3.15 3.15C7.24 7.95 7.37 8 7.5 8s0.26-0.05 0.35-0.15c0.2-0.2 0.2-0.51 0-0.71L4.71 4z"/></svg></div>\
                </li>\
            ';

            $('.'+mode+'-files-list').append(uploadedImg);
            imageCnt++;

            if(UPLOADED) {
                if(UPLOAD==UPLOADED) {
                    setTimeout(function() {
                        $.uploadOFF();
                        UPLOAD = 0;
                        UPLOADED = 0;
                        PROGRESS = 0;
                    },1000);
                }
            }
        },
        progressall: function (e, data) {
            $.upload_progressall(e,data);
        },
        start : function(e, data) {
            $.upload_start(e,data);
            progress1 = 0; progress2 = 0; PROGRESS = 0;
        },
        dragover : function(e, data) {
            e.preventDefault();
        },
    }).prop('disabled', !$.support.fileInput)
        .parent().addClass($.support.fileInput ? undefined : 'disabled');
}

var deleteReviewQnaImg = function(e) {
    var mode = e.data.mode;
    if(mode != 'qna' && mode != 'review'){
        return false;
    }
    var parent = $(this).closest('li');
    var src_orig = parent.find('input[name="'+mode+'_image_orig[]"]').val();
    var seq = $('#'+mode+'-file').data('seq');
    var src_files = '';
    var src_files_orig = '';

    if(seq) {
        if($('.'+mode+'-files-list').children('li').length > 0) {
            $('.'+mode+'-files-list').children('li').each(function() {
                if(src_orig != $(this).find('input[name="'+mode+'_image_orig[]"]').val()) {
                    if(src_files != '')  src_files +='||';
                    src_files += $(this).find('input[name="'+mode+'_image[]"]').val();
                    if(src_files_orig != '')  src_files_orig +='||';
                    src_files_orig += $(this).find('input[name="'+mode+'_image_orig[]"]').val();
                }
            });
        }
    }

    $.processON('Deleting File...');
    $.ajax({
        type: 'POST',
        url: '/_image_delete',
        data: {
            s: src_orig,
            seq: seq,
            src_files: src_files,
            src_files_orig: src_files_orig,
            mode: mode,
        },
        async: true,
        success: function(data) {
            // console.log(data);
            checkError(data);
            parent.remove();
            $.processOFF();
        }
    });
}

var addrSearchModal = function(input_mode) {
    if(typeof input_mode == 'undefined' || input_mode.length == 0)  input_mode = 'input';

    if($('script[src="https://ssl.daumcdn.net/dmaps/map_js_init/postcode.v2.js"]').length === 0) {
        $.getScript('https://ssl.daumcdn.net/dmaps/map_js_init/postcode.v2.js')
            .done(function() { 
                $('head').append('<script src="https://ssl.daumcdn.net/dmaps/map_js_init/postcode.v2.js"></script>'); 
                // $('head').append('<script src="http://dmaps.daum.net/map_js_init/postcode.v2.js?autoload=false"></script>'); 
                setTimeout(function() { addrSearchModal(input_mode); }, 500);
            }).fail(function() { console.log('daum maps script fail'); });
    } else {

        if($('#addr-modal').length === 0) {
            var add_position = ($('.mall-mypage-wrap').length > 0) ? $('.mall-mypage-wrap') : $('body'),
                as_backdrop = '<div class="addr-modal-backdrop" style="display: none;"></div>';
                as_modal = '<div id="addr-modal" style="display: none;">\
                                <div class="close">\
                                    주소 찾기\
                                    <div id="btn-addr-close"><img src="https://storage.googleapis.com/i.addblock.net/fa-close-modal.png" alt="close"></div>\
                                </div>\
                                <div id="addr-body"></div>\
                            </div>';

            add_position.append(as_backdrop + as_modal);
        } else {
            $('#addr-body').html('');
        }


        $(document).on('click','#btn-addr-close, .addr-modal-backdrop', function() {
            $('#addr-modal').fadeOut(300);
            $('.addr-modal-backdrop').fadeOut(300, function() { $(this).removeClass('in'); });
        });



        // Internet Explorer 6-11
        var isIE = /*@cc_on!@*/false || !!document.documentMode;

        if(isIE && input_mode == 'my-input') {

            daum.postcode.load(function(){
                new daum.Postcode({
                    oncomplete: function(data) {
                        var addr = ''; // 주소 변수
                        var extraAddr = ''; // 참고항목 변수

                        if (data.userSelectedType === 'R') { // 사용자가 도로명 주소를 선택했을 경우
                            addr = data.roadAddress;
                        } else { // 사용자가 지번 주소를 선택했을 경우(J)
                            addr = data.jibunAddress;
                        }

                        if(data.userSelectedType === 'R'){
                            if(data.bname !== '' && /[동|로|가]$/g.test(data.bname)){
                                extraAddr += data.bname;
                            }

                            if(data.buildingName !== '' && data.apartment === 'Y'){
                                extraAddr += (extraAddr !== '' ? ', ' + data.buildingName : data.buildingName);
                            }

                            if(extraAddr !== ''){
                                extraAddr = ' (' + extraAddr + ')';
                            }
                        }

                        $('#'+input_mode+"-postcode").attr('value',data.zonecode);
                        $('#'+input_mode+"-addr1").attr('value',addr+extraAddr).addClass('has-value');

                        setTimeout(function() {
                            $('#'+input_mode+"-addr2").focus();
                        },200);

                    },
                    width : '100%',
                    height : '100%',
                    maxSuggestItems : 5
                }).open();
            });

        } else {


            daum.postcode.load(function(){
                new daum.Postcode({
                    oncomplete: function(data) {
                        var addr = ''; // 주소 변수
                        var extraAddr = ''; // 참고항목 변수

                        if (data.userSelectedType === 'R') { // 사용자가 도로명 주소를 선택했을 경우
                            addr = data.roadAddress;
                        } else { // 사용자가 지번 주소를 선택했을 경우(J)
                            addr = data.jibunAddress;
                        }

                        if(data.userSelectedType === 'R'){
                            if(data.bname !== '' && /[동|로|가]$/g.test(data.bname)){
                                extraAddr += data.bname;
                            }

                            if(data.buildingName !== '' && data.apartment === 'Y'){
                                extraAddr += (extraAddr !== '' ? ', ' + data.buildingName : data.buildingName);
                            }

                            if(extraAddr !== ''){
                                extraAddr = ' (' + extraAddr + ')';
                            }
                        }

                        $('#'+input_mode+"-postcode").attr('value',data.zonecode);
                        $('#'+input_mode+"-addr1").attr('value',addr+extraAddr).addClass('has-value');  
                        $('#addr-modal').fadeOut(300);
                        $('.addr-modal-backdrop').fadeOut(300, function() { $(this).removeClass('in'); });

                        setTimeout(function() {
                            $('#'+input_mode+"-addr2").focus();
                        },200);

                    },
                    width : '100%',
                    height : '100%',
                    maxSuggestItems : 5
                }).embed(document.getElementById('addr-body'));

                $('#addr-modal').fadeIn(300);
                $('.addr-modal-backdrop').fadeIn(300, function() { $(this).addClass('in'); });
            });

        }
    }
}
var stickyToolbar = function() {
    if($('.gallery-header').length == 0) return;
    var sticky = $('.gallery-modal > .container').offset().top - 50,
        w = $('.gallery-items .table-item').width();
    if($('.gallery-modal > .container').outerHeight() + sticky < 0) { 
        $('.gallery-modal .toolbar, .gallery-modal .table-col').addClass('sticky');
        $('.table-toolbar').css('width',w + 'px');
    } else {
        $('.gallery-modal .toolbar, .gallery-modal .table-col').removeClass('sticky');
        $('.table-toolbar').css('width','auto');
    }
}            

var saveGalleryBlockName = function($this,blockname) {
    var blockID = $this.parents('.gallery-name').attr('data-gallery-id');
    if(typeof blockID == "undefined" || !blockID) {
        $this.showModalFlat('ERROR',$.lang[LANG]['board.error-setting-value'],true,false,'','ok');
        return false;
    }
    var settings = (typeof SETTINGS =='undefined') ? $.gallery.site_settings : SETTINGS;
    var bookmark_list = (typeof settings.blockBookmarkList != 'undefined' && settings.blockBookmarkList) ? settings.blockBookmarkList : {},
        isBookmark = (typeof bookmark_list['bookmark'+blockID] != 'undefined' && bookmark_list['bookmark'+blockID]) ? true : false,
        before_bookmark_name_arr = [],
        blockname_list = (typeof settings.blocknameList != 'undefined' && settings.blocknameList) ? settings.blocknameList : {},
        regex = /[\{\}\[\]\/!?.,;:|\)*~`^\-+<>@\#$%&\\\=\(\'\"]/gi,
        err_str = '', 
        isUpdate = false;

    if(!$.isEmptyObject(bookmark_list)) { // 이전 bookmark name 설정한 블럭 이름 포함
        $.each(bookmark_list, function(k,v) { 
            if(typeof blockname_list[k.replace('bookmark','blockname')] == 'undefined') {
                before_bookmark_name_arr.push(v);
            }
        });
    }

    var blockname_list_arr = (!$.isEmptyObject(blockname_list)) ? Object.keys(blockname_list).map(function(e) { return blockname_list[e]; }) : new Array();

    if(typeof blockname_list['blockname'+blockID] != 'undefined' && blockname_list['blockname'+blockID] == blockname) {
        $('.blockname-edit').remove();
        return false;
    } else if (blockname.length == 0 || blockname.length > 20) {
        err_str = $.lang[LANG]['config.blockinfo.name.length'];
    } else if (regex.test(blockname)) {
        err_str = $.lang[LANG]['config.blockinfo.name.specialchar'];
    } else if ($.inArray(blockname,blockname_list_arr) > -1 || $.inArray(blockname,before_bookmark_name_arr) > -1) {
        err_str = $.lang[LANG]['config.blockinfo.name.overlap'];
    } else {
        $.post('/template/element/type/blockname/seq/'+blockID, { sid: SID, val: blockname }, function(data) {
            if(typeof data.error != 'undefined' && data.error) {
                err_str = data.error;
            } else {
                isUpdate = true;
            }
        }, 'json');
    }

    if(err_str.length > 0 ) {
        $this.showModalFlat($.lang[LANG]['config.information'],err_str,true,false,'','ok', '', 'cl-p130 cl-cmmodal cl-s-btn w560 cl-p0 cl-okbtn-pbt70');
    } else {
        $this.parents('.gallery-name').find('.gallery-block-name').text(blockname);
        $this.parents('.gallery-name-edit-input').remove();
        if($.gallery.block_id == blockID) {
            $('#gallery-name').text(blockname);
        }
    }

    if(!isUpdate) return false;
    blocknameUpdate(SID,blockID,blockname);
    blocknameListUpdate('update',SID,blockID,blockname);
    if(isBookmark) blockBookmarkListUpdate('update',SID,blockID,blockname);
}

var blocknameDelete = function(sid, seq) {
    var settings = (typeof SETTINGS =='undefined') ? $.gallery.site_settings : SETTINGS;
    if (typeof seq == 'undefined' || typeof sid == 'undefined' || !seq || !sid || typeof settings.blockBookmarkList == 'undefined' || typeof settings.blockBookmarkList['bookmark' + seq] == 'undefined') return false;
    if ($('#tpl-menu li a[href="@' + seq + '"][attr-bookmark]').length > 0) {
        resetLink($('#tpl-menu li a[href="@' + seq + '"][attr-bookmark]').text());
    }
    blocknameUpdate(sid, seq, '');
    blocknameListUpdate('delete', sid, seq);
}

var blocknameUpdate = function(sid, id, name) {
    var elsettings = { blockname: name },
        delete_key = (typeof name == 'undefined' || !name) ? 'blockname' : '';

    $.post('/template/settings', { sid: sid, settings: JSON.stringify(elsettings), el: id, delete: delete_key }, function(data) {
        var isCheck = checkError(data);
        if (!isCheck) return false;

        $('.property-blockname-wrap .blockname-txt').text(name);
    }, 'json');
}

var blocknameListUpdate = function(fn, sid, id, name) {
    var settings = (typeof SETTINGS =='undefined') ? $.gallery.site_settings : SETTINGS;

    if (typeof settings.blocknameList == 'undefined') { settings.blocknameList = {}; }
    var blockname_list = {};

    if (fn == 'update') {
        var blockname_item = {};
        blockname_item['blockname' + id] = name;
        blockname_list = $.extend({}, settings.blocknameList, blockname_item);
    } else if (fn == 'delete') {
        if (typeof settings.blocknameList['blockname' + id] == 'undefined') { return false; }
        delete settings.blocknameList['blockname' + id];
        blockname_list = settings.blocknameList;
    }

    var update = { blocknameList: blockname_list },
        delete_key = ($.isEmptyObject(blockname_list)) ? 'blocknameList' : '';

    $.post('/template/settings', { sid: sid, settings: JSON.stringify(update), el: 'site_settings', delete: delete_key }, function(data) {
        var isCheck = checkError(data);
        if (!isCheck) return false;
        settings.blocknameList = blockname_list;
    }, 'json');
}

var blockBookmarkDelete = function(sid, seq) {
    var settings = (typeof SETTINGS =='undefined') ? $.gallery.site_settings : SETTINGS;
    if (typeof seq == 'undefined' || typeof sid == 'undefined' || !seq || !sid || typeof settings.blockBookmarkList == 'undefined' || typeof settings.blockBookmarkList['bookmark' + seq] == 'undefined') return false;
    if ($('#tpl-menu li a[href="@' + seq + '"][attr-bookmark]').length > 0) {
        resetLink($('#tpl-menu li a[href="@' + seq + '"][attr-bookmark]').text());
    }
    blockBookmarkUpdate(sid, seq, false);
    blockBookmarkListUpdate('delete', sid, seq);
}

var blockBookmarkUpdate = function(sid, id, onoff) {
    var elsettings = { bookmark: onoff },
        delete_key = (onoff) ? '' : 'bookmark';

    $.post('/template/settings', { sid: sid, settings: JSON.stringify(elsettings), el: id, delete: delete_key }, function(data) {
        var isCheck = checkError(data);
        if (!isCheck) return false;

        if (onoff) $('.element[data-id="' + id + '"]').removeAttr('data-bookmark');
        else $('.element[data-id="' + id + '"]').attr('data-bookmark', id);
    }, 'json');
}

var blockBookmarkListUpdate = function(fn, sid, id, name) {
    var settings = (typeof SETTINGS =='undefined') ? $.gallery.site_settings : SETTINGS;
    if (typeof settings.blockBookmarkList == 'undefined') { settings.blockBookmarkList = {}; }
    var bookmark_list = {};

    if (fn == 'update') {
        var bookmark_item = {};
        bookmark_item['bookmark' + id] = name;
        bookmark_list = $.extend({}, settings.blockBookmarkList, bookmark_item);
    } else if (fn == 'delete') {
        if (typeof settings.blockBookmarkList['bookmark' + id] == 'undefined') { return false; }
        delete settings.blockBookmarkList['bookmark' + id];
        bookmark_list = settings.blockBookmarkList;
    }

    var update = { blockBookmarkList: bookmark_list },
        delete_key = ($.isEmptyObject(bookmark_list)) ? 'blockBookmarkList' : '';

    $.post('/template/settings', { sid: sid, settings: JSON.stringify(update), el: 'site_settings', delete: delete_key }, function(data) {
        var isCheck = checkError(data);
        if (!isCheck) return false;
        settings.blockBookmarkList = bookmark_list;
    }, 'json');

    if (fn == 'delete') { //gallery item - link(attr-bookmark) unset
        $.post('/template/element/type/gitem-bookmarklink-delete/seq/' + id, { sid: SID }, function(data) {
            checkError(data);
        }, 'json');
    }
}

var makeBookmarkList = function(bookmarklist, type, id, link) {
    var str = '',
        isActive = '';

    if (typeof bookmarklist == 'undefined' || !bookmarklist) return str;
    if (bookmarklist == '{}') bookmarklist = {};
    var hideArray = (typeof bookmarklist.hide == 'undefined' || !bookmarklist.hide) ? {} : bookmarklist.hide;

    $.each(bookmarklist, function(k, v) {
        var n_k = k.replace('bookmark', '');
        if (k != 'hide') {
            isActive = (k == link.replace(/^\@/g, 'bookmark')) ? 'active' : '';
            if (hideArray.length > 0) {
                if (hideArray.includes(n_k)) {
                    return true;
                } else {
                    str = str + '<li class="' + isActive + '" data-bookmark="' + k + '" data-bookmark-name="' + v + '"><a href="javascript:;">' + v + '</a></li>';
                }
            } else {
                str = str + '<li class="' + isActive + '" data-bookmark="' + k + '" data-bookmark-name="' + v + '"><a href="javascript:;">' + v + '</a></li>';
            }
        }
    });
    return str;
}

var galleryStatusInit = function() {
    $('.gallery-items > div').removeClass('active ui-selected').find('input').prop('checked','');
    // $('.table-toolbar > li').addClass('disabled').find('i[data-cmd="visible"]').text('숨김');
    $('.table-toolbar > li').find('i[data-cmd="visible"]').text('숨김');
    $('.gallery-toolbar .toolbar.mod-gallery').remove();
}

var shoppingGalleryResize = function() {
    var $list = $('.product-gallery-list'),
        $category = $('.gallery-category'),
        $more = $('.gallery-items-loadmore'),
        $items = $('.gallery-items'),
        $toggle = $('.product-gallery-list-toggle'),
        $pagination = $('.pagination-wrap'),
        $filter = $('.gallery-list-filter'),
        $name = $('.selected-gallery-name'),
        $lux_filter = $('.shop-filter-header'),
        svg_open = '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-chevron-right" viewBox="0 0 16 16"><path fill-rule="evenodd" d="M4.646 1.646a.5.5 0 0 1 .708 0l6 6a.5.5 0 0 1 0 .708l-6 6a.5.5 0 0 1-.708-.708L10.293 8 4.646 2.354a.5.5 0 0 1 0-.708z"/></svg>',
        svg_close = '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-chevron-left" viewBox="0 0 16 16"><path fill-rule="evenodd" d="M11.354 1.646a.5.5 0 0 1 0 .708L5.707 8l5.647 5.646a.5.5 0 0 1-.708.708l-6-6a.5.5 0 0 1 0-.708l6-6a.5.5 0 0 1 .708 0"/></svg>',
        status = window.localStorage.getItem('product-gallery-closed');
    var w = $('.gallery-modal')[0]['clientWidth'],
        t = ($('.gallery-modal').hasClass('shopping')) ? true : false,
        g = (t) ? 1440 : 0,
        o = ($('.product-gallery-list').hasClass('open')) ? true : false;

    if(g > 0 && w <= g && o == true) {
        $toggle.removeClass('open');
        $list.removeClass('open');
        $category.removeClass('open');
        $more.removeClass('open');
        $items.removeClass('open');
        $pagination.removeClass('open');
        $filter.removeClass('open');
        $name.removeClass('open');
        $lux_filter.removeClass('open');
        if($toggle.hasClass('open')) {
            $toggle.html(svg_open);
        } else {
            $toggle.html(svg_close);
        }
    } 
    if(w > g && status == 'false') {
        $toggle.addClass('open');
        $list.addClass('open');
        $category.addClass('open');
        $more.addClass('open');
        $items.addClass('open');
        $pagination.addClass('open');
        $filter.addClass('open');
        $name.addClass('open');
        $lux_filter.addClass('open');
        if($toggle.hasClass('open')) {
            $toggle.html(svg_open);
        } else {
            $toggle.html(svg_close);
        }
    }
}

var resizeGalleryModal = function() {
    var w = $('.gallery-modal')[0]['clientWidth'],
        $c_p = $('.gallery-modal > .gallery-header'),
        $c_m = $('.gallery-modal > .container, .gallery-modal > .gallery-items, .gallery-modal > .gallery-items-loadmore'),
        t = ($('.gallery-modal').hasClass('shopping')) ? true : false,
        g = (t) ? 1124 : 1146,
        p = ((w-g) > 0) ? (w-g)/2 : 0,
        scroll_bar = ($.browser.safari == undefined) ? 17 : 8;
    if(p < 50) p = 50;
    $c_p.css({'padding-left': p + 'px', 'padding-right': p + 'px'});
    $c_m.css({'margin-left': p + 'px', 'margin-right': p + 'px', 'width': 'auto', 'max-width': '100%'});
    document.querySelector('.gallery-modal').style.setProperty('--gallery-modal-pl', p+'px', null);
    document.querySelector('.gallery-modal').style.setProperty('--gallery-modal-pr', (p+scroll_bar)+'px', null);
}

var switchDownload = function(option_onoff) {
    if($('#download-product').is(':checked') === true) { //다운로드 상품
        var firstOption = $('.prod-option[data-option_mode="normal"] .prod-option-list > li').eq(1);
        var noneOption = $('.prod-option[data-option_mode="normal"] .prod-option-list > li').eq(0);
        
        var downloadContent = '';
        var state = false;

        if ($('#none-option-file').length > 0 && option_onoff == 'on') {
            if ($('#none-option-file .file-name').length > 0) {
                // var optionSeq = (firstOption.find('.prod-option-title').attr('data-seq')!='')? firstOption.find('.prod-option-title').attr('data-seq') : '';
                var fileUrl = $('#none-option-file .file-url').text(),
                    fileSize = $('#none-option-file .file-size').text(),
                    fileNameDetail = $('#none-option-file .file-name-detail').text(),
                    realFileName = $('#none-option-file .real-file-name').text();
                state = true;
            } else if($('#none-option-file .none-file-name').length > 0) {
                // var optionSeq = (firstOption.find('.prod-option-title').attr('data-seq')!='')? firstOption.find('.prod-option-title').attr('data-seq') : '';
                var fileUrl = $('#none-option-file .none-file-url').text(),
                    fileSize = $('#none-option-file .none-file-size').text(),
                    fileNameDetail = $('#none-option-file .none-file-name-detail').text(),
                    realFileName = $('#none-option-file .none-real-file-name').text();

                state = true;        
            }

            var dataPn = $('#none-option-file .cl_icon_close').attr('data-pn'),
                dataFile = $('#none-option-file .cl_icon_close').attr('data-file');
            var fileCnt = 2;
            var optionSeq = $('#none-option-file .cl_icon_close').attr('data-seq');
        }
        if(firstOption.find('.file-name').length > 0 && option_onoff == 'off'){
            var optionSeq = (noneOption.find('.prod-option-title').attr('data-seq')!='')? noneOption.find('.prod-option-title').attr('data-seq') : '';
            var fileUrl = firstOption.find('.file-url').text(),
                fileSize = firstOption.find('.file-size').text(),
                fileNameDetail = firstOption.find('.file-name-detail').text(),
                realFileName = firstOption.find('.real-file-name').text(),
                dataPn = firstOption.find('.cl_icon_close').attr('data-pn'),
                dataFile = firstOption.find('.cl_icon_close').attr('data-file');
            var fileCnt = 1;
            state = true;
        }
        // console.log(state);
        if(state === true) {
            downloadContent = '\
                <div class="file-name file-name-'+fileCnt+'">\
                    <span class="real-file-name">'+realFileName+'</span>\
                    <span class="file-name-detail" title="'+realFileName+'">'+fileNameDetail+'</span>\
                    <span class="file-size">'+fileSize+'</span>\
                    <span class="cl-icon cl_icon_close" data-cnt="1" data-pn="'+dataPn+'" data-file="'+dataFile+'" data-seq="'+optionSeq+'"></span>\
                    <span class="file-url">'+fileUrl+'</span>\
                </div>\
            ';
        }
        // console.log(downloadContent);
        if ($('#normal-option').is(':checked') === true) {
            // console.log(firstOption.find('.file-box-list'));
            firstOption.find('.file-box-list').html(downloadContent);
            firstOption.find('.prod-option-status').text('판매').attr('data-val', 'S');

            $('#add-upload-check .product-upload').remove();
            noneOption.find('.file-name').remove();   
        } else {
            var html = '\
                <div class="product-upload">\
                    <div class="title">파일 업로드</div>\
                    <div class="download-contents">\
                        <span class="cl_icon_upload02" data-cnt="0">업로드</span>\
                        <div id="none-option-file">'+downloadContent+'</div>\
                    </div>\
                </div>';

            $('#add-upload-check').prepend(html);
            noneOption.find('.file-box-list').html(downloadContent);
            if ($('#none-option-file').length == 0) {
                $('.switch-product[value="off"]').prop('checked', true);
                $('#status-append').fadeOut(0);
                $('#sale-calendar').hide();
            }
            // firstOption.find('.file-name').remove();;
        }
    }
}

var addProductOption = function(optionMode) {
    var $parent;
    var option_mode; //일반, 입력, 추가
    
    if(optionMode=='normal' || optionMode=='text' || optionMode=='additional'){
        $parent = $('.prod-option[data-option_mode="'+optionMode+'"]');
        option_mode = optionMode; //일반, 입력, 추가
    } else {
        $parent = $(this).parent();
        option_mode = $parent.data('option_mode'); //일반, 입력, 추가
    }
    
    if($parent.find('.prod-option-item.hide').length) {
        $parent.find('.prod-option-item.hide').closest('li').addClass('err').find('.edit-option-title input').focus();
        r = shoppingSetOption($parent.find('.prod-option-item.hide'));
        if(r == false) return r;
    }

    var state = 'normal-product';
    $('.cl_product_state_check').each(function () {
        if ($(this).hasClass('active') === true) {
            state = $(this).attr('for');
        }
    });
    var status = true;
    var productNumber = $('#prod-no').val();
    
    // if (option_mode == "normal" && productNumber) {
    //     if($('.prod-option[data-option_mode="normal"] .prod-option-list>li').length <= 1) {
    //         $.ajax({
    //             url: '/shopping/download_list_check',
    //             type: 'post',
    //             dataType: 'json',
    //             data: {'product_number': productNumber},
    //             success: function (data) {
    //                 if (data.code == 'fail') {
    //                     alert(data.message);
    //                     status = false;
    //                     return false;
    //                 }
    //             }
    //         });
    //     }
    // }
    
    // if (status == false) return false;
    
    var tax = $('#tax').attr('data-total-tax'),
        check_quantity = $('.prod-detail-wrap .switch-quantity').prop('checked');

    var item = '';
    if(option_mode == "text") {
        if($parent.find('li').length >= 6) {
            $('.prod-option[data-option_mode="text"] > .prod-option-add').addClass('disabled');
        }
        if($parent.find('li').length >= 7) {
            alert('입력형 옵션은 최대 7개까지 추가할 수 있습니다.');    
            return false;
        }
        item = '\
            <li>\
                <div class="prod-option-item hide">\
                    <span class="prod-option-title"></span>\
                    <span class="prod-option-require"></span>\
                </div>\
                <div class="prod-option-edit">\
                    <div class="form-wrap">\
                        <div class="form-group edit-option-title">\
                            <input type="text" maxlength="20" placeholder="안내문구 입력 (예:두께를 mm단위로 입력해주세요.)"/>\
                        </div>\
                        <div class="edit-option-delete"><svg viewBox="0 0 12 13" width="12" height="13"><path d="M12 2h-1H9V0H3.02v2H1 0v1h1v8c0 1.1 0.9 2 2 2h6c1.1 0 2-0.9 2-2V3h1V2zM4.02 1H8v1H4.02V1zM10 11c0 0.55-0.45 1-1 1H3c-0.55 0-1-0.45-1-1V3h1.02H9h1V11z"/><rect x="4" y="4" width="1" height="7"/><rect x="7" y="4" width="1" height="7"/></svg></div>\
                    </div>\
                </div>';
    } else {
        item = '\
            <li>\
                <div class="prod-option-item hide">\
                    <span class="prod-option-title"></span>\
                    <span class="prod-option-price"></span>\
                    <span class="prod-option-quantity"></span>\
                    <span class="prod-option-status"></span>\
                    <span class="prod-option-move"><i class="fa fa-arrows" aria-hidden="true"></i></span>\
                </div>\
                <div class="prod-option-edit">\
                    <div class="form-wrap">\
                        <div class="form-group edit-option-title">\
                            <input type="text" maxlength="60" placeholder="옵션값"/>\
                        </div>\
                        <div class="form-group edit-option-price">\
                            <input type="text" class="option-price-number sign" placeholder="0" numberonly/>\
                        </div>\
                        <div class="form-group edit-option-quantity" ' + ((check_quantity) ? '' : 'style="display:none"') + '>\
                            <input type="text" class="option-price-quantity" maxlength="5" placeholder="0" numberonly/>\
                        </div>\
                        <div class="form-group edit-option-select">';
                        if (state == 'download-product' && $parent.attr('data-option_mode') == "normal") item += '<div class="option-price-status-str hand" data-val="O">품절</div>';
                        else item += '<div class="option-price-status-str hand" data-val="S">판매</div>';
                        item += '<ul class="option-price-status-select">\
                                <li data-val="S">판매</li>\
                                <li data-val="O">품절</li>\
                                <li data-val="H">숨김</li>\
                            </ul>\
                        </div>\
                        <div class="edit-option-delete"><svg viewBox="0 0 12 13" width="12" height="13"><path d="M12 2h-1H9V0H3.02v2H1 0v1h1v8c0 1.1 0.9 2 2 2h6c1.1 0 2-0.9 2-2V3h1V2zM4.02 1H8v1H4.02V1zM10 11c0 0.55-0.45 1-1 1H3c-0.55 0-1-0.45-1-1V3h1.02H9h1V11z"/><rect x="4" y="4" width="1" height="7"/><rect x="7" y="4" width="1" height="7"/></svg></div>\
                    </div>\
                </div>';
        if (state == 'download-product' && $parent.attr('data-option_mode') == "normal") {
            item += '\
                <div class="form-group product-status">\
                    <div class="product-state-box">\
                        <div class="product-upload">\
                            <div class="title">파일 업로드</div>\
                            <div class="download-contents">\
                                <span class="cl_icon_upload02" data-cnt="'+fileUpdateCnt+'">업로드</span>\
                                <div class="file-box-list" id="file-box-'+fileUpdateCnt+'"></div>\
                            </div>\
                        </div>\
                    </div>\
                </div>';
            fileUpdateCnt++;
        }
    }
    
    
        item += '</li>';
    var $item = $(item);
    
    $parent.find('.prod-option-list').append($item);
    $('.prod-option[data-option_mode="'+option_mode+'"] .prod-option-list>li:last-child').find('.edit-option-title input').focus();

    $('.plus-price').removeClass('hide');
    // $('.plus-quantity').removeClass('hide');
    $('.plus-status').removeClass('hide');

    // if(option_mode == "normal") {
    //     $('.plus-price').text('추가금액');
    //     $('.plus-quantity').text('수량');
    //     $('.plus-status').text('상태');
    // } else if(option_mode == "additional") {
    //     $('#plus-addt-price').text('금액');
    //     $('#plus-addt-quantity').text('수량');
    //     $('#plus-addt-status').text('상태');
    // } else if (option_mode == "text") {
    //     $('#check-require').text('필수여부');
    // }
    
    if($('.switch-quantity').is(":checked") == true) {
        if($('#normal-option').is(':checked') === true) {
            // $('#prod-quantity').attr('readonly','true').removeClass('hide').attr('placeholder','옵션에서 재고 관리');
            $('.quantity-label').addClass('on');
            $('.plus-quantity').removeClass('hide');
        } else if($('#normal-option').is(':checked') === false && $('#additional-option').is(':checked') === true) {
            $('.quantity-label').removeClass('on');
            $('#prod-quantity').removeAttr('readonly').removeClass('hide');
            $('.plus-quantity').removeClass('hide');
        } else {
            $('.quantity-label').removeClass('on');
            $('#prod-quantity').removeAttr('readonly').removeClass('hide');
            $('.plus-quantity').addClass('hide');
        }
    } else {
        $('.quantity-label').removeClass('on');
        $('.switch-quantity').parents('.form-wrap').addClass('disabled');
        $('#prod-quantity').addClass('hide');
        $('.prod-option-quantity, .prod-plus-quantity, .edit-option-quantity').hide();
        $('.plus-quantity').addClass('hide');
    }

    return true;
}

var shoppingSetOption = function(optionItem) {

    if($('.prod-option-item.hide').length) {
        var $o = (optionItem)? optionItem : $('.prod-option-item.hide');
        var ret = true;

        $o.each(function(){
            var $t = $(this).parent().find('.prod-option-edit input');
            // console.log($t);

            var $title = $t.closest('.form-wrap').find('.edit-option-title input'),
                $desc = $t.closest('.form-wrap').find('.edit-option-desc input'),
                $price = $t.closest('.form-wrap').find('.edit-option-price input'),
                $quantity = $t.closest('.form-wrap').find('.edit-option-quantity input'),
                $status = $t.closest('.form-wrap').find('.option-price-status-str'),
                $text_require = $t.closest('.form-wrap').find('.option-require-str');
        
            var price = removeCommas($price.val()), quantity = removeCommas($quantity.val());
            if (!price) price = 0;
            if (!quantity) quantity = 0;

            if(typeof quantity == 'string') {
                quantity = quantity.replace(/,/gi,'') ;
            }

            quantity = Number(quantity);

            price = parseInt(price);
            quantity = (quantity * 1);
            if(String(price) == "NaN") price = 0;
            var abs_price = Math.abs(price),
                str_price = abs_price.toString(),
                str_quantity = quantity.toString(); 

             if(isNaN(price) === true) {
                $price.val(0);
                price = 0;
                $t.closest('li').find('.prod-option-price').attr('data-option-price', price);
            }

            $t.closest('li').find('.prod-option-title').text($title.val());
            $t.closest('li').find('.prod-option-desc').text($desc.val());
            $t.closest('li').find('.prod-option-price').text(addCommas(str_price));
            $t.closest('li').find('.prod-option-quantity').text(addCommas(str_quantity));
            $t.closest('li').find('.prod-option-status').text($status.text());

            if(price < 0) {
                $t.closest('li').find('.prod-option-price').addClass('minus');
            } else {
                $t.closest('li').find('.prod-option-price').removeClass('minus');
            }
            // if($text_require.find('input').is(':checked') == true) {
            //     var checkbox = "\
            //     <span>필수</span>\
            //     <svg class='active' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' width='16' height='16'>\
            //     <path d='M13 0H3C1.34 0 0 1.34 0 3v10c0 1.66 1.34 3 3 3h10c1.66 0 3-1.34 3-3V3C16 1.34 14.66 0 13 0zM13.03 6.03l-5.5 5.5C7.38 11.68 7.19 11.75 7 11.75s-0.38-0.07-0.53-0.22l-3.5-3.5c-0.29-0.29-0.29-0.77 0-1.06s0.77-0.29 1.06 0L7 9.94l4.97-4.97c0.29-0.29 0.77-0.29 1.06 0S13.32 5.74 13.03 6.03z'/>\
            //     </svg>";
            //     $t.parents('li').find('.prod-option-require').html(checkbox);
            // } else {
            //     var checkbox = "\
            //     <span>필수</span>\
            //     <svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' width='16' height='16'>\
            //     <path d='M13 0H3C1.3 0 0 1.3 0 3v10c0 1.7 1.3 3 3 3h10c1.7 0 3-1.3 3-3V3C16 1.3 14.7 0 13 0zM15 13c0 1.1-0.9 2-2 2H3c-1.1 0-2-0.9-2-2V3c0-1.1 0.9-2 2-2h10c1.1 0 2 0.9 2 2V13z'/>\
            //     </svg>";
            //     $t.parents('li').find('.prod-option-require').html(checkbox);
            // }
            var option_type = $t.closest('.prod-option').attr('data-option_mode');

            if(product_options.advanced == 'false') {
                if($title.val() === undefined || $title.val().trim().length == 0 || (option_type == 'text' && $title.val().trim().length > 20)) {
                    $t.closest('li').addClass('err');
                    if($title.val().trim().length > 20) {
                        alert('옵션명은 20자까지 입력이 가능합니다.');
                    }
                    ret = false;
                    return false;
                }
            }
            if($quantity.val() == '') $t.closest('li').find('.prod-option-quantity').text('0');
            if($('.switch-quantity').is(':checked') == true && $t.closest('li').find('.prod-option-quantity').text() == '0') {
                $t.closest('li').find('.option-price-status-str').attr('data-val','O').text('품절');
                $t.closest('li').find('.prod-option-status').attr('data-val','O').text('품절');
            }

            $t.closest('.prod-option-edit').addClass('hide');
            $t.closest('li').find('.prod-option-item').removeClass('hide');
            $t.closest('li').removeClass('err');

            ret = true;
        });
        
        return ret;
    }
}

var checkDuplicateOptionName = function(el) {
    var titles = $('.prod-option-title').map(function(idx, v) { 
            var str = $(v).text().trim();
            if(str.length > 0) return str;                        
        }).get();
    var input = el.val().trim();
    var cnt = titles.filter(function(el){
                return el == input;
            }).length;
    var flag = false;

    if(input.length > 0 && cnt > 1) {
        el.parents('li').find('.prod-option-title').text('');
        el.val('');
        el.focus();
        flag = true;
        alert('옵션명 중복 오류입니다.'); 
    } else {
        el.parents('li').find('.prod-option-title').removeClass('now-input');
    }

    return flag;
}

var siteConfigOthersCheckModal = function(sid,check_id,check_uadmin,success_callback,cancel_callback) {

    var config_url = (check_uadmin) ? '/_config' : '/config',
        check_data = {
            'id': check_id,
            'edit': check_uadmin,
            'step': 'check'
        };

    $.post('/umember/login/others', {
        'sid': sid,
        'data': JSON.stringify(check_data)
    }, function(data) {

        if(typeof data.error != 'undefined' && data.error) {
            $(this).showModalFlat('ERROR', data.error, true, false, '', 'close');
            return false;
        }

        if(typeof success_callback == 'undefined' || !success_callback) {
            success_callback = function() { 
                setSiteLogs('config','enter','','dashboard');
                location.href = config_url;
            };
        }

        if(!data.result) {
            success_callback();
        } else {
            var o_id = data.others_id,
                str = $.lang[LANG]['config.modal.others-login.3'] + o_id + $.lang[LANG]['config.modal.others-login.1'] + o_id + $.lang[LANG]['config.modal.others-login.2'],
                checkOtherLoginModal = $(this).showModalFlat($.lang[LANG]['config.information'], str, true, true, function() {
                    $.processON('Other Login Disconnecting...');

                    var set_data = check_data;
                    set_data['step'] = 'set';

                    $.ajax({
                        type: 'POST',
                        url: '/umember/login/others',
                        data: { sid: SID, data: JSON.stringify(set_data) },
                        dataType: 'json',
                        async: true,
                        success: function(data) {
                            setTimeout(function() {
                                $.processOFF();
                                success_callback();
                            }, 400);
                        }
                    });
                    
                }, 'cancel', 'ok', 'cl-p70 cl-cmmodal cl-s-btn w560 cl-p0 login-modal', '', '', '', cancel_callback);
        }

    }, 'json');
}

var changeBrokenImages = function(el) {
    if($(el).length == 0) return;
    // if($(el).find('.hideBlockWrap').length > 0) return;
    var broken_icon = '//storage.googleapis.com/i.addblock.net/icon_broken_img.png',
        broken_image = '//storage.googleapis.com/i.addblock.net/img_broken.png',
        broken_popup = '//storage.googleapis.com/i.addblock.net/img_broken_fill_500.png';

    var checkBlockConfig = $(el).is('#el-blockConfig'),
        checkSiteConfig = $(el).is('#el-siteConfig'),
        checkElement = $(el).is('.element'),
        checkMenu = $(el).is('header'),
        // broken_img =  (checkBlockConfig || checkMenu) ? '//storage.googleapis.com/i.addblock.net/icon_broken_img.png' : '//storage.googleapis.com/i.addblock.net/img_broken.png',
        broken_img =  (checkBlockConfig) ? broken_icon : broken_image,
        broken_bg = (checkBlockConfig) ? 'none' : 'url(' + broken_img + ')';

    if(checkElement || checkMenu) {
        var el_bg = $(el).css('background-image').replace(/^url\(['"]?([^'"]+)['"]?\)/, '$1');
        
        el_bg = el_bg.replace(/^(http)?(s)?(:)?\/\/i\.addblock\.net\//g,'//storage.googleapis.com/i.addblock.net/');
        if(el_bg.match(/(http)?(s)?(\:)?\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/) != null) {
            $('<img>', { src : el_bg }).on('error', function(e) {
                console.log('block bg img error: '+el_bg);

                $(el).css('background-image',broken_bg);
                e.target.remove();
            }.bind(this));
        }
    }

    $(el).find('[data-attach="true"]:not(img), #preview-image').each(function() {
        var this_attach = $(this),
            attch_bg = this_attach.css('background-image').replace(/^url\(['"]?([^'"]+)['"]?\)/, '$1'),
            this_el = this_attach.closest('.element').attr('data-el');

        attch_bg = attch_bg.replace(/^(http)?(s)?(:)?\/\/i\.addblock\.net\//g,'//storage.googleapis.com/i.addblock.net/');
        if(attch_bg.match(/(http)?(s)?(\:)?\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/) != null) {
            $('<img>', { src : attch_bg }).on('error', function(e) {
                console.log('attach bg img error: '+attch_bg);

                if(this_attach.is('[data-target]')) {
                    // img_broken background-image inline css reset
                    var attach_html = this_attach.outerHTML();
                    this_attach.replaceWith(attach_html.replace(/style\=\"(.+)?background\-image\:([^\;]+)\;\"(\=\"\")?/gi,''));

                    var this_selector = '.' + $('.'+this_el).attr('data-name') + ' ' + this_attach.attr('data-target'),
                        this_css = $('#'+this_el+'css').html();
                    $('#'+this_el+'css').html( this_css + this_selector + ' { background-image: ' + broken_bg + '; }');
                } else {
                    this_attach.css('background-image',broken_bg);
                }
                e.target.remove();
            }.bind(this));
        }
    });

    $(el).find('img').each(function() {
        var el_img = $(this);
        var this_img = el_img.attr('src');
        if(typeof this_img == 'undefined') return;

        if(this_img.match(/^\/\/i\.addblock\.net\//gi) !== null) {
            this_img = this_img.replace(/^\/\/i\.addblock\.net\//gi,'//storage.googleapis.com/i.addblock.net/');
            $(this).attr('src',this_img);
        }

        $(this).error(function() {
            console.log('img error: '+this_img);

            if(checkSiteConfig) {
                if($(this).closest('.sc-banner-img-thumb').length > 0) {
                    var e_b_type = $(this).closest('.tab-panel').attr('data-type'),
                        e_b_id = $(this).closest('.panel-banner-item').attr('data-id'),
                        e_b_device = $(this).closest('.sc-banner-img').attr('data-device');

                    $(this).unbind('error').attr('src', broken_icon);
                    if(e_b_device == 'p') $(this).closest('.panel-banner-item').find('.pt-thumb img').unbind('error').attr('src', broken_icon);
                    if(e_b_type == 'band') {
                        var e_b_root = (e_b_device == 'p') ? '--scbandBanner-img-pc' : '--scbandBanner-img-mobile';
                        document.querySelector('#el-siteConfig .sc-siteBanner .banner-box[data-id="'+e_b_id+'"][data-type="'+e_b_type+'"] .banner-img').style.setProperty(e_b_root, 'url('+broken_popup+')', null);
                    }
                }
            } else {
                $(this).unbind('error').attr('src', broken_img)
                    .removeAttr('data-storage')
                    .removeAttr('data-photo-id')
                    .removeAttr('data-img-val')
                    .removeAttr('data-width');
                if(checkBlockConfig) {
                    if($(this).closest('.attach-thumb').length > 0) $(this).closest('.attach-thumb').eq(0).css('background-image', broken_bg);
                } else {
                    if($(this).closest('.img-wrapper').find('.g-img').length > 0) $(this).closest('.img-wrapper').find('.g-img').css('background-image', broken_bg);
                }
            }
        });

        if(checkBlockConfig) {
            this_img = replaceBrokenImages(this_img, 'icon');
            if(this_img.match(/^(http)?(s)?(:)?\/\/storage\.googleapis\.com\/i\.addblock\.net\/icon_broken_img\.png/gi) !== null) $(this).closest('.attach-thumb').eq(0).css('background-image', broken_bg);
        }

        el_img.attr('src', this_img);
    });
}

var replaceBrokenImages = function(path,return_type) {
    var check_broken_icon = /^(http)?(s)?(:)?\/\/storage\.googleapis\.com\/i\.addblock\.net\/icon_broken_img\.png/gi,
        check_broken_img = /^(http)?(s)?(:)?\/\/storage\.googleapis\.com\/i\.addblock\.net\/img_broken\.png/gi,
        v = path;

    if(return_type == 'img') return v.replace(check_broken_icon, '//storage.googleapis.com/i.addblock.net/img_broken.png');
    else return v.replace(check_broken_img, '//storage.googleapis.com/i.addblock.net/icon_broken_img.png');
}

var getServeImage = function(f,w,path) {
    if(f == undefined) return;
    var r = '';
    if(typeof w === 'number') w = String(w);
    if(f.indexOf('googleusercontent') > -1) {
        var magic_type = (typeof SETTINGS != 'undefined') ? SETTINGS.magic_type : property.SETTINGS.magic_type,
            check_magic_type = (typeof magic_type != 'undefined' && magic_type == 'webp') ? true : false;
            t =  (check_magic_type) ? '-rw' : '';

        var n = f.indexOf('=');
        f = f.substring(0, n != -1 ? n : f.length);
        switch(w) {
            case "0"      : r = f + '=s0'+t;            break;
            case "30"     : r = f + '=w30'+t;            break;
            case "60"     : r = f + '=w60-h60-n'+t;     break;
            case "250"    : r = f + '=w250-h250-n'+t;   break;
            case "300"    : r = f + '=w300-h300-n'+t;   break;
            case "600"    : r = f + '=w600-h600-n'+t;   break;
            case "650"    : r = f + '=w650-h370-n'+t;   break;
            case "670"    : r = f + '=w670-h980-n'+t;   break;
            case "700"    : r = f + '=w700-h500-n'+t;   break;
            case "800"    : r = f + '=w800'+t;          break;
            case "1920"   :
                $.ajax({
                    type: 'POST',
                    url: '/template/image',
                    data: { url : f, width : w },
                    dataType: 'json',                    
                    async: false,
                    success: function(data) {
                        if(typeof data.s800 != 'undefined') {
                            if(w == "800")
                                r = (Number(data.s800) > 2560) ? f + '=s0' : f + '=w800-h' + data.s800 + '-n';
                            if(w == "1920")
                                r = (Number(data.s1920) > 2560) ? f + '=s0' : f + '=w1920-h' + data.s1920 + '-n';
                            r+=t;
                        } else {
                            r = (check_magic_type) ? f+'=-rw' : f;
                        }
                    }
                });
                break;                           
            case "map-info"    : r = f + '=w640-h550-n'+t;   break;
            default       : r = (check_magic_type) ? f+'=-rw' : f;  break;
        }
    } else {
        if(f.indexOf('matcheslux.com') > -1 || f.indexOf('bullanseo.com') > -1 || f.indexOf('bullanseon.com') > -1 || f.indexOf('eccla.co.kr') > -1 || f.indexOf('bullanseo.cafe24.com') > -1) {
            r = f;
        } else {
            path = (path.slice(-1) == '/') ? path : path + '/';
            // r = (f.indexOf('http:') > -1) ? f : (w == "0" || w == "") ? path + f : path + w + '/' + f;
            if(f.indexOf('//') > -1) {
                if(w == "0" || w == "") {
                    file_name = f.split('/').pop();
                    r = path + file_name;
                }
            } else {
                r = (w == "0" || w == "") ? path + f : path + w + '/' + f;
            }
            // r = (f.indexOf('//') > -1) ? f : (w == "0" || w == "") ? path + f : path + w + '/' + f;
        }
    }
    return r;
}

Date.prototype.format = function (f) {
    if (!this.valueOf()) return " ";

    var weekName = ["일요일", "월요일", "화요일", "수요일", "목요일", "금요일", "토요일"];
    var d = this;
    
    return f.replace(/(yyyy|yy|MM|dd|E|hh|mm|ss|a\/p)/gi, function(da) {
        switch (da) {
            case "yyyy": return d.getFullYear();
            case "yy": return (d.getFullYear() % 1000).zf(2);
            case "MM": return (d.getMonth() + 1).zf(2);
            case "dd": return d.getDate().zf(2);
            case "E": return weekName[d.getDay()];
            case "HH": return d.getHours().zf(2);
            case "hh": return ((h = d.getHours() % 12) ? h : 12).zf(2);
            case "mm": return d.getMinutes().zf(2);
            case "ss": return d.getSeconds().zf(2);
            case "a/p": return d.getHours() < 12 ? "오전" : "오후";
            default: return da;
        }
    });
};

String.prototype.string = function(len){var s = '', i = 0; while (i++ < len) { s += this; } return s;};
String.prototype.zf = function(len){return "0".string(len - this.length) + this;};
Number.prototype.zf = function(len){return this.toString().zf(len);};

var galleryDeleteItem = function(seq,callback) {
    if(CANCEL) return true;
    var item_page = $('.gallery-items div[data-seq="' + seq + '"]').attr('data-page');
    $.ajax({
        url: '/template/element/type/get-projectPage-bookmarkBlock/seq/' + seq,
        data: {sid: SID, page: item_page},
        dataType: 'json',
        type: 'POST',
        async: true,
        cache: false,
        success: function (data) {
            checkError(data);
            if(typeof callback == 'function') {
                callback(data);
            }
        }
    }, 'json');                
}

var glItemDelete = function(ids, page) {
    $.post('/template/gallery/delete', { sid: SID, s: ids, page: page }, function(data) {
        checkError(data);
    }, 'json');
}
function removeOptionModal(optionList, optionMode) {
    // console.log(optionList);
    var sid = (typeof SID == 'undefined') ? property.SID : SID;
    if(optionList.length > 0) {
        var modal = $(this).showModalFlat($.lang[LANG]['config.information'], '선택한 옵션을 삭제하시겠습니까?', true, true, function() {
            optionList.each(function(){
                var seq = $(this).find('.prod-option-title').attr('data-seq');
                
                if(typeof seq != "undefined" || seq) {
                    $.post('/template/products', { seq : seq, sid : sid, type : 'delete', mode: 'option' }, function(data) {
                        if(typeof data.error != "undefined" || data.error) {
                            alert(data.error);
                            return false;
                        }

                        var liTotal = 0;
                        $('.prod-option-list > li').each(function () { liTotal++; });
                        if (liTotal < 2) $('.prod-option .plus-price').addClass('hide');
                    }, 'json');
                } else {
                    var liTotal = 0;
                    $('.prod-option-list > li').each(function () { liTotal++; });
                    if (liTotal < 2) $('.prod-str-price').text('');
                }
            });

            optionList.remove();
            $('.prod-option[data-option_mode="'+optionMode+'"]').addClass('hide');

            var cnt = $('.prod-option[data-option_mode="normal"] .prod-option-list > li').length;
            if (cnt <= 1) {
                var html = '<div class="download-contents">\
                                <span class="cl_icon_upload02" data-cnt="0">업로드</span>\
                                <div id="none-option-file"></div>\
                            </div>';
                fileUpdateCnt++;

                $('#add-upload-check').prepend(html);
                if ($('#none-option-file').length > 0) {
                    $('.switch-product[value="off"]').prop('checked', true);
                    $('#status-append').fadeOut(0);
                    $('#sale-calendar').hide();
                }
            }

            modal.modal('hide');
        }, 'cancel', 'ok', 'cl-p130 cl-cmmodal cl-s-btn w560 cl-p0', false, function(){
            $('#'+optionMode+'-option').prop('checked', true);
        }, '', function(){
            if(optionMode == 'normal') {
                if($('.prod-option[data-option_mode="normal"] .prod-option-list > li').length > 1) {
                    $('#'+optionMode+'-option').prop('checked', true);
                } 
            } else {
                if($('.prod-option[data-option_mode="'+optionMode+'"] .prod-option-list > li').length > 0) {
                    $('#'+optionMode+'-option').prop('checked', true);
                }
            }
        });
    } else {
        $('.prod-option[data-option_mode="'+optionMode+'"]').addClass('hide');
    }
}

$(function () {
    $(document).on('change', '.review-checkbox-check', function () {
        if ($(this).is(':checked') === true) {
            $('.photo-review-tab').css('display', 'block');
        } else {
            $('.photo-review-tab').css('display', 'none');
        }
    });

    $(document).on('change', '.option-state-box .status-checkbox', function (e) {
        if($(this).attr('id') == 'normal-option') {
            var li = $('.prod-option[data-option_mode="normal"] .prod-option-list > li').slice(1);
            if(product_options.advanced == 'true' && li.length == 0) {
                $(this).prop('checked',false);
                // alert('고급 설정이 적용되어 있어 입력형 옵션과 추가 옵션은 고급 설정창에서 설정이 가능합니다');
                var modal = $(this).showModalFlat('','고급 설정이 적용되어 있어 입력형 옵션과 추가 옵션은 고급 설정창에서 설정이 가능합니다',true,false,'','ok','','cl-cmmodal cl-s-btn w560 cl-p130 cl-t80 cl-modal cl-none-title cl-close-btn','','',function() {
                    $(document).on('keydown', function(e) {
                        if(e.keyCode == 27) modal.modal('hide');
                    });
                });
                return false;
            }
            if ($(this).is(':checked') === true) {
                if(li.length == 0) {
                    var r = addProductOption('normal');
                    if(r == false) {
                        $('#normal-option').prop('checked', false);
                        return false;
                    }
                }
                $('.prod-option-tab').removeClass('hide');
                $('.prod-option[data-option_mode="normal"]').removeClass('hide');
                $('.prod-option[data-option_mode="normal"] .plus-price').removeClass('hide');
                $('.prod-option[data-option_mode="normal"] .plus-status').removeClass('hide');
                switchDownload('on'); //다운로드 파일        
            } else {         
                switchDownload('off'); //다운로드 파일
                // removeOptionModal(li, 'normal');
                if(li.length == 1 && li.find('.prod-option-item .prod-option-title').text() == '') {
                    li.remove();
                }
                $('.prod-option[data-option_mode="normal"]').addClass('hide');
            }
        } else if($(this).attr('id') == 'text-option') {
            if($('#download-product').is(':checked') === true) { //다운로드 상품
                alert('다운로드 상품은 입력옵션을 지원하지 않습니다.');
                $(this).prop('checked', false);
                return false;
            }
            var li = $('.prod-option[data-option_mode="text"] .prod-option-list > li');
            if(product_options.advanced == 'true' && li.length == 0) {
                $(this).prop('checked',false);
                // alert('고급 설정이 적용되어 있어 입력형 옵션과 추가 옵션은 고급 설정창에서 설정이 가능합니다');
                var modal = $(this).showModalFlat('','고급 설정이 적용되어 있어 입력형 옵션과 추가 옵션은 고급 설정창에서 설정이 가능합니다',true,false,'','ok','','cl-cmmodal cl-s-btn w560 cl-p130 cl-t80 cl-modal cl-none-title cl-close-btn','','',function() {
                    $(document).on('keydown', function(e) {
                        if(e.keyCode == 27) modal.modal('hide');
                    });
                });
                return false;
            }
            if ($(this).is(':checked') === true) {   
                $('.prod-option-tab').removeClass('hide');
                $('.prod-option[data-option_mode="text"]').removeClass('hide');

                if(li.length == 0) addProductOption('text');
                if(li.length >= 7) {
                    $('.prod-option[data-option_mode="text"] > .prod-option-add').addClass('disabled');
                } else {
                    $('.prod-option[data-option_mode="text"] > .prod-option-add').removeClass('disabled');
                }
            } else {
                // removeOptionModal(li, 'text');
                if(li.length == 1 && li.find('.prod-option-item .prod-option-title').text() == '') {
                    li.remove();
                }
                $('.prod-option[data-option_mode="text"]').addClass('hide');
            }
        } else if($(this).attr('id') == 'additional-option') {
            if($('#download-product').is(':checked') === true) { //다운로드 상품
                alert('다운로드 상품은 추가옵션을 지원하지 않습니다.');
                $(this).prop('checked', false);
                return false;
            }
            var li = $('.prod-option[data-option_mode="additional"] .prod-option-list > li');
            if(product_options.advanced == 'true' && li.length == 0) {
                $(this).prop('checked',false);
                // alert('고급 설정이 적용되어 있어 입력형 옵션과 추가 옵션은 고급 설정창에서 설정이 가능합니다.');
                var modal = $(this).showModalFlat('','고급 설정이 적용되어 있어 입력형 옵션과 추가 옵션은 고급 설정창에서 설정이 가능합니다',true,false,'','ok','','cl-cmmodal cl-s-btn w560 cl-p130 cl-t80 cl-modal cl-none-title cl-close-btn','','',function() {
                    $(document).on('keydown', function(e) {
                        if(e.keyCode == 27) modal.modal('hide');
                    });
                });
                return false;
            }

            if ($(this).is(':checked') === true) {
                $('.prod-option-tab').removeClass('hide');
                $('.prod-option[data-option_mode="additional"]').removeClass('hide');
                $('.prod-option[data-option_mode="additional"] .plus-price').removeClass('hide');
                $('.prod-option[data-option_mode="additional"] .plus-status').removeClass('hide');

                if(li.length == 0) addProductOption('additional');
            } else {
                // removeOptionModal(li, 'additional');
                if(li.length == 1 && li.find('.prod-option-item .prod-option-title').text() == '') {
                    li.remove();
                }

                $('.prod-option[data-option_mode="additional"]').addClass('hide');
            }
        }

        if($('.switch-quantity').is(":checked") == true) {
            if($('#normal-option').is(':checked') === true) {
                // $('#prod-quantity').attr('readonly','true').removeClass('hide').attr('placeholder','옵션에서 재고 관리');
                $('.quantity-label').addClass('on');
                $('.plus-quantity').removeClass('hide');
            } else if($('#normal-option').is(':checked') === false && $('#additional-option').is(':checked') === true) {
                $('.quantity-label').removeClass('on');
                $('#prod-quantity').removeAttr('readonly').removeClass('hide');
                $('.plus-quantity').removeClass('hide');
            } else {
                $('.quantity-label').removeClass('on');
                $('#prod-quantity').removeAttr('readonly').removeClass('hide');
                $('.plus-quantity').addClass('hide');
            }

        //     $parent.find('.prod-option-quantity, .edit-option-quantity').show();
        //     $parent.find('.plus-quantity').removeClass('hide');
        } else {
            $('.quantity-label').removeClass('on');
            $('#prod-quantity').addClass('hide');
            $('.prod-option-quantity, .prod-plus-quantity, .edit-option-quantity').hide();
            $('.plus-quantity').addClass('hide');
        }

        if($('.prod-option-tab .prod-option.hide').length == 3) { //탭 모두 비활성화일때
            $('.prod-option-tab').addClass('hide');
            if(product_options.advanced == 'true')
                $('.reset-wrap').addClass('hide');
            if($('.switch-quantity').is(":checked") == true) {
                $('.quantity-label').removeClass('on');
            }
        } else {
            if(product_options.advanced == 'true')
                $('.reset-wrap').removeClass('hide');
        }
    });

    $(document).on('click','.btn-fblogin.btn-warning', function(e) {
        var facebook_disabled_str = '\
        <div class="text-left" style="padding: 20px 15px;"><br>\
        ' + $.lang[LANG]['config.modal.fblogin.error.1'] + '\
            <ol style="padding-inline-start: 15px; margin-top: 10px; line-height: 2;">\
            ' + $.lang[LANG]['config.modal.fblogin.error.2'] + '\
            </ol>\
        ' + $.lang[LANG]['config.modal.fblogin.error.3'] + '\
        </div>';

        $(this).showModalFlat('INFORMATION',facebook_disabled_str,true,false,'','ok','','w555');
    });

    //$(document).off('click', '#etc-start-date.etc_date');
    // $(document).on('click', '#etc-start-date-txt', function (e) {
    //     $('.cl_etc_date_time').each(function () {
    //         $(this).removeClass('active');
    //     });

    //     if($('#etc-start-date-picker').css('display') == 'block') {
    //         $(this).removeClass('active');
    //         $('#etc-start-date-picker').hide();
    //     } else {
    //         $('.etc-date').removeClass('active');
    //         $(this).addClass('active');
    //         $('#etc-start-date-picker').show();
    //     }
    //     $('#etc-end-date-picker').hide();
    //     $('#etc-except-date-picker').hide();
            
    //     $('#select-calendar').val('etc-start-date');
    //     startPicker.generateDates();
    //     var i = 0;
    //     var width = 0;
    //     $('#etc-end-date-picker .Datepickk .d-table input + label').each(function () {
    //         if (i == 0) width = $(this).width();
    //         $(this).css('height', width+'px');
    //         i++;
    //     });
    //     var i = 0;
    //     var width = 0;
    //     $('#etc-start-date-picker .Datepickk .d-table input + label').each(function () {
    //         if (i == 0) width = $(this).width();
    //         $(this).css('height', width+'px');
    //         i++;
    //     });
    // });

    // $(document).on('click', '#etc-end-date-txt', function () {
    //     $('.cl_etc_date_time').each(function () {
    //         $(this).removeClass('active');
    //     });

    //     if($('#etc-end-date-picker').css('display') == 'block') {
    //         $(this).removeClass('active');
    //         $('#etc-end-date-picker').hide();
    //     } else {
    //         $('.etc-date').removeClass('active');
    //         $(this).addClass('active');
    //         $('#etc-end-date-picker').show();
    //     }

    //     $('#etc-start-date-picker').hide();
    //     $('#etc-except-date-picker').hide();

    //     $('#select-calendar').val('etc-end-date');
    //     endPicker.generateDates();
    //     var i = 0;
    //     var width = 0;
    //     $('#etc-end-date-picker .Datepickk .d-table input + label').each(function () {
    //         if (i == 0) width = $(this).width();
    //         $(this).css('height', width+'px');
    //         i++;
    //     });
    //     var i = 0;
    //     var width = 0;
    //     $('#etc-start-date-picker .Datepickk .d-table input + label').each(function () {
    //         if (i == 0) width = $(this).width();
    //         $(this).css('height', width+'px');
    //         i++;
    //     });
    // });

    // $(document).on('click', '#etc-except-date', function () {
    //     $('.unselect-all').remove();
        
    //     if($('#etc-except-date-picker').css('display') == 'block') {
    //         $(this).removeClass('active');
    //         $('#etc-except-date-picker').hide();
    //     } else {
    //         $('.etc-date').removeClass('active');
    //         $(this).addClass('active');
    //         $('#etc-except-date-picker').show();
    //         $('#etc-except-date-picker').append('<div class="unselect-all"><svg viewBox="0 0 24 24" width="24" height="24"><path d="M12 5c-3.64 0-6.63 2.78-6.97 6.33L3.35 9.65l-0.71 0.71 2.85 2.85 2.85-2.85L7.65 9.65l-1.59 1.59C6.43 8.29 8.95 6 12 6c3.31 0 6 2.69 6 6s-2.69 6-6 6c-1.66 0-3.17-0.68-4.26-1.78l-0.71 0.71C8.3 18.21 10.06 19 12 19c3.87 0 7-3.13 7-7S15.87 5 12 5z"/></svg> 초기화</div>');
    //         displaySelectedDates();
    //     }

    //     $('#etc-start-date-picker').hide();
    //     $('#etc-end-date-picker').hide();

    //     setExceptPicker();
    //     // exceptPicker.generateDates(true);
    //     var i = 0;
    //     var width = 0;
    //     $('#etc-except-date-picker .Datepickk .d-table input + label').each(function () {
    //         if (i == 0) width = $(this).width();
    //         $(this).css('height', width+'px');
    //         i++;
    //     });


    // });

    // $(document).on('click', '#etc-except-date-picker .unselect-all', function (e) {
    //     e.preventDefault();
    //     exceptPicker.unselectExceptAll();
    //     //exceptPicker.generateDates(true);
    //     setExceptPicker();
    //     $('#etc-except-date').val('-');
    //     $('.etc-except-date-status').text('');
    //     $(this).addClass('disabled');
    // });

    

    $(document).on('click', '.email-add-box:not(.disabled)', function(e){

        if (!$(e.target).is('.email-box')) {
            $('#email-add-input').focus();
        }
    });

    $(document).on('keydown', '.email-add-box:not(.disabled) #email-add-input', function (e) {
        var keyCode = e.keyCode || e.which;
        if (keyCode == 9 || keyCode == 13) {
            e.preventDefault();
            enterEmailBox($(this), 'add');
        }
    });

    $(document).on('click', function(e) {
        if($('#email-add-input').length > 0 && !$(e.target).is('#email-add-input')) {
            e.stopPropagation();
            enterEmailBox($('#email-add-input'), 'add');
        }
    });

    $(document).on('click', '.email-add-box:not(.disabled) .email-box-delt', function (e) {
        e.stopPropagation();
        enterEmailBox($(this), 'delete');
    });

    $(document).on('click', '.email-add-box:not(.disabled) .email-box', function (e) {

        e.stopPropagation();

        var textWidth = $(this).find('.email-text').width();
        var emailTextInput = $(this).find('.email-text-input');
        var otherBox = $('.email-box').not(this); //선택한 박스 외 다른 박스
        var emailBox = enterEmailBox(otherBox.find('.email-text-input.active input'), 'modify');
        if (emailBox) {
            otherBox.find('.email-text').removeClass('hidden');
            otherBox.find('.email-text-input').addClass('hidden');
            otherBox.find('.email-text-input').removeClass('active');
        }
        if(emailTextInput.hasClass('hidden')) {
            $(this).find('.email-text').addClass('hidden');
            emailTextInput.removeClass('hidden');
            emailTextInput.addClass('active');
            emailTextInput.find('input').css('width', textWidth+'px');
            emailTextInput.find('input').focus();
        }
    });

    $(document).on('keydown', '.email-box', function (e) {
        var keyCode = e.keyCode || e.which;
        if (keyCode == 9 || keyCode == 13) {
            var emailBox = enterEmailBox($('.email-text-input').not('.hidden').find('input'), 'modify');

            if (emailBox) {
                $(this).find('.email-text').removeClass('hidden');
                $(this).find('.email-text-input').addClass('hidden');
            }
        }
    });

    $(document).on('click', function (e) {
        if (!$(e.target).is('.email-box')) {
            e.stopPropagation();
            var emailBox = enterEmailBox($('.email-text-input.active input'), 'modify');

            if (emailBox) {
                $(this).find('.email-text').removeClass('hidden');
                $(this).find('.email-text-input').addClass('hidden');
                $(this).find('.email-text-input').removeClass('active');
            }
        }
    });
    // if ($('#email-line-box').length > 0) {
    //     var name = $('#email-line-box').attr('name');
    //     var className = $('#email-line-box').attr('class');
    //     var value = $('#email-line-box').val();

    //     var emailList = value.split(',');

    //     var html = '\
    //         <input type="hidden" id="email-line-box" name="'+name+'" class="'+className+'" value="'+value+'">\
    //         <div class="email-add-box">\
    //             <input type="text" id="email-add-input">\
    //         </div>\
    //     ';
    //     $('#email-line-box').before(html);

    //     var html = '';
    //     if (emailList.length >= 1) {
    //         if (emailList[0] != '') {
    //             for (var i=0;i<emailList.length;i++) {
    //                 html += '<div class="email-box">'+emailList[i]+'<span class="email-box-delt"><svg viewBox="0 0 8 8"><polygon points="8 0.71 7.29 0 4 3.29 0.71 0 0 0.71 3.29 4 0 7.29 0.71 8 4 4.71 7.29 8 8 7.29 4.71 4 "/></svg></span></div>'
    //             }

    //             $('#email-add-input').before(html);
    //             var boxWidth = 0;
    //             $('.email-add-box .email-box').each(function () {
    //                 boxWidth += $(this).innerWidth() + 10;
    //             });
    //             var textWidth = $('#email-add-input').parent().innerWidth() - 20,
    //                 uni = 'px';

    //             var totalWidth = textWidth - boxWidth;

    //             if (totalWidth <= 40) {
    //                 totalWidth = 100;
    //                 uni = '%'
    //             }

    //             $('#email-add-input').css('width', totalWidth+uni);
    //         }
    //     }
    //     $('#email-line-box').remove();
    // } L.20211008.
});

function enterEmailBox (el, mode) {
    var regExp = /^[0-9a-zA-Z]([-_\.]?[0-9a-zA-Z])*@[0-9a-zA-Z]([-_\.]?[0-9a-zA-Z])*\.[a-zA-Z]{2,3}$/i;
    if(mode == 'add' || mode == 'modify') {
        var val = (typeof el.val() !== 'undefined')? el.val().trim() : '';
        if (val == '') return true;
        if(!regExp.test(val)) {
            // alert('이메일 형식이 올바르지 않습니다.');
            var modal = $(this).showModalFlat('','이메일 형식이 올바르지 않습니다.',true,false,function() {
                    modal.modal('hide');
                },'ok','','cl-cmmodal cl-s-btn w560 cl-p130 cl-t80 cl-modal cl-none-title cl-close-btn','','',function() {
                $(document).on('keydown', function(e) {
                    if(e.keyCode == 27) modal.modal('hide');
                });
            });
            el.val('');
            el.focus();
            return false;
        }
        var flag = true;
        $('.email-text').not('.hidden').each(function(idx, v) {
            if($(v).text() == val) {
                // alert('이미 등록된 이메일입니다.');
                var modal = $(this).showModalFlat('','이미 등록된 이메일입니다.',true,false,function() {
                    modal.modal('hide');
                },'ok','','cl-cmmodal cl-s-btn w560 cl-p130 cl-t80 cl-modal cl-none-title cl-close-btn','','',function() {
                    $(document).on('keydown', function(e) {
                        if(e.keyCode == 27) modal.modal('hide');
                    });
                });
                el.val('');
                el.focus();
                flag = false;
                return false;
            }
        });

        if(flag === false) {
            return false;
        }
    }

    if(mode == 'add') {
        var html = '<div class="email-box">\
        <div class="email-text">'+val+'</div>\
        <div class="email-text-input hidden"><input type="text" value="'+val+'"></div>\
        <span class="email-box-delt"><svg viewBox="0 0 8 8"><polygon points="8 0.71 7.29 0 4 3.29 0.71 0 0 0.71 3.29 4 0 7.29 0.71 8 4 4.71 7.29 8 8 7.29 4.71 4 "/></svg></span>\
        </div>';
               
        if($('.email-box').length < 5) { //이메일 최대 5개까지
            el.before(html);
        }
        el.val('');
    } else if (mode == 'delete') {
        if($('.email-box').length <= 1) {
            alert('관리자 수신메일은 최소 1개 이상 등록되어 있어야 합니다.');
            return false;
        }
        el.parent().remove();
    } else if (mode == 'modify') {
        var emailBox = el.closest('.email-box').find('.email-text');
        emailBox.text(val);
    } else {
        return false;
    }
    
    var emailArr = new Array();
    $('.email-add-box .email-box .email-text').each(function () {
        emailArr.push($(this).text());
    });
    console.log(emailArr);
    $('#email-line-box').val(emailArr.join(','))

    if($('.email-box').length >= 5) {
        $('#email-add-input').remove();
    } else {
        if($('#email-add-input').length == 0) {
            $('.email-add-box').append('<input type="text" id="email-add-input">');
        }
        if (mode != 'modify') {
            $('#email-add-input').focus();
        }
    }

    return true;
}

function enterGeneralBox (el, mode){
    var regExp = /^[0-9+]+$/;    
    if(mode == 'add' || mode == 'modify') {

        var val = (typeof el.val() !== 'undefined')? el.val().trim() : '';//value 체크        
        val = val.replace(/ /g,""); 
        if (val == '') return true; //입력내용 비어있으면 종료

    // console.log(val.replace('+',''));
    // console.log(val.replace('+','').length);
        if ( val.replace('+','').length < 10 || val.replace('+','').length > 15) {           

                    siteNotice('kakao_number_length');
                    el.val('');
                    el.focus();
                    return false;            
        }
        if(!regExp.test(val)) {
                siteNotice('kakao_onlynumber');
                el.val('');
                el.focus();
                return false;
        }
        var flag = true;
        
        $('.generalnum-text').not('.hidden').each(function(idx, v) {
            
            if($(v).text().replace('+','') == val.replace('+','')) {
                // alert('이미 등록 된 이메일입니다.');
                siteNotice('kakao_dupnumber');
                el.val('');
                el.focus();
                flag = false;
                return false;
            }
        });

        if(flag === false) {
            return false;
        }
    }
    if(mode == 'add') {

        //0206 18:00 working..
        if(val.substring(0, 1) == '0'){
            var firststring_delete = val.substring(1);
            var sliceValue ='';        
            var text_array = new Array();
                firststring_delete = '+82'+firststring_delete;
                
                $('.generalnum-text').each(function(idx, v) {           
                    sliceValue = text_array.push($(v).text());
                });
        } else if(val.slice(0,2) =='82' || val.slice(0,3) =='+82'){
            if(val.slice(0,1) == '+') val = val.substring(1);

            var firststring_delete = val.substring(2);
            var sliceValue =''; 
                firststring_delete = '0'+firststring_delete;
                   
            var text_array = new Array();
                $('.generalnum-text').each(function(idx, v) {           
                    sliceValue = text_array.push($(v).text());
                });            
        } else {
            var firststring_delete = val;
            var text_array = new Array();

        } 
            if(text_array.includes(firststring_delete)){
                var modal = $(this).showModalFlat('',$.lang[LANG]['shopping.dashboard.kakaoNotice.dupnumber'],true,false,function() {
                    modal.modal('hide');
                },'ok','','cl-cmmodal cl-s-btn w560 cl-p130 cl-t80 cl-modal cl-none-title cl-close-btn','','',function() {
                    $(document).on('keydown', function(e) {
                        if(e.keyCode == 27) modal.modal('hide');
                    });
                });                
                el.val('');
                el.focus();                
                return false ;
            }
       
        //0206 18:00 working..

        
        let val_chk = val.substring(0, 1);
        if(val_chk !== '0' && val_chk !=='+'){
            val = '+'+val;
        }           
        var html = '<div class="generalnum-box">\
        <div class="generalnum-text">'+val+'</div>\
        <div class="generalnum-text-input hidden"><input type="text" value="'+val+'"></div>\
        <span class="generalnum-box-delt"><svg viewBox="0 0 8 8"><polygon points="8 0.71 7.29 0 4 3.29 0.71 0 0 0.71 3.29 4 0 7.29 0.71 8 4 4.71 7.29 8 8 7.29 4.71 4 "/></svg></span>\
        </div>';
               
        
       el.before(html);
           
        el.val('');
    } else if (mode == 'delete') {

        // if($('.generalnum-box').length <= 1) {
        //   $(this).siblings(input);
        // }         
        el.parent().remove();
    } 
    else if (mode == 'modify') {
        // if(val.substring(0, 1) == '0'){
        //     var firststring_delete = val.substring(1);
        //     var sliceValue ='';        
        //     var text_array = new Array();
        //         firststring_delete = '+82'+firststring_delete;
        //         $('.generalnum-text').each(function(idx, v) {           
        //             sliceValue = text_array.push($(v).text());
        //         });
        // }

        if(val.substring(0, 1) == '0'){
            var firststring_delete = val.substring(1);
            var sliceValue ='';        
            var text_array = new Array();
                firststring_delete = '+82'+firststring_delete;
                
                $('.generalnum-text').each(function(idx, v) {           
                    sliceValue = text_array.push($(v).text());
                });
        } else if(val.slice(0,2) =='82' || val.slice(0,3) =='+82'){     
          if(val.slice(0,1) == '+') val = val.substring(1);       
            var firststring_delete = val.substring(2);
            var sliceValue =''; 
                firststring_delete = '0'+firststring_delete;
                   
            var text_array = new Array();
                $('.generalnum-text').each(function(idx, v) {           
                    sliceValue = text_array.push($(v).text());
                });            
        } else {
            var firststring_delete = val;
            var text_array = new Array();

        }         
            if(text_array.includes(firststring_delete)){
                var modal = $(this).showModalFlat('',$.lang[LANG]['shopping.dashboard.kakaoNotice.dupnumber'],true,false,function() {
                    modal.modal('hide');
                },'ok','','cl-cmmodal cl-s-btn w560 cl-p130 cl-t80 cl-modal cl-none-title cl-close-btn','','',function() {
                    $(document).on('keydown', function(e) {
                        if(e.keyCode == 27) modal.modal('hide');
                    });
                });                
                el.val('');
                el.focus();                
                return false ;
            }
       

        
        let val_chk = val.substring(0, 1);
        if(val_chk !== '0' && val_chk !=='+'){
            val = '+'+val;
        }      
        var emailBox = el.closest('.generalnum-box').find('.generalnum-text');
        emailBox.text(val);
       
    } else {
        return false;
    }


 var emailArr = new Array();
    $('.generalnum-add-box .generalnum-box .generalnum-text').each(function () {
        emailArr.push($(this).text());
    });
    
    $('#generalnum-line-box').val(emailArr.join(','))
    $('#generalnum-add-input').remove();

    (LANG =='ko') ? LangPlaceholderNumber = '번호를 입력해주세요.' : LangPlaceholderNumber = 'Please enter the Number.';
   
        if($('#generalnum-add-input').length == 0) {
            $('.generalnum-add-box').append('<input type="text" id="generalnum-add-input">');
            if ($('.generalnum-box').length == 0) {
                $('#generalnum-add-input').attr('placeholder',LangPlaceholderNumber)
            }
        }
        if (mode != 'modify') {
            $('#generalnum-add-input').focus();
        }
    

    return true;    
}

    $(document).on('click', function(e) {
        if($('#generalnum-add-input').length > 0 && !$(e.target).is('#generalnum-add-input')) {
            e.stopPropagation();
            enterGeneralBox($('#generalnum-add-input'), 'add');
           
        }
    });

    $(document).on('keydown', '#generalnum-add-input', function (e) {
        var keyCode = e.keyCode || e.which;
        if (keyCode == 9 || keyCode == 13) {
            e.preventDefault();
            enterGeneralBox($(this), 'add');
        }
    });

    $(document).on('click', '.generalnum-box', function (e) {
        e.stopPropagation();
        var textWidth = $(this).find('.generalnum-text').width();
        var emailTextInput = $(this).find('.generalnum-text-input');
        var otherBox = $('.generalnum-box').not(this); //선택한 박스 외 다른 박스
        var emailBox = enterGeneralBox(otherBox.find('.generalnum-text-input.active input'), 'modify');
        if (emailBox) {
            otherBox.find('.generalnum-text').removeClass('hidden');
            otherBox.find('.generalnum-text-input').addClass('hidden');
            otherBox.find('.generalnum-text-input').removeClass('active');
        }
        if(emailTextInput.hasClass('hidden')) {
            $(this).find('.generalnum-text').addClass('hidden');
            emailTextInput.removeClass('hidden');
            emailTextInput.addClass('active');
            emailTextInput.find('input').css('width', textWidth+'px');
            emailTextInput.find('input').focus();
        }
    });

    $(document).on('click', '.generalnum-add-box', function(e){
        if (!$(e.target).is('.generalnum-box')) {

            $('#generalnum-add-input').focus();
        }
    });

   $(document).on('keydown', '.generalnum-box', function (e) {
        var keyCode = e.keyCode || e.which;
        if (keyCode == 9 || keyCode == 13) {
            $(this).find('.generalnum-text-input').removeClass('active');
            var emailBox = enterGeneralBox($('.generalnum-text-input').not('.hidden').find('input').not(this), 'modify');

            if (emailBox) {
                $(this).find('.generalnum-text-input').addClass('hidden');
                $(this).find('.generalnum-text').removeClass('hidden');

            }
        }
    });

    $(document).on('click', function (e) {
        if (!$(e.target).is('.generalnum-box')) {
            e.stopPropagation();
            var emailBox = enterGeneralBox($('.generalnum-text-input.active input'), 'modify');


            if (emailBox) {
                $(this).find('.generalnum-text').removeClass('hidden');
                $(this).find('.generalnum-text-input').addClass('hidden');
                $(this).find('.generalnum-text-input').removeClass('active');
            }
        }
    });    

    $(document).on('click', '.generalnum-box-delt', function (e) {
        e.stopPropagation();
        enterGeneralBox($(this), 'delete');
    });


function emailLineFunc () {
    var emailBox = enterEmailBox($('#email-add-input'), 'add');
    
    if ($('.email-box.none').length > 0) {
        alert('옳바르지 않은 이메일 주소가 포함되어있습니다.');
        return false;
    }
    
    if (emailBox === false) {
        $('#email-add-input').focus();
        return false;
    }

    return true;
}

function division (option, n) {
    var arr = option;
    var len = arr.length;
    var cnt = Math.floor(len / n) + (Math.floor(len % n) > 0 ? 1 : 0);
    var tmp = [];

    for (var i=0;i<cnt;i++) {
        tmp.push(arr.splice(0, n));
    }

    return tmp;
}

function truncateReviewTitle (reviewArr) { //상품후기 제목 자르기
    $('.s-table-review .review-content>div').each(function(idx, item){
        var reviewContent = reviewArr[idx];
        
        if(reviewContent !== undefined) {
            $(this).html(reviewContent);

            for(var i = reviewContent.length; i > 0; i--){
                if($(this).height() > 60) {
                    $(this).html(reviewContent.substr(0, i));
                    $(this).append('...');
                }
                else {
                    break;
                }
            }
        }
    });
}

function nl2br (str, is_xhtml) {
    if (typeof str === 'undefined' || str === null) {
        return '';
    }
    var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';
    return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');
}

function extra_charge_info($obj, status, free_flag, change_flag) {
    $(".order-cancel-content.extra-info").remove();
    var s = '\
    <div class="order-cancel-content extra-info">\
        <div class="cancel-info-box">\
            <p class="error">\
            ' + (free_flag ? '- 결제 당시 무료배송 조건을 충족하지 못해 배송료가 발생 할 수 있습니다.<br>' : '' ) + '\
            ' + (change_flag ? '- 주문 상품 ' + (status == 'C' ? '취소' : '반품') + ' 시 배송비 조건에 따라 배송비가 달라질 수 있습니다.<br>' : '') + '\
            - 자세한 사항은 판매자의 안내를 따라주세요.\
            </p>\
        </div>\
    </div>\
    ';
    if(free_flag || change_flag) {
        if($obj.find(".modal-comment.point-used-desc").length) {
            $obj.find(".modal-comment.point-used-desc").before(s);
        } else {
            $obj.append(s);
        }
    }
}

function setCLEscrowFooter(sid,plantype,obj) {
    if(typeof sid == 'undefined') return false;

    if( typeof plantype == 'undefined' || plantype != 'SM' || 
        typeof obj == 'undefined' || 
        typeof obj.onoff == 'undefined' || !obj.onoff || obj.onoff === false ||
        typeof obj.key == 'undefined' || !obj.key || obj.key == ''
    ) {
        $('.el-footer').find('.escrow-image-wrap-box').remove();
        return false;
    }

    var escrow_img = (typeof obj.type != 'undefined' && obj.type) ? obj.type : 1,
        escrow_key = obj.key,
        checkCLEscrowFooter = ($('.el-footer').find('.escrow-image-wrap-box').length > 0) ? true : false,
        checkCLFooter = ($('.el-footer').find('.cl-footer-site-element').length > 0) ? true : false;
    
    var escrow_link = '';
    if(obj.pg_company == 'KCP') {
        escrow_img = '<img src="//storage.googleapis.com/i.addblock.net/shopping_mall/escrow_site/escrow_site0' + escrow_img + '.png" />';
        escrow_link = '//admin.kcp.co.kr/Modules/escrow/kcp_pop.jsp?site_cd=' + escrow_key;
    } else if(obj.pg_company == 'NICEPAY') {
        escrow_img = '<img src="//storage.googleapis.com/i.addblock.net/shopping_mall/escrow_setting/nicepay_escrow_setting0' + escrow_img + '.png" />';
        escrow_link = 'https://npg.nicepay.co.kr/issue/issueEscrow.do?Mid=' + escrow_key + '&CoNo=' + obj.b_number.replace(/-/g,'');
    }
        
    var clef_str = '\
            <div class="escrow-image-wrap">\
                <a href="' + escrow_link + '" target="_blank">\
                    ' + escrow_img + '\
                </a>\
            </div>\
    ';

    if(checkCLEscrowFooter) {
        $('.el-footer').find('.escrow-image-wrap-box').html('<br>'+clef_str);
    } else if(checkCLFooter) {
        $('.el-footer').find('.escrow-image-wrap').remove();
        $('.el-footer').find('.cl-footer-site-element').last().append('<br><div class="escrow-image-wrap-box">'+clef_str+'</div>');
    } else {
        $('.el-footer').find('.container .row').last().append('<div class="col-xs-12 col-sm-12 col-md-12 clearfix clear escrow-image-wrap-box"><br>' + clef_str + '</div>');
    }
}


function setConfigLogs(action,v,obj,page) {
    $.post('/adm/clog/set', { action : action, v : v , obj : (typeof obj == 'object' && Object.keys(obj).length > 0) ? JSON.stringify(obj) : obj, page : page }, function(data) {
        if(typeof data.error != 'undefined' && data.error) {
            console.log(data.error);
            return false;
        }
    },'json');
}

function setSiteLogs(action,v,obj,page,ref) {
    $.post('/slog/set', { action : action, v : v , obj : (typeof obj == 'object' && Object.keys(obj).length > 0) ? JSON.stringify(obj) : obj, page : page, ref : ref }, function(data) {
        if(typeof data.error != 'undefined' && data.error) {
            console.log(data.error);
            return false;
        }
    },'json');
}

function getProductInfoList() {
    var input_empty = false,
        cate_null = false,
        idx = 0,
        prod_info_cate = $('.prod-select-title').text().trim(),
        $prod_info_lists = $('.prod-lists > div'),
        prod_info = {
            'title' : prod_info_cate,
            'content' : []
        };
        prod_null = new Array();

    if(prod_info_cate=='선택하세요') {
        cate_null = true;
    }

    $.each($prod_info_lists, function(i,v) {
        if($(this).hasClass('prod-info-list-save')) return true;

        var info_list_title = $(this).find('label').text(),
            info_list_content = ($(this).find('.prod-input-value').length > 0) ? $(this).find('.prod-input-value').html().trim() : '';
        if(info_list_content.length > 0) info_list_content = info_list_content.replace(/&nbsp;/gi, '');

        if(info_list_content.length==0) { 
            idx = i;
            input_empty = true;
            prod_null.push(idx);
        }
        var s = { 
            'title' : info_list_title,
            'content' : info_list_content
        }
        prod_info.content.push(s);
    });
    prod_info.input_empty = input_empty;
    prod_info.input_idx = idx;
    prod_info.cate_null = cate_null;
    return prod_info;
}

function setOptionlist($data, func) {
    var check_quantity = $('.prod-detail-wrap .switch-quantity').prop('checked'),
        normal_options_count = 0;

    $.each($data, function(idx,o) { //상품옵션 로드
        switch(o.option_status) {
            case "S" : str = '판매'; break;
            case "O" : str = '품절'; break;
            case "H" : str = '숨김'; break;
            default : str = '판매'; o.option_status = 'S'; break;
        }

        if(typeof o.option_quantity == 'undefined' || o.option_quantity == null) o.option_quantity = 0;
        if(typeof o.option_price == 'undefined' || o.option_price == null) o.option_price = 0;

        var s = "";
        if(typeof o.option_type !='undefined' && o.option_type.indexOf('T') > -1) {
            s = '\
            <li>\
                <div class="prod-option-item">\
                    <span class="prod-option-title" data-seq="' + o.seq + '">' + o.option_name + '</span>\
                    <span class="prod-option-require" data-val="' + o.option_type + '">';
                s += '</span>\
                </div>\
                <div class="prod-option-edit hide">\
                    <div class="form-wrap">\
                        <div class="form-group edit-option-title">\
                            <input type="text" maxlength="20" placeholder="안내문구 입력 (예:두께를 mm단위로 입력해주세요.)"/>\
                        </div>\
                        <div class="edit-option-delete" data-seq="' + o.seq + '"><svg viewBox="0 0 12 13" width="12" height="13"><path d="M12 2h-1H9V0H3.02v2H1 0v1h1v8c0 1.1 0.9 2 2 2h6c1.1 0 2-0.9 2-2V3h1V2zM4.02 1H8v1H4.02V1zM10 11c0 0.55-0.45 1-1 1H3c-0.55 0-1-0.45-1-1V3h1.02H9h1V11z"/><rect x="4" y="4" width="1" height="7"/><rect x="7" y="4" width="1" height="7"/></svg></div>\
                    </div>\
                </div>';
        } else {
            var option_price = Number(o.option_price),
                only_price = Math.abs(option_price),
                str_price = only_price.toString(),
                str_quantity = (o.option_quantity).toString(),
                minus = (option_price < 0)? 'minus':'',
                option_name = o.option_name;

                if(o.option_mix3) {
                    option_name = '<label class="owidth ow1">' + o.option_mix2 + '</label><label class="owidth ow2">' + o.option_mix3 + '</label><label class="owidth ow3">' + option_name + '</label>';
                } else {
                    if(o.option_mix2) {
                        option_name = '<label class="owidth ow1">' + o.option_mix2 + '</label><label class="owidth ow2">' + option_name + '</label>';
                    } else if(o.option_group) {
                        option_name = '<label class="owidth ow1">' + o.option_group + '</label><label class="owidth ow2">' + option_name + '</label>';
                    }
                }
            s = '\
            <li>\
                <div class="prod-option-item">\
                    <span class="prod-option-title" data-seq="' + o.seq + '">' + option_name + '</span>\
                    <span class="prod-option-price '+minus+'" data-option-price="'+o.option_price+'">' + addCommas(str_price) + '</span>\
                    <span class="prod-option-quantity" ' + ((check_quantity) ? '' : 'style="display:none"') + '>' + addCommas(str_quantity) + '</span>\
                    <span class="prod-option-status" data-val="' + o.option_status + '">' + str + '</span>\
                    <span class="prod-option-move"><i class="fa fa-arrows" aria-hidden="true"></i></span>\
                </div>\
                <div class="prod-option-edit hide">\
                    <div class="form-wrap">\
                        <div class="form-group edit-option-title">\
                            <input type="text" maxlength="60" placeholder="옵션값"/>\
                        </div>\
                        <div class="form-group edit-option-price">\
                            <input type="text" class="option-price-number sign" placeholder="0" numberOnly/>\
                        </div>\
                        <div class="form-group edit-option-quantity" ' + ((check_quantity) ? '' : 'style="display:none"') + '>\
                            <input type="text" class="option-price-quantity" maxlength="5" placeholder="0" numberonly/>\
                        </div>\
                        <div class="form-group edit-option-select">\
                            <div class="option-price-status-str hand" data-val="' + o.option_status + '">' + str + '</div>\
                            <ul class="option-price-status-select">\
                                <li data-val="S">판매</li>\
                                <li data-val="O">품절</li>\
                                <li data-val="H">숨김</li>\
                            </ul>\
                        </div>\
                        <div class="edit-option-delete" data-seq="' + o.seq + '"><svg viewBox="0 0 12 13" width="12" height="13"><path d="M12 2h-1H9V0H3.02v2H1 0v1h1v8c0 1.1 0.9 2 2 2h6c1.1 0 2-0.9 2-2V3h1V2zM4.02 1H8v1H4.02V1zM10 11c0 0.55-0.45 1-1 1H3c-0.55 0-1-0.45-1-1V3h1.02H9h1V11z"/><rect x="4" y="4" width="1" height="7"/><rect x="7" y="4" width="1" height="7"/></svg></div>\
                    </div>\
                </div>';
                // console.log('option_type:'+o.option_type);
            if (o.product_state && o.option_type!='A' && o.option_type!='T') {
                var p_s_data = JSON.parse(o.product_state);

                if (p_s_data.file_name) {
                    if (fileUpdateCnt == 0) fileUpdateCnt++;
                    if (loadFile == 0) loadFile++;
                    s += '<div class="form-group product-status">\
                            <div class="product-state-box">\
                                <div class="product-upload">\
                                    <div class="title">파일 업로드</div>\
                                    <div class="download-contents">\
                                        <span class="cl_icon_upload02" data-cnt="'+fileUpdateCnt+'">업로드</span>\
                                        <div class="file-box-list" id="file-box-'+fileUpdateCnt+'">';

                                            var serverName = p_s_data.file_url.split('/');
                                            s += '<div class="file-name file-name-'+loadFile+'">\
                                                    <span class="real-file-name">'+p_s_data.file_name+'</span>\
                                                    <span class="file-name-detail" title="'+p_s_data.file_name+'">'+p_s_data.file_str_name+'</span>\
                                                    <span class="file-size">'+p_s_data.file_size+'</span>\
                                                    <span class="cl-icon cl_icon_close" data-cnt="'+loadFile+'" data-pn="'+o.product_number+'" data-file="'+serverName[8]+'" data-seq="'+o.seq+'"></span>\
                                                    <span class="file-url">'+p_s_data.file_url+'</span>\
                                                </div>';
                                            loadFile++;

                    s += '              </div>\
                                    </div>\
                                </div>\
                            </div>\
                        </div>';
                }
            }
            fileUpdateCnt++;
        }
        s += "</li>";

        optionLength = Object.keys($data).length;
        if($data.length == 1 && o.option_name=='noneOption') {
            $('.prod-option[data-option_mode="normal"] .prod-option-list').append(s);
        } else {      
            if(o.option_type !== undefined && o.option_type.indexOf('T') > -1) {
                if($data.length > 0) {
                    $('.prod-option[data-option_mode="text"] .prod-option-list').append(s);
                    $('.option-state-box .newcheckbox').eq(1).find('#text-option').prop('checked',true);
                    $('.prod-option-tab').removeClass('hide');
                    $('.prod-option[data-option_mode="text"]').removeClass('hide');
                }
            } else if(o.option_type == 'A') {
                if($data.length > 0) {
                    $('.prod-option[data-option_mode="additional"] .prod-option-list').append(s);
                    $('.option-state-box .newcheckbox').eq(2).find('#additional-option').prop('checked',true);
                    $('.prod-option-tab').removeClass('hide');
                    $('.prod-option[data-option_mode="additional"]').removeClass('hide');
                    $('.prod-option[data-option_mode="additional"] .plus-price').removeClass('hide');
                    $('.prod-option[data-option_mode="additional"] .plus-status').removeClass('hide');

                }
            } else {
                $('.prod-option[data-option_mode="normal"] .prod-option-list').append(s);
                normal_options_count++;
                if(normal_options_count > 1) {
                    $('.option-state-box .newcheckbox').eq(0).find('#normal-option').prop('checked',true);
                    $('.prod-option-tab').removeClass('hide');
                    $('.prod-option[data-option_mode="normal"]').removeClass('hide');
                    $('.prod-option[data-option_mode="normal"] .plus-price').removeClass('hide');
                    $('.prod-option[data-option_mode="normal"] .plus-status').removeClass('hide');
                }
            }
        }

        if($('.prod-option[data-option_mode="normal"] .prod-option-list > li').length == 1) {
            $('.prod-option[data-option_mode="normal"]').addClass('hide');
            $('.option-state-box .newcheckbox').eq(0).find('#normal-option').prop('checked',false);
        }
        if($('.prod-option[data-option_mode="text"] .prod-option-list > li').length == 0) {
            $('.prod-option[data-option_mode="text"]').addClass('hide');
            $('.option-state-box .newcheckbox').eq(1).find('#text-option').prop('checked',false);
        }
        if($('.prod-option[data-option_mode="additional"] .prod-option-list > li').length == 0) {
            $('.prod-option[data-option_mode="additional"]').addClass('hide');
            $('.option-state-box .newcheckbox').eq(2).find('#additional-option').prop('checked',false);
        }
        
        $('#product-state').find('input[type="file"]').attr('data-cnt', loadFile).click();
    }); 
    
    if(typeof func == 'function') {
        func();
    }
}

var setAdvancedMode = function(r) {
    if(r == "true") { // 고급모드
        $('.option-type-title.tp2, .option-type-title.tp3').removeClass('hide');
        $('.option-type-title3.tp2, .option-type-title3.tp3').removeClass('hide');
        $('.options-config').addClass('active');
        $('.prod-option-list').sortable('disable');
        $('.edit-option-title input').prop('disabled', true);
        $('.prod-option-item .prod-option-move').addClass('invisible');
        $('.edit-option-delete').addClass('invisible');
        $('.prod-option-add').addClass('hide');
        $('.reset-wrap').removeClass('hide');
        $('.option-type-title.tp1').removeClass('editable');
        $('.prod-option[data-option_mode="text"] > .text-option-info').removeClass('editable');
        $('.prod-option[data-option_mode="text"] > .option-head').removeClass('editable');
        $('.option-type-title3.tp1').removeClass('editable');
    } else {
        $('.option-type-title.tp2, .option-type-title.tp3').addClass('hide');
        $('.option-type-title3.tp2, .option-type-title3.tp3').addClass('hide');
        $('.options-config').removeClass('active');
        $('.prod-option-list').sortable('enable');
        $('.edit-option-title input').prop('disabled', false);
        $('.prod-option-item .prod-option-move').removeClass('invisible');
        $('.edit-option-delete').removeClass('invisible');
        $('.prod-option-add').removeClass('hide');
        $('.reset-wrap').addClass('hide');
        $('.option-type-title.tp1').addClass('editable');
        $('.prod-option[data-option_mode="text"] > .text-option-info').addClass('editable');
        $('.prod-option[data-option_mode="text"] > .option-head').addClass('editable');
        $('.option-type-title3.tp1').addClass('editable');
    }
    if($('.prod-option-tab .prod-option.hide').length == 3) { //탭 모두 비활성화일때
        $('.reset-wrap').addClass('hide');
    }

    switch(product_options.type) {
        case "1": 
            $('.option-head-str').text('단일형');
            $('.option-type-title.tp1').text('옵션명');
            $('.option-type-title.tp2').text('옵션값');
            $('.option-type-title.tp3').text('');
            break;
        case "2": 
            $('.option-head-str').text('2개 조합형');
            if(product_options['config1'][0] !== undefined)
                $('.option-type-title.tp1').text(product_options['config1'][0]['title']).removeClass('editable');
            if(product_options['config1'][0] !== undefined)
                $('.option-type-title.tp2').text(product_options['config1'][0]['value']);
            $('.option-type-title.tp3').text('');
            break;
        case "3": 
            $('.option-head-str').text('3개 조합형');
            if(product_options['config1'][0] !== undefined)
                $('.option-type-title.tp1').text(product_options['config1'][0]['title']).removeClass('editable');
            if(product_options['config1'][0] !== undefined)
                $('.option-type-title.tp2').text(product_options['config1'][0]['value']);
            if(product_options['config1'][0] !== undefined)
                $('.option-type-title.tp3').text(product_options['config1'][0]['value2']);
            break;
        default:
            $('.option-head-str').text('기본형');
            $('.option-type-title.tp1').text('옵션명');
            $('.option-type-title.tp2').text('옵션값');
            $('.option-type-title.tp3').text('');
            break;            
    }
}
var switchQuantity = function() {
    if($('.switch-quantity').is(':checked')) {
        $('.switch-quantity').parents('.form-wrap').removeClass('disabled');
        $('.prod-option-quantity, .prod-plus-quantity, .edit-option-quantity').show();

        if($('#normal-option').is(':checked') === true) {
            // $('#prod-quantity').attr('readonly','true').removeClass('hide').attr('placeholder','옵션에서 재고 관리');
            $('.quantity-label').addClass('on');
            $('.plus-quantity').removeClass('hide');
        } else if($('#normal-option').is(':checked') === false && $('#additional-option').is(':checked') === true) {
            $('.quantity-label').removeClass('on');
            $('#prod-quantity').removeAttr('readonly').removeClass('hide');
            $('.plus-quantity').removeClass('hide');
        } else {
            $('.quantity-label').removeClass('on');
            $('#prod-quantity').removeAttr('readonly').removeClass('hide');
            $('.plus-quantity').addClass('hide');
        }
    } else {
        $('.quantity-label').removeClass('on');
        $('.switch-quantity').parents('.form-wrap').addClass('disabled');
        $('#prod-quantity').addClass('hide');
        $('.prod-option-quantity, .prod-plus-quantity, .edit-option-quantity').hide();
        $('.plus-quantity').addClass('hide');
    }
}        

function getMapURL(map_url, return_type) {
    /*
        https://www.google.co.kr/maps/@37.4817147,127.0069527,14z
        https://www.google.co.kr/maps/place/%EB%82%B4%EB%B0%A9%EC%97%AD/@37.4817147,127.0069527,14z/data=!4m5!3m4!1s0x357ca1a63a309789:0xb47e374059d4245b!8m2!3d37.487707!4d126.993598
        <iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3163.016222643161!2d126.96939075969449!3d37.554681575448!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x357ca266e3947003%3A0xe7be97c172b7af6a!2z7ISc7Jq47Jet!5e0!3m2!1sko!2skr!4v1628745599351!5m2!1sko!2skr" width="600" height="450" style="border:0;" allowfullscreen="" loading="lazy"></iframe>
    

        https://www.google.com/maps/place/%EC%9D%B4%EC%88%98%EC%97%AD/@37.4857251,126.9797283,17z/data=!4m9!1m2!2m1!1z7J207IiY7Jet!3m5!1s0x357ca1b3e26dcf3d:0xa16abe6619550e35!8m2!3d37.486491!4d126.981876!15sCgnsnbTsiJjsl62SAQtidXNfc3RhdGlvbg?hl=ko
        https://www.google.com/maps/search/%EC%9D%B4%EC%88%98%EC%97%AD/@37.4857251,126.9797283,17z/data=!3m1!4b1?hl=ko
    */
    

    var checkGoogle = (map_url.match(/^(https|http)\:\/\/www\.google(\.co\.kr|\.com)\/maps\//g) !== null) ? true : false;
    if(checkGoogle) {
        var checkEmbed = (map_url.match(/^(https|http)\:\/\/www\.google(\.co\.kr|\.com)\/maps\/embed\?/g) !== null) ? true : false,
            checkPlace = (map_url.match(/^(https|http)\:\/\/www\.google(\.co\.kr|\.com)\/maps\/(place|search)/g) !== null) ? true : false;
        if(checkEmbed) {
            var map_src = map_url;
        } else {
            var map_arr = map_url.replace(/^(https|http)\:\/\/www\.google(\.co\.kr|\.com)\/maps\//g,'').split('/'),
                map_tmp = (checkPlace) ? map_arr[2].split(',') : map_arr[0].split(','),
                map_unit = (typeof map_tmp[2] != 'undefined' && map_tmp[2]) ? map_tmp[2].replace(/[0-9.]/g,'') : '',
                map_place = (checkPlace) ? map_arr[1] : '',
                map_xy = map_tmp[0].replace(/^@/,'') + ' ' + map_tmp[1],
                map_zoom = (map_unit == 'z') ? parseInt(map_tmp[2].replace('z','')) : 17,
                // 위성지도 map_miter = (map_unit == 'm') ? map_tmp[2].replace('m','') : '',
                map_query = (checkPlace) ? map_place : map_xy;


            if(map_unit == 'z') map_query += '&z='+map_zoom;
            // 위성지도  if(map_unit == 'm') map_query += '&t=k';

            // 언어
            var check_lang = map_arr[map_arr.length-1];
            if(typeof check_lang != 'undefined' && check_lang) {
                var lang_arr = check_lang.split('?'),
                    lang_str = '';
                $.each(lang_arr, function(i,tmp) {
                    if(tmp.match(/^hl\=(ko|en|eu|ca|hr|cs|da|nl}fi|fr|de|gl|el|hi|id|it|ja|no|nn|pt|rm|ru|sr|sk|sl|es|sv|th|tr|uk|vi)/g) !== null) {
                        map_query += '&hl=' + tmp.replace(/^hl=/g,'');
                    }
                });
            }
            
            var map_src = '//www.google.com/maps?q=' + map_query + '&ll=' + map_xy.replace(/ /,',') + '&output=embed';
        }

        var map_iframe = '\
            <iframe class="google-map" src="' + map_src + '" data-map="true" data-url="' + map_url + '" allowfullscreen="" loading="lazy"></iframe>\
        ';
        if(return_type == 'html') return map_iframe;
        else if(return_type == 'src') return map_src;
        // else if(return_type == 'obj') {
        //     return {
        //         'url' : map_url,
        //         'src' : map_src,
        //         'html' : map_iframe.trim(),
        //         'place' : (checkPlace) ? map_place : '',
        //         'xy' : (checkPlace) ? map_xy : '',
        //         'unit' : (checkPlace) ? map_unit : '',
        //         'zoom' : (checkPlace) ? map_zoom : '',
        //     };
        // }
    } else {
        var map_src = '//www.google.com/maps?q=서울특별시&z=10&output=embed',
            map_iframe = '\
            <iframe class="google-map disabled" src="' + map_src + '" data-map="true" data-url="' + map_src + '" allowfullscreen="" loading="lazy"></iframe>\
            <div class="map-undefined"><span>지도 URL을 다시 설정해주세요</span></div>\
        ';

        if(return_type == 'html') return map_iframe;
        else if(return_type == 'src') return map_src;
    }
}

var deliveryTemplateListModal = function(shopping_url, close_func) {
$.processON();
    var html = '';

    html += '\
        <div class="setting-sub-content setting-delivery-template">\
            <div class="setting-sub-content-desc">여러 유형의 배송 조건을 설정하고, 상품 등록 시 미리 설정해둔 배송 조건을<br>간편하게 적용할 수 있습니다.</div>\
            <button type="button" class="btn-add-template btn btn-sm f-right"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10" width="10" height="10"><path d="M10 4H6V0H4v4H0v2h4v4h2V6h4z"/></svg>배송설정 추가</button>\
            <div class="delivery-template-area"></div>\
        </div>\
    '

    var modal = $(this).showModalFlat($.lang[LANG]['shopping.delivery.template.title'],html,true,false, function() {
        modal.modal('hide');
    }, 'close','','cl-cmmodal cl-s-btn w680 cl-p70 cover delivery-template-modal', true, function() {
        if(typeof close_func == 'function') {
            close_func();
        }
    }, function() {
        
        var getDeliveryTemplateList = function() {
            $.ajax({
                url: shopping_url + '/getDeliveryTemplateList',
                type: 'post',
                dataType: 'json',
                data:{'sid' : SID},
                async: false,
                success:function(data) {
                    console.log(data);
                    var html = '';
                    if(data.length) {
                        $(data).each(function(idx) {
                            var row = this;

                            html += '<div class="template-row-box" data-seq="' + row.seq + '">';
                            html += '<div class="template-row-title-box">';
                            html += '<div class="template-row-title">' + row.name + '</div>';

                            if(LUX) {
                                if(idx > 0) {
                                    html += '<div class="template-row-buttons">\
                                                <span class="btn-edit-template"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 12 12" width="12" height="12"><path d="m11.56.57-.13-.13C11.14.15 10.76 0 10.37 0c-.38 0-.77.15-1.06.44L.75 9 0 12l3-.75 8.56-8.56c.59-.59.59-1.54 0-2.12zm-9.07 9.78-1.11.28.28-1.11 6.58-6.58.84.84-6.59 6.57zm8.36-8.37L9.77 3.06l-.83-.83 1.08-1.08a.487.487 0 0 1 .7 0l.13.13c.2.19.2.51 0 .7z"></path></svg></span>\
                                                <span class="btn-copy-template"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 12 13" width="12" height="13"><path d="M10.5 0h-6C3.67 0 3 .67 3 1.5V2H1.5C.67 2 0 2.67 0 3.5v8c0 .83.67 1.5 1.5 1.5h6c.83 0 1.5-.67 1.5-1.5V11h1.5c.83 0 1.5-.67 1.5-1.5v-8c0-.83-.67-1.5-1.5-1.5zM8 11.5c0 .28-.22.5-.5.5h-6c-.28 0-.5-.22-.5-.5v-8c0-.28.22-.5.5-.5H3v6.5c0 .83.67 1.5 1.5 1.5H8v.5zm3-2c0 .28-.22.5-.5.5h-6c-.28 0-.5-.22-.5-.5v-8c0-.28.22-.5.5-.5h6c.28 0 .5.22.5.5v8z"></path></svg></span>\
                                    ';
                                    if(idx > 1) {
                                        html += '\
                                                    <span class="btn-delete-template"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 12 13" width="12" height="13"><path d="M11 2H9V0H3.02v2H1 0v1h1v8c0 1.1 0.9 2 2 2h6c1.1 0 2-0.9 2-2V3h1V2H11zM4.02 1H8v1H4.02V1zM10 11c0 0.55-0.45 1-1 1H3c-0.55 0-1-0.45-1-1V3h1.02H9h1V11z"></path><rect x="4" y="4" width="1" height="7"></rect><rect x="7" y="4" width="1" height="7"></rect></svg></span>\
                                        ';
                                    }
                                    html += '\
                                            </div>';
                                }
                            } else {
                                html += '<div class="template-row-buttons">\
                                            <span class="btn-edit-template"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 12 12" width="12" height="12"><path d="m11.56.57-.13-.13C11.14.15 10.76 0 10.37 0c-.38 0-.77.15-1.06.44L.75 9 0 12l3-.75 8.56-8.56c.59-.59.59-1.54 0-2.12zm-9.07 9.78-1.11.28.28-1.11 6.58-6.58.84.84-6.59 6.57zm8.36-8.37L9.77 3.06l-.83-.83 1.08-1.08a.487.487 0 0 1 .7 0l.13.13c.2.19.2.51 0 .7z"></path></svg></span>\
                                            <span class="btn-copy-template"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 12 13" width="12" height="13"><path d="M10.5 0h-6C3.67 0 3 .67 3 1.5V2H1.5C.67 2 0 2.67 0 3.5v8c0 .83.67 1.5 1.5 1.5h6c.83 0 1.5-.67 1.5-1.5V11h1.5c.83 0 1.5-.67 1.5-1.5v-8c0-.83-.67-1.5-1.5-1.5zM8 11.5c0 .28-.22.5-.5.5h-6c-.28 0-.5-.22-.5-.5v-8c0-.28.22-.5.5-.5H3v6.5c0 .83.67 1.5 1.5 1.5H8v.5zm3-2c0 .28-.22.5-.5.5h-6c-.28 0-.5-.22-.5-.5v-8c0-.28.22-.5.5-.5h6c.28 0 .5.22.5.5v8z"></path></svg></span>\
                                ';
                                if(idx > 0) {
                                    html += '\
                                                <span class="btn-delete-template"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 12 13" width="12" height="13"><path d="M11 2H9V0H3.02v2H1 0v1h1v8c0 1.1 0.9 2 2 2h6c1.1 0 2-0.9 2-2V3h1V2H11zM4.02 1H8v1H4.02V1zM10 11c0 0.55-0.45 1-1 1H3c-0.55 0-1-0.45-1-1V3h1.02H9h1V11z"></path><rect x="4" y="4" width="1" height="7"></rect><rect x="7" y="4" width="1" height="7"></rect></svg></span>\
                                    ';
                                }
                                html += '\
                                        </div>';
                            }
                            html += '</div>';

                            html += '<div class="template-row-content">';
                            html += (row.mix_yn == 'Y' ? '묶음배송' : '개별배송') + ' / ';

                            var delivery_type_arr = row.delivery_type.split(',');
                            var delivery_type_str = '';
                            $(delivery_type_arr).each(function(k,v) {
                                if(delivery_type_str) delivery_type_str += ', ';
                                delivery_type_str += $.lang[LANG]['shopping.delivery.template.delivery_type.' + v.toLowerCase()];
                            });


                            if(delivery_type_str) html += delivery_type_str + ' / ';
                            if(delivery_type_arr.indexOf('DELIVERY') > -1) 
                                html += $.lang[LANG]['shopping.delivery.' + row.delivery_company.toLowerCase()] + ' / ';
                            html += $.lang[LANG]['shopping.delivery.template.price_type.' + row.price_type.toLowerCase()]; 

                            if(row.price_type == 'FIX') {
                                html += '(' + number_format(row.delivery_fee) + '원)';
                            } else if(row.price_type == 'QUANTITY' || row.price_type == 'WEIGHT') {
                                var price_type_detail = row.price_type_detail ? JSON.parse(row.price_type_detail) : {};
                                
                                if(price_type_detail.method == 'DIFFERENTIAL') {
                                    var detail = '';
                                    var popup_content = '';
                                    if(price_type_detail.detail) {
                                        $.each(price_type_detail.detail, function(k, v) {
                                            var value = Object.keys(v);
                                            var price = Object.values(v);

                                            if(row.price_type == 'QUANTITY') {
                                                if(k < 2) {
                                                    if(detail) detail += ', ';
                                                    detail += value + '개 이상(' + number_format(price) + '원)';
                                                }
                                                popup_content += value + '개 이상 ' + number_format(price) + '원' + '<br>';
                                            } else if(row.price_type == 'WEIGHT') {
                                                if(k < 2) {
                                                    if(detail) detail += ', ';
                                                    detail += value + 'Kg 이상(' + number_format(price) + '원)';
                                                }
                                                popup_content += value + 'Kg 이상 ' + number_format(price) + '원' + '<br>';
                                            }
                                        });

                                        if(price_type_detail.detail.length > 2) {
                                            popup_content = $.lang[LANG]['shopping.delivery.template.price_type.' + row.price_type.toLowerCase()] + '<br>' + popup_content;
                                            if(!LUX) popup_content += '<br>※ 추가 상품은 배송비 조건에 반영되지 않습니다.';
                                            detail += '<span class="cm-popover-info" data-toggle="popover" tabindex="0" data-trigger="hover" data-html="true" data-placement="bottom" data-content="' + popup_content + '"> 더보기 </span>';
                                        }
                                    }
                                    if(detail) {
                                        detail = '(차등 / ' + detail + ')';
                                        html += detail;
                                    }
                                } else if(price_type_detail.method == 'REPEAT') {
                                    var detail = '';
                                    var value = Object.keys(price_type_detail.detail);
                                    var price = Object.values(price_type_detail.detail);

                                    if(row.price_type == 'QUANTITY') {
                                        detail += value + '개 구매시마다 ' + number_format(price) + '원 반복 부과';
                                    } else if(row.price_type == 'WEIGHT') {
                                        detail += value + 'Kg마다 ' + number_format(price) + '원 반복 부과';
                                    }

                                    if(detail) {
                                        detail = '(반복 / ' + detail + ')';
                                        html += detail;
                                    }
                                }
                            }

                            if(row.additional_yn == 'Y') {
                                html += ' / 도서산간 지역 추가 배송비 (제주 ' + number_format(row.additional_jeju_price) + '원, 제주 외 도서산간 ' + number_format(row.additional_land_price) + '원';
                            }

                            html += ' / ' + $.lang[LANG]['shopping.delivery.template.pay_type.' + row.pay_type.toLowerCase()];

                            if(row.free_condition_yn == 'Y') {
                                html += ' / ' + number_format(row.free_condition) + '원 이상 무료 배송';
                            }

                            if(row.make_to_order_yn == 'Y') {
                                html += ' / 주문 확인 후 ' + row.due_date + '일 후 배송 예정';
                            }

                            if(row.install_fee_yn == 'Y') {
                                html += ' / 별도 설치비 있음';
                            }

                            html += '</div>';
                            html += '</div>';
                        });
                    } else {
                        html += '<div>배송 템플릿이 없습니다.</div>';
                    }
                    html += '</div>';
                    $('.delivery-template-area').html(html);
                    $('.delivery-template-area').find('[data-toggle="popover"]').popover();
                }, complete: function() {
                    $.processOFF();
                }
            });
        }

        getDeliveryTemplateList();

        $('.btn-add-template').on('click', function() {
            deliveryTemplateEditModal(shopping_url, '', getDeliveryTemplateList);
        });

        modal.on('click', '.btn-edit-template', function() {
            var seq = $(this).closest('.template-row-box').data('seq');
            deliveryTemplateEditModal(shopping_url, seq, getDeliveryTemplateList);
        });

        modal.on('click', '.btn-copy-template', function() {
            var seq = $(this).closest('.template-row-box').data('seq');
            var copy_modal = $(this).showModalFlat('배송설정 복제', '선택한 배송설정을 복제하시겠습니까?', true, true, function() {
                    $.processON();
                    setTimeout(function() {
                        $.ajax({
                            url: shopping_url + '/copyDeliveryTemplate',
                            type:'post',
                            dataType:'json',
                            async: false,
                            data:{'sid' : SID, 'seq' : seq},
                            success:function(data) {
                                getDeliveryTemplateList();
                            }, complete: function() {
                                $.processOFF();
                            }
                        });
                    });
                    
                copy_modal.modal('hide');
            }, 'cancel', 'ok', 'cl-cmmodal cl-s-btn w560 cl-p130');
            var backdrop_z_index = Number(copy_modal.css('zIndex'));
            backdrop_z_index+=2;
            copy_modal.css('zIndex', backdrop_z_index + 1);
            copy_modal.parent().next('.modal-backdrop').css('zIndex', backdrop_z_index);
        });

        modal.on('click', '.btn-delete-template', function() {
            var seq = $(this).closest('.template-row-box').data('seq');
            var delete_modal = $(this).showModalFlat('배송설정 삭제', '선택한 배송설정이 적용되었던 상품들은 기본 배송설정으로 변경됩니다.<br><br>선택한 배송설정을 삭제하시겠습니까?', true, true, function() {
                    $.processON();
                    setTimeout(function() {
                        $.ajax({
                            url: shopping_url + '/deleteDeliveryTemplate',
                            type:'post',
                            dataType:'json',
                            async: false,
                            data: {
                                'sid' : SID,
                                'seq' : seq
                            },
                            success:function(data) {
                                getDeliveryTemplateList();
                            },
                            complete: function() {
                                $.processOFF();
                            }
                        });
                    });
                delete_modal.modal('hide');
            }, 'cancel', 'ok', 'cl-cmmodal cl-s-btn w560 cl-p130',true);
                
            var backdrop_z_index = Number(delete_modal.css('zIndex'));
            backdrop_z_index+=2;
            delete_modal.css('zIndex', backdrop_z_index + 1);
            delete_modal.parent().next('.modal-backdrop').css('zIndex', backdrop_z_index);
        }); 
    }, function() {
        // if(typeof close_func == 'function') {
        //     close_func();
        // }
    });
}

var deliveryTemplateEditModal = function(shopping_url, template_seq, callback_func) {

    var seq = template_seq ? template_seq : '';

    var opts = {
        'seq' : '',
        'name':'',
        'mix_yn' : 'Y',
        'delivery_type' : 'DELIVERY',
        'price_type' : 'FIX',
        'delivery_fee' : 2500,
        'additional_yn' : 'N',
        'pay_type' : 'PREPAY',
        'free_condition_yn' : 'N',
        'make_to_order_yn' : 'N',
        'install_fee_yn' : 'N',
        'additional_jeju_price' : 0,
        'additional_land_price' : 0,
        'due_date' : '',
        'free_condition' : 0,
        'delivery_company' : 'pt',
        'price_type_detail' : {}
    };

    if(seq) {
        $.ajax({
            url:shopping_url + '/getDeliveryTemplate',
            type:'post',
            dataType:'json',
            async: false,
            data:{
                'seq' : seq,
                'sid' : SID,
            },
            success:function(data) {
                $.extend(opts, data);
            }
        });
    }

    opts.delivery_type = opts.delivery_type.split(',');
    if(opts.price_type == 'QUANTITY' || opts.price_type == 'WEIGHT') {
        opts.price_type_detail = opts.price_type_detail ? JSON.parse(opts.price_type_detail) : {};
        
        if(!opts.price_type_detail.detail) {
            opts.price_type_detail.detail = {};
        }

        if(opts.price_type_detail.method && opts.price_type_detail.method == 'REPEAT') {
            if(opts.price_type == 'QUANTITY') {
                opts.quantity_repeat_value = Object.keys(opts.price_type_detail.detail)[0];
                opts.quantity_repeat_price = Object.values(opts.price_type_detail.detail)[0];
            } else if(opts.price_type == 'WEIGHT') {
                opts.weight_repeat_value = Object.keys(opts.price_type_detail.detail)[0];
                opts.weight_repeat_price = Object.values(opts.price_type_detail.detail)[0];
            }
        } else {
            opts.price_type_detail.method = 'DIFFERENTIAL';
        }
    }

    if(opts.delivery_company == '') opts.delivery_company = 'pt';

    var tracking_delivery_company_arr = ['cj','pt','hj','lg','lt','post'];

    var delivery_company_arr = [
        'etc',
        'cj',
        'pt',
        'hj',
        'lg',
        'lt',
        'post',
        'koryo',
        'wevill',
        'daesin',
        'ilyang',
        'kdexp',
        'chunil',
        'cv',
        'cu',
        'hdexp',
        'dhl',
        'dhlglobalmail',
        'dhlde',
        'fedex',
        'gsmnton',
        'warpex',
        'ems',
        'ace',
        'qxpress',
        'aciexpress',
        'lineexp',
        'pantos',
        'smartlogis',
        'hlcglobal',
        'ups',
        'korexg',
        'tnt',
        'swgexp',
        'daewoon',
        'usps',
        'iparcel',
        'kunyoung',
        'hpl',
        'gnetwork',
        'slx',
        'daelim',
        'honam',
        'gsiexpress',
        'eunha',
        'homeinno',
        'hybrid',
        'airway',
        'woorihb',
        'yjsworld',
        'yjs',
        'crlx',
        'homepick',
        'cwayexpress',
        'anytrack',
        'bridge',
        'gpslogix',
        'esther',
        'lotos',
        'ufreight',
        'ik',
        'lslogis',
        'sebang',
        'nonghyup',
        'yongma',
        'europarcel',
        'kgsl',
        'sunghun',
        'forever',
        'airboy',
        'ecmsexpress',
        'efs',
        'handex',
        'kglnet',
        'twofastexpress',
        'gos',
        'gspostbox',
        'adcair',
        'donggang',
        'kin',
        'hanwoori',
        'lglogistics',
        'generalpost',
        'ezusa',
        'handalum',
        'howser',
        'dpd',
        'gop',
        'wizwa',
        'selc',
        'sfex',
        'wihtyou',
        'roadsunexpress',
        'dongjin',
        'ilshin',
        'ky',
        'tpmlogis',
        'zeniel',
        'fresh',
        'jlogist',
        'chainlogis',
        'hivecity',
        'hanssem',
        'todaypickup',
        'qrun',
        'nogok',
        'spasys1',
        'freshmates',
        'etomars',
        'shipnergy',
        'geniego',
        'dodoflex',
        'ltl',
        'vendorpia',
        'coship',
        'gdakorea',
        'lge',
        'teamfresh',
        'yunda',
        'alltakorea',
        'lottechilsung',
        'valex',
        'bababa',
        'ch1',
        'apex',
        'homeplus',
        'gsfresh',
        'hanaromart',
        'choroc',
        'vroong',
        'dcommerce',
        'aboutpet',
        '1004home',
        'gtslogis',
        'sbgls',
        'ssg',
        'kokusai',
        'goodtoluck',
        'ekdp',
        'woongji',
        'xinpatek',
        'herewego',
        'panasia',
        'pingpong',
        'cargoplease',
		'kjt', // 케이제이티
		'rush', // 오늘회러쉬
		'ntlps', // 엔티엘피스
		'actcore', // 에이씨티앤코아
		'logisvalley', // 로지스밸리
		'drabbit', // 딜리래빗
		'naeun', // 나은물류
		'logispartner', // UFO 로지스
		'ndexkorea', // NDEX KOREA
    ];

        // console.log(new_delivery_company_arr)
    var tmp_delivery_company_arr = {}, new_delivery_company_arr = {};
    var delivery_company_options = '';
    $(delivery_company_arr).each(function(k, v) {
        tmp_delivery_company_arr[$.lang[LANG]['shopping.delivery.' + v]] = v;
    });

    $(Object.keys(tmp_delivery_company_arr).sort()).each(function(k, v) {
        new_delivery_company_arr[v] = tmp_delivery_company_arr[v];
    });

    delivery_company_options = '';
    $.each(new_delivery_company_arr, function(k, v) {
        var data_content = '';
        if(tracking_delivery_company_arr.indexOf(v) > -1) {
            data_content = '<span class="tracking-delivery-icon"></span>';
        }
        delivery_company_options += '<option value="' + v + '" ' + (opts.delivery_company == v ? ' selected ' : '') + (data_content ? ' data-content=\'' + k + data_content + '\'' : '') + '>' + k + '</option>';
    });

    var html = '\
        <div class="delivery-template-layer">\
            <form id="deliveryTemplateForm">\
                <div class="item-row">\
                    <div class="">' + $.lang[LANG]['shopping.delivery.template.name'] + '</div>\
                    <div class=""><input type="hidden" name="sid" value="' + SID + '" /><input type="text" name="name" class="form-control" value="' + opts.name + '" maxlength="50" autocomplete="off" /><input type="hidden" name="seq" value="' + opts.seq + '" /></div>\
                </div>\
                <div class="item-row">\
                    <div class="">' + $.lang[LANG]['shopping.delivery.template.mix_yn'] + '<svg class="cm-popover-info" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 13 13" width="13" height="13" tabindex="0" data-trigger="hover" data-toggle="popover" fill="#4789e7" data-html="true" data-placement="top" data-content="<ul><li class=\'item\'>묶음 배송 : 여러 상품을 같이 구매할 경우, 동일한 배송설정이 적용되어 있다면 구매자에게 배송비가 한 번만 부과됩니다.</li><li class=\'item\'>개별 배송 : 여러 상품을 구매하더라도, 상품 별로 설정한 배송비가 부과됩니다.</li></ul>" data-original-title="" title=""><path d="M6.5 0C2.91 0 0 2.91 0 6.5S2.91 13 6.5 13 13 10.09 13 6.5 10.09 0 6.5 0zM6.5 12C3.47 12 1 9.53 1 6.5S3.47 1 6.5 1 12 3.47 12 6.5 9.53 12 6.5 12z"></path><path d="M6.66 3.01C5.61 3.01 4.58 3.5 4.5 4.8c0 0.06-0.01 0.12 0 0.2h1.02c0-0.07 0.01-0.15 0.02-0.23 0.08-0.62 0.52-0.76 1.08-0.76 0.63 0 1.02 0.37 1.02 0.95 -0.01 0.48-0.3 0.87-0.76 1.34C6.21 6.97 6.02 7.37 6 8h0.99C7 7.66 7.04 7.37 7.67 6.75 8.17 6.27 8.7 5.68 8.7 4.87 8.7 3.85 7.89 3.01 6.66 3.01z"></path><rect x="6" y="9" width="1" height="1"></rect></svg></div>\
                    <div class="mix-yn-row"><label><input type="radio" name="mix_yn" value="Y" ' + (opts.mix_yn == 'Y' ? ' checked ' : '') + ' /><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 18 18" width="18" height="18"><path d="M9 0a9 9 0 1 0 .001 18.001A9 9 0 0 0 9 0zm0 17c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z"/></svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 18 18" width="18" height="18"><path d="M9 0a9 9 0 1 0 .001 18.001A9 9 0 0 0 9 0zm0 17c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z"/><circle cx="9" cy="9" r="6"/></svg>' + $.lang[LANG]['shopping.delivery.template.mix_yn.y'] + '</label> <label><input type="radio" name="mix_yn" value="N" ' + (opts.mix_yn == 'N' ? ' checked ' : '') + ' /><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 18 18" width="18" height="18"><path d="M9 0a9 9 0 1 0 .001 18.001A9 9 0 0 0 9 0zm0 17c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z"/></svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 18 18" width="18" height="18"><path d="M9 0a9 9 0 1 0 .001 18.001A9 9 0 0 0 9 0zm0 17c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z"/><circle cx="9" cy="9" r="6"/></svg>' + $.lang[LANG]['shopping.delivery.template.mix_yn.n'] + '</label></div>\
                </div>\
                <div class="item-row">\
                    <div class="">' + $.lang[LANG]['shopping.delivery.template.delivery_type'] + '<svg class="cm-popover-info" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 13 13" width="13" height="13" tabindex="0" data-trigger="hover" data-toggle="popover" fill="#4789e7" data-html="true" data-placement="top" data-content="<ul><li class=\'title\'>상품을 배송하는 수단을 선택합니다.</li><li class=\'item\'>택배 : 택배사를 이용하여 상품을 발송합니다.</li><li class=\'item\'>직접배송(화물배달) : 판매자가 직접 배송을 하거나 화물로 발송합니다.</li><li class=\'item\'>퀵서비스 : 퀵서비스를 이용하여 상품을 발송합니다. 배송비는 별도 안내로 설정되고 결제 방식은 착불만 지원합니다.<div class=\'desc\'>* 퀵서비스 가능 여부 및 배송비에 대해 상세페이지에 내용을 입력하거나 구매자와 협의해 주세요.</div></li><li class=\'item\'>방문수령 : 구매자가 판매자에게 방문하여 직접 상품을 받아 갑니다. 배송비는 무료 배송으로 설정되고 결제방식은 지원하지 않습니다.</li></ul>" data-original-title="" title=""><path d="M6.5 0C2.91 0 0 2.91 0 6.5S2.91 13 6.5 13 13 10.09 13 6.5 10.09 0 6.5 0zM6.5 12C3.47 12 1 9.53 1 6.5S3.47 1 6.5 1 12 3.47 12 6.5 9.53 12 6.5 12z"></path><path d="M6.66 3.01C5.61 3.01 4.58 3.5 4.5 4.8c0 0.06-0.01 0.12 0 0.2h1.02c0-0.07 0.01-0.15 0.02-0.23 0.08-0.62 0.52-0.76 1.08-0.76 0.63 0 1.02 0.37 1.02 0.95 -0.01 0.48-0.3 0.87-0.76 1.34C6.21 6.97 6.02 7.37 6 8h0.99C7 7.66 7.04 7.37 7.67 6.75 8.17 6.27 8.7 5.68 8.7 4.87 8.7 3.85 7.89 3.01 6.66 3.01z"></path><rect x="6" y="9" width="1" height="1"></rect></svg></div>\
                    <div class="delivery-type-row"><label class="btn-delivery-type"><input type="radio" name="delivery_type[]" value="DELIVERY" ' + (opts.delivery_type.indexOf('DELIVERY') > -1 ? ' checked ' : '') + ' /><div>' + $.lang[LANG]['shopping.delivery.template.delivery_type.delivery'] + '</div></label> <label class="btn-delivery-type"><input type="radio" name="delivery_type[]" value="DIRECT" ' + (opts.delivery_type.indexOf('DIRECT') > -1 ? ' checked ' : '') + ' /><div>' + $.lang[LANG]['shopping.delivery.template.delivery_type.direct'] + '</div></label> <label><input type="checkbox" name="delivery_type[]" value="QUICK" ' + (opts.delivery_type.indexOf('QUICK') > -1 ? ' checked ' : '') + ' /><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16"><path d="M13 0H3C1.3 0 0 1.3 0 3v10c0 1.7 1.3 3 3 3h10c1.7 0 3-1.3 3-3V3C16 1.3 14.7 0 13 0zM15 13c0 1.1-0.9 2-2 2H3c-1.1 0-2-0.9-2-2V3c0-1.1 0.9-2 2-2h10c1.1 0 2 0.9 2 2V13z"></path></svg><svg class="active" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16"><path d="M13 0H3C1.34 0 0 1.34 0 3v10c0 1.66 1.34 3 3 3h10c1.66 0 3-1.34 3-3V3C16 1.34 14.66 0 13 0zM13.03 6.03l-5.5 5.5C7.38 11.68 7.19 11.75 7 11.75s-0.38-0.07-0.53-0.22l-3.5-3.5c-0.29-0.29-0.29-0.77 0-1.06s0.77-0.29 1.06 0L7 9.94l4.97-4.97c0.29-0.29 0.77-0.29 1.06 0S13.32 5.74 13.03 6.03z"></path></svg>' + $.lang[LANG]['shopping.delivery.template.delivery_type.quick'] + '</label> <label><input type="checkbox" name="delivery_type[]" value="VISIT" ' + (opts.delivery_type.indexOf('VISIT') > -1 ? ' checked ' : '') + ' /><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16"><path d="M13 0H3C1.3 0 0 1.3 0 3v10c0 1.7 1.3 3 3 3h10c1.7 0 3-1.3 3-3V3C16 1.3 14.7 0 13 0zM15 13c0 1.1-0.9 2-2 2H3c-1.1 0-2-0.9-2-2V3c0-1.1 0.9-2 2-2h10c1.1 0 2 0.9 2 2V13z"></path></svg><svg class="active" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16"><path d="M13 0H3C1.34 0 0 1.34 0 3v10c0 1.66 1.34 3 3 3h10c1.66 0 3-1.34 3-3V3C16 1.34 14.66 0 13 0zM13.03 6.03l-5.5 5.5C7.38 11.68 7.19 11.75 7 11.75s-0.38-0.07-0.53-0.22l-3.5-3.5c-0.29-0.29-0.29-0.77 0-1.06s0.77-0.29 1.06 0L7 9.94l4.97-4.97c0.29-0.29 0.77-0.29 1.06 0S13.32 5.74 13.03 6.03z"></path></svg>' + $.lang[LANG]['shopping.delivery.template.delivery_type.visit'] + '</label>\
                        <div class="delivery-company-row" style="' + (opts.delivery_type.indexOf('DELIVERY') > -1 ? '' : ' display: none; ') + '">\
                            <div class="row-sub-title">' + $.lang[LANG]['shopping.delivery.template.delivery_company'] + '</div>\
                            <select name="delivery_company" class="form-control">\
                                ' + delivery_company_options + '\
                            </select>\
                        </div>\
                    </div>\
                </div>\
                <div class="item-row">\
                    <div class="">' + $.lang[LANG]['shopping.delivery.template.price_type'] + '<svg class="cm-popover-info" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 13 13" width="13" height="13" tabindex="0" data-trigger="hover" data-toggle="popover" fill="#4789e7" data-html="true" data-placement="top" data-content="<ul><li class=\'title\'>배송비 계산 방법을 선택합니다.</li><li class=\'item\'>고정 배송비(기본설정) : 설정한 배송비로 부과합니다. (네이버 페이 결제 가능)</li><li class=\'item\'>수량별 배송비 : 수량에 따라서 배송비를 차등/반복 옵션으로 부과합니다.<div class=\'desc\'>* 네이버 페이 결제 가능 (단, 수량별 배송비 차등 항목이 4개 이상인 경우 네이버 페이 결제 불가능)</div></li><li class=\'item\'>무게별 배송비 : 무게에 따라서 배송비를 차등/반복 옵션으로 부과합니다. (네이버 페이 결제 불가능)</li><li class=\'item\'>무료 배송 : 배송비가 무료입니다. (네이버 페이 결제 가능)</li><li class=\'item\'>별도 안내 : 결제 시 배송비가 부과하지 않고 판매자와 별도로 협의하여 배송비를 별도로 측정 및 계산합니다. (네이버 페이 결제 가능)</li></ul>" data-original-title="" title=""><path d="M6.5 0C2.91 0 0 2.91 0 6.5S2.91 13 6.5 13 13 10.09 13 6.5 10.09 0 6.5 0zM6.5 12C3.47 12 1 9.53 1 6.5S3.47 1 6.5 1 12 3.47 12 6.5 9.53 12 6.5 12z"></path><path d="M6.66 3.01C5.61 3.01 4.58 3.5 4.5 4.8c0 0.06-0.01 0.12 0 0.2h1.02c0-0.07 0.01-0.15 0.02-0.23 0.08-0.62 0.52-0.76 1.08-0.76 0.63 0 1.02 0.37 1.02 0.95 -0.01 0.48-0.3 0.87-0.76 1.34C6.21 6.97 6.02 7.37 6 8h0.99C7 7.66 7.04 7.37 7.67 6.75 8.17 6.27 8.7 5.68 8.7 4.87 8.7 3.85 7.89 3.01 6.66 3.01z"></path><rect x="6" y="9" width="1" height="1"></rect></svg></div>\
                    <div class=""><select name="price_type" class="form-control"><option value="FIX" ' + (opts.price_type == 'FIX' ? ' selected ' : '') + '>' + $.lang[LANG]['shopping.delivery.template.price_type.fix'] + '</option><option value="FREE_CONDITION" ' + (opts.price_type == 'FREE_CONDITION' ? ' selected ' : '') + '>' + $.lang[LANG]['shopping.delivery.template.price_type.free_condition'] + '</option><option value="QUANTITY" ' + (opts.price_type == 'QUANTITY' ? ' selected ' : '') + '>' + $.lang[LANG]['shopping.delivery.template.price_type.quantity'] + '</option><option value="WEIGHT" ' + (opts.price_type == 'WEIGHT' ? ' selected ' : '') + '>' + $.lang[LANG]['shopping.delivery.template.price_type.weight'] + '</option><option value="FREE" ' + (opts.price_type == 'FREE' ? ' selected ' : '') + '>' + $.lang[LANG]['shopping.delivery.template.price_type.free'] + '</option><option value="ETC" ' + (opts.price_type == 'ETC' ? ' selected ' : '') + '>' + $.lang[LANG]['shopping.delivery.template.price_type.etc'] + '</option></select>\
                        <div class="fix-row free-condition-row m15t" style="' + (opts.price_type == 'FIX' || opts.price_type == 'FREE_CONDITION' ? '' : ' display: none; ') + '">\
                            <div class="row-sub-title">기본 배송비</div>\
                            <div class="m5t"><input type="text" name="delivery_fee" class="form-control" value="' + (opts.delivery_fee ? number_format(opts.delivery_fee) : 0) + '" numberonly maxlength="13" />원</div>\
                        </div>\
                        <div class="free-condition-row m15t" style="' + (opts.price_type == 'FREE_CONDITION' ? '' : ' display: none; ') + '">\
                            <div class="row-sub-title">무료 배송 조건</div>\
                            <div class="m5t">\
                                <input type="text" name="free_condition" class="form-control" value="' + (number_format(opts.free_condition)) + '" numberonly maxlength="13" />원 이상 구매 시 무료 배송\
                            </div>\
                            <div class="row-sub-title m10t"><svg class="cm-popover-info m5r" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 13 13" width="13" height="13" tabindex="0"><path d="M6.5 0C2.91 0 0 2.91 0 6.5S2.91 13 6.5 13 13 10.09 13 6.5 10.09 0 6.5 0zM6.5 12.13c-3.11 0-5.63-2.53-5.63-5.63S3.39 0.87 6.5 0.87s5.63 2.53 5.63 5.63S9.61 12.13 6.5 12.13z"></path><path d="M7.44 9.58c-0.1-0.02-0.18-0.05-0.25-0.1C7.12 9.44 7.07 9.37 7.03 9.28 6.98 9.19 6.96 9.07 6.96 8.92V5h-1.7v0.4h0.03c0.11 0 0.21 0.01 0.3 0.02 0.09 0.02 0.18 0.05 0.25 0.09 0.07 0.05 0.13 0.11 0.17 0.2 0.04 0.09 0.06 0.2 0.06 0.34v2.91c0 0.14-0.02 0.25-0.06 0.34C5.97 9.39 5.91 9.45 5.84 9.5 5.77 9.54 5.68 9.57 5.59 9.58 5.49 9.6 5.39 9.6 5.29 9.6H5.16v0.4h2.71V9.6H7.75C7.64 9.6 7.54 9.6 7.44 9.58z"></path><rect x="6" y="3" width="1" height="1"></rect></svg>배송비를 제외한 상품 주문금액 합계가 조건 금액 이상인 경우 무료 배송으로 적용됩니다.</div>\
                        </div>\
                        <div class="price-type-detail-method-row quantity-row weight-row" style="' + (opts.price_type == 'QUANTITY' || opts.price_type == 'WEIGHT' ? '' : ' display: none;') + '">\
                            <label><input type="radio" id="price_type_detail_method_D" name="price_type_detail_method" value="DIFFERENTIAL" ' + (opts.price_type_detail.method == 'DIFFERENTIAL' ? ' checked ' : '') + ' /><div>차등</div></label>\
                            <label><input type="radio" id="price_type_detail_method_R" name="price_type_detail_method" value="REPEAT" ' + (opts.price_type_detail.method == 'REPEAT' ? ' checked ' : '') + ' /><div>반복</div></label>\
                        </div>\
                        <div class="quantity-row" style="' + (opts.price_type == 'QUANTITY' ? '' : ' display: none; ') + '">\
                        <div class="quantity-differential" style="' + (opts.price_type_detail.method == 'DIFFERENTIAL' ? '' : ' display: none;') + '">\
                            <table>\
                                <colgroup><col width="45%" /><col width="40%" /><col width="20%" /></colgroup>\
                        ';

                        if(opts.price_type == 'QUANTITY' && opts.price_type_detail.method == 'DIFFERENTIAL' && opts.price_type_detail.detail.length) {
                            $.each(opts.price_type_detail.detail, function(k, v) {
                                var value = Object.keys(v);
                                var price = Object.values(v);
                                if(k == 0) value = 1;
                                html += '<tr><td><input type="text" class="form-control" name="quantity_differential_value[]" value="' + (number_format(value)) + '" ' + (k == 0 ? ' readonly ' : '') + ' numberonly maxlength="13" /> 개 이상</td><td><input type="text" class="form-control" name="quantity_differential_price[]" value="' + number_format(price) + '" numberonly maxlength="13" />원</td><td>' + (k > 0 ? '<span class="btn-delete-condition-row"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 12 13" width="12" height="13"><path d="M11 2H9V0H3.02v2H1 0v1h1v8c0 1.1 0.9 2 2 2h6c1.1 0 2-0.9 2-2V3h1V2H11zM4.02 1H8v1H4.02V1zM10 11c0 0.55-0.45 1-1 1H3c-0.55 0-1-0.45-1-1V3h1.02H9h1V11z"/><rect x="4" y="4" width="1" height="7"/><rect x="7" y="4" width="1" height="7"/></svg></span>' : '') + '</td></tr>';
                            });
                        } else {
                            html += '<tr><td><input type="text" class="form-control" name="quantity_differential_value[]" value="1" readonly numberonly maxlength="13" /> 개 이상</td><td><input type="text" class="form-control" name="quantity_differential_price[]" numberonly maxlength="13" />원</td><td></td></tr>';
                        }

                        html += '\
                                </table>\
                                <div><button type="button" class="btn btn-quantity-diff">+ 조건 추가</button></div>\
                            </div>\
                            <div class="quantity-repeat" style="' + (opts.price_type_detail.method == 'REPEAT' ? '' : ' display: none;') + '">\
                                <div class="row-sub-title">기본 배송비</div>\
                                <div class="m5t"><input type="text" class="form-control m5r" name="quantity_repeat_price" value="' + (opts.quantity_repeat_price ? opts.quantity_repeat_price : 0) + '" numberonly maxlength="13" />원</div>\
                                <div class="m10t"><input type="text" class="form-control m5r" name="quantity_repeat_value" value="' + (opts.quantity_repeat_value ? opts.quantity_repeat_value : 0) + '" numberonly maxlength="13" />개마다 기본 배송비 반복 부과</div>\
                            </div>\
                        </div>\
                        <div class="weight-row" style="' + (opts.price_type == 'WEIGHT' ? '' : ' display: none;') + '">\
                        <div class="weight-differential" style="' + (opts.price_type_detail.method == 'DIFFERENTIAL' ? '' : ' display: none;') + '">\
                            <table>\
                                <colgroup><col width="45%" /><col width="40%" /><col width="20%" /></colgroup>\
                        ';

                        if(opts.price_type == 'WEIGHT' && opts.price_type_detail.method == 'DIFFERENTIAL' && opts.price_type_detail.detail.length) {
                            $(opts.price_type_detail.detail).each(function(k, v) {
                                var value = Object.keys(v);
                                var price = Object.values(v);
                                if(k == 0) value = 0;
                                html += '<tr><td><input type="text" class="form-control isFloat" name="weight_differential_value[]" value="' + (number_format(value)) + '" ' + (k == 0 ? ' readonly ' : '') + ' numberonly maxlength="13" /> Kg 이상</td><td><input type="text" class="form-control" name="weight_differential_price[]" value="' + (number_format(price)) + '" numberonly maxlength="13" />원</td><td>' + (k > 0 ? '<span class="btn-delete-condition-row"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 12 13" width="12" height="13"><path d="M11 2H9V0H3.02v2H1 0v1h1v8c0 1.1 0.9 2 2 2h6c1.1 0 2-0.9 2-2V3h1V2H11zM4.02 1H8v1H4.02V1zM10 11c0 0.55-0.45 1-1 1H3c-0.55 0-1-0.45-1-1V3h1.02H9h1V11z"/><rect x="4" y="4" width="1" height="7"/><rect x="7" y="4" width="1" height="7"/></svg></span>' : '') + '</td></tr>';
                            });
                        } else {
                            html += '<tr><td><input type="text" class="form-control isFloat" name="weight_differential_value[]" value="0" readonly numberonly maxlength="13" /> Kg 이상</td><td><input type="text" class="form-control" name="weight_differential_price[]" numberonly maxlength="13" />원</td><td></td></tr>';
                        }
                        html += '\
                                </table>\
                                <div><button type="button" class="btn btn-weight-diff">+ 조건 추가</button></div>\
                            </div>\
                            <div class="weight-repeat" style="' + (opts.price_type_detail.method == 'REPEAT' ? '' : ' display: none; ') + '">\
                                <div>기본 배송비</div>\
                                <div class="m5t"><input type="text" class="form-control" name="weight_repeat_price" value="' + (opts.weight_repeat_price ? opts.weight_repeat_price : 0) + '" numberonly maxlength="13" />원</div>\
                                <div class="m10t"><input type="text" class="form-control isFloat" name="weight_repeat_value" value="' + (opts.weight_repeat_value ? opts.weight_repeat_value : 0) + '" numberonly maxlength="13" />Kg마다 기본 배송비 반복 부과</div>\
                            </div>\
                        </div>\
                        ';
                        if(!LUX) {
                            html += '\
                        <div class="quantity-row weight-row" style="' + (opts.price_type == 'QUANTITY' || opts.price_type == 'WEIGHT' ? '' : ' display: none;') + '">\
                            <div class="row-sub-title m10t"><svg class="cm-popover-info" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 13 13" width="13" height="13" tabindex="0"><path d="M6.5 0C2.91 0 0 2.91 0 6.5S2.91 13 6.5 13 13 10.09 13 6.5 10.09 0 6.5 0zM6.5 12.13c-3.11 0-5.63-2.53-5.63-5.63S3.39 0.87 6.5 0.87s5.63 2.53 5.63 5.63S9.61 12.13 6.5 12.13z"></path><path d="M7.44 9.58c-0.1-0.02-0.18-0.05-0.25-0.1C7.12 9.44 7.07 9.37 7.03 9.28 6.98 9.19 6.96 9.07 6.96 8.92V5h-1.7v0.4h0.03c0.11 0 0.21 0.01 0.3 0.02 0.09 0.02 0.18 0.05 0.25 0.09 0.07 0.05 0.13 0.11 0.17 0.2 0.04 0.09 0.06 0.2 0.06 0.34v2.91c0 0.14-0.02 0.25-0.06 0.34C5.97 9.39 5.91 9.45 5.84 9.5 5.77 9.54 5.68 9.57 5.59 9.58 5.49 9.6 5.39 9.6 5.29 9.6H5.16v0.4h2.71V9.6H7.75C7.64 9.6 7.54 9.6 7.44 9.58z"></path><rect x="6" y="3" width="1" height="1"></rect></svg> 추가 상품은 배송비 조건에 반영되지 않습니다. </div>\
                        </div>\
                            ';
                        }
                        html += '\
                    </div>\
                </div>\
                <div class="item-row">\
                    <div class="">' + $.lang[LANG]['shopping.delivery.template.additional_yn'] + '<svg class="cm-popover-info" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 13 13" width="13" height="13" tabindex="0" data-trigger="hover" data-toggle="popover" fill="#4789e7" data-html="true" data-placement="top" data-content="주소지가 제주 및 도서산간 지역이면 기본 배송비에 제주/제주 외 도서산간 지역 배송비가 추가로 부과됩니다." data-original-title="" title=""><path d="M6.5 0C2.91 0 0 2.91 0 6.5S2.91 13 6.5 13 13 10.09 13 6.5 10.09 0 6.5 0zM6.5 12C3.47 12 1 9.53 1 6.5S3.47 1 6.5 1 12 3.47 12 6.5 9.53 12 6.5 12z"></path><path d="M6.66 3.01C5.61 3.01 4.58 3.5 4.5 4.8c0 0.06-0.01 0.12 0 0.2h1.02c0-0.07 0.01-0.15 0.02-0.23 0.08-0.62 0.52-0.76 1.08-0.76 0.63 0 1.02 0.37 1.02 0.95 -0.01 0.48-0.3 0.87-0.76 1.34C6.21 6.97 6.02 7.37 6 8h0.99C7 7.66 7.04 7.37 7.67 6.75 8.17 6.27 8.7 5.68 8.7 4.87 8.7 3.85 7.89 3.01 6.66 3.01z"></path><rect x="6" y="9" width="1" height="1"></rect></svg></div>\
                    <div class="additional-yn-row"><label><input type="radio" name="additional_yn" value="N" ' + (opts.additional_yn == 'N' ? ' checked ' : '') + ' /><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 18 18" width="18" height="18"><path d="M9 0a9 9 0 1 0 .001 18.001A9 9 0 0 0 9 0zm0 17c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z"/></svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 18 18" width="18" height="18"><path d="M9 0a9 9 0 1 0 .001 18.001A9 9 0 0 0 9 0zm0 17c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z"/><circle cx="9" cy="9" r="6"/></svg>' + $.lang[LANG]['shopping.delivery.template.additional_yn.n'] + '</label> <label><input type="radio" name="additional_yn" value="Y" ' + (opts.additional_yn == 'Y' ? ' checked ' : '') + ' /><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 18 18" width="18" height="18"><path d="M9 0a9 9 0 1 0 .001 18.001A9 9 0 0 0 9 0zm0 17c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z"/></svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 18 18" width="18" height="18"><path d="M9 0a9 9 0 1 0 .001 18.001A9 9 0 0 0 9 0zm0 17c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z"/><circle cx="9" cy="9" r="6"/></svg>' + $.lang[LANG]['shopping.delivery.template.additional_yn.y'] + '</label>\
                        <div class="additional-row m15t" style="' + (opts.additional_yn == 'Y' ? '' : ' display: none; ') + '">\
                            <div class="row-sub-title">제주</div>\
                            <div class="m5t"><input type="text" name="additional_jeju_price" class="form-control m5r" value="' + number_format(opts.additional_jeju_price) + '" numberonly maxlength="13" />원</div>\
                            <div class="row-sub-title m15t">제주 외 도서산간</div>\
                            <div class="m5t"><input type="text" name="additional_land_price" class="form-control m5r" value="' + number_format(opts.additional_land_price) + '" numberonly maxlength="13" />원</div>\
                        </div>\
                    </div>\
                </div>\
                <div class="item-row">\
                    <div class="">' + $.lang[LANG]['shopping.delivery.template.pay_type'] + '<svg class="cm-popover-info" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 13 13" width="13" height="13" tabindex="0" data-trigger="hover" data-toggle="popover" fill="#4789e7" data-html="true" data-placement="top" data-content="<ul><li class=\'title\'>배송비 결제 방식을 선택할 수 있습니다.</li><li class=\'item\'>선결제 : 상품 결제 시 배송비를 같이 결제합니다.</li><li class=\'item\'>착불 : 상품 결제 시 배송비가 포함되지 않고 구매자가 상품을 받을 때 배송비를 따로 결제합니다.</li><li class=\'item\'>선결제 또는 착불 : 구매자가 선결제 또는 착불로 결제할지 선택할 수 있습니다.</li></ul>" data-original-title="" title=""><path d="M6.5 0C2.91 0 0 2.91 0 6.5S2.91 13 6.5 13 13 10.09 13 6.5 10.09 0 6.5 0zM6.5 12C3.47 12 1 9.53 1 6.5S3.47 1 6.5 1 12 3.47 12 6.5 9.53 12 6.5 12z"></path><path d="M6.66 3.01C5.61 3.01 4.58 3.5 4.5 4.8c0 0.06-0.01 0.12 0 0.2h1.02c0-0.07 0.01-0.15 0.02-0.23 0.08-0.62 0.52-0.76 1.08-0.76 0.63 0 1.02 0.37 1.02 0.95 -0.01 0.48-0.3 0.87-0.76 1.34C6.21 6.97 6.02 7.37 6 8h0.99C7 7.66 7.04 7.37 7.67 6.75 8.17 6.27 8.7 5.68 8.7 4.87 8.7 3.85 7.89 3.01 6.66 3.01z"></path><rect x="6" y="9" width="1" height="1"></rect></svg></div>\
                    <div class="pay-type-row"><label><input type="radio" name="pay_type" value="PREPAY" ' + (opts.pay_type == 'PREPAY' ? ' checked ' : '') + ' /><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 18 18" width="18" height="18"><path d="M9 0a9 9 0 1 0 .001 18.001A9 9 0 0 0 9 0zm0 17c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z"/></svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 18 18" width="18" height="18"><path d="M9 0a9 9 0 1 0 .001 18.001A9 9 0 0 0 9 0zm0 17c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z"/><circle cx="9" cy="9" r="6"/></svg>' + $.lang[LANG]['shopping.delivery.template.pay_type.prepay'] + '</label> <label><input type="radio" name="pay_type" value="DELIVERED" ' + (opts.pay_type == 'DELIVERED' ? ' checked ' : '') + ' /><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 18 18" width="18" height="18"><path d="M9 0a9 9 0 1 0 .001 18.001A9 9 0 0 0 9 0zm0 17c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z"/></svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 18 18" width="18" height="18"><path d="M9 0a9 9 0 1 0 .001 18.001A9 9 0 0 0 9 0zm0 17c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z"/><circle cx="9" cy="9" r="6"/></svg>' + $.lang[LANG]['shopping.delivery.template.pay_type.delivered'] + '</label> <label><input type="radio" name="pay_type" value="BOTH" ' + (opts.pay_type == 'BOTH' ? ' checked ' : '') + ' /><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 18 18" width="18" height="18"><path d="M9 0a9 9 0 1 0 .001 18.001A9 9 0 0 0 9 0zm0 17c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z"/></svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 18 18" width="18" height="18"><path d="M9 0a9 9 0 1 0 .001 18.001A9 9 0 0 0 9 0zm0 17c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z"/><circle cx="9" cy="9" r="6"/></svg>' + $.lang[LANG]['shopping.delivery.template.pay_type.both'] + '</label></div>\
                </div>\
                <div class="item-row">\
                    <div class="">' + $.lang[LANG]['shopping.delivery.template.make_to_order_yn'] + '<svg class="cm-popover-info" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 13 13" width="13" height="13" tabindex="0" data-trigger="hover" data-toggle="popover" fill="#4789e7" data-html="true" data-placement="top" data-content="판매 상품이 주문 접수 후 제작에 들어간다면, 구매자에게 상품 제작 후 배송되는 기간을 알려줄 수 있습니다." data-original-title="" title=""><path d="M6.5 0C2.91 0 0 2.91 0 6.5S2.91 13 6.5 13 13 10.09 13 6.5 10.09 0 6.5 0zM6.5 12C3.47 12 1 9.53 1 6.5S3.47 1 6.5 1 12 3.47 12 6.5 9.53 12 6.5 12z"></path><path d="M6.66 3.01C5.61 3.01 4.58 3.5 4.5 4.8c0 0.06-0.01 0.12 0 0.2h1.02c0-0.07 0.01-0.15 0.02-0.23 0.08-0.62 0.52-0.76 1.08-0.76 0.63 0 1.02 0.37 1.02 0.95 -0.01 0.48-0.3 0.87-0.76 1.34C6.21 6.97 6.02 7.37 6 8h0.99C7 7.66 7.04 7.37 7.67 6.75 8.17 6.27 8.7 5.68 8.7 4.87 8.7 3.85 7.89 3.01 6.66 3.01z"></path><rect x="6" y="9" width="1" height="1"></rect></svg></div>\
                    <div class="make-to-order-yn-row"><label><input type="radio" name="make_to_order_yn" value="N" ' + (opts.make_to_order_yn == 'N' ? ' checked ' : '') + ' /><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 18 18" width="18" height="18"><path d="M9 0a9 9 0 1 0 .001 18.001A9 9 0 0 0 9 0zm0 17c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z"/></svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 18 18" width="18" height="18"><path d="M9 0a9 9 0 1 0 .001 18.001A9 9 0 0 0 9 0zm0 17c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z"/><circle cx="9" cy="9" r="6"/></svg>' + $.lang[LANG]['shopping.delivery.template.make_to_order_yn.n'] + '</label> <label><input type="radio" name="make_to_order_yn" value="Y" ' + (opts.make_to_order_yn == 'Y' ? ' checked ' : '') + ' /><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 18 18" width="18" height="18"><path d="M9 0a9 9 0 1 0 .001 18.001A9 9 0 0 0 9 0zm0 17c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z"/></svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 18 18" width="18" height="18"><path d="M9 0a9 9 0 1 0 .001 18.001A9 9 0 0 0 9 0zm0 17c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z"/><circle cx="9" cy="9" r="6"/></svg>' + $.lang[LANG]['shopping.delivery.template.make_to_order_yn.y'] + '</label>\
                        <div class="make-to-order-row" style="' + (opts.make_to_order_yn == 'Y' ? '' : ' display : none; ') + '">\
                            <div class="row-sub-title m15t">발송 예정일</div>\
                            <div class="m5t">\
                                <select name="due_date" class="form-control">\
                                    <option value="">선택</option>\
                    ';

                    for(var i=2; i<=14; i++) {
                        html += '<option value="' + i + '" ' + (opts.due_date == i ? ' selected ' : '') + '>' + i + '</option>';
                    }

                    html += '   </select> 일 이내 발송 예정\
                            </div>\
                            <div class="row-sub-title m10t"><svg class="cm-popover-info" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 13 13" width="13" height="13" tabindex="0"><path d="M6.5 0C2.91 0 0 2.91 0 6.5S2.91 13 6.5 13 13 10.09 13 6.5 10.09 0 6.5 0zM6.5 12.13c-3.11 0-5.63-2.53-5.63-5.63S3.39 0.87 6.5 0.87s5.63 2.53 5.63 5.63S9.61 12.13 6.5 12.13z"></path><path d="M7.44 9.58c-0.1-0.02-0.18-0.05-0.25-0.1C7.12 9.44 7.07 9.37 7.03 9.28 6.98 9.19 6.96 9.07 6.96 8.92V5h-1.7v0.4h0.03c0.11 0 0.21 0.01 0.3 0.02 0.09 0.02 0.18 0.05 0.25 0.09 0.07 0.05 0.13 0.11 0.17 0.2 0.04 0.09 0.06 0.2 0.06 0.34v2.91c0 0.14-0.02 0.25-0.06 0.34C5.97 9.39 5.91 9.45 5.84 9.5 5.77 9.54 5.68 9.57 5.59 9.58 5.49 9.6 5.39 9.6 5.29 9.6H5.16v0.4h2.71V9.6H7.75C7.64 9.6 7.54 9.6 7.44 9.58z"></path><rect x="6" y="3" width="1" height="1"></rect></svg>주말/공휴일을 제외한 영업일 기준으로 입력</div>\
                        </div>\
                    </div>\
                </div>\
                <div class="item-row">\
                    <div class="">' + $.lang[LANG]['shopping.delivery.template.install_fee_yn'] + '<svg class="cm-popover-info" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 13 13" width="13" height="13" tabindex="0" data-trigger="hover" data-toggle="popover" fill="#4789e7" data-html="true" data-placement="top" data-content="<ul><li class=\'title\'>상품 배송 외에 별도 설치비가 발생된다면, 사용자에게 별도 설치비가 발생한다고 안내할 수 있습니다.</li><li class=\'item\'>별도 설치비에 관한 자세한 내용은 상세 페이지에 별도로 표기해 주세요.</li><li class=\'item\'>별도 설치비 설정 시 네이버 쇼핑에도 반영됩니다.</li></ul>" data-original-title="" title=""><path d="M6.5 0C2.91 0 0 2.91 0 6.5S2.91 13 6.5 13 13 10.09 13 6.5 10.09 0 6.5 0zM6.5 12C3.47 12 1 9.53 1 6.5S3.47 1 6.5 1 12 3.47 12 6.5 9.53 12 6.5 12z"></path><path d="M6.66 3.01C5.61 3.01 4.58 3.5 4.5 4.8c0 0.06-0.01 0.12 0 0.2h1.02c0-0.07 0.01-0.15 0.02-0.23 0.08-0.62 0.52-0.76 1.08-0.76 0.63 0 1.02 0.37 1.02 0.95 -0.01 0.48-0.3 0.87-0.76 1.34C6.21 6.97 6.02 7.37 6 8h0.99C7 7.66 7.04 7.37 7.67 6.75 8.17 6.27 8.7 5.68 8.7 4.87 8.7 3.85 7.89 3.01 6.66 3.01z"></path><rect x="6" y="9" width="1" height="1"></rect></svg></div>\
                    <div class="install-fee-yn-row"><label><input type="radio" name="install_fee_yn" value="N" ' + (opts.install_fee_yn == 'N' ? ' checked ' : '') + ' /><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 18 18" width="18" height="18"><path d="M9 0a9 9 0 1 0 .001 18.001A9 9 0 0 0 9 0zm0 17c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z"/></svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 18 18" width="18" height="18"><path d="M9 0a9 9 0 1 0 .001 18.001A9 9 0 0 0 9 0zm0 17c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z"/><circle cx="9" cy="9" r="6"/></svg>' + $.lang[LANG]['shopping.delivery.template.install_fee_yn.n'] + '</label> <label><input type="radio" name="install_fee_yn" value="Y" ' + (opts.install_fee_yn == 'Y' ? ' checked ' : '') + ' /><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 18 18" width="18" height="18"><path d="M9 0a9 9 0 1 0 .001 18.001A9 9 0 0 0 9 0zm0 17c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z"/></svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 18 18" width="18" height="18"><path d="M9 0a9 9 0 1 0 .001 18.001A9 9 0 0 0 9 0zm0 17c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z"/><circle cx="9" cy="9" r="6"/></svg>' + $.lang[LANG]['shopping.delivery.template.install_fee_yn.y'] + '</label></div>\
                </div>\
            </form>\
        </div>\
    ';

    var modal = $(this).showModalFlat($.lang[LANG]['shopping.delivery.template.title.' + (seq != '' ? 'm' : 'n')],html,true,true, function() {
        modal.find('.error').remove();
        modal.find('.error-box').removeClass('error-box');

        var result = true;

        if($.trim(modal.find('input[name="name"]').val()) == '') {
            modal.find('input[name="name"]').after('<div class="error name-error m5t"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 13 13" width="13" height="13"><path d="M6.5 0C2.91 0 0 2.91 0 6.5S2.91 13 6.5 13 13 10.09 13 6.5 10.09 0 6.5 0zM6.5 12C3.47 12 1 9.53 1 6.5S3.47 1 6.5 1 12 3.47 12 6.5 9.53 12 6.5 12z"/><rect x="6" y="3" width="1" height="5"/><rect x="6" y="9" width="1" height="1"/></svg>템플릿 이름을 입력해 주세요.</div>');
            modal.find('input[name="name"]').addClass('error-box').focus();
            result = false;
        } 

        if(checkEmojis(modal.find('input[name="name"]').val())) {
            modal.find('input[name="name"]').after('<div class="error name-error m5t"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 13 13" width="13" height="13"><path d="M6.5 0C2.91 0 0 2.91 0 6.5S2.91 13 6.5 13 13 10.09 13 6.5 10.09 0 6.5 0zM6.5 12C3.47 12 1 9.53 1 6.5S3.47 1 6.5 1 12 3.47 12 6.5 9.53 12 6.5 12z"/><rect x="6" y="3" width="1" height="5"/><rect x="6" y="9" width="1" height="1"/></svg>이모지는 사용할 수 없습니다.</div>');
            modal.find('input[name="name"]').addClass('error-box').focus();
            result = false;
        }

        $.ajax({
            url: shopping_url + '/deliveryTemplateNameCheck',
            type: 'post',
            dataType: 'json',
            async: false,
            data: {
                'sid' : SID,
                'seq' : modal.find('input[name="seq"]').val(),
                'name' : $.trim(modal.find('input[name="name"]').val())
            },
            success:function(data) {
                if(data.result != 'N') {
                    modal.find('input[name="name"]').after('<div class="error name-error m5t"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 13 13" width="13" height="13"><path d="M6.5 0C2.91 0 0 2.91 0 6.5S2.91 13 6.5 13 13 10.09 13 6.5 10.09 0 6.5 0zM6.5 12C3.47 12 1 9.53 1 6.5S3.47 1 6.5 1 12 3.47 12 6.5 9.53 12 6.5 12z"/><rect x="6" y="3" width="1" height="5"/><rect x="6" y="9" width="1" height="1"/></svg>이미 사용 중인 이름입니다.</div>');
                    modal.find('input[name="name"]').focus();
                    result = false;
                }
            }
        });

        if((modal.find('select[name="price_type"]').val() == 'FIX' || modal.find('select[name="price_type"]').val() == 'FREE_CONDITION') && (!modal.find('input[name="delivery_fee"]').val() || modal.find('input[name="delivery_fee"]').val() < 10)) {
            modal.find('input[name="delivery_fee"]').parent().after('<div class="error m5t"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 13 13" width="13" height="13"><path d="M6.5 0C2.91 0 0 2.91 0 6.5S2.91 13 6.5 13 13 10.09 13 6.5 10.09 0 6.5 0zM6.5 12C3.47 12 1 9.53 1 6.5S3.47 1 6.5 1 12 3.47 12 6.5 9.53 12 6.5 12z"/><rect x="6" y="3" width="1" height="5"/><rect x="6" y="9" width="1" height="1"/></svg>배송비를 10원 이상 입력해 주세요.</div>');
            modal.find('input[name="delivery_fee"]').addClass('error-box').focus();
            result = false;
        } 

        if(modal.find('select[name="price_type"]').val() == 'FREE_CONDITION') {
            if(!modal.find('input[name="free_condition"]').val() || modal.find('input[name="free_condition"]').val() < 10) {
                modal.find('input[name="free_condition"]').parent().after('<div class="error m5t"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 13 13" width="13" height="13"><path d="M6.5 0C2.91 0 0 2.91 0 6.5S2.91 13 6.5 13 13 10.09 13 6.5 10.09 0 6.5 0zM6.5 12C3.47 12 1 9.53 1 6.5S3.47 1 6.5 1 12 3.47 12 6.5 9.53 12 6.5 12z"/><rect x="6" y="3" width="1" height="5"/><rect x="6" y="9" width="1" height="1"/></svg>무료 배송 조건 금액을 10원 이상 입력해 주세요.</div>');
                modal.find('input[name="free_condition"]').addClass('error-box').focus();;
                result = false;
            }
        } else if(modal.find('select[name="price_type"] option:selected').val() == 'QUANTITY') { // 수량별
            if(modal.find('input[name="price_type_detail_method"]:checked').val() == 'DIFFERENTIAL') { // 차등 부과
                modal.find('input[name="quantity_differential_value[]"]:not([readonly]), input[name="quantity_differential_price[]"]').each(function() {
                    if($(this).attr('name') == 'quantity_differential_value[]') {   
                        if($.trim($(this).val()) == '' || $(this).val() == 0) {
                            $(this).closest('tr').after('<tr class="error m5t"><td colspan="2"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 13 13" width="13" height="13"><path d="M6.5 0C2.91 0 0 2.91 0 6.5S2.91 13 6.5 13 13 10.09 13 6.5 10.09 0 6.5 0zM6.5 12C3.47 12 1 9.53 1 6.5S3.47 1 6.5 1 12 3.47 12 6.5 9.53 12 6.5 12z"/><rect x="6" y="3" width="1" height="5"/><rect x="6" y="9" width="1" height="1"/></svg>수량을 입력해 주세요. </td></tr>');
                            result = false;
                            $(this).addClass('error-box');
                        } else {
                            var val = $(this).val();
                            var cur_elem = this;
                            var dup_elem = modal.find('input[name="quantity_differential_value[]"]').filter(function() { return cur_elem != this && $(this).val() == val;});
                            if(dup_elem.length) {
                                dup_elem.addClass('error-box');
                                result = false;
                                $(dup_elem).closest('tr').after('<tr class="error dup-value m5t"><td colspan="2"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 13 13" width="13" height="13"><path d="M6.5 0C2.91 0 0 2.91 0 6.5S2.91 13 6.5 13 13 10.09 13 6.5 10.09 0 6.5 0zM6.5 12C3.47 12 1 9.53 1 6.5S3.47 1 6.5 1 12 3.47 12 6.5 9.53 12 6.5 12z"/><rect x="6" y="3" width="1" height="5"/><rect x="6" y="9" width="1" height="1"/></svg>동일한 값이 존재합니다.</td></tr>');
                            }
                        }
                    } 

                    if($(this).attr('name') == 'quantity_differential_price[]') {
                        if($.trim($(this).val()) == '' || $.trim($(this).val()) < 10) {
                            if(!$(this).closest('tr').next('tr.error').length)
                                $(this).closest('tr').after('<tr class="error m5t"><td colspan="2"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 13 13" width="13" height="13"><path d="M6.5 0C2.91 0 0 2.91 0 6.5S2.91 13 6.5 13 13 10.09 13 6.5 10.09 0 6.5 0zM6.5 12C3.47 12 1 9.53 1 6.5S3.47 1 6.5 1 12 3.47 12 6.5 9.53 12 6.5 12z"/><rect x="6" y="3" width="1" height="5"/><rect x="6" y="9" width="1" height="1"/></svg>배송비를 10원 이상 입력해 주세요.</td></tr>')
                            $(this).addClass('error-box');
                            result = false;
                        }
                    }
                });
            } else if(modal.find('input[name="price_type_detail_method"]:checked').val() == 'REPEAT') {
                if(modal.find('input[name="quantity_repeat_value"]').val() == 0 || modal.find('input[name="quantity_repeat_value"]').val() == '') { // 반복 부과
                    modal.find('.quantity-repeat').append('<div class="error m5t"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 13 13" width="13" height="13"><path d="M6.5 0C2.91 0 0 2.91 0 6.5S2.91 13 6.5 13 13 10.09 13 6.5 10.09 0 6.5 0zM6.5 12C3.47 12 1 9.53 1 6.5S3.47 1 6.5 1 12 3.47 12 6.5 9.53 12 6.5 12z"/><rect x="6" y="3" width="1" height="5"/><rect x="6" y="9" width="1" height="1"/></svg>수량을 입력해 주세요.</div>');
                    modal.find('input[name="quantity_repeat_value"]').addClass('error-box');
                    modal.find('input[name="quantity_repeat_value"]').focus();
                    result = false;
                } 

                if(!modal.find('input[name="quantity_repeat_price"]').val() || modal.find('input[name="quantity_repeat_price"]').val() < 10) {
                    modal.find('input[name="quantity_repeat_price"]').parent().after('<div class="error m5t"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 13 13" width="13" height="13"><path d="M6.5 0C2.91 0 0 2.91 0 6.5S2.91 13 6.5 13 13 10.09 13 6.5 10.09 0 6.5 0zM6.5 12C3.47 12 1 9.53 1 6.5S3.47 1 6.5 1 12 3.47 12 6.5 9.53 12 6.5 12z"/><rect x="6" y="3" width="1" height="5"/><rect x="6" y="9" width="1" height="1"/></svg>배송비를 10원 이상 입력해 주세요.</div>');
                    modal.find('input[name="quantity_repeat_price"]').addClass('error-box');
                    modal.find('input[name="quantity_repeat_price"]').focus();
                    result = false;
                }
            }
        } else if(modal.find('select[name="price_type"] option:selected').val() == 'WEIGHT') { // 무게별
            if(modal.find('input[name="price_type_detail_method"]:checked').val() == 'DIFFERENTIAL') { // 차등 부과
                
                modal.find('input[name="weight_differential_value[]"], input[name="weight_differential_price[]"]').not('[readonly]').each(function() {
                    if($(this).attr('name') == 'weight_differential_value[]') {
                        if($.trim($(this).val()) == '' || $.trim($(this).val()) == 0) {
                            result = false;
                            $(this).addClass('error-box');
                            $(this).focus();
                            $(this).closest('tr').after('<tr class="error m5t"><td colspan="2"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 13 13" width="13" height="13"><path d="M6.5 0C2.91 0 0 2.91 0 6.5S2.91 13 6.5 13 13 10.09 13 6.5 10.09 0 6.5 0zM6.5 12C3.47 12 1 9.53 1 6.5S3.47 1 6.5 1 12 3.47 12 6.5 9.53 12 6.5 12z"/><rect x="6" y="3" width="1" height="5"/><rect x="6" y="9" width="1" height="1"/></svg>무게를 0 이상 입력해 주세요. </td></tr>');
                            
                        } else {
                            var val = $(this).val();
                            var cur_elem = this;
                            var dup_elem = modal.find('input[name="weight_differential_value[]"]').filter(function() { return cur_elem != this && $(this).val() == val;});
                            if(dup_elem.length) {
                                dup_elem.addClass('error-box');
                                dup_elem.eq(0).focus();
                                result = false;
                                $(dup_elem).closest('tr').after('<tr class="error dup-value m5t"><td colspan="2"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 13 13" width="13" height="13"><path d="M6.5 0C2.91 0 0 2.91 0 6.5S2.91 13 6.5 13 13 10.09 13 6.5 10.09 0 6.5 0zM6.5 12C3.47 12 1 9.53 1 6.5S3.47 1 6.5 1 12 3.47 12 6.5 9.53 12 6.5 12z"/><rect x="6" y="3" width="1" height="5"/><rect x="6" y="9" width="1" height="1"/></svg>동일한 값이 존재합니다.</td></tr>');
                                
                            }
                        }
                    }
                    
                    if($(this).attr('name') == 'weight_differential_price[]') {
                        if(!$(this).val() || $(this).val() < 10) {
                            if(!$(this).closest('tr').next('tr.error').length)
                                $(this).closest('tr').after('<tr class="error m5t"><td colspan="2"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 13 13" width="13" height="13"><path d="M6.5 0C2.91 0 0 2.91 0 6.5S2.91 13 6.5 13 13 10.09 13 6.5 10.09 0 6.5 0zM6.5 12C3.47 12 1 9.53 1 6.5S3.47 1 6.5 1 12 3.47 12 6.5 9.53 12 6.5 12z"/><rect x="6" y="3" width="1" height="5"/><rect x="6" y="9" width="1" height="1"/></svg>배송비를 10원 이상 입력해 주세요.</td></tr>')
                            $(this).addClass('error-box');
                            $(this).focus();
                            result = false;
                        }
                    }
                });
            } else if(modal.find('input[name="price_type_detail_method"]:checked').val() == 'REPEAT') { // 반복 부과
                if(modal.find('input[name="weight_repeat_value"]').val() == 0 || modal.find('input[name="weight_repeat_value"]').val() == '') {
                    modal.find('.weight-repeat').append('<div class="error m5t"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 13 13" width="13" height="13"><path d="M6.5 0C2.91 0 0 2.91 0 6.5S2.91 13 6.5 13 13 10.09 13 6.5 10.09 0 6.5 0zM6.5 12C3.47 12 1 9.53 1 6.5S3.47 1 6.5 1 12 3.47 12 6.5 9.53 12 6.5 12z"/><rect x="6" y="3" width="1" height="5"/><rect x="6" y="9" width="1" height="1"/></svg>무게를 0 이상 입력해 주세요.</div>');
                    modal.find('input[name="weight_repeat_value"]').addClass('error-box');
                    modal.find('input[name="weight_repeat_value"]').focus();
                    result = false;
                }

                if(!modal.find('input[name="weight_repeat_price"]').val() || modal.find('input[name="weight_repeat_price"]').val() < 10) {
                    modal.find('input[name="weight_repeat_price"]').parent().after('<div class="error m5t"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 13 13" width="13" height="13"><path d="M6.5 0C2.91 0 0 2.91 0 6.5S2.91 13 6.5 13 13 10.09 13 6.5 10.09 0 6.5 0zM6.5 12C3.47 12 1 9.53 1 6.5S3.47 1 6.5 1 12 3.47 12 6.5 9.53 12 6.5 12z"/><rect x="6" y="3" width="1" height="5"/><rect x="6" y="9" width="1" height="1"/></svg>배송비를 10원 이상 입력해 주세요.</div>');
                    modal.find('input[name="weight_repeat_price"]').addClass('error-box');
                    modal.find('input[name="weight_repeat_price"]').focus();
                    result = false;
                }
            }
        }

        if(modal.find('input[name="additional_yn"]:checked').val() == 'Y') {
            modal.find('input[name="additional_jeju_price"]').parent().next('.error').remove();
            if($.trim(modal.find('input[name="additional_jeju_price"]').val()) == '' || $.trim(modal.find('input[name="additional_jeju_price"]').val()) < 10) {
                modal.find('input[name="additional_jeju_price"]').parent().after('<div class="error m5t"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 13 13" width="13" height="13"><path d="M6.5 0C2.91 0 0 2.91 0 6.5S2.91 13 6.5 13 13 10.09 13 6.5 10.09 0 6.5 0zM6.5 12C3.47 12 1 9.53 1 6.5S3.47 1 6.5 1 12 3.47 12 6.5 9.53 12 6.5 12z"/><rect x="6" y="3" width="1" height="5"/><rect x="6" y="9" width="1" height="1"/></svg>배송비를 10원 이상 입력해 주세요.</div>');
                modal.find('input[name="additional_jeju_price"]').addClass('error-box');
                result = false;
            }

            modal.find('input[name="additional_land_price"]').parent().next('.error').remove();
            if($.trim(modal.find('input[name="additional_land_price"]').val()) == '' || $.trim(modal.find('input[name="additional_jeju_price"]').val()) < 10) {
                modal.find('input[name="additional_land_price"]').parent().after('<div class="error m5t"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 13 13" width="13" height="13"><path d="M6.5 0C2.91 0 0 2.91 0 6.5S2.91 13 6.5 13 13 10.09 13 6.5 10.09 0 6.5 0zM6.5 12C3.47 12 1 9.53 1 6.5S3.47 1 6.5 1 12 3.47 12 6.5 9.53 12 6.5 12z"/><rect x="6" y="3" width="1" height="5"/><rect x="6" y="9" width="1" height="1"/></svg>배송비를 10원 이상 입력해 주세요.</div>');
                modal.find('input[name="additional_land_price"]').addClass('error-box');
                result = false;
            }
        }

        if(modal.find('input[name="make_to_order_yn"]:checked').val() == 'Y' && modal.find('select[name="due_date"]').val() == '') {
            modal.find('select[name="due_date"]').parent().parent().append('<div class="error due-date-error m5t"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 13 13" width="13" height="13"><path d="M6.5 0C2.91 0 0 2.91 0 6.5S2.91 13 6.5 13 13 10.09 13 6.5 10.09 0 6.5 0zM6.5 12C3.47 12 1 9.53 1 6.5S3.47 1 6.5 1 12 3.47 12 6.5 9.53 12 6.5 12z"/><rect x="6" y="3" width="1" height="5"/><rect x="6" y="9" width="1" height="1"/></svg>발송 예정일을 선택해 주세요.</div>');
            modal.find('.make-to-order-row button').addClass('error-box');
            result = false;
        }

        if(!result) return false;

        $.processON();
        setTimeout(function() {
            $.ajax({
                url: shopping_url + '/insertDeliveryTemplate',
                type:'post',
                dataType:'json',
                async:false,
                data: $('#deliveryTemplateForm').serialize(),
                success:function(data) {

                },
                complete: function() {
                    $.processOFF();
                    if(typeof callback_func == 'function') callback_func();
                }
            });
        });
        
        modal.modal('hide');
    }, 'cancel','save','cl-cmmodal cover delivery-template-modal cl-s-btn w620 cl-p80', true, '', function() {
        modal.find('#deliveryTemplateForm input[name="name"]').on('blur', function() {
            modal.find('.name-error').remove();
            $(this).removeClass('error-box');

            if($.trim($(this).val()) == '') {
                $(this).addClass('error-box');
                modal.find('input[name="name"]').after('<div class="error name-error m5t"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 13 13" width="13" height="13"><path d="M6.5 0C2.91 0 0 2.91 0 6.5S2.91 13 6.5 13 13 10.09 13 6.5 10.09 0 6.5 0zM6.5 12C3.47 12 1 9.53 1 6.5S3.47 1 6.5 1 12 3.47 12 6.5 9.53 12 6.5 12z"/><rect x="6" y="3" width="1" height="5"/><rect x="6" y="9" width="1" height="1"/></svg>템플릿 이름을 입력해 주세요.</div>');
                return;  
            } 

            if(checkEmojis($(this).val())) {
                $(this).addClass('error-box');
                modal.find('input[name="name"]').after('<div class="error name-error m5t"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 13 13" width="13" height="13"><path d="M6.5 0C2.91 0 0 2.91 0 6.5S2.91 13 6.5 13 13 10.09 13 6.5 10.09 0 6.5 0zM6.5 12C3.47 12 1 9.53 1 6.5S3.47 1 6.5 1 12 3.47 12 6.5 9.53 12 6.5 12z"/><rect x="6" y="3" width="1" height="5"/><rect x="6" y="9" width="1" height="1"/></svg>이모지는 사용할 수 없습니다.</div>');
                return false;
            }

            $.ajax({
                url: shopping_url + '/deliveryTemplateNameCheck',
                type: 'post',
                dataType: 'json',
                data: {
                    'sid' : SID,
                    'seq' : modal.find('input[name="seq"]').val(),
                    'name' : $.trim($(this).val())
                },
                success:function(data) {
                    if(data.result != 'N') {
                        $(this).addClass('error-box');
                        modal.find('input[name="name"]').after('<div class="error name-error m5t"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 13 13" width="13" height="13"><path d="M6.5 0C2.91 0 0 2.91 0 6.5S2.91 13 6.5 13 13 10.09 13 6.5 10.09 0 6.5 0zM6.5 12C3.47 12 1 9.53 1 6.5S3.47 1 6.5 1 12 3.47 12 6.5 9.53 12 6.5 12z"/><rect x="6" y="3" width="1" height="5"/><rect x="6" y="9" width="1" height="1"/></svg>이미 사용 중인 이름입니다.</div>');
                    } else {
                        modal.find('.name-error').remove();
                        modal.find('#deliveryTemplateForm input[name="name"]').removeClass('error-box');
                    }
                }
            });
        }).on('input', function() {
            var regexp = /^[ㄱ-ㅎㅏ-ㅣ가-힣a-zA-Z0-9\(\)\[\]\_\- ]+$/;
            if(!regexp.test($.trim($(this).val()))) {
                $(this).val($.trim($(this).val()).replace(/[^ㄱ-ㅎㅏ-ㅣ가-힣a-zA-Z0-9\(\)\[\]\_\- ]/gi, ''));
            }
        });

        modal.find('input[name="mix_yn"]').on('change', function() {
            if($('input[name="mix_yn"]:checked').val() == 'Y') {
                modal.find('.mix-price-type-row').show();
            } else {
                modal.find('.mix-price-type-row').hide();
            }
        });

        modal.find('select[name="price_type"]').on('change', function() {
            if($(this).find('option:selected').val() == 'QUANTITY') {
                modal.find('input[name="price_type_detail_method"]:first').prop('checked', true).change();
                modal.find('.weight-row').hide();
                modal.find('.fix-row').hide();
                modal.find('.free-condition-row').hide();
                modal.find('.quantity-row').show();
            } else if($(this).find('option:selected').val() == 'WEIGHT') {
                modal.find('input[name="price_type_detail_method"]:first').prop('checked', true).change();
                modal.find('.quantity-row').hide();
                modal.find('.fix-row').hide();
                modal.find('.free-condition-row').hide();
                modal.find('.weight-row').show();
            } else if($(this).find('option:selected').val() == 'FIX') {
                modal.find('.quantity-row').hide();
                modal.find('.weight-row').hide();
                modal.find('.free-condition-row').hide();
                modal.find('.fix-row').show();
            } else if($(this).find('option:selected').val() == 'FREE_CONDITION') {
                modal.find('.quantity-row').hide();
                modal.find('.weight-row').hide();
                modal.find('.fix-row').hide();
                modal.find('.free-condition-row').show();
            } else {
                modal.find('.fix-row').hide();
                modal.find('.quantity-row').hide();
                modal.find('.weight-row').hide();
                modal.find('.free-condition-row').hide();
            }
        });

        modal.find('.btn-quantity-diff').on('click', function() {
            var html = '<tr><td><input type="text" class="form-control" name="quantity_differential_value[]" numberonly /> 개 이상</td><td><input type="text" class="form-control" name="quantity_differential_price[]" numberonly /> 원</td><td><span class="btn-delete-condition-row"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 12 13" width="12" height="13"><path d="M11 2H9V0H3.02v2H1 0v1h1v8c0 1.1 0.9 2 2 2h6c1.1 0 2-0.9 2-2V3h1V2H11zM4.02 1H8v1H4.02V1zM10 11c0 0.55-0.45 1-1 1H3c-0.55 0-1-0.45-1-1V3h1.02H9h1V11z"/><rect x="4" y="4" width="1" height="7"/><rect x="7" y="4" width="1" height="7"/></svg></span></td></tr>';
            modal.find('.quantity-differential table').append(html);
        });

        modal.find('.btn-weight-diff').on('click', function() {
            var html = '<tr><td><input type="text" class="form-control isFloat" name="weight_differential_value[]" numberonly> Kg 이상</td><td><input type="text" class="form-control" name="weight_differential_price[]" numberonly /> 원</td><td><span class="btn-delete-condition-row"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 12 13" width="12" height="13"><path d="M11 2H9V0H3.02v2H1 0v1h1v8c0 1.1 0.9 2 2 2h6c1.1 0 2-0.9 2-2V3h1V2H11zM4.02 1H8v1H4.02V1zM10 11c0 0.55-0.45 1-1 1H3c-0.55 0-1-0.45-1-1V3h1.02H9h1V11z"/><rect x="4" y="4" width="1" height="7"/><rect x="7" y="4" width="1" height="7"/></svg></span></td></tr>';
            modal.find('.weight-differential table').append(html);
        });

        modal.find('input[name="delivery_type[]"]').on('change', function() {
            if(modal.find('input[name="delivery_type[]"][value="DELIVERY"]:checked').length) {
                modal.find('.delivery-company-row').show();
            } else {
                modal.find('.delivery-company-row').hide();
            }

            modal.find('select[name="price_type"]').prop('disabled', false);

            // modal.find('input[name="additional_yn"]').prop('disabled', false);
            modal.find('.additional-yn-row').removeClass('disabled-area');
            
            // modal.find('input[name="pay_type"]').prop('disabled', false);
            modal.find('.pay-type-row').removeClass('disabled-area');

            if(modal.find('input[name="delivery_type[]"]:checked').length == 1 && modal.find('input[name="delivery_type[]"]:checked').val() == 'VISIT') {
                modal.find('select[name="price_type"]').val('FREE').change().prop('disabled', true);
                modal.find('input[name="delivery_fee"]').val(0);
                modal.find('input[name="additional_yn"][value="N"]').prop('checked', true).change();
                // modal.find('input[name="additional_yn"]').prop('disabled', true);
                modal.find('.additional-yn-row').addClass('disabled-area');
                modal.find('input[name="pay_type"][value="PREPAY"]').prop('checked', true).change();
                // modal.find('input[name="pay_type"]').prop('disabled', true);
                modal.find('.pay-type-row').addClass('disabled-area');
            } else if(modal.find('input[name="delivery_type[]"]:checked').length == 1 && modal.find('input[name="delivery_type[]"]:checked').val() == 'QUICK') {
                modal.find('select[name="price_type"]').val('ETC').change().prop('disabled', true);
                modal.find('input[name="additional_yn"][value="N"]').prop('checked', true).change();
                // modal.find('input[name="additional_yn"]').prop('disabled', true);
                modal.find('.additional-yn-row').addClass('disabled-area');
                modal.find('input[name="pay_type"][value="DELIVERED"]').prop('checked', true).change();
                modal.find('input[name="pay_type"]').prop('disabled', true);
                modal.find('.pay-type-row').addClass('disabled-area');
            } else if(modal.find('input[name="delivery_type[]"][value="DELIVERY"]:checked').length == 0 && modal.find('input[name="delivery_type[]"][value="DIRECT"]:checked').length == 0) {
                modal.find('select[name="price_type"]').val('ETC').prop('disabled', true).change();
                modal.find('input[name="additional_yn"][value="N"]').prop('checked', true).change()
                // modal.find('input[name="additional_yn"]').prop('disabled', true);
                modal.find('.additional-yn-row').removeClass('disabled-area');
                modal.find('input[name="pay_type"][value="DELIVERED"]').prop('checked', true).change();
                // modal.find('input[name="pay_type"]').prop('disabled', true);
                modal.find('.pay-type-row').addClass('disabled-area');
            }
            modal.find('select[name="price_type"]').selectpicker('refresh');
        });

        modal.on('input', 'input[numberonly]', function(){
            var max_num = 1000000000; //10억
            if(Number($(this).val().replace(/,/g, '')) > max_num) {
                $(this).val(number_format(max_num));
            }
        });

        modal.on('input', 'input[name="weight_repeat_value"], input[name="weight_differential_value[]"]', function(){
            var max_num = 100;

            var val = $(this).val().replace(/,/g, '');
            if(val.indexOf('.') > -1 && val.indexOf('.') < val.length-4) {
                val = Number((Math.floor(Number(val) * 1000) / 1000).toFixed(3));
            }

            if(Number(val) > max_num) {
                val = max_num;
            }
            $(this).val(number_format(val));
        });

        modal.find('input[name="price_type_detail_method"]').on('change', function() {
            if(modal.find('select[name="price_type"] option:selected').val() == 'QUANTITY') {
                if(modal.find('input[name="price_type_detail_method"]:checked').val() == 'DIFFERENTIAL') {
                    $('.quantity-differential').show();
                    $('.quantity-repeat').hide();
                } else if(modal.find('input[name="price_type_detail_method"]:checked').val() == 'REPEAT') {
                    $('.quantity-repeat').show();
                    $('.quantity-differential').hide();
                }
            } else if(modal.find('select[name="price_type"] option:selected').val() == 'WEIGHT') {
                if(modal.find('input[name="price_type_detail_method"]:checked').val() == 'DIFFERENTIAL') {
                    $('.weight-differential').show();
                    $('.weight-repeat').hide();
                } else if(modal.find('input[name="price_type_detail_method"]:checked').val() == 'REPEAT') {
                    $('.weight-repeat').show();
                    $('.weight-differential').hide();
                }
            }
        });

        modal.find('input[name="delivery_fee"]').on('blur', function() {
            $(this).removeClass('error-box');
            $(this).parent().next('.error').remove();            
            if($.trim($(this).val()) == '' || $(this).val() < 10) {
                $(this).addClass('error-box');
                modal.find('input[name="delivery_fee"]').parent().after('<div class="error m5t"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 13 13" width="13" height="13"><path d="M6.5 0C2.91 0 0 2.91 0 6.5S2.91 13 6.5 13 13 10.09 13 6.5 10.09 0 6.5 0zM6.5 12C3.47 12 1 9.53 1 6.5S3.47 1 6.5 1 12 3.47 12 6.5 9.53 12 6.5 12z"/><rect x="6" y="3" width="1" height="5"/><rect x="6" y="9" width="1" height="1"/></svg>배송비를 10원 이상 입력해 주세요.</div>');
            }
        });

        modal.find('input[name="additional_yn"]').on('change', function() {
            if(modal.find('input[name="additional_yn"]:checked').val() == 'Y') {
                modal.find('.additional-row').show();
            } else {
                modal.find('.additional-row').hide();
            }
        });

        modal.find('input[name="free_condition_yn"]').on('change', function() {
            if(modal.find('input[name="free_condition_yn"]:checked').val() == 'Y') {
                modal.find('.free-condition-row').show();
            } else {
                modal.find('.free-condition-row').hide();
            }
        });

        modal.find('input[name="free_condition"]').on('blur', function() {
            $(this).removeClass('error-box');
            $(this).parent().next('.error').remove();
            if($.trim($(this).val()) == '' || $(this).val() < 10) {
                $(this).addClass('error-box');
                $(this).parent().after('<div class="error m5t"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 13 13" width="13" height="13"><path d="M6.5 0C2.91 0 0 2.91 0 6.5S2.91 13 6.5 13 13 10.09 13 6.5 10.09 0 6.5 0zM6.5 12C3.47 12 1 9.53 1 6.5S3.47 1 6.5 1 12 3.47 12 6.5 9.53 12 6.5 12z"/><rect x="6" y="3" width="1" height="5"/><rect x="6" y="9" width="1" height="1"/></svg>무료 배송 조건 금액을 10원 이상 입력해 주세요.</div>');
            }
        });

        modal.find('input[name="make_to_order_yn"]').on('change', function() {
            if(modal.find('input[name="make_to_order_yn"]:checked').val() == 'Y') {
                modal.find('.make-to-order-row').show();
            } else {
                modal.find('.make-to-order-row').hide();
            }
        });

        modal.on('blur', 'input[name="quantity_repeat_price"], input[name="weight_repeat_price"], input[name="additional_jeju_price"], input[name="additional_land_price"]', function() {
            $(this).removeClass('error-box');
            $(this).parent().next('.error').remove();
            if($.trim($(this).val()) == '' || $.trim($(this).val()) < 10) {
                $(this).parent().after('<div class="error m5t"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 13 13" width="13" height="13"><path d="M6.5 0C2.91 0 0 2.91 0 6.5S2.91 13 6.5 13 13 10.09 13 6.5 10.09 0 6.5 0zM6.5 12C3.47 12 1 9.53 1 6.5S3.47 1 6.5 1 12 3.47 12 6.5 9.53 12 6.5 12z"/><rect x="6" y="3" width="1" height="5"/><rect x="6" y="9" width="1" height="1"/></svg>배송비를 10원 이상 입력해 주세요.</div>');
                $(this).addClass('error-box');
            }
        })

        modal.on('blur', 'input[name="quantity_repeat_value"]', function() {
            $(this).removeClass('error-box');
            $(this).parent().next('.error').remove();
            if($.trim($(this).val()) == '' || $.trim($(this).val()) == 0) {
                $(this).parent().after('<div class="error m5t"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 13 13" width="13" height="13"><path d="M6.5 0C2.91 0 0 2.91 0 6.5S2.91 13 6.5 13 13 10.09 13 6.5 10.09 0 6.5 0zM6.5 12C3.47 12 1 9.53 1 6.5S3.47 1 6.5 1 12 3.47 12 6.5 9.53 12 6.5 12z"/><rect x="6" y="3" width="1" height="5"/><rect x="6" y="9" width="1" height="1"/></svg>수량을 입력해 주세요.</div>');
                $(this).addClass('error-box');
            }
        });

        modal.on('blur', 'input[name="weight_repeat_value"]', function() {
            $(this).removeClass('error-box');
            $(this).parent().next('.error').remove();
            if($.trim($(this).val()) == '' || $.trim($(this).val()) == 0) {
                $(this).parent().after('<div class="error m5t"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 13 13" width="13" height="13"><path d="M6.5 0C2.91 0 0 2.91 0 6.5S2.91 13 6.5 13 13 10.09 13 6.5 10.09 0 6.5 0zM6.5 12C3.47 12 1 9.53 1 6.5S3.47 1 6.5 1 12 3.47 12 6.5 9.53 12 6.5 12z"/><rect x="6" y="3" width="1" height="5"/><rect x="6" y="9" width="1" height="1"/></svg>무게를 0 이상 입력해 주세요.</div>');
                $(this).addClass('error-box');
            }
        });

        modal.on('blur', 'input[name="quantity_differential_value[]"]', function() {
            $(this).removeClass('error-box');
            $(this).closest('tr').next('tr.error').remove();
            if($.trim($(this).val()) == '' || $(this).val() == 0) {
                $(this).closest('tr').after('<tr class="error m5t"><td colspan="2"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 13 13" width="13" height="13"><path d="M6.5 0C2.91 0 0 2.91 0 6.5S2.91 13 6.5 13 13 10.09 13 6.5 10.09 0 6.5 0zM6.5 12C3.47 12 1 9.53 1 6.5S3.47 1 6.5 1 12 3.47 12 6.5 9.53 12 6.5 12z"/><rect x="6" y="3" width="1" height="5"/><rect x="6" y="9" width="1" height="1"/></svg>수량을 입력해 주세요.</td></tr>')
                $(this).addClass('error-box');
                return false;
            }
            modal.find('input[name="quantity_differential_value[]"]').removeClass('error-box');
            modal.find('.error.dup-value').remove();
            modal.find('input[name="quantity_differential_value[]"]').each(function() {
                var val = $(this).val();
                var cur_elem = this;
                var dup_elem = modal.find('input[name="quantity_differential_value[]"]').filter(function() { return cur_elem != this && $(this).val() == val;});
                if(dup_elem.length) {
                    dup_elem.addClass('error-box');
                    $(dup_elem).closest('tr').after('<tr class="error dup-value m5t"><td colspan="2"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 13 13" width="13" height="13"><path d="M6.5 0C2.91 0 0 2.91 0 6.5S2.91 13 6.5 13 13 10.09 13 6.5 10.09 0 6.5 0zM6.5 12C3.47 12 1 9.53 1 6.5S3.47 1 6.5 1 12 3.47 12 6.5 9.53 12 6.5 12z"/><rect x="6" y="3" width="1" height="5"/><rect x="6" y="9" width="1" height="1"/></svg>동일한 값이 존재합니다.</td></tr>');
                    return false;
                }
            });
        });

        modal.on('blur', 'input[name="weight_differential_value[]"]', function() {
            $(this).removeClass('error-box');
            $(this).closest('tr').next('tr.error').remove();
            if(!$('input[name="weight_differential_value[]"]').is('[readonly]') && ($.trim($(this).val()) == '' || $(this).val() == 0)) {
                $(this).closest('tr').after('<tr class="error m5t"><td colspan="2"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 13 13" width="13" height="13"><path d="M6.5 0C2.91 0 0 2.91 0 6.5S2.91 13 6.5 13 13 10.09 13 6.5 10.09 0 6.5 0zM6.5 12C3.47 12 1 9.53 1 6.5S3.47 1 6.5 1 12 3.47 12 6.5 9.53 12 6.5 12z"/><rect x="6" y="3" width="1" height="5"/><rect x="6" y="9" width="1" height="1"/></svg>무게를 0 이상 입력해 주세요.</td></tr>')
                $(this).addClass('error-box');
                return false;
            }
            modal.find('input[name="weight_differential_value[]"]').removeClass('error-box');
            modal.find('.error.dup-value').remove();
            modal.find('input[name="weight_differential_value[]"]').each(function() {
                var val = $(this).val();
                var cur_elem = this;
                var dup_elem = modal.find('input[name="weight_differential_value[]"]').filter(function() { return cur_elem != this && $(this).val() == val;});
                if(dup_elem.length) {
                    dup_elem.addClass('error-box');
                    $(dup_elem).closest('tr').after('<tr class="error dup-value m5t"><td colspan="2"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 13 13" width="13" height="13"><path d="M6.5 0C2.91 0 0 2.91 0 6.5S2.91 13 6.5 13 13 10.09 13 6.5 10.09 0 6.5 0zM6.5 12C3.47 12 1 9.53 1 6.5S3.47 1 6.5 1 12 3.47 12 6.5 9.53 12 6.5 12z"/><rect x="6" y="3" width="1" height="5"/><rect x="6" y="9" width="1" height="1"/></svg>동일한 값이 존재합니다.</td></tr>');
                    return false;
                }
            });
        });

        modal.on('blur', 'input[name="quantity_differential_price[]"], input[name="weight_differential_price[]"]', function() {
            $(this).removeClass('error-box');
            $(this).closest('tr').next('tr.error').remove();
            if($.trim($(this).val()) == '' || $(this).val() < 10) {
                $(this).closest('tr').after('<tr class="error m5t"><td colspan="2"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 13 13" width="13" height="13"><path d="M6.5 0C2.91 0 0 2.91 0 6.5S2.91 13 6.5 13 13 10.09 13 6.5 10.09 0 6.5 0zM6.5 12C3.47 12 1 9.53 1 6.5S3.47 1 6.5 1 12 3.47 12 6.5 9.53 12 6.5 12z"/><rect x="6" y="3" width="1" height="5"/><rect x="6" y="9" width="1" height="1"/></svg>배송비를 10원 이상 입력해 주세요.</td></tr>')
                $(this).addClass('error-box');
            }
        });

        modal.on('change', 'select[name="due_date"]', function() {
            modal.find('select[name="due_date"]').parent().parent().find('.due-date-error').remove();
            modal.find('.make-to-order-row button').removeClass('error-box');
            if($(this).val() == '') {
                modal.find('select[name="due_date"]').parent().parent().append('<div class="error due-date-error m5t"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 13 13" width="13" height="13"><path d="M6.5 0C2.91 0 0 2.91 0 6.5S2.91 13 6.5 13 13 10.09 13 6.5 10.09 0 6.5 0zM6.5 12C3.47 12 1 9.53 1 6.5S3.47 1 6.5 1 12 3.47 12 6.5 9.53 12 6.5 12z"/><rect x="6" y="3" width="1" height="5"/><rect x="6" y="9" width="1" height="1"/></svg>발송 예정일을 선택해 주세요.</div>');
                modal.find('.make-to-order-row button').addClass('error-box');
            }
        });

        modal.on('click', '.btn-delete-condition-row', function() {
            var btn = this;
            var modal = $(this).showModalFlat('배송비 조건 구간 삭제', '선택한 배송비 조건 구간을 삭제하시겠습니까?', true, true, function() {
                $(btn).closest('tr').remove();
                modal.modal('hide');
            }, 'cancel', 'ok', 'cl-cmmodal cl-s-btn w560 cl-p130');
            var backdrop_z_index = Number(modal.css('zIndex'));
            modal.css('zIndex', backdrop_z_index + 1);
            modal.parent().next('.modal-backdrop').css('zIndex', backdrop_z_index);
        }); 

        modal.find('[data-toggle="popover"]').popover();

        modal.find('select').selectpicker();

        modal.find('.delivery-company-row').find('.tracking-delivery-icon').replaceWith('<svg data-toggle="popover" data-content="배송 추적 가능" data-trigger="hover" data-placement="top" data-html="true" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24"><path d="m11.6 17.72-.98.61v-5.37l5.2-3.25v.76c.39-.08.79-.13 1.2-.13V8.62c0-.01-.01-.02-.01-.03 0-.06-.02-.12-.04-.17a.625.625 0 0 0-.23-.3l-6.4-4a.614.614 0 0 0-.64 0l-6.4 4c-.11.07-.18.18-.23.3-.02.05-.03.11-.04.17 0 .01-.01.02-.01.03v6.8c0 .21.11.4.28.51l6.4 4a.62.62 0 0 0 .64 0l1.75-1.1c-.2-.34-.36-.71-.49-1.11zM10.02 5.33l2.11 1.32-5.28 3.3-2.1-1.32 5.27-3.3zm-.6 13.01-5.2-3.25V9.72l5.2 3.25v5.37zm.6-6.41-2.04-1.27 5.28-3.3 2.04 1.27-5.28 3.3z"/><path d="m22.85 21-2.61-2.61c.49-.66.79-1.48.79-2.36 0-2.21-1.79-4-4-4s-4 1.79-4 4 1.79 4 4 4c.89 0 1.7-.3 2.36-.79L22 21.85c.12.12.27.18.42.18s.31-.06.42-.18a.6.6 0 0 0 .01-.85zm-8.63-4.98c0-1.54 1.26-2.8 2.8-2.8s2.8 1.26 2.8 2.8c0 .77-.31 1.46-.81 1.97 0 0-.01 0-.01.01s0 .01-.01.01a2.799 2.799 0 0 1-4.77-1.99z"/></svg>');
        modal.find('.delivery-company-row').find('[data-toggle="popover"]').popover();
        modal.find('select[name="delivery_company"]').on('shown.bs.select changed.bs.select', function(select_event, dropdown_event) {
            modal.find('.delivery-company-row').find('.tracking-delivery-icon').replaceWith('<svg data-toggle="popover" data-content="배송 추적 가능" data-trigger="hover" data-placement="top" data-html="true" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24"><path d="m11.6 17.72-.98.61v-5.37l5.2-3.25v.76c.39-.08.79-.13 1.2-.13V8.62c0-.01-.01-.02-.01-.03 0-.06-.02-.12-.04-.17a.625.625 0 0 0-.23-.3l-6.4-4a.614.614 0 0 0-.64 0l-6.4 4c-.11.07-.18.18-.23.3-.02.05-.03.11-.04.17 0 .01-.01.02-.01.03v6.8c0 .21.11.4.28.51l6.4 4a.62.62 0 0 0 .64 0l1.75-1.1c-.2-.34-.36-.71-.49-1.11zM10.02 5.33l2.11 1.32-5.28 3.3-2.1-1.32 5.27-3.3zm-.6 13.01-5.2-3.25V9.72l5.2 3.25v5.37zm.6-6.41-2.04-1.27 5.28-3.3 2.04 1.27-5.28 3.3z"/><path d="m22.85 21-2.61-2.61c.49-.66.79-1.48.79-2.36 0-2.21-1.79-4-4-4s-4 1.79-4 4 1.79 4 4 4c.89 0 1.7-.3 2.36-.79L22 21.85c.12.12.27.18.42.18s.31-.06.42-.18a.6.6 0 0 0 .01-.85zm-8.63-4.98c0-1.54 1.26-2.8 2.8-2.8s2.8 1.26 2.8 2.8c0 .77-.31 1.46-.81 1.97 0 0-.01 0-.01.01s0 .01-.01.01a2.799 2.799 0 0 1-4.77-1.99z"/></svg>');
            modal.find('.delivery-company-row').find('[data-toggle="popover"]').popover();
            // if(select_event.type == 'shown') {
            //     var select = select_event.target;
            //     var dropdown = dropdown_event.target;
            //     var selected_text = $(select).find('option:selected').text();
            //     // console.log(dropdown);
            //     var target = $(dropdown).find('li').filter(function() { return $(this).find('span.text').text() == selected_text});
            //     var pos = $(target).offset().top;
            //     $(dropdown).find('.inner').scrollTop($(dropdown).find('.inner').scrollTop() + pos);
            // }
        });

    });
}

var formDateTimePicker = function(id, type) {

    if(typeof id === undefined || !id) {
        return false;
    }
    var sid = (typeof property != 'undefined') ? property.SID : SID;
    var blocklang = ($('[form-seq="'+id+'"]').closest('.element').attr('data-blocklang'))? $('[form-seq="'+id+'"]').closest('.element').attr('data-blocklang'):LANG;
    var field_setting = {};
    var etcDateState = 'N';

    if(type == 'etc-product-date' || type == 'etc-product-datetime') {
        blocklang = LANG;
        etcDateState = $('#etc-state').val();
        field_setting.term = JSON.parse($('#etc-term-setting').val());
        field_setting.excludeDate = {'date': $('#etc-exclude-date').val()};
        if(type == 'etc-product-datetime') field_setting.time = JSON.parse($('#etc-time-setting').val());
    } else {
        $.ajax({
            url: '/template/forms/field_config',
            dataType: 'json',
            type: 'POST',
            data:  { sid: sid, id : id },
            async: false,
            cache: false,
            success: function(data) {
                checkError(data);
                field_setting = data;
            }
        });
    }

    var term = (field_setting.term)? field_setting.term:{};
    var excludeDate = (field_setting.excludeDate)? field_setting.excludeDate:{};
    var time = (type != 'date' && field_setting.time)? field_setting.time:{};
    var color = (field_setting.color)? field_setting.color:{};

    var startDate = (term.start_date !== undefined)? term.start_date:'';
    var endDate = (term.end_date !== undefined)? term.end_date:'';
    var dateWeek = (term.date_week !== undefined)? term.date_week:'';
    var days = (term.days !== undefined)? term.days.split('|'):[];
    var daysObj = {
        'sun': 0,
        'mon': 1,
        'tue': 2,
        'wed': 3,
        'thu': 4,
        'fri': 5,
        'sat': 6,
    }

    //excludeDate
    var exceptDate = (excludeDate.date !== undefined)? excludeDate.date.split(','):[];

    //time
    if(type == 'date2' || type == 'etc-product-datetime') {
        var interval = (time.interval!==undefined)? time.interval:'30';
        var am = (time.am!==undefined && time.am)? time.am.split('|'):[];
        var pm = (time.pm!==undefined && time.pm)? time.pm.split('|'):[];
    }
    
    var disabled = null;
    if(term.select_terms == 'Y') {
        if(dateWeek == 'W') {
            disabled = [0, 6];
        } else if(dateWeek == 'K') {
            disabled = [1, 2, 3, 4, 5];
        }
        if(days.length > 0) {
            disabled = [0, 1, 2, 3, 4, 5, 6];
            $.each(days, function(i, v){
                enableIdx = disabled.indexOf(daysObj[v]);
                if(enableIdx > -1) {
                    disabled.splice(enableIdx, 1);
                }
            });
        }
    }
    var modal_title = (type == 'date2' || type == 'etc-product-datetime')? $.lang[blocklang]['config.form.date2.select'] : $.lang[blocklang]['config.form.date.select'];
    var modal_str = '\
        <div class="term-calendar-box form-calendar-box" data-type="'+type+'">\
            <input type="hidden" id="select-calendar" value="term-datepicker">\
            <input type="hidden" id="etc-start-date-txt" value="'+startDate+'">\
            <input type="hidden" id="etc-end-date-txt" value="'+endDate+'">\
            <input type="hidden" id="etc-date-week" value="'+dateWeek+'">\
            <input type="hidden" id="etc-except-date" value="'+exceptDate+'">\
            <input type="hidden" id="select-date-ymd">\
            <div id="form-date2-datepicker-'+id+'"></div>\
        </div>';
    if(type == 'etc-product-date' || type == 'etc-product-datetime') {
        modal_str = '\
        <div class="term-calendar-box form-calendar-box" data-type="'+type+'">\
            <input type="hidden" id="select-calendar" value="term-datepicker">\
            <input type="hidden" id="etc-start-date-txt" value="">\
            <input type="hidden" id="etc-end-date-txt" value="">\
            <input type="hidden" id="etc-date-week" value="'+dateWeek+'">\
            <input type="hidden" id="etc-except-date" value="'+exceptDate+'">\
            <input type="hidden" id="select-date-ymd">\
            <div id="form-date2-datepicker-'+id+'"></div>\
        </div>';
    }
    if(type == 'date2' || type == 'etc-product-datetime') {
        modal_str+='\
        <div class="setting-row">\
            <div class="setting-label am">'+$.lang[blocklang]['config.form.date2.time.am']+'</div>\
            <div class="display-flex time-interval" data-time="am"></div>\
        </div>\
        <div class="setting-row">\
            <div class="setting-label pm">'+$.lang[blocklang]['config.form.date2.time.pm']+'</div>\
            <div class="display-flex time-interval" data-time="pm"></div>\
        </div>';
    
    }
    if($('#etc-status').val() == 'P') {
        modal_str+='\
        <div class="term-setting hide" data-blocklang="'+blocklang+'">\
            <span class="start-date"></span> ~ <span class="end-date"></span><span class="time"></span>\
        </div>';
    } else {
        modal_str+='\
        <div class="term-setting hide" data-blocklang="'+blocklang+'"></div>';
    }
    

    var modal_class = 'modal-dialog cl-cmmodal cl-s-btn form-date2 cl-close-btn cover';
    if(type == 'etc-product-date' || type == 'etc-product-datetime') modal_class = 'modal-dialog cl-cmmodal cl-s-btn form-date2 etc-product-date cl-close-btn cover';
    var etcText = '';
    var dateTimeModal = $(this).showModalFlat(modal_title, modal_str, true, true, function () { //confirm
        //input value
        $('[form-seq="'+id+'"] .date-ymd').attr('data-select_date', $('#select-date-ymd').val());
        var dateVal = ($('#select-date-ymd').val() && $('.term-setting').text())? true : false;
        switch(type) {
            case 'date2':
                if(dateVal) {
                    $('[form-seq="'+id+'"] .date-ymd').attr('data-select_time', $('.time-interval input:checked').attr('id'));
                    $('[form-seq="'+id+'"] .date-ymd').val($('.term-setting').text());
                    $('[form-seq="'+id+'"] .date-ymd').css('width', '240px');
                } else {
                    alert($.lang[blocklang]['config.form.date2.notSelected']);
                    return false;
                }
                break;
            case 'etc-product-date':
                if(dateVal) {
                    if($('#etc-status').val() == 'P') {
                        var selectedDate = $('#select-date-ymd').val().split('|');

                        $('.option-body #etc-start-date-option').val(selectedDate[0]);
                        $('.modal-cart-option-change #etc-start-date-option').val(selectedDate[0]);
                        $('input[name="change_option_start_date"]').val(selectedDate[0]);

                        $('.option-body #etc-end-date').val(selectedDate[1]);
                        $('.modal-cart-option-change #etc-end-date').val(selectedDate[1]);
                        $('input[name="change_option_end_date"]').val(selectedDate[1]);

                        etcText = selectedDate[0] + ' - ' + selectedDate[1];
                    } else {
                        var selectedDate = $('#select-date-ymd').val();
                        $('.option-body #etc-start-date-option').val(selectedDate);
                        $('.modal-cart-option-change #etc-start-date-option').val(selectedDate);
                        $('input[name="change_option_start_date"]').val(selectedDate);
                        etcText = selectedDate;
                    }

                    $('#etc-date-text').text(etcText);
                    console.log(etcText);
                } else {
                    alert('날짜를 선택해 주세요.');
                    return false;
                }
                break;
            case 'etc-product-datetime':
                if(!dateTimeModal.find('.time-interval input:checked').val() || !dateVal) {
                    alert('날짜와 시간을 선택해 주세요.');
                    return false;
                }
                if(dateVal) {
                    $('.option-body #etc-time').val($('.time-interval input:checked').val());
                    $('.modal-cart-option-change #etc-time').val($('.time-interval input:checked').val());
                    if($('#etc-status').val() == 'P') {
                        var selectedDate = $('#select-date-ymd').val().split('|');

                        $('.option-body #etc-start-date-option').val(selectedDate[0]);
                        $('.modal-cart-option-change #etc-start-date-option').val(selectedDate[0]);
                        $('input[name="change_option_start_date"]').val(selectedDate[0]);

                        $('.option-body #etc-end-date').val(selectedDate[1]);
                        $('.modal-cart-option-change #etc-end-date').val(selectedDate[1]);
                        $('input[name="change_option_end_date"]').val(selectedDate[1]);

                        etcText = selectedDate[0] + ' - ' + selectedDate[1];
                    } else {
                        var selectedDate = $('#select-date-ymd').val();
                        $('.option-body #etc-start-date-option').val(selectedDate);
                        $('.modal-cart-option-change #etc-start-date-option').val(selectedDate);
                        $('input[name="change_option_start_date"]').val(selectedDate);
                        etcText = selectedDate;
                    }

                    if($('#etc-time').val()) {
                        var etcTime = $('#etc-time').val().split(' ');
                        if(etcTime[0] == 'am') {
                            etcText += (' 오전 ' + etcTime[1]);
                        } else {
                            etcText += (' 오후 ' + etcTime[1]);
                        }
                    }

                    $('#etc-date-text').text(etcText);
                }
                break;
            default:
                if(dateVal) {
                    $('[form-seq="'+id+'"] .date-ymd').val($('.term-setting').text());
                } else {
                    alert($.lang[blocklang]['config.form.date.notSelected']);
                    return false;
                }
                break;
        }
        
        if(type == 'etc-product-date' || type == 'etc-product-datetime') {
            if ($('.cl-s-normal-option-selector').length <= 0) {
                var quantity = $('#product-quantity').val();
                var price = $('#product_c_price').val();
                var option = document.createElement('div');
                console.log(etcText + '||0||' + quantity);
                $(option).attr('data-val', etcText + '||0||' + quantity);
                productOptionPick(option, price, 'etc_none_option');
            }
        }
        
        //old
        if($('[form-seq="'+id+'"] .date-yyyy').length > 0) {
            var selectedDate = $('#select-date-ymd').val();
            var dateArr = selectedDate.split('.');
            $('[form-seq="'+id+'"] .date-yyyy').val(dateArr[0]);
            $('[form-seq="'+id+'"] .date-mm').val(dateArr[1]);
            $('[form-seq="'+id+'"] .date-dd').val(dateArr[2]);

            if($('[form-seq="'+id+'"] .date-hh').length > 0) {
                var checkedTime = $('.time-interval input:checked').val();
                var timeArr = checkedTime.replace(/am |pm /g, '').split(':');
                var hh = timeArr[0];
                var ii = timeArr[1];

                if(checkedTime.indexOf('pm') > -1) {
                    hh = (timeArr[0] == '12')? timeArr[0] : Number(timeArr[0])+12;
                }

                $('[form-seq="'+id+'"] .date-hh').val(hh);
                $('[form-seq="'+id+'"] .date-ii').val(ii);
            }
        } 
        dateTimeModal.modal('hide');
    },$.lang[blocklang]['config.cancel'],$.lang[blocklang]['config.ok'], modal_class, true, '', function() { //show
        var currentYear = new Date().getFullYear();
        var termPicker = new Datepickk({
            container: document.querySelector('#form-date2-datepicker-'+id),
            inline:true,
            today:true,
            range: ((type == 'etc-product-date' || type == 'etc-product-datetime') && $('#etc-status').val() == 'P')? true : false,
            disabledDays: disabled,
            lang: blocklang,
            minDate: new Date(1900, 0, 1),
            maxDate: new Date(currentYear + 15, 11, 31),
        });

        if(type.indexOf('etc-product-date') > -1) {
            startDate = $('#etc-min-date').val();
            endDate = $('#etc-max-date').val();
        }

        if(exceptDate) {
            var disabledDateArr = new Array();
            $.each(exceptDate, function(idx, item){
                item = item.replace(/\./g,'/'); //date for firefox
                disabledDateArr.push(new Date(item));
            });
            termPicker.disabledDates = disabledDateArr;
        }
        
        if(startDate && endDate) {
            var checkStartDate = startDate.split('.');
            var checkEndDate = endDate.split('.');
            termPicker.minDate = new Date(checkStartDate[0], (checkStartDate[1] * 1) - 1, checkStartDate[2]);
            termPicker.maxDate = new Date(checkEndDate[0], (checkEndDate[1] * 1) - 1, checkEndDate[2]);
        }

        $(document).off('click', '.d-year, .d-month');
        $(document).on('click', '.d-year, .d-month', function(){
            $('.d-month-year-picker').toggleClass('d-show');
            scrollToCurrentYearMonth();
        });

        if((type=='date'||type=='date2') && color) {
            $('#datetime-style-'+id).remove();
            var highlight = '#'+color.highlight;
            var h_rgba = hexToRgba(highlight);
            var rgba_str = h_rgba.r+','+h_rgba.g+','+h_rgba.b;
            var style = '\
                <style id="datetime-style-'+id+'">\
                    .form-date2 .Datepickk .d-table input:not(:disabled):not(:checked) + label:hover:before{border: 1px solid '+highlight+'; background-color: transparent;}\
                    .form-date2 .Datepickk .d-table input:not(:disabled) + label:hover:before{border: 1px solid '+highlight+'; background-color: transparent;}\
                    .form-date2 .Datepickk .d-table input:checked + label:before, .form-date2 .Datepickk .d-table input:checked + label:hover:before {background-color: '+highlight+'; border: 1px solid '+highlight+';}\
                    .form-date2 .time-interval input:checked + label {color: '+highlight+'; border: 1px solid '+highlight+';}\
                    .form-date2 .time-interval label{background-color: rgba('+rgba_str+', 0.05); border: 1px solid rgba('+rgba_str+', 0.1);}\
                    .form-date2 .term-setting{background-color: rgba('+rgba_str+', 0.05);}\
                </style>\
             ';
            $('.cl-cmmodal.form-date2').append(style);
        }
        if(type == 'date2' || type == 'etc-product-datetime') {
            dateTimeModal.find('.time-interval').each(function(i, v){
                var mna = $(v).data('time');
                var times = '\
                    <input type="checkbox" id="'+mna+'-12-00" class="hide" name="'+mna+'" value="'+mna+' 12:00" data-setting_time="1200">\
                    <label for="'+mna+'-12-00">12:00</label>\
                    <input type="checkbox" id="'+mna+'-12-30" class="half-time hide" name="'+mna+'" value="'+mna+' 12:30" data-setting_time="1230">\
                    <label for="'+mna+'-12-30" class="half-time">12:30</label>\
                    \
                    <input type="checkbox" id="'+mna+'-1-00" class="hide" name="'+mna+'" value="'+mna+' 01:00" data-setting_time="0100">\
                    <label for="'+mna+'-1-00">1:00</label>\
                    <input type="checkbox" id="'+mna+'-1-30" class="half-time hide" name="'+mna+'" value="'+mna+' 01:30" data-setting_time="0130">\
                    <label for="'+mna+'-1-30" class="half-time">1:30</label>\
                    \
                    <input type="checkbox" id="'+mna+'-2-00" class="hide" name="'+mna+'" value="'+mna+' 02:00" data-setting_time="0200">\
                    <label for="'+mna+'-2-00">2:00</label>\
                    <input type="checkbox" id="'+mna+'-2-30" class="half-time hide" name="'+mna+'" value="'+mna+' 02:30" data-setting_time="0230">\
                    <label for="'+mna+'-2-30" class="half-time">2:30</label>\
                    \
                    <input type="checkbox" id="'+mna+'-3-00" class="hide" name="'+mna+'" value="'+mna+' 03:00" data-setting_time="0300">\
                    <label for="'+mna+'-3-00">3:00</label>\
                    <input type="checkbox" id="'+mna+'-3-30" class="half-time hide" name="'+mna+'" value="'+mna+' 03:30" data-setting_time="0330">\
                    <label for="'+mna+'-3-30" class="half-time">3:30</label>\
                    \
                    <input type="checkbox" id="'+mna+'-4-00" class="hide" name="'+mna+'" value="'+mna+' 04:00" data-setting_time="0400">\
                    <label for="'+mna+'-4-00">4:00</label>\
                    <input type="checkbox" id="'+mna+'-4-30" class="half-time hide" name="'+mna+'" value="'+mna+' 04:30" data-setting_time="0430">\
                    <label for="'+mna+'-4-30" class="half-time">4:30</label>\
                    \
                    <input type="checkbox" id="'+mna+'-5-00" class="hide" name="'+mna+'" value="'+mna+' 05:00" data-setting_time="0500">\
                    <label for="'+mna+'-5-00">5:00</label>\
                    <input type="checkbox" id="'+mna+'-5-30" class="half-time hide" name="'+mna+'" value="'+mna+' 05:30" data-setting_time="0530">\
                    <label for="'+mna+'-5-30" class="half-time">5:30</label>\
                    \
                    <input type="checkbox" id="'+mna+'-6-00" class="hide" name="'+mna+'" value="'+mna+' 06:00" data-setting_time="0600">\
                    <label for="'+mna+'-6-00">6:00</label>\
                    <input type="checkbox" id="'+mna+'-6-30" class="half-time hide" name="'+mna+'" value="'+mna+' 06:30" data-setting_time="0630">\
                    <label for="'+mna+'-6-30" class="half-time">6:30</label>\
                    \
                    <input type="checkbox" id="'+mna+'-7-00" class="hide" name="'+mna+'" value="'+mna+' 07:00" data-setting_time="0700">\
                    <label for="'+mna+'-7-00">7:00</label>\
                    <input type="checkbox" id="'+mna+'-7-30" class="half-time hide" name="'+mna+'" value="'+mna+' 07:30" data-setting_time="0730">\
                    <label for="'+mna+'-7-30" class="half-time">7:30</label>\
                    \
                    <input type="checkbox" id="'+mna+'-8-00" class="hide" name="'+mna+'" value="'+mna+' 08:00" data-setting_time="0800">\
                    <label for="'+mna+'-8-00">8:00</label>\
                    <input type="checkbox" id="'+mna+'-8-30" class="half-time hide" name="'+mna+'" value="'+mna+' 08:30" data-setting_time="0830">\
                    <label for="'+mna+'-8-30" class="half-time">8:30</label>\
                    \
                    <input type="checkbox" id="'+mna+'-9-00" class="hide" name="'+mna+'" value="'+mna+' 09:00" data-setting_time="0900">\
                    <label for="'+mna+'-9-00">9:00</label>\
                    <input type="checkbox" id="'+mna+'-9-30" class="half-time hide" name="'+mna+'" value="'+mna+' 09:30" data-setting_time="0930">\
                    <label for="'+mna+'-9-30" class="half-time">9:30</label>\
                    \
                    <input type="checkbox" id="'+mna+'-10-00" class="hide" name="'+mna+'" value="'+mna+' 10:00" data-setting_time="1000">\
                    <label for="'+mna+'-10-00">10:00</label>\
                    <input type="checkbox" id="'+mna+'-10-30" class="half-time hide" name="'+mna+'" value="'+mna+' 10:30" data-setting_time="1030">\
                    <label for="'+mna+'-10-30" class="half-time">10:30</label>\
                    \
                    <input type="checkbox" id="'+mna+'-11-00" class="hide" name="'+mna+'" value="'+mna+' 11:00" data-setting_time="1100">\
                    <label for="'+mna+'-11-00">11:00</label>\
                    <input type="checkbox" id="'+mna+'-11-30" class="half-time hide" name="'+mna+'" value="'+mna+' 11:30" data-setting_time="1130">\
                    <label for="'+mna+'-11-30" class="half-time">11:30</label>\
                    ';
                $(v).html(times);
            }); //end each
            
            dateTimeModal.find('.time-interval input').prop('disabled', true);
            
            if(am.length > 0) {
                $.each(am, function(i, v){
                    dateTimeModal.find('.time-interval[data-time="am"] input[data-setting_time="'+v+'"]').prop('disabled', false);
                });
            } else {
                $('.setting-label.am').addClass('hide');
            }

            if(pm.length > 0) {
                $.each(pm, function(i, v){
                    dateTimeModal.find('.time-interval[data-time="pm"] input[data-setting_time="'+v+'"]').prop('disabled', false);
                });
            } else {
                $('.setting-label.pm').addClass('hide');
            }
            
            if(interval == 60) {
                dateTimeModal.find('.time-interval label.half-time').addClass('hide');
            } else { //30
                dateTimeModal.find('.time-interval label.half-time').removeClass('hide');
            }

            var num = 1;
            var length = 0;
            dateTimeModal.find('.time-interval label').not('.hide').each(function(i, v){
                $(v).prev('input').addClass('row-'+num);
                if($(v).prev('input').prop('disabled')) {
                    length++;
                }

                if((i+1)%4 == 0) {
                    if(length == 4) $('input.row-'+num+' + label').addClass('hide');
                    length = 0;
                    num ++;
                }
            });

            dateTimeModal.find('.time-interval input').on('change', function(){
                $('.time-interval input').prop('checked', false);
                $(this).prop('checked', true);
                
                if(type == 'etc-product-datetime') {
                    if($('#etc-status').val() == 'P') {
                        if(!$('#etc-start-date-txt').val() || !$('#etc-end-date-txt').val()) return false;
                    } else {
                        if(!$('#etc-start-date-txt').val()) return false;
                    }
                }

                getDateTimeStr(blocklang);
            });
        } //date2

        if($('[form-seq="'+id+'"] .date-ymd').val()) { //form
            var sDate = $('[form-seq="'+id+'"] .date-ymd').attr('data-select_date');
            var sDateObj = new Date(sDate);
            termPicker.currentDate  = sDateObj;
            termPicker.selectDate(sDateObj);
            $('#select-date-ymd').val(sDate);
            
            if(type == 'date2') {
                var sTime = $('[form-seq="'+id+'"] .date-ymd').attr('data-select_time');
                $('#'+sTime).prop('checked', true);
            }
            getDateTimeStr(blocklang);
        }

        if(type.indexOf('etc-product-date') > -1 && $('#etc-start-date-option').val()) { //etc product
            if($('#etc-status').val() == 'P') { //기간
                document.querySelector('#etc-start-date-txt').value = document.querySelector('#etc-start-date-option').value;
                document.querySelector('#etc-end-date-txt').value = document.querySelector('#etc-end-date').value;
                document.querySelector('#select-date-ymd').value = document.querySelector('#etc-start-date-option').value + '|' + document.querySelector('#etc-end-date').value
                termPicker.startDate = $('#etc-start-date-option').val();
                termPicker.endDate = $('#etc-end-date').val();
            } else {
                document.querySelector('#etc-start-date-txt').value = document.querySelector('#etc-start-date-option').value;
                document.querySelector('#select-date-ymd').value = document.querySelector('#etc-start-date-option').value;
                var sDate = $('#etc-start-date-option').val();
                var sDateObj = new Date(sDate);
                termPicker.selectDate(sDateObj);
            }

            if($('#etc-time').val()) {
                var sTime = $('#etc-time').val();
                $('.time-interval input[value="'+sTime+'"]').prop('checked', true);
            }
            
            setTimeout(function(){
                getDateTimeStr('ko')
            }, 500);
        }
    });
}

function getDateTimeStr(blocklang, w) {
    if(typeof w == 'undefined') w = '';
    var lang = (blocklang)? blocklang:LANG
    var selectedDate = $('#select-date-ymd').val();
    var checkSelectedDate = selectedDate.split('.');
    var inputType = ($('.setting-datetime-input').length > 0)? $('.setting-datetime-input').attr('data-type') : $('.form-calendar-box').attr('data-type');
    var selectedTime = $('.time-interval input:checked');

    switch (inputType) {
        case 'date2':
            if(selectedDate && selectedTime.length > 0) {
                $('.term-setting').removeClass('hide');
                var selectedTimeTxt = ' '+$.lang[lang]['config.form.date2.time.'+selectedTime.attr('name')]+' '+selectedTime.next('label').text();            
                if(lang == 'ko') {
                    $('.term-setting').text(checkSelectedDate[0]+'년 '+checkSelectedDate[1]+'월 '+checkSelectedDate[2]+'일'+selectedTimeTxt);
                } else {
                    $('.term-setting').text(checkSelectedDate[1]+'/'+checkSelectedDate[2]+'/'+checkSelectedDate[0]+selectedTimeTxt);
                }
            }
            break;
        case 'etc-product-date':
        case 'etc-product-datetime':
            lang = 'ko';
            blocklang = 'ko';
            
            var selectedTimeTxt = '';
            selectedDate = $('#etc-start-date-txt').val();
            checkSelectedDate = selectedDate.split('.');

            var startDate = $('#etc-start-date-txt').val();
            var endDate = $('#etc-end-date-txt').val();
            if(selectedDate) {
                $('.term-setting').removeClass('hide');
                if($('#etc-status').val() == 'P') { //기간
                    var checkStartDate = startDate.split('.');
                    var checkEndDate = endDate.split('.');
                    if (selectedTime.length > 0) selectedTimeTxt = '<br>'+$.lang[lang]['config.form.date2.time.'+selectedTime.attr('name')]+' '+selectedTime.next('label').text();            
                    if(blocklang == 'ko') {
                        $('.term-setting .start-date').html(checkStartDate[0]+'년 '+checkStartDate[1]+'월 '+checkStartDate[2]+' 일');
                        $('.term-setting .end-date').html(checkEndDate[0]+'년 '+checkEndDate[1]+'월 '+checkEndDate[2]+' 일'+selectedTimeTxt);
                    } else {
                        $('.term-setting .start-date').html(checkStartDate[1]+'/'+checkStartDate[2]+'/'+checkStartDate[0]);
                        $('.term-setting .end-date').html(checkEndDate[1]+'/'+checkEndDate[2]+'/'+checkEndDate[0]+selectedTimeTxt);
                    }
                } else {
                    if (selectedTime.length > 0) selectedTimeTxt = ' '+$.lang[lang]['config.form.date2.time.'+selectedTime.attr('name')]+' '+selectedTime.next('label').text();            
                    if(lang == 'ko') {
                        $('.term-setting').html(checkSelectedDate[0]+'년 '+checkSelectedDate[1]+'월 '+checkSelectedDate[2]+'일'+selectedTimeTxt);
                    } else {
                        $('.term-setting').html(checkSelectedDate[1]+'/'+checkSelectedDate[2]+'/'+checkSelectedDate[0]+selectedTimeTxt);
                    }
                }
            }
            break;
        case 'saleStartDateTime':
            lang = 'ko';
            blocklang = 'ko';
            console.log('w', w);
            var selectedTimeTxt = '';
            checkSelectedDate = selectedDate.split('.');

            if(selectedDate) {
                if(lang == 'ko') {
                    $('.sale-calendar-box .start-date').html(checkSelectedDate[0]+'년 '+checkSelectedDate[1]+'월 '+checkSelectedDate[2]+'일');
                } else {
                    $('.sale-calendar-box .start-date').html(checkSelectedDate[1]+'/'+checkSelectedDate[2]+'/'+checkSelectedDate[0]);
                }
                
                var saleStartDateTime = $('#sale-start-datetime').val();
                
                if (w == 'calendar') {
                    $('.setting-sale-date .setting-datetime-input').slideUp(400, function(){
                        $('.setting-sale-date').removeClass('open');
                    });

                    $('.setting-sale-time .setting-datetime-input').slideDown(400, function(){
                        $('.setting-sale-time').addClass('open');
                    });
                } else {
                    if(!w && saleStartDateTime) {
                        $('.setting-sale-date').removeClass('open');
                        $('.setting-sale-date .setting-datetime-input').css('display', 'none');
                        
                        $('.setting-sale-time').removeClass('open');
                        $('.setting-sale-time .setting-datetime-input').css('display', 'none');
                    }
                }
            }

            if (selectedTime.length > 0) {
                var timeArr = selectedTime.next('label').text().split(':');
                selectedTimeTxt = $.lang[lang]['config.form.date2.time.'+selectedTime.closest('.time-interval').attr('data-time')]+' '+timeArr[0]+'시 '+timeArr[1]+'분';
                $('.sale-calendar-box .start-time').html(selectedTimeTxt);
                
                if (w == 'time') {
                    $('.setting-sale-time .setting-datetime-input').slideUp(400, function(){
                        $('.setting-sale-time').removeClass('open');
                    });
                }
            }
            break;
        case 'saleEndDateTime':
            lang = 'ko';
            blocklang = 'ko';

            var selectedTimeTxt = '';
            checkSelectedDate = selectedDate.split('.');

            if(selectedDate) {
                if(lang == 'ko') {
                    $('.sale-calendar-box .end-date').html(checkSelectedDate[0]+'년 '+checkSelectedDate[1]+'월 '+checkSelectedDate[2]+'일');
                } else {
                    $('.sale-calendar-box .end-date').html(checkSelectedDate[1]+'/'+checkSelectedDate[2]+'/'+checkSelectedDate[0]);
                }

                var saleStartDateTime = $('#sale-start-datetime').val();
                var saleEndDateTime = $('#sale-end-datetime').val();

                var startDate = saleStartDateTime.split(' ')[0];
                var startTime = saleStartDateTime.split(' ')[1];

                if (w == 'calendar') {
                    $('.setting-sale-date .setting-datetime-input').slideUp(400, function(){
                        $('.setting-sale-date').removeClass('open');
                    });

                    $('.setting-sale-time .setting-datetime-input').slideDown(400, function(){
                        $('.setting-sale-time').addClass('open');
                    });
                } else {
                    if(!w && saleStartDateTime) {
                        $('.setting-sale-date').removeClass('open');
                        $('.setting-sale-date .setting-datetime-input').css('display', 'none');
                        
                        $('.setting-sale-time').removeClass('open');
                        $('.setting-sale-time .setting-datetime-input').css('display', 'none');
                    }
                }

                $('.time-interval input').prop('disabled', false);
                if(saleStartDateTime && startDate == selectedDate.replace(/\./g,'-')) {
                    var hour = parseInt(startTime.split(':')[0]);
                    var minute = parseInt(startTime.split(':')[1]);
                    var mna = (hour >= 12)? 'pm' : 'am';

                    if(hour >= 12) {
                        if (hour > 12) hour -= 12;
                    } else if (hour == 0) hour += 12

                    var formattedStartTime = hour.toString().padStart(2, '0') + minute.toString().padStart(2, '0');
                    $('.time-interval[data-time="' + mna + '"] input[value="' + formattedStartTime + '"]').prop('disabled', true);
                    if(mna == 'pm') {
                        $('.time-interval[data-time="am"] input').prop('disabled', true);
                        $('.time-interval[data-time="pm"] input[value="' + formattedStartTime + '"]').prevAll('input').prop('disabled', true);
                    } else {
                        $('.time-interval[data-time="am"] input[value="' + formattedStartTime + '"]').prevAll('input').prop('disabled', true);
                    }
                    if($('.time-interval input:checked').is(':disabled')) {
                        $('.time-interval input:checked').prop('checked', false);
                        $('.sale-calendar-box .end-time').html('');
                        selectedTime = '';
                    }
                }
            }

            if (selectedTime.length > 0) {
                var timeArr = selectedTime.next('label').text().split(':');
                selectedTimeTxt = $.lang[lang]['config.form.date2.time.'+selectedTime.closest('.time-interval').attr('data-time')]+' '+timeArr[0]+'시 '+timeArr[1]+'분';
                $('.sale-calendar-box .end-time').html(selectedTimeTxt);

                if (w == 'time') {
                    $('.setting-sale-time .setting-datetime-input').slideUp(400, function(){
                        $('.setting-sale-time').removeClass('open');
                    });
                }
            }
            break;
        default:
            if(selectedDate) {
                $('.term-setting').removeClass('hide');
                if(lang == 'ko') {
                    $('.term-setting').text(checkSelectedDate[0]+'년 '+checkSelectedDate[1]+'월 '+checkSelectedDate[2]+'일');
                } else {
                    $('.term-setting').text(checkSelectedDate[1]+'/'+checkSelectedDate[2]+'/'+checkSelectedDate[0]);
                }
            }
            break;
    }
    // if(selectedDate && startTime.length > 0 && endTime.length > 0) {
    //     var startTimeTxt = (startTime.attr('name') == 'am') ? '오전 '+startTime.next('label').text():'오후 '+startTime.next('label').text();
    //     var endTimeTxt = (endTime.attr('name') == 'am') ? '오전 '+endTime.next('label').text() :'오후 '+endTime.next('label').text();

    //     var s = startTime.val();
    //     var e = endTime.val();
    //     var sHour = (startTime.attr('name') == 'pm')? Number(s.substr(0, 2))+12 : Number(s.substr(0, 2));
    //     var sMinute = Number(s.substr(2));
    //     var eHour = (endTime.attr('name') == 'pm')? Number(e.substr(0, 2))+12 : Number(e.substr(0, 2));
    //     var eMinute = Number(e.substr(2));
        
    //     if(sHour == 24) sHour = 12;
    //     else if(sHour == 12) sHour = 0;
    //     if(eHour == 24) eHour = 12;
    //     else if(eHour == 12) eHour = 0;

    //     var startDateTime = new Date(checkSelectedDate[0], checkSelectedDate[1], checkSelectedDate[2], sHour, sMinute);
    //     var endDateTime = new Date(checkSelectedDate[0], checkSelectedDate[1], checkSelectedDate[2], eHour, eMinute);
    //     var elapsedMSec = endDateTime.getTime()-startDateTime.getTime();
    //     var elapsedHour = elapsedMSec/1000/60/60;
    //     console.log(sHour, sMinute, startDateTime, endDateTime, elapsedMSec, elapsedHour);
    //     var totalTimesTxt = (elapsedMSec%3600000 == 0)? ' ('+elapsedHour+'시간)' : ' ('+Math.floor(elapsedHour)+'시간 30분)';
    //     $('.term-setting').removeClass('hide');
    //     $('.term-setting').text(checkSelectedDate[0]+'년 '+checkSelectedDate[1]+'월 '+checkSelectedDate[2]+' 일 '+startTimeTxt+' ~ '+ endTimeTxt + totalTimesTxt);
    // }
}

function scrollToCurrentYearMonth() {
    $('.year-picker').scrollTop(0);
    $('.month-picker').scrollTop(0);
    var offsetYear = $('.year-picker .current').position().top - 30;
    var offsetMonth = $('.month-picker .current').position().top - 30;
    $('.year-picker').scrollTop(offsetYear);
    $('.month-picker').scrollTop(offsetMonth);
}

function calInputWidth(inputObj) {
    let inputTxt = inputObj.val().replace(/[\u3131-\u318E\uAC00-\uD7A3]/g, '');
    let Num = Number(removeCommas(inputTxt));

    let $tempSpan = $('<span>').css({
        'font-size': inputObj.css('font-size'),
        'font-family': inputObj.css('font-family'),
        'visibility': 'hidden',
        'white-space': 'pre'
    }).text(inputTxt);
    
    $('body').append($tempSpan);
    
    let inputWidth = Math.floor($tempSpan.width()) + 5;
    if(inputWidth < 13 || Num == 0) inputWidth = 13;
    inputObj.width(inputWidth);
    $tempSpan.remove();
}

function calDiscount(inputObj) {
    var orgPrice = Number(removeCommas($('#prod-sale').text())),
        discountRate = inputObj.val(),
        discountUnit = $('#prod-discount-unit').attr('data-value'),
        price = 0;

    discountRate = Number(discountRate.replace(/[^0-9]/g, ''));
    if($('.form-group.discount-append').hasClass('discount-multi')) {
        switch(discountUnit) {
            case 'W':
                inputObj.val(number_format(discountRate));
                break;
            case 'P':
                if(discountRate >= 100) {
                    discountRate = 100;
                }
                inputObj.val(discountRate);
                
                break;
        }
    } else {
        switch(discountUnit) {
            case 'W':
                price = orgPrice - discountRate;
                if(price < 0) {
                    price = 0;
                    inputObj.val(number_format(orgPrice));
                } else {
                    inputObj.val(number_format(discountRate));
                }
                break;
            case 'P':
                if(discountRate >= 100) {
                    price = 0;
                    discountRate = 100;
                } else {
                    var discountPrice = orgPrice * (discountRate / 100);
                    price = Math.round(orgPrice - discountPrice);
                    // if($('#price-cut-btn').is(':checked')) price = Math.floor(price / 10) * 10;
                }
                
                // if (price % 10 == 0 || price == 0) $('#price-cut-btn').addClass('disabled');
                // else $('#price-cut-btn').removeClass('disabled');
                inputObj.val(discountRate);
                
                break;
        } //end switch
        console.log('price', price);

        $('#prod-price').val(number_format(price));
        calInputWidth($('#prod-price'));
    }
    
}

$(document).on('click', '.element[data-type="review"]  a[data-review]', function(e){
    e.preventDefault();
    if ($(this).closest('.element').hasClass('review-sample-block')) return false;

    if (PAGE_MODE != 'c') {
        var seq = $(this).attr('data-review');
        $.shoppingmall.viewReviewModal(property.SID, seq);
    }
});


var configDateTime = function(el) {
    var field_type = $(el).attr('data-type');
    var id = (field_type.indexOf('etc-product-date') > -1) ? $('#prod-no').val() : $(el).closest('.form-sort-item').attr('data-id');
    var func = $(el).attr('data-setting');
    var field_setting = {};
    // console.log('field_type', field_type, el);

    if (field_type.indexOf('etc-product-date') > -1) {
        field_setting.term = ($('#etc-term').val()) ? JSON.parse($('#etc-term').val()) : {};
        field_setting.excludeDate = { 'date': $('#etc-exclude-date').val() };
        field_setting.time = ($('#etc-time').val()) ? JSON.parse($('#etc-time').val()) : {};
    } else if (field_type.indexOf('sale-product-datetime') > -1) {
        field_setting.term = ($('#etc-term').val()) ? JSON.parse($('#etc-term').val()) : {};
    } else {
        $.ajax({
            url: '/template/forms/field_config',
            dataType: 'json',
            type: 'POST',
            data: { sid: SID, id: id },
            async: false,
            cache: false,
            success: function(data) {
                checkError(data);
                field_setting = data;
            }
        });
    }
    // console.log(field_setting);

    var term = (field_setting.term) ? field_setting.term : {};
    var excludeDate = (field_setting.excludeDate) ? field_setting.excludeDate : {};
    var time = (field_setting.time) ? field_setting.time : {};

    //term
    var startDate = (term.start_date !== undefined && term.start_date != '') ? term.start_date : '';
    var endDate = (term.end_date !== undefined && term.end_date != '') ? term.end_date : '';
    var dateWeek = (term.date_week !== undefined && term.date_week != '') ? term.date_week : 'A';
    var days = (term.days !== undefined && term.days != '') ? term.days.split('|') : [];
    var daysObj = {
        'sun': 0,
        'mon': 1,
        'tue': 2,
        'wed': 3,
        'thu': 4,
        'fri': 5,
        'sat': 6,
    }

    //excludeDate
    var exceptDate = (excludeDate.date !== undefined) ? excludeDate.date : '';

    //time
    var interval = (time.interval !== undefined) ? time.interval : '30';
    var am = (time.am !== undefined) ? time.am.split('|') : [];
    var pm = (time.pm !== undefined) ? time.pm.split('|') : [];
    var timeCnt = am.length + pm.length;
    // var disabled = null;

    var allTimeChecked = '';
    if (interval == '30' && timeCnt == 48) allTimeChecked = 'checked';
    if (interval == '60' && timeCnt == 24) allTimeChecked = 'checked';

    var language = (LANG != 'ko') ? 'en' : 'ko';
    var blocklang = ($('[form-seq="' + id + '"]').closest('.element').attr('data-blocklang')) ? $('[form-seq="' + id + '"]').closest('.element').attr('data-blocklang') : LANG;

    var modal_title = '';
    var modal_str = '';
    var modal_class = 'modal-dialog cl-cmmodal cl-s-btn setting-form-option-date2 cl-close-btn cover';
    switch (func) {
        case 'term':
            modal_title = $.lang[LANG]['config.form.date.title'];
            modal_str = '\
                <input type="hidden" id="etc-date-week" value="' + dateWeek + '">\
                <div class="display-flex align-items-center setting-row">\
                    <div class="setting-label">' + $.lang[LANG]['config.form.date.dateWeek.label'] + '</div>\
                    <div class="btn-group btn-group-justified week">\
                        <label class="btn checked">' + $.lang[LANG]['config.form.date.dateWeek.entire'] + '<input type="radio" name="week" value="A" checked></label>\
                        <label class="btn">' + $.lang[LANG]['config.form.date.dateWeek.weekday'] + '<input type="radio" name="week" value="W"></label>\
                        <label class="btn">' + $.lang[LANG]['config.form.date.dateWeek.weekend'] + '<input type="radio" name="week" value="K"></label>\
                    </div>\
                </div>\
                <div class="display-flex align-items-center setting-row">\
                    <div class="setting-label">' + $.lang[LANG]['config.form.date.day.label'] + '</div>\
                    <div class="btn-group btn-group-justified day">\
                        <label class="btn checked">' + $.lang[LANG]['config.form.date.day.sun'] + '<input type="checkbox" name="day" value="sun" checked></label>\
                        <label class="btn checked">' + $.lang[LANG]['config.form.date.day.mon'] + '<input type="checkbox" name="day" value="mon" checked></label>\
                        <label class="btn checked">' + $.lang[LANG]['config.form.date.day.tue'] + '<input type="checkbox" name="day" value="tue" checked></label>\
                        <label class="btn checked">' + $.lang[LANG]['config.form.date.day.wed'] + '<input type="checkbox" name="day" value="wed" checked></label>\
                        <label class="btn checked">' + $.lang[LANG]['config.form.date.day.thu'] + '<input type="checkbox" name="day" value="thu" checked></label>\
                        <label class="btn checked">' + $.lang[LANG]['config.form.date.day.fri'] + '<input type="checkbox" name="day" value="fri" checked></label>\
                        <label class="btn checked">' + $.lang[LANG]['config.form.date.day.sat'] + '<input type="checkbox" name="day" value="sat" checked></label>\
                    </div>\
                </div>\
                <div class="term-calendar-box">\
                    <input type="hidden" id="select-calendar" value="term-datepicker">\
                    <input type="hidden" id="etc-start-date-prev" value="' + startDate + '">\
                    <input type="hidden" id="etc-end-date-prev" value="' + endDate + '">\
                    <input type="hidden" id="etc-start-date-txt" value="' + startDate + '">\
                    <input type="hidden" id="etc-end-date-txt" value="' + endDate + '">\
                    <input type="hidden" id="select-except-date">\
                    <div id="term-datepicker"></div>\
                </div>\
                <div class="term-setting hide" data-blocklang="' + blocklang + '">\
                    <span class="start-date"></span> ~ <span class="end-date"></span>\
                </div>\
            ';
            break;
        case 'saleStartDateTime':
        case 'saleEndDateTime':
            modal_class = 'modal-dialog cl-cmmodal cl-s-btn setting-form-option-date2 setting-product-sale-datetime cl-close-btn cover';
            var timeClass = 'start-time';
            if(func == 'saleStartDateTime') {
                modal_title = '시작 날짜/시간 선택';
                modal_str = '\
                <div class="term-calendar-box sale-calendar-box setting-sale-date">\
                    <div class="setting-label display-flex align-items-center space-between">\
                        <div class="display-flex align-items-center">\
                            <span>날짜 선택</span>\
                            <span class="start-date datetime-txt" data-blocklang="' + blocklang + '"></span>\
                        </div>\
                        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16"><path d="M8 12.5a.47.47 0 0 1-.35-.15l-7.5-7.5c-.2-.2-.2-.51 0-.71.2-.2.51-.2.71 0L8 11.29l7.15-7.15c.2-.2.51-.2.71 0 .2.2.2.51 0 .71l-7.5 7.5c-.1.1-.23.15-.36.15z"></path></svg>\
                    </div>\
                    <div class="setting-datetime-input" data-type="' + func + '">\
                        <input type="hidden" id="select-calendar" value="term-datepicker">\
                        <input type="hidden" id="select-date-ymd" value="">\
                        <input type="hidden" id="etc-start-date-prev" value="">\
                        <input type="hidden" id="etc-start-date-txt" value="">\
                        <div id="sale-datepicker"></div>\
                    </div>\
                </div>\
                ';
            } else {
                modal_title = '종료 날짜/시간 선택';
                modal_str = '\
                <div class="term-calendar-box sale-calendar-box setting-sale-date">\
                    <div class="setting-label display-flex align-items-center space-between">\
                        <div class="display-flex align-items-center">\
                            <span>날짜 선택</span>\
                            <span class="end-date datetime-txt" data-blocklang="' + blocklang + '"></span>\
                        </div>\
                        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16"><path d="M8 12.5a.47.47 0 0 1-.35-.15l-7.5-7.5c-.2-.2-.2-.51 0-.71.2-.2.51-.2.71 0L8 11.29l7.15-7.15c.2-.2.51-.2.71 0 .2.2.2.51 0 .71l-7.5 7.5c-.1.1-.23.15-.36.15z"></path></svg>\
                    </div>\
                    <div class="setting-datetime-input" data-type="' + func + '">\
                        <input type="hidden" id="select-calendar" value="term-datepicker">\
                        <input type="hidden" id="select-date-ymd" value="">\
                        <input type="hidden" id="etc-start-date-prev" value="">\
                        <input type="hidden" id="etc-start-date-txt" value="">\
                        <input type="hidden" id="etc-end-date-prev" value="">\
                        <input type="hidden" id="etc-end-date-txt" value="">\
                        <div id="sale-datepicker"></div>\
                    </div>\
                </div>\
                ';
                timeClass = 'end-time';
            }
            
            modal_str += '\
                <div class="term-calendar-box sale-calendar-box setting-sale-time">\
                    <div class="setting-label display-flex align-items-center space-between">\
                        <div class="display-flex align-items-center">\
                            <span>시간 선택</span>\
                            <span class="'+timeClass+' datetime-txt" data-blocklang="' + blocklang + '"></span>\
                        </div>\
                        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16"><path d="M8 12.5a.47.47 0 0 1-.35-.15l-7.5-7.5c-.2-.2-.2-.51 0-.71.2-.2.51-.2.71 0L8 11.29l7.15-7.15c.2-.2.51-.2.71 0 .2.2.2.51 0 .71l-7.5 7.5c-.1.1-.23.15-.36.15z"></path></svg>\
                    </div>\
                    <div class="setting-datetime-input" data-type="' + func + '" style="display:none;">\
                        <div class="display-flex align-items-center setting-row">\
                            <div class="setting-label">' + $.lang[LANG]['config.form.date2.time.interval.label'] + '</div>\
                            <div class="newcheckbox hand">\
                                <label>\
                                    <div class="newcheckboxSvgRadio">\
                                        <input type="radio" class="cl-common-form-radio-hide" name="time_interval" value="30" checked>\
                                        <svg viewBox="0 0 18 18" width="18" height="18">\
                                            <path d="M9 0C4.03 0 0 4.03 0 9c0 4.97 4.03 9 9 9s9-4.03 9-9C18 4.03 13.97 0 9 0zM9 17c-4.41 0-8-3.59-8-8 0-4.41 3.59-8 8-8s8 3.59 8 8C17 13.41 13.41 17 9 17z"></path>\
                                        </svg>\
                                        <svg class="active" viewBox="0 0 18 18" width="18" height="18">\
                                            <path d="M9 0C4.03 0 0 4.03 0 9c0 4.97 4.03 9 9 9s9-4.03 9-9C18 4.03 13.97 0 9 0zM9 17c-4.41 0-8-3.59-8-8 0-4.41 3.59-8 8-8s8 3.59 8 8C17 13.41 13.41 17 9 17z"></path>\
                                            <circle cx="9" cy="9" r="6"></circle>\
                                        </svg>\
                                    </div>\
                                    <span>' + $.lang[LANG]['config.form.date2.time.interval.30'] + '</span>\
                                </label>\
                            </div>\
                            <div class="newcheckbox hand">\
                                <label>\
                                    <div class="newcheckboxSvgRadio">\
                                        <input type="radio" class="cl-common-form-radio-hide" name="time_interval" value="60">\
                                        <svg viewBox="0 0 18 18" width="18" height="18">\
                                            <path d="M9 0C4.03 0 0 4.03 0 9c0 4.97 4.03 9 9 9s9-4.03 9-9C18 4.03 13.97 0 9 0zM9 17c-4.41 0-8-3.59-8-8 0-4.41 3.59-8 8-8s8 3.59 8 8C17 13.41 13.41 17 9 17z"></path>\
                                        </svg>\
                                        <svg class="active" viewBox="0 0 18 18" width="18" height="18">\
                                            <path d="M9 0C4.03 0 0 4.03 0 9c0 4.97 4.03 9 9 9s9-4.03 9-9C18 4.03 13.97 0 9 0zM9 17c-4.41 0-8-3.59-8-8 0-4.41 3.59-8 8-8s8 3.59 8 8C17 13.41 13.41 17 9 17z"></path>\
                                            <circle cx="9" cy="9" r="6"></circle>\
                                        </svg>\
                                    </div>\
                                    <span>' + $.lang[LANG]['config.form.date2.time.interval.60'] + '</span>\
                                </label>\
                            </div>\
                        </div>\
                        <div class="setting-row am">\
                            <div class="setting-label">' + $.lang[LANG]['config.form.date2.time.am'] + '</div>\
                            <div class="display-flex time-interval" data-time="am"></div>\
                        </div>\
                        <div class="setting-row">\
                            <div class="setting-label">' + $.lang[LANG]['config.form.date2.time.pm'] + '</div>\
                            <div class="display-flex time-interval" data-time="pm"></div>\
                        </div>\
                    </div>\
                </div>\
            ';
            break;
        case 'excludeDate':
            modal_title = $.lang[LANG]['config.form.date.excludeDate'];
            modal_str = '\
            <div class="except-calendar-box">\
                <div class="unselect-all hand"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16"><path d="m15.29 7-1.32 1.32c.01-.11.03-.21.03-.32 0-3.31-2.69-6-6-6-1.66 0-3.16.67-4.24 1.76l.71.71C5.37 3.56 6.62 3 8 3c2.76 0 5 2.24 5 5 0 .09-.02.18-.03.27L11.71 7l-.71.71 2.5 2.5 2.5-2.5-.71-.71z"/><path d="M8 13c-2.76 0-5-2.24-5-5 0-.09.02-.18.03-.27L4.29 9 5 8.29l-2.5-2.5L0 8.29.71 9l1.32-1.32C2.02 7.79 2 7.89 2 8c0 3.31 2.69 6 6 6 1.66 0 3.16-.67 4.24-1.76l-.71-.71C10.63 12.44 9.38 13 8 13z"/></svg> ' + $.lang[LANG]['config.form.date.excludeDate.clear'] + '</div>\
                <input type="hidden" id="select-calendar" value="etc-except-date-picker">\
                <input type="hidden" class="etc-date" id="etc-except-date" value="">\
                <input type="hidden" id="etc-start-date-txt" value="' + startDate + '">\
                <input type="hidden" id="etc-end-date-txt" value="' + endDate + '">\
                <input type="hidden" id="etc-date-week" value="' + dateWeek + '">\
                <input type="hidden" id="select-except-date" value="' + exceptDate + '">\
                <input type="hidden" id="term-days" value="' + term.days + '">\
                <div id="etc-except-date-picker"></div>\
            </div>\
            <div class="term-setting hide" data-blocklang="' + blocklang + '">\
                <span class="start-date"></span> ~ <span class="end-date"></span>\
            </div>\
            ';
            break;
        case 'time':
            modal_title = $.lang[LANG]['config.form.date2.time'];
            modal_class += ' setting-times';
            modal_str = '\
            <div class="guide-wrap">\
                <div class="display-flex align-items-center setting-row">\
                    <div class="setting-label">' + $.lang[LANG]['config.form.date2.time.interval.label'] + '</div>\
                    <div class="newcheckbox hand">\
                        <label>\
                            <div class="newcheckboxSvgRadio">\
                                <input type="radio" class="cl-common-form-radio-hide" name="time_interval" value="30" checked>\
                                <svg viewBox="0 0 18 18" width="18" height="18">\
                                    <path d="M9 0C4.03 0 0 4.03 0 9c0 4.97 4.03 9 9 9s9-4.03 9-9C18 4.03 13.97 0 9 0zM9 17c-4.41 0-8-3.59-8-8 0-4.41 3.59-8 8-8s8 3.59 8 8C17 13.41 13.41 17 9 17z"></path>\
                                </svg>\
                                <svg class="active" viewBox="0 0 18 18" width="18" height="18">\
                                    <path d="M9 0C4.03 0 0 4.03 0 9c0 4.97 4.03 9 9 9s9-4.03 9-9C18 4.03 13.97 0 9 0zM9 17c-4.41 0-8-3.59-8-8 0-4.41 3.59-8 8-8s8 3.59 8 8C17 13.41 13.41 17 9 17z"></path>\
                                    <circle cx="9" cy="9" r="6"></circle>\
                                </svg>\
                            </div>\
                            <span>' + $.lang[LANG]['config.form.date2.time.interval.30'] + '</span>\
                        </label>\
                    </div>\
                    <div class="newcheckbox hand">\
                        <label>\
                            <div class="newcheckboxSvgRadio">\
                                <input type="radio" class="cl-common-form-radio-hide" name="time_interval" value="60">\
                                <svg viewBox="0 0 18 18" width="18" height="18">\
                                    <path d="M9 0C4.03 0 0 4.03 0 9c0 4.97 4.03 9 9 9s9-4.03 9-9C18 4.03 13.97 0 9 0zM9 17c-4.41 0-8-3.59-8-8 0-4.41 3.59-8 8-8s8 3.59 8 8C17 13.41 13.41 17 9 17z"></path>\
                                </svg>\
                                <svg class="active" viewBox="0 0 18 18" width="18" height="18">\
                                    <path d="M9 0C4.03 0 0 4.03 0 9c0 4.97 4.03 9 9 9s9-4.03 9-9C18 4.03 13.97 0 9 0zM9 17c-4.41 0-8-3.59-8-8 0-4.41 3.59-8 8-8s8 3.59 8 8C17 13.41 13.41 17 9 17z"></path>\
                                    <circle cx="9" cy="9" r="6"></circle>\
                                </svg>\
                            </div>\
                            <span>' + $.lang[LANG]['config.form.date2.time.interval.60'] + '</span>\
                        </label>\
                    </div>\
                </div>\
                <div class="setting-row am">\
                    <div class="all-time">\
                        <input id="all-time-select" class="hide" type="checkbox" ' + allTimeChecked + '><label class="hand" for="all-time-select">' + $.lang[LANG]['config.form.date2.time.selectAll'] + '</label>\
                    </div>\
                    <div class="setting-label">' + $.lang[LANG]['config.form.date2.time.am'] + '</div>\
                    <div class="display-flex time-interval" data-time="am"></div>\
                </div>\
                <div class="setting-row">\
                    <div class="setting-label">' + $.lang[LANG]['config.form.date2.time.pm'] + '</div>\
                    <div class="display-flex time-interval" data-time="pm"></div>\
                </div>\
            </div>\
            ';
            break;
    }

    var settingModal = $(el).showModalFlat(modal_title, modal_str, true, true, function() { //confirm
        var postData = {};
        switch (func) {
            case 'term':
                if (!$('#etc-start-date-txt').val() || !$('#etc-end-date-txt').val()) {
                    alert('날짜 기간을 선택해주세요.');
                    return false;
                }
                var days = new Array();
                $('input[name="day"]:checked').each(function(i, v) {
                    days.push($(v).val());
                });
                postData = {
                    'term': {
                        'select_terms': 'Y',
                        'date_week': $('#etc-date-week').val(),
                        'start_date': $('#etc-start-date-txt').val(),
                        'end_date': $('#etc-end-date-txt').val(),
                        'days': (days.length > 0) ? days.join('|') : ''
                    }
                };

                startDate = $('#etc-start-date-txt').val();
                endDate = $('#etc-end-date-txt').val();

                if (field_type.indexOf('etc-product-date') > -1 && startDate && endDate) { //etc product
                    $('#etc-week').val($('#etc-date-week').val());
                    $('#etc-start-date').val(startDate);
                    $('#etc-end-date').val(endDate);
                    $('#etc-term').val(JSON.stringify(postData.term));
                    $('.term-setting .setting-text .content').text(startDate + ' ~ ' + endDate);
                }

                break;
            case 'saleStartDateTime':
            case 'saleEndDateTime':
                var selectedDate = $('#select-date-ymd').val();

                if (!selectedDate || $('.time-interval input:checked').length == 0) {
                    alert('날짜와 시간을 선택해주세요.');
                    return false;
                }

                if (!selectedDate || $('.time-interval input:checked').length == 0) {
                    alert('날짜와 시간을 선택해주세요.');
                    return false;
                }

                var mna = $('.time-interval input:checked').parent().attr('data-time');
                var selectedTime = convertTime24(mna, $('.time-interval input:checked').val());
                var saleDateTime = selectedDate + '. ' + convertTime12(selectedTime);
                var saleDateTimeVal = selectedDate.replace(/\./g, '-') + ' ' + selectedTime + ':00';
                console.log(selectedTime);
                if(func == 'saleStartDateTime') {
                    var startDateTime = new Date(saleDateTimeVal);
                    var currentDateTime = new Date();

                    if($('#sale-end-datetime').val()) {
                        var endDateTime = new Date($('#sale-end-datetime').val());
                        if(endDateTime <= startDateTime) {
                            startDateTime.setHours(startDateTime.getHours() + 1);
                            console.log(startDateTime);
                            var endDateTimeVal = convertDateObjToStr(startDateTime);
                            var endDateTime = endDateTimeVal.split(' ');

                            $('#sale-end-datetime').val(endDateTimeVal);
                            $('.sale-setting .setting-text .content-end').text(endDateTime[0] + '. ' + convertTime12(endDateTime[1]));
                        }
                    }
                    
                    $('.sale-setting .setting-text .content-start').text(saleDateTime);
                    $('#sale-start-datetime').val(saleDateTimeVal);
                } else {
                    var endDateTime = new Date(saleDateTimeVal);

                    if($('#sale-start-datetime').val()) {
                        var startDateTime = new Date($('#sale-start-datetime').val());
                        if(startDateTime >= endDateTime) {
                            alert('판매 시작 시간보다 나중 시간을 선택해 주세요.');
                            return false;
                        }
                    }

                    $('.sale-setting .setting-text .content-end').text(saleDateTime);
                    $('#sale-end-datetime').val(saleDateTimeVal);
                }

                break;
            case 'excludeDate':
                postData = {
                    'excludeDate': {
                        'date': $('#select-except-date').val(),
                    }
                };

                if (field_type.indexOf('etc-product-date') > -1) { //etc product
                    if ($('#select-except-date').val()) {
                        $('#etc-exclude-date').val($('#select-except-date').val());
                        $('.exclude-setting .setting-text .content').text($('#select-except-date').val());
                        $('.exclude-setting .setting-text').attr('data-toggle', 'tooltip');
                        $('.exclude-setting .setting-text').attr('data-original-title', "<div class='except-date-tooltip'>" + $('#select-except-date').val() + "</div>");
                    } else {
                        $('#etc-exclude-date').val('');
                        $('.exclude-setting .setting-text .content').text('');
                        $('.exclude-setting .setting-text').removeAttr('data-toggle');
                        $('.exclude-setting .setting-text').removeAttr('data-original-title');
                    }
                }
                break;
            case 'time':
                if ($('.time-interval input:checked').length == 0) {
                    alert($.lang[LANG]['config.form.date2.time.excludeAll']);
                    return false;
                }

                var interval = $('input[name="time_interval"]:checked').val();
                var am = new Array();
                var pm = new Array();
                $('input[name="am"]:checked').each(function(i, v) {
                    if (interval == '60' && $(v).hasClass('half-time')) {
                        return true;
                    }
                    am.push($(v).val());
                });
                $('input[name="pm"]:checked').each(function(i, v) {
                    if (interval == '60' && $(v).hasClass('half-time')) {
                        return true;
                    }
                    pm.push($(v).val());
                });
                postData = {
                    'time': {
                        'interval': interval,
                        'am': (am.length > 0) ? am.join('|') : '',
                        'pm': (pm.length > 0) ? pm.join('|') : '',
                    }
                };

                if (field_type.indexOf('etc-product-date') > -1) {
                    $('#etc-time').val(JSON.stringify(postData.time));
                }
                break;
        }
        // console.log(id, postData);
        // console.log('field_type', field_type);
        if (field_type.indexOf('etc-product-date') == -1 && field_type.indexOf('sale-product-datetime') == -1) { //form date
            var settings = {
                'type': 'val',
                'value': JSON.stringify(postData),
            }

            if (itemsAjax) itemsAjax.abort();
            itemsAjax = $.ajax({
                url: "/template/forms/items",
                async: true,
                type: "post",
                dataType: "json",
                data: {
                    sid: SID,
                    id: id,
                    field: field_type,
                    val_type: func,
                    settings: settings
                },
                success: function(data) {
                    checkError(data);
                    initDateTimeConf(SID, id, field_type);
                }
            });
        }


        // saveFormElement();
        settingModal.modal('hide');
    }, 'cancel', 'ok', modal_class, true, function() { //close
        if (func == 'term' && (!$('#etc-start-date-txt').val() || !$('#etc-end-date-txt').val())) {
            if (!$('#etc-start-date-prev').val() && !$('#etc-end-date-prev').val()) {
                $('input[name="select_terms-' + id + '"][value="N"]').prop('checked', true);
                $('.form-sort-item[data-id="' + id + '"] .setting-date2[data-setting="term"]').addClass('disabled');
            }
        }
        settingModal.modal('hide');
    }, function() { //show
        if (field_type.indexOf('etc-product-date') > -1) {
            startDate = $('#etc-start-date').val();
            endDate = $('#etc-end-date').val();
            lang = 'ko';
            $('#etc-start-date-txt').val(startDate);
            $('#etc-end-date-txt').val(endDate);
        }

        if (startDate && endDate) {
            var checkStartDate = startDate.split('.');
            var checkEndDate = endDate.split('.');

            $('.term-setting').removeClass('hide');
            if (blocklang == 'ko') {
                $('.term-setting .start-date').text(checkStartDate[0] + '년 ' + checkStartDate[1] + '월 ' + checkStartDate[2] + ' 일');
                $('.term-setting .end-date').text(checkEndDate[0] + '년 ' + checkEndDate[1] + '월 ' + checkEndDate[2] + ' 일');
            } else {
                $('.term-setting .start-date').text(checkStartDate[1] + '/' + checkStartDate[2] + '/' + checkStartDate[0]);
                $('.term-setting .end-date').text(checkEndDate[1] + '/' + checkEndDate[2] + '/' + checkEndDate[0]);
            }
        }
        // console.log(language);
        $('#term-datepicker').html('');
        var currentYear = new Date().getFullYear();
        switch (func) {
            case 'term':
                var termPicker = new Datepickk({
                    container: document.querySelector('#term-datepicker'),
                    inline: true,
                    range: true,
                    exp: false,
                    lang: language,
                    startDate: (startDate.replace(/\./g, '/')) ? new Date(startDate.replace(/\./g, '/')) : new Date(),
                    minDate: new Date(1900, 0, 1),
                    maxDate: new Date(currentYear + 15, 11, 31),
                });

                if (dateWeek) {
                    $('.btn-group.week label').removeClass('checked');
                    $('input[value="' + dateWeek + '"]').prop('checked', true);
                    $('input[value="' + dateWeek + '"]').closest('label').addClass('checked');
                    disabled = (days.length > 0) ? getDisabledDays(days) : [];
                    termPicker.disabledDays = (disabled.length > 0) ? disabled : null;
                }

                if (startDate && endDate) {
                    $('input[name="day"]').prop('checked', false);
                    $('input[name="day"]').closest('label').removeClass('checked');
                    termPicker.setSelectedDates(startDate, 'start');
                    termPicker.setSelectedDates(endDate, 'end');
                }

                if (days) {
                    $.each(days, function(i, v) {
                        $('input[value="' + v + '"]').prop('checked', true);
                        $('input[value="' + v + '"]').closest('label').addClass('checked');
                    });
                }
                $('input[name="week"]').on('change', function() {
                    var value = $(this).val();
                    $('#etc-date-week').val(value);
                    $('.btn-group.week label').removeClass('checked');
                    if ($(this).is(':checked')) $(this).closest('label').addClass('checked');
                    termPicker.disabledDays = null;
                    $('#etc-start-date-txt').val('');
                    $('#etc-end-date-txt').val('');
                    if (field_type.indexOf('etc-product-date') == -1) $('.term-setting').addClass('hide');
                    switch (value) {
                        case 'A':
                            $('input[name="day"]').prop('checked', true);
                            $('input[name="day"]').closest('label').addClass('checked');
                            termPicker.disabledDays = null;
                            break;
                        case 'W':
                            $('input[name="day"][value="sat"], input[name="day"][value="sun"]').prop('checked', false)
                            $('input[name="day"][value="sat"], input[name="day"][value="sun"]').closest('label').removeClass('checked');
                            $('input[name="day"]').not('[value="sat"],[value="sun"]').prop('checked', true);
                            $('input[name="day"]').not('[value="sat"],[value="sun"]').closest('label').addClass('checked');
                            termPicker.disabledDays = [0, 6];
                            break;
                        case 'K':
                            $('input[name="day"][value="sat"], input[name="day"][value="sun"]').prop('checked', true);
                            $('input[name="day"][value="sat"], input[name="day"][value="sun"]').closest('label').addClass('checked');
                            $('input[name="day"]').not('[value="sat"],[value="sun"]').prop('checked', false);
                            $('input[name="day"]').not('[value="sat"],[value="sun"]').closest('label').removeClass('checked');
                            termPicker.disabledDays = [1, 2, 3, 4, 5];
                            break;
                    }

                    termPicker.setSelectedDates($('#etc-start-date-txt').val(), 'start');
                    termPicker.setSelectedDates($('#etc-end-date-txt').val(), 'end');
                });

                $('input[name="day"]').on('change', function() {
                    if ($(this).is(':checked')) $(this).closest('label').addClass('checked');
                    else $(this).closest('label').removeClass('checked');

                    if ($('input[name="day"]:checked').length == 0) {
                        alert($.lang[LANG]['config.form.date.day.excludeAll']);
                        $(this).prop('checked', true);
                        $(this).closest('label').addClass('checked');
                        return false;
                    }

                    termPicker.disabledDays = null;
                    disabled = getDisabledDays();

                    termPicker.disabledDays = disabled;
                    termPicker.setSelectedDates($('#etc-start-date-txt').val(), 'start');
                    termPicker.setSelectedDates($('#etc-end-date-txt').val(), 'end');
                });
                break;
            case 'excludeDate':
                var disabled = null;
                if (dateWeek == 'W') {
                    disabled = [0, 6];
                } else if (dateWeek == 'K') {
                    disabled = [1, 2, 3, 4, 5];
                }
                if (days.length > 0) {
                    disabled = [0, 1, 2, 3, 4, 5, 6];
                    $.each(days, function(i, v) {
                        enableIdx = disabled.indexOf(daysObj[v]);
                        if (enableIdx > -1) {
                            disabled.splice(enableIdx, 1);
                        }
                    });
                }

                var exceptPicker = new Datepickk({
                    container: document.querySelector('#etc-except-date-picker'),
                    inline: true,
                    exp: true,
                    disabledDays: disabled,
                    lang: language,
                    minDate: new Date(1900, 0, 1),
                    maxDate: new Date(currentYear + 15, 11, 31),
                });

                exceptPicker.disabledDays = (disabled.length > 0) ? disabled : null;

                if (startDate && endDate) {
                    var checkStartDate = startDate.split('.');
                    var checkEndDate = endDate.split('.');

                    exceptPicker.minDate = new Date(Number(checkStartDate[0]), Number(checkStartDate[1]) - 1, Number(checkStartDate[2]));
                    exceptPicker.maxDate = new Date(Number(checkEndDate[0]), Number(checkEndDate[1]) - 1, Number(checkEndDate[2]));
                }

                displaySelectedDates();

                $('.unselect-all').on('click', function() {
                    $('#select-except-date').val('');
                    $('#etc-except-date-picker input').prop('checked', false);
                    $('#etc-except-date-picker input').removeClass('active');
                });

                break;
            case 'saleStartDateTime':
            case 'saleEndDateTime':
                var saleStartDateTime = $('#sale-start-datetime').val();
                var saleEndDateTime = $('#sale-end-datetime').val();
                startDate = saleStartDateTime.split(' ')[0];
                endDate = saleEndDateTime.split(' ')[0];
                var startTime = saleStartDateTime.split(' ')[1];
                var endTime = saleEndDateTime.split(' ')[1];

                var currentDateTime = new Date();
                currentDateTime.setDate(currentDateTime.getDate() - 1);
                // console.log('currentDateTime', currentDateTime, new Date());

                var datepickkObj = {
                    container: document.querySelector('#sale-datepicker'),
                    inline: true,
                    range: false,
                    exp: false,
                    lang: language,
                    startDate: (startDate)? startDate : currentDateTime,
                    minDate: currentDateTime,
                    maxDate: new Date(currentYear + 15, 11, 31),
                };
                
                if(func == 'saleStartDateTime') {
                    if(saleStartDateTime) {
                        $('#select-date-ymd').val(startDate.replace(/-/g, '.'));
                    } else {
                        $('.setting-sale-date').addClass('open');
                    }
                }
                console.log('currentDateTime', currentDateTime);
                if(func == 'saleEndDateTime') {
                    var datepickk_startDate = currentDateTime;

                    if(saleStartDateTime) {
                        datepickk_startDate = (new Date() > new Date(saleStartDateTime))? new Date() : new Date(saleStartDateTime.replace(/-/g, '/'));
                        console.log('datepickk_startDate', datepickk_startDate);
                        datepickk_startDate.setDate(datepickk_startDate.getDate() - 1);
                    }
                    if(saleEndDateTime) {
                        $('#select-date-ymd').val(endDate.replace(/-/g, '.'));
                        if(new Date() > new Date(saleEndDateTime)) {
                            datepickk_startDate = new Date();
                            datepickk_startDate.setDate(datepickk_startDate.getDate() - 1);
                        }
                    } else {
                        $('.setting-sale-date').addClass('open');
                    }

                    datepickkObj = {
                        container: document.querySelector('#sale-datepicker'),
                        inline: true,
                        range: false,
                        exp: false,
                        lang: language,
                        startDate: (endDate)? endDate : datepickk_startDate,
                        minDate: datepickk_startDate,
                        maxDate: new Date(currentYear + 15, 11, 31),
                    };
                }
                var termPicker = new Datepickk(datepickkObj);
                displaySelectedDates();
                
                $('.time-interval').each(function(i, v) {
                    var mna = $(v).data('time');
                    var times = '\
                        <input type="radio" id="' + mna + '-12-00" class="hide" name="sale_time" value="1200">\
                        <label for="' + mna + '-12-00">12:00</label>\
                        <input type="radio" id="' + mna + '-12-30" class="half-time hide" name="sale_time" value="1230">\
                        <label for="' + mna + '-12-30" class="half-time">12:30</label>\
                        \
                        <input type="radio" id="' + mna + '-1-00" class="hide" name="sale_time" value="0100">\
                        <label for="' + mna + '-1-00">1:00</label>\
                        <input type="radio" id="' + mna + '-1-30" class="half-time hide" name="sale_time" value="0130">\
                        <label for="' + mna + '-1-30" class="half-time">1:30</label>\
                        \
                        <input type="radio" id="' + mna + '-2-00" class="hide" name="sale_time" value="0200">\
                        <label for="' + mna + '-2-00">2:00</label>\
                        <input type="radio" id="' + mna + '-2-30" class="half-time hide" name="sale_time" value="0230">\
                        <label for="' + mna + '-2-30" class="half-time">2:30</label>\
                        \
                        <input type="radio" id="' + mna + '-3-00" class="hide" name="sale_time" value="0300">\
                        <label for="' + mna + '-3-00">3:00</label>\
                        <input type="radio" id="' + mna + '-3-30" class="half-time hide" name="sale_time" value="0330">\
                        <label for="' + mna + '-3-30" class="half-time">3:30</label>\
                        \
                        <input type="radio" id="' + mna + '-4-00" class="hide" name="sale_time" value="0400">\
                        <label for="' + mna + '-4-00">4:00</label>\
                        <input type="radio" id="' + mna + '-4-30" class="half-time hide" name="sale_time" value="0430">\
                        <label for="' + mna + '-4-30" class="half-time">4:30</label>\
                        \
                        <input type="radio" id="' + mna + '-5-00" class="hide" name="sale_time" value="0500">\
                        <label for="' + mna + '-5-00">5:00</label>\
                        <input type="radio" id="' + mna + '-5-30" class="half-time hide" name="sale_time" value="0530">\
                        <label for="' + mna + '-5-30" class="half-time">5:30</label>\
                        \
                        <input type="radio" id="' + mna + '-6-00" class="hide" name="sale_time" value="0600">\
                        <label for="' + mna + '-6-00">6:00</label>\
                        <input type="radio" id="' + mna + '-6-30" class="half-time hide" name="sale_time" value="0630">\
                        <label for="' + mna + '-6-30" class="half-time">6:30</label>\
                        \
                        <input type="radio" id="' + mna + '-7-00" class="hide" name="sale_time" value="0700">\
                        <label for="' + mna + '-7-00">7:00</label>\
                        <input type="radio" id="' + mna + '-7-30" class="half-time hide" name="sale_time" value="0730">\
                        <label for="' + mna + '-7-30" class="half-time">7:30</label>\
                        \
                        <input type="radio" id="' + mna + '-8-00" class="hide" name="sale_time" value="0800">\
                        <label for="' + mna + '-8-00">8:00</label>\
                        <input type="radio" id="' + mna + '-8-30" class="half-time hide" name="sale_time" value="0830">\
                        <label for="' + mna + '-8-30" class="half-time">8:30</label>\
                        \
                        <input type="radio" id="' + mna + '-9-00" class="hide" name="sale_time" value="0900">\
                        <label for="' + mna + '-9-00">9:00</label>\
                        <input type="radio" id="' + mna + '-9-30" class="half-time hide" name="sale_time" value="0930">\
                        <label for="' + mna + '-9-30" class="half-time">9:30</label>\
                        \
                        <input type="radio" id="' + mna + '-10-00" class="hide" name="sale_time" value="1000">\
                        <label for="' + mna + '-10-00">10:00</label>\
                        <input type="radio" id="' + mna + '-10-30" class="half-time hide" name="sale_time" value="1030">\
                        <label for="' + mna + '-10-30" class="half-time">10:30</label>\
                        \
                        <input type="radio" id="' + mna + '-11-00" class="hide" name="sale_time" value="1100">\
                        <label for="' + mna + '-11-00">11:00</label>\
                        <input type="radio" id="' + mna + '-11-30" class="half-time hide" name="sale_time" value="1130">\
                        <label for="' + mna + '-11-30" class="half-time">11:30</label>\
                        ';
                    $(v).html(times);
                }); //end each

                $('input[name="time_interval"][value="' + interval + '"]').prop('checked', true);

                if(func == 'saleStartDateTime' && saleStartDateTime) {
                    var hour = parseInt(startTime.split(':')[0]);
                    var minute = parseInt(startTime.split(':')[1]);
                    var mna = 'am';
                    if(hour >= 12) {
                        if (hour > 12) hour -= 12;
                        mna = 'pm';   
                    } else if (hour == 0) hour += 12
                    var formattedTime = hour.toString().padStart(2, '0') + minute.toString().padStart(2, '0');
                    $('.time-interval[data-time="' + mna + '"] input[value="' + formattedTime + '"]').prop('checked', true);
                    getDateTimeStr(language);
                }
 
                if(func == 'saleEndDateTime') {
                    if(saleStartDateTime && startDate == endDate) {
                        var hour = parseInt(startTime.split(':')[0]);
                        var minute = parseInt(startTime.split(':')[1]);
                        var mna = (hour >= 12)? 'pm' : 'am';

                        if(hour >= 12) {
                            if (hour > 12) hour -= 12;
                        } else if (hour == 0) hour += 12

                        var formattedStartTime = hour.toString().padStart(2, '0') + minute.toString().padStart(2, '0');
                        $('.time-interval[data-time="' + mna + '"] input[value="' + formattedStartTime + '"]').prop('disabled', true);
                        if(mna == 'pm') {
                            $('.time-interval[data-time="am"] input').prop('disabled', true);
                            $('.time-interval[data-time="pm"] input[value="' + formattedStartTime + '"]').prevAll('input').prop('disabled', true);
                        } else {
                            $('.time-interval[data-time="am"] input[value="' + formattedStartTime + '"]').prevAll('input').prop('disabled', true);
                        }
                    }
                    if(saleEndDateTime) {
                        var hour = parseInt(endTime.split(':')[0]);
                        var minute = parseInt(endTime.split(':')[1]);
                        var mna = 'am';
                        if(hour >= 12) {
                            if (hour > 12) hour -= 12;
                            mna = 'pm';   
                        } else if (hour == 0) hour += 12
                        var formattedTime = hour.toString().padStart(2, '0') + minute.toString().padStart(2, '0');
                        $('.time-interval[data-time="' + mna + '"] input[value="' + formattedTime + '"]').prop('checked', true);
                        getDateTimeStr(language);
                    }
                }

                var time_interval = $('input[name="time_interval"]:checked').val();
                if (time_interval == 60) {
                    $('.time-interval label.half-time').addClass('hide');
                } else { //30
                    $('.time-interval label.half-time').removeClass('hide');
                }

                $('input[name="time_interval"]').on('change', function() {
                    if ($(this).val() == 60) {
                        $('.time-interval label.half-time').addClass('hide');
                        if ($('#all-time-select').is(':checked')) {
                            $('.time-interval input:not(.half-time)').prop('checked', true);
                        }
                    } else { //30
                        $('.time-interval label.half-time').removeClass('hide');
                        if ($('#all-time-select').is(':checked')) {
                            $('.time-interval input').prop('checked', true);
                        }
                    }
                });

                $('.time-interval input').on('change', function(){
                    getDateTimeStr(language, 'time');
                });

                $('.sale-calendar-box .setting-label').on('click', function(){
                    var $saleCalendarBox = $(this).closest('.sale-calendar-box');

                    if($saleCalendarBox.hasClass('open')) {
                        $('.sale-calendar-box .setting-datetime-input').slideUp(400, function(){
                            $('.sale-calendar-box').removeClass('open');
                        });
                    } else{
                        $('.sale-calendar-box .setting-datetime-input').slideUp(400, function(){
                            $('.sale-calendar-box').removeClass('open');
                        });

                        $saleCalendarBox.find('.setting-datetime-input').slideDown(400, function(){
                            $saleCalendarBox.addClass('open');
                        });
                    }
                });

                break;
            case 'time':
                $('.time-interval').each(function(i, v) {
                    var mna = $(v).data('time');
                    var times = '\
                        <input type="checkbox" id="' + mna + '-12-00" class="hide" name="' + mna + '" value="1200">\
                        <label for="' + mna + '-12-00">12:00</label>\
                        <input type="checkbox" id="' + mna + '-12-30" class="half-time hide" name="' + mna + '" value="1230">\
                        <label for="' + mna + '-12-30" class="half-time">12:30</label>\
                        \
                        <input type="checkbox" id="' + mna + '-1-00" class="hide" name="' + mna + '" value="0100">\
                        <label for="' + mna + '-1-00">1:00</label>\
                        <input type="checkbox" id="' + mna + '-1-30" class="half-time hide" name="' + mna + '" value="0130">\
                        <label for="' + mna + '-1-30" class="half-time">1:30</label>\
                        \
                        <input type="checkbox" id="' + mna + '-2-00" class="hide" name="' + mna + '" value="0200">\
                        <label for="' + mna + '-2-00">2:00</label>\
                        <input type="checkbox" id="' + mna + '-2-30" class="half-time hide" name="' + mna + '" value="0230">\
                        <label for="' + mna + '-2-30" class="half-time">2:30</label>\
                        \
                        <input type="checkbox" id="' + mna + '-3-00" class="hide" name="' + mna + '" value="0300">\
                        <label for="' + mna + '-3-00">3:00</label>\
                        <input type="checkbox" id="' + mna + '-3-30" class="half-time hide" name="' + mna + '" value="0330">\
                        <label for="' + mna + '-3-30" class="half-time">3:30</label>\
                        \
                        <input type="checkbox" id="' + mna + '-4-00" class="hide" name="' + mna + '" value="0400">\
                        <label for="' + mna + '-4-00">4:00</label>\
                        <input type="checkbox" id="' + mna + '-4-30" class="half-time hide" name="' + mna + '" value="0430">\
                        <label for="' + mna + '-4-30" class="half-time">4:30</label>\
                        \
                        <input type="checkbox" id="' + mna + '-5-00" class="hide" name="' + mna + '" value="0500">\
                        <label for="' + mna + '-5-00">5:00</label>\
                        <input type="checkbox" id="' + mna + '-5-30" class="half-time hide" name="' + mna + '" value="0530">\
                        <label for="' + mna + '-5-30" class="half-time">5:30</label>\
                        \
                        <input type="checkbox" id="' + mna + '-6-00" class="hide" name="' + mna + '" value="0600">\
                        <label for="' + mna + '-6-00">6:00</label>\
                        <input type="checkbox" id="' + mna + '-6-30" class="half-time hide" name="' + mna + '" value="0630">\
                        <label for="' + mna + '-6-30" class="half-time">6:30</label>\
                        \
                        <input type="checkbox" id="' + mna + '-7-00" class="hide" name="' + mna + '" value="0700">\
                        <label for="' + mna + '-7-00">7:00</label>\
                        <input type="checkbox" id="' + mna + '-7-30" class="half-time hide" name="' + mna + '" value="0730">\
                        <label for="' + mna + '-7-30" class="half-time">7:30</label>\
                        \
                        <input type="checkbox" id="' + mna + '-8-00" class="hide" name="' + mna + '" value="0800">\
                        <label for="' + mna + '-8-00">8:00</label>\
                        <input type="checkbox" id="' + mna + '-8-30" class="half-time hide" name="' + mna + '" value="0830">\
                        <label for="' + mna + '-8-30" class="half-time">8:30</label>\
                        \
                        <input type="checkbox" id="' + mna + '-9-00" class="hide" name="' + mna + '" value="0900">\
                        <label for="' + mna + '-9-00">9:00</label>\
                        <input type="checkbox" id="' + mna + '-9-30" class="half-time hide" name="' + mna + '" value="0930">\
                        <label for="' + mna + '-9-30" class="half-time">9:30</label>\
                        \
                        <input type="checkbox" id="' + mna + '-10-00" class="hide" name="' + mna + '" value="1000">\
                        <label for="' + mna + '-10-00">10:00</label>\
                        <input type="checkbox" id="' + mna + '-10-30" class="half-time hide" name="' + mna + '" value="1030">\
                        <label for="' + mna + '-10-30" class="half-time">10:30</label>\
                        \
                        <input type="checkbox" id="' + mna + '-11-00" class="hide" name="' + mna + '" value="1100">\
                        <label for="' + mna + '-11-00">11:00</label>\
                        <input type="checkbox" id="' + mna + '-11-30" class="half-time hide" name="' + mna + '" value="1130">\
                        <label for="' + mna + '-11-30" class="half-time">11:30</label>\
                        ';
                    $(v).html(times);
                }); //end each

                $('input[name="time_interval"][value="' + interval + '"]').prop('checked', true);
                if (am) {
                    $.each(am, function(i, v) {
                        $('.time-interval[data-time="am"] input[value="' + v + '"]').prop('checked', true);
                    });
                }
                if (pm) {
                    $.each(pm, function(i, v) {
                        $('.time-interval[data-time="pm"] input[value="' + v + '"]').prop('checked', true);
                    });
                }

                var time_interval = $('input[name="time_interval"]:checked').val();
                if (time_interval == 60) {
                    $('.time-interval label.half-time').addClass('hide');
                } else { //30
                    $('.time-interval label.half-time').removeClass('hide');
                }

                $('input[name="time_interval"]').on('change', function() {
                    if ($(this).val() == 60) {
                        $('.time-interval label.half-time').addClass('hide');
                        if ($('#all-time-select').is(':checked')) {
                            $('.time-interval input:not(.half-time)').prop('checked', true);
                        }
                    } else { //30
                        $('.time-interval label.half-time').removeClass('hide');
                        if ($('#all-time-select').is(':checked')) {
                            $('.time-interval input').prop('checked', true);
                        }
                    }
                });

                $('#all-time-select').change(function() {
                    var time_interval = $('input[name="time_interval"]:checked').val();
                    if ($(this).is(':checked')) {
                        if (time_interval == 60) {
                            $('.time-interval input:not(.half-time)').prop('checked', true);
                        } else {
                            $('.time-interval input').prop('checked', true);
                        }
                    } else {
                        $('.time-interval input').prop('checked', false);
                    }
                });

                break;
        }

        $(document).off('click', '.d-year, .d-month');
        $(document).on('click', '.d-year, .d-month', function() {
            $('.d-month-year-picker').toggleClass('d-show');
            scrollToCurrentYearMonth();
        });
    }, function() { //hide
        if (func == 'term' && (!$('#etc-start-date-txt').val() || !$('#etc-end-date-txt').val())) {
            if (!$('#etc-start-date-prev').val() && !$('#etc-end-date-prev').val()) {
                $('input[name="select_terms-' + id + '"][value="N"]').prop('checked', true);
                $('.form-sort-item[data-id="' + id + '"] .setting-date2[data-setting="term"]').addClass('disabled');
            }
        }
        settingModal.modal('hide');
    });
}

function convertTime24(mna, timeString) {
    var hour = parseInt(timeString.substring(0, 2));
    var minute = timeString.substring(2);
    console.log(timeString, minute);
    if (mna == 'am' && hour == 12) {
        hour -= 12;
    }
    if (mna == 'pm' && hour !== 12) {
        hour += 12;
    }

    var formattedHour = hour.toString().padStart(2, '0');

    return formattedHour + ':' + minute;
}

function convertTime12(timeString) {
    var hour = parseInt(timeString.split(':')[0]);
    var minute = parseInt(timeString.split(':')[1]);
    var mna = 'am';
    if(hour >= 12) {
        if (hour > 12) hour -= 12;
        mna = 'pm';   
    } else if (hour == 0) hour += 12;
    var formattedTime = $.lang[LANG]['config.form.date2.time.' + mna] + ' ' + hour.toString().padStart(2, '0') + ':' +  minute.toString().padStart(2, '0');

    return formattedTime;
}

function convertDateObjToStr(dateObj) {
    var year = dateObj.getFullYear();
    var month = ("0" + (dateObj.getMonth() + 1)).slice(-2);
    var day = ("0" + dateObj.getDate()).slice(-2);
    var hours = ("0" + dateObj.getHours()).slice(-2);
    var minutes = ("0" + dateObj.getMinutes()).slice(-2);
    var seconds = ("0" + dateObj.getSeconds()).slice(-2);
    var formattedDate = year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
    return formattedDate;
}

var changeStatus = function(status,seq) {
    if(status == 'lim') return '';
    var s = '\
    <span class="status-change"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-caret-down-fill" viewBox="0 0 16 16"><path d="M7.247 11.14 2.451 5.658C1.885 5.013 2.345 4 3.204 4h9.592a1 1 0 0 1 .753 1.659l-4.796 5.48a1 1 0 0 1-1.506 0z"/></svg></span>\
    <ul class="table-item-status" data-seq="' + seq + '">\
        <li class="' + ((status == 'on') ? 'active' : '') + '" data-val="on">판매중</li>\
        <li class="' + ((status == 'off' || status == '') ? 'active' : '') + '" data-val="off">판매중지</li>\
    </ul>\
    ';
    return s;
}

var makeLinkUrl = function(link, one, view) {
    var link_url = '',
        link_val = '',
        is_menu = ($.inArray(link.replace(/^\//g, '').replace(/ /g, '-'), MENULIST) > -1) ? true : false,
        regex = /^(((http(s?))\:\/\/)?)([0-9a-zA-Z\-]+\.)+[a-zA-Z]{2,7}(\:[0-9]+)?(\/\S[^\{\}]*)?$/,
        regex2 = /^((http(s?))\:\/\/)([0-9a-zA-Z\-]+\.)+[a-zA-Z]{2,7}(\:[0-9]+)?(\/\S[^\{\}]*)?$/;

    if (one) {
        link_url = (view) ? '/' + CONFIG_URL + 'config/page/view/index#' : '#';
        if (is_menu) link_url = '/';
    } else {
        link_url = (is_menu) ? '/' : '/' + CONFIG_URL + 'config/page/';
    }

    if (link) {
        if (link.match(/^\@/g) !== null) { // link-type: link-bookmark ==> a[attr-bookmark]
            var bookmark_seq = link.replace(/^\@/g, '');
            if (typeof SETTINGS.blockBookmarkList == 'undefined' || typeof SETTINGS.blockBookmarkList['bookmark' + bookmark_seq] == 'undefined') {
                return '';
            }
        } else if (link.match(/^flink\@[0-9]/gi) !== null) { // link-type: link-file     ==> a[attr-flink]
            return link;
        } else if ($.inArray(link.replace(/^\//g, '').replace(/ /g, '-'), MENULIST) > -1) { // link-type: link-menu     ==> a[data-user-link]
            link_val = link_url + link.replace(/ /g, '-');
        } else { // link-type: link-out      ==> a[attr-link]
            if(checkBase64Encode(decodeURIComponent(link))) link = Base64.decode(decodeURIComponent(link));
            else if (checkBase64Encode(link)) link = Base64.decode(link);

            if(!regex2.test(link) && regex.test(link)) link_val = '//' + link;
        }

        if(link_val == '') link_val = link;
    }
    return link_val;
}

var makeLinkList = function(e, type, id, prev_link) {
    // console.log('makeLinkList');
    // console.log('type: '+type);
    // console.log('id: '+id);
    // console.log('prev_link: '+prev_link);
    // type: editor -  id : text, button, image
    var valid_plan = (typeof VALIDPLAN == 'undefined') ? $.gallery.valid_plan : VALIDPLAN,
        valid_type = (typeof VALIDTYPE == 'undefined') ? $.gallery.valid_type : VALIDTYPE;

    var link_content = ((type == 'gallery')) ? '' : '<ul class="link-content edit-link-Content" data-type="' + type + '" data-name="' + id + '">',
        link_icon = { 'menu': 'active', 'bookmark': 'active', 'flink': (valid_plan && valid_type != 'PK') ? 'active' : 'inactive', 'imagePopup': (valid_plan && valid_type != 'PK') ? 'active' : 'inactive' },
        link_disabled = { 'submenu': '', 'bookmark': '', 'flink': (valid_plan && valid_type != 'PK') ? '' : 'disabled', 'imagePopup': (valid_plan && valid_type != 'PK') ? '' : 'disabled' },
        isDefault = '',
        isOut = '',
        isFolder = '',
        isInner = '',
        isBookmark = '',
        isFlink = '',
        isPopup = '',
        out_link = '',
        flink_link = {},
        popup_link = {},
        org_prev_link = (prev_link) ? prev_link : '';

    if (prev_link.match(/^\@/g) !== null) {
        isBookmark = 'active';
    } else if (prev_link.match(/^flink\@[0-9]/gi) !== null) {
        if (valid_plan) {
            $.getJSON('/down/flink/get/id/' + prev_link.replace(/^flink\@/gi, ''), {}, function(data) {
                checkError(data);

                if (typeof data.data == 'object' && !$.isEmptyObject(data.data)) {
                    isFlink = 'active';
                    flink_link = data.data;
                } else {
                    prev_link = '';
                }
            }, 'json');
        } else {
            prev_link = '';
        }
    } else if (prev_link.indexOf('googleusercontent') !== -1 || prev_link.indexOf('storage.googleapis.com/cr-resource/image') !== -1){
        isPopup = (valid_plan)? 'active':'';
    } else {
        if (type == 'menu') {
            if (prev_link == id) { isDefault = 'active'; } else if (MENULIST.includes(prev_link.replace(/ /g, '-'))) { isInner = 'active'; } else if (prev_link == 'folder-menu') { isFolder = 'active'; } else {
                isOut = 'active';
                if(checkBase64Encode(decodeURIComponent(prev_link))) out_link = Base64.decode(decodeURIComponent(prev_link));
                else out_link = decodeURI(prev_link.replace(/%27/g, '&#39;')).replace(/\"/g, '&#34;');
            }
        }

        if ($.inArray(type, ['image', 'gallery', 'popup', 'popupbanner', 'bandbanner', 'fnav', 'showcase', 'editor']) > -1) {
            var check_menu_str = (type == 'editor') ? prev_link.replace(/^\//g, '') : prev_link;
            if (prev_link == '') {
                if (type == 'fnav' || (type == 'editor' && id == 'text')) { 
                    isOut = 'active'; 
                } else { 
                    isDefault = 'active'; 
                }
            } else if (MENULIST.includes(check_menu_str.replace(/ /g, '-'))) { 
                isInner = 'active'; 
        } else {
                isOut = 'active';
                if(checkBase64Encode(decodeURIComponent(prev_link))) out_link = Base64.decode(decodeURIComponent(prev_link));
                else out_link = decodeURI(prev_link.replace(/%27/g, '&#39;')).replace(/\"/g, '&#34;');
            }
        }
    }
    var one = (typeof ONE == 'undefined') ? $.gallery.one : ONE;
    var temp = (type == 'menu') ? 'editor.link.inner.select.menu' : (one) ? 'editor.link.inner.select.page.1' : 'editor.link.inner.select.page.0',
        select_menu_str = (isInner) ? prev_link : $.lang[LANG][temp],
        select_menu_selected = '';

    var site_smenu = (typeof SMENU == 'undefined') ? $.gallery.SMENU : SMENU;
    var menulist_val = makeMenuLinkList(site_smenu, type, id, prev_link),
        isList = true;

    if (menulist_val.length == 0) {
        select_menu_str = $.lang[LANG]['editor.link.inner.empty'];
        isList = false;
        link_disabled['submenu'] = 'disabled';
        if (type == 'menu') {
            isInner = (isInner == 'active') ? '' : isInner;
            isFolder = (isFolder == 'active') ? '' : isFolder;
            link_icon['menu'] = 'inactive';
        }
    }

    var isBookmarkList = true,
        select_bookmark_str = $.lang[LANG]['editor.link.bookmark.select'],
        select_bookmark_selected = '',
        bookmarklist_val = makeBookmarkList(SETTINGS.blockBookmarkList, type, id, org_prev_link);

    var blockBookmarkList = (typeof SETTINGS.blockBookmarkList != 'undefined' && SETTINGS.blockBookmarkList) ? SETTINGS.blockBookmarkList : {},
        hideArray = (typeof blockBookmarkList.hide == 'undefined' || !blockBookmarkList.hide) ? {} : blockBookmarkList.hide,
        bookmark_orgprev_link = org_prev_link.replace('@', '');

    if (bookmarklist_val.length == 0) {
        if (isBookmark == 'active') {
            isBookmark = '';
            isDefault = 'active';
            select_menu_str = $.lang[LANG][temp];
        }
        isBookmarkList = false;
        link_disabled['bookmark'] = 'disabled';
        link_icon['bookmark'] = 'inactive';
        select_bookmark_str = $.lang[LANG]['editor.link.bookmark.empty'];
    } else {
        if (typeof SETTINGS.blockBookmarkList[org_prev_link.replace(/^\@/g, 'bookmark')] != 'undefined' && SETTINGS.blockBookmarkList[org_prev_link.replace(/^\@/g, 'bookmark')]) {
            select_bookmark_str = SETTINGS.blockBookmarkList['bookmark' + org_prev_link.replace(/^\@/g, '')];
            select_bookmark_selected = ' data-link-seq="' + org_prev_link.replace(/^\@/g, '') + '"';
        } else {
            if (isBookmark == 'active') {
                isBookmark = '';
                isDefault = 'active';
                prev_link = $.lang[LANG][temp];
            }
        }
    }

    if (hideArray.length > 0) {
        if (hideArray.includes(bookmark_orgprev_link)) {
            isBookmark = '';
            isDefault = 'active';
        }
    }

    // if($('.' + selectEL).attr('data-img-parallax') == 'true') {
    //     link_disabled['imagePopup'] = 'disabled';
    //     link_icon['imagePopup'] = 'inactive';
    //     if(isPopup == 'active') {
    //         isPopup = '';
    //         isDefault = 'active';
    //     }
    // }

    if (type == 'menu') {
        if (isDefault == '' && isOut == '' && isInner == '' && isBookmark == '' && isFlink == '' && isFolder == '') { isDefault = 'active'; }
    }
    if (type == 'showcase') {
        if (isDefault == '' && isOut == '' && isInner == '' && isBookmark == '') { isDefault = 'active'; }
    }
    if ($.inArray(type, ['gallery', 'popup', 'popupbanner', 'bandbanner']) > -1) {
        if (isDefault == '' && isOut == '' && isInner == '' && isBookmark == '' && isFlink == '') { isDefault = 'active'; }
    }
    if (type == 'image') {
        if (isDefault == '' && isOut == '' && isInner == '' && isBookmark == '' && isFlink == '' && isPopup == '') { isDefault = 'active'; }
    }
    if (type == 'fnav') {
        if (isOut == '' && isInner == '' && isBookmark == '') { isOut = 'active'; }
    }
    if (type == 'editor') {
        if (isOut == '' && isInner == '' && isBookmark == '' && isFlink == '') {
            if (id == 'text') { isOut = 'active'; } else if (id == 'button' || id == 'image') { isDefault = 'active'; }
        }
    }

    var link_deafult_text = {
        'menu': $.lang[LANG]['editor.link.default'],
        'gallery': $.lang[LANG]['editor.link.default'],
        'image': $.lang[LANG]['editor.link.default.image'],
        'popup': $.lang[LANG]['editor.link.default.popup'],
        'popupbanner': $.lang[LANG]['editor.link.default.popupbanner'],
        'bandbanner': $.lang[LANG]['editor.link.default.bandbanner'],
        'showcase': $.lang[LANG]['editor.link.default.showcase'],
        'editor': $.lang[LANG]['editor.link.default.editor'],
    };

    link_content += (type == 'fnav' || (type == 'editor' && id == 'text')) ? '' : '\
            <li class="link-type ' + isDefault + '">\
                <div class="link-default">\
                    ' + clSVG('checkbox_active',20,20,false) + '\
                    <h5>' + link_deafult_text[type] + '</h5>\
                </div>\
            </li>\
    ';

    link_content += '\
            <li class="link-type ' + isOut + '">\
                <div class="link-out">\
                    ' + clSVG('checkbox_active',20,20,false) + '\
                    <h5>' + $.lang[LANG]['editor.link.out'] + '</h5>\
                    <div class="cl-common-form-wrap nonplace-holder">\
                        <div class="cl-common-form-group">\
                            <input type="text" class="link-input" placeholder="' + $.lang[LANG]['editor.link.input.info'] + '" value="' + out_link + '">\
                        </div>\
                    </div>\
                </div>\
            </li>\
    ';

    if (type == 'menu') {
        link_content += '\
            <li class="link-type ' + isInner + ' ' + link_disabled['submenu'] + '">\
                <div class="link-inner">\
                    ' + clSVG('checkbox_'+link_icon['menu'],20,20,false) + '\
                    <h5>' + $.lang[LANG]['editor.link.inner'] + '</h5>\
                    <div class="group-wrap">\
                        <div class="input-group">\
                            <div class="inner-toggle btn btn-sm dropdown-toggle ' + link_disabled['submenu'] + '" data-toggle="dropdown">\
                                <span class="select-link">' + select_menu_str + '</span>';
        if (isList) link_content += '<svg viewBox="0 0 8 4" width="8" height="4" class="hand"><polygon points="0 0 4 4 8 0 "/></svg>';
        link_content += '\
                            </div>\
                            <ul class="dropdown-menu link-innerlist" role="menu">\
                                ' + menulist_val + '\
                            </ul>\
                        </div>\
                    <div>\
                </div>\
            </li>\
        ';
    }

    if ($.inArray(type, ['image', 'gallery', 'popup', 'popupbanner', 'bandbanner', 'fnav', 'showcase', 'editor']) > -1) {
        var lang_text = 'editor.link.inner.menu';
        if (isInner && type == 'image' && $('<ul>' + menulist_val + '</ul>').children('li[data-userlink="' + prev_link + '"]').length == 0) {
            $('<ul>' + menulist_val + '</ul>').children().each(function() {
                if ($(this).attr('data-userlink').replace(/ /g, '-') == prev_link.replace(/ /g, '-')) {
                    prev_link = $(this).attr('data-userlink');
                }
            });
        }


        var select_inner_str = (isInner && type == 'editor') ? prev_link.replace(/\//g, '') : select_menu_str,
            select_inner_selected = (isInner) ? ' data-link-val="' + prev_link.replace(/\//g, '') + '"' : '';

        link_content += '\
            <li class="link-type ' + isInner + ' ' + link_disabled['submenu'] + '">\
                <div class="link-menu">\
                    ' + clSVG('checkbox_active',20,20,false) + '\
                    <h5>' + $.lang[LANG][lang_text] + '</h5>\
                    <svg class="cm-popover-info hand" viewBox="0 0 13 13" width="13" height="13" tabindex="0" data-toggle="popover" data-trigger="focus" data-html="true" data-placement="top" data-content="' + $.lang[LANG]['editor.link.inner.menu.info'] + '">\
                        <path d="M6.5 0C2.91 0 0 2.91 0 6.5S2.91 13 6.5 13 13 10.09 13 6.5 10.09 0 6.5 0zM6.5 12C3.47 12 1 9.53 1 6.5S3.47 1 6.5 1 12 3.47 12 6.5 9.53 12 6.5 12z"/>\
                        <rect x="6" y="9" width="1" height="1"/>\
                        <path d="M6.66 3.01C5.61 3.01 4.58 3.5 4.5 4.8c0 0.06-0.01 0.12 0 0.2h1.02c0-0.07 0.01-0.15 0.02-0.23 0.08-0.62 0.52-0.76 1.08-0.76 0.63 0 1.02 0.37 1.02 0.95 -0.01 0.48-0.3 0.87-0.76 1.34C6.21 6.97 6.02 7.37 6 8h0.99C7 7.66 7.04 7.37 7.67 6.75 8.17 6.27 8.7 5.68 8.7 4.87 8.7 3.85 7.89 3.01 6.66 3.01z"/>\
                    </svg>\
                    <div class="group-wrap">\
                        <div class="btn-group">\
                            <div class="inner-toggle btn btn-sm dropdown-toggle ' + link_disabled['submenu'] + '" data-toggle="dropdown">\
                                <span class="select-link" ' + select_inner_selected + '>' + select_inner_str + '</span>';
        if (isList) link_content += '<svg viewBox="0 0 8 4" width="8" height="4" class="hand"><polygon points="0 0 4 4 8 0 "/></svg>';
        link_content += '\
                            </div>\
                            <ul class="dropdown-menu link-innerlist" role="menu">\
                                ' + menulist_val + '\
                            </ul>\
                        </div>\
                    </div>\
                </div>\
            </li>\
        ';
    }

    link_content += '\
            <li class="link-type ' + isBookmark + ' ' + link_disabled['bookmark'] + '">\
                <div class="link-bookmark">\
                    ' + clSVG('checkbox_'+link_icon['bookmark'],20,20,false) + '\
                    <h5>' + $.lang[LANG]['editor.link.bookmark'] + '</h5>\
                    <svg class="cm-popover-info hand" viewBox="0 0 13 13" width="13" height="13" tabindex="0" data-toggle="popover" data-trigger="focus" data-html="true" data-placement="top" data-content="' + $.lang[LANG]['editor.link.bookmark.info'] + '">\
                        <path d="M6.5 0C2.91 0 0 2.91 0 6.5S2.91 13 6.5 13 13 10.09 13 6.5 10.09 0 6.5 0zM6.5 12C3.47 12 1 9.53 1 6.5S3.47 1 6.5 1 12 3.47 12 6.5 9.53 12 6.5 12z"/>\
                        <rect x="6" y="9" width="1" height="1"/>\
                        <path d="M6.66 3.01C5.61 3.01 4.58 3.5 4.5 4.8c0 0.06-0.01 0.12 0 0.2h1.02c0-0.07 0.01-0.15 0.02-0.23 0.08-0.62 0.52-0.76 1.08-0.76 0.63 0 1.02 0.37 1.02 0.95 -0.01 0.48-0.3 0.87-0.76 1.34C6.21 6.97 6.02 7.37 6 8h0.99C7 7.66 7.04 7.37 7.67 6.75 8.17 6.27 8.7 5.68 8.7 4.87 8.7 3.85 7.89 3.01 6.66 3.01z"/>\
                    </svg>\
                    <div class="group-wrap">\
                        <div class="btn-group">\
                            <div class="bookmark-toggle btn btn-sm dropdown-toggle inner-toggle ' + link_disabled['bookmark'] + '" data-toggle="dropdown">\
                                <span class="select-bookmark" ' + select_bookmark_selected + '>' + select_bookmark_str + '</span>\
    ';

    if (isBookmarkList) link_content += '<svg viewBox="0 0 8 4" width="8" height="4" class="hand"><polygon points="0 0 4 4 8 0 "/></svg>';
    link_content += '\
                            </div>\
                            <ul class="dropdown-menu link-bookmarklist" role="bookmark">\
                                ' + bookmarklist_val + '\
                            </ul>\
                        </div>\
                    </div>\
                </div>\
            </li>\
    ';

    if ($.inArray(type, ['menu', 'image', 'gallery', 'popup', 'popupbanner', 'bandbanner', 'editor']) > -1) {
        var service = (typeof SERVICE == 'undefined') ? $.gallery.service : SERVICE;
        var flink_popover_str = (service.indexOf('gabia') > -1) ? $.lang[LANG]['editor.link.file.info.gabia'] : $.lang[LANG]['editor.link.file.info'],
            flink_s = Number(flink_link.size),
            flink_unit = (flink_s > 1024) ? 'unit_m' : '',
            flink_size = (flink_s > 1024) ? flink_s / 1024 : flink_s;

        if(LUX) flink_popover_str = $.lang[LANG]['editor.link.file.info.lux'];

        link_content += '\
            <li class="link-type ' + isFlink + ' ' + link_disabled['flink'] + ' flink">\
                <div class="link-file">\
                    ' + clSVG('checkbox_'+link_icon['flink'],20,20,false) + '\
                    <h5>' + $.lang[LANG]['editor.link.file'] + '<svg class="cm-popover-info hand ' + LANG + '" viewBox="0 0 13 13" width="13" height="13" tabindex="0" data-toggle="popover" data-trigger="focus" data-html="true" data-placement="top" data-content="' + flink_popover_str + '">\
                        <path d="M6.5 0C2.91 0 0 2.91 0 6.5S2.91 13 6.5 13 13 10.09 13 6.5 10.09 0 6.5 0zM6.5 12C3.47 12 1 9.53 1 6.5S3.47 1 6.5 1 12 3.47 12 6.5 9.53 12 6.5 12z"/>\
                        <rect x="6" y="9" width="1" height="1"/>\
                        <path d="M6.66 3.01C5.61 3.01 4.58 3.5 4.5 4.8c0 0.06-0.01 0.12 0 0.2h1.02c0-0.07 0.01-0.15 0.02-0.23 0.08-0.62 0.52-0.76 1.08-0.76 0.63 0 1.02 0.37 1.02 0.95 -0.01 0.48-0.3 0.87-0.76 1.34C6.21 6.97 6.02 7.37 6 8h0.99C7 7.66 7.04 7.37 7.67 6.75 8.17 6.27 8.7 5.68 8.7 4.87 8.7 3.85 7.89 3.01 6.66 3.01z"/>\
                    </svg></h5>\
                    <div class="group-wrap">\
        ';
        var valid_plan = (typeof VALIDPLAN == 'undefined') ? $.gallery.valid_plan : VALIDPLAN,
            valid_type = (typeof VALIDTYPE == 'undefined') ? $.gallery.valid_type : VALIDTYPE;

        link_content += (valid_plan && valid_type != 'PK') ? '\
                        <div class="btn-group">\
                            <span class="btn btn-sm fileinput-button flink-add">\
                              ' + clSVG('paperclip', '16', '16', false, '') + '\
                              <span> ' + $.lang[LANG]['editor.link.file.btn'] + '</span>\
                            </span>\
                        </div>\
                        <span class="prop-flink-ctrl ' + isFlink + '">\
                            <span class="flink-info" ' + ((isFlink) ? 'data-id="' + flink_link.seq + '"' : '') + '>\
                                <span class="flink-name">' + ((isFlink) ? flink_link.name : '') + '</span>\
                                <span class="flink-size ' + flink_unit + '">' + ((isFlink) ? flink_size.toFixed(0) : '') + '</span>\
                            </span>\
                            <span class="hand flink-cancel"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="10" height="10"><path d="M8.71 8l7.15-7.15c0.2-0.2 0.2-0.51 0-0.71s-0.51-0.2-0.71 0L8 7.29 0.85 0.15c-0.2-0.2-0.51-0.2-0.71 0s-0.2 0.51 0 0.71L7.29 8l-7.15 7.15c-0.2 0.2-0.2 0.51 0 0.71C0.24 15.95 0.37 16 0.5 16s0.26-0.05 0.35-0.15L8 8.71l7.15 7.15c0.1 0.1 0.23 0.15 0.35 0.15s0.26-0.05 0.35-0.15c0.2-0.2 0.2-0.51 0-0.71L8.71 8z"></path></svg></span>\
                        </span>\
        ' : '\
                        <div class="btn-group">\
                            <span class="btn btn-sm btn-flink-upgrade">\
                              ' + clSVG('paperclip', '16', '16', false, '') + '\
                              <span> ' + $.lang[LANG]['editor.link.file.btn'] + '</span>\
                            </span>\
                        </div>\
                        <!--<div class="btn-group">\
                            <a class="btn btn-sm btn-flink-upgrade" href="' + ((SERVICE.indexOf('gabia') > -1) ? '//www.gabia.com/mygabia/service" target="_blank' : '/upgrade/site/') + '">\
                              <svg viewBox="0 0 18 18" width="18" height="18"><polygon points="9 0 1 8 5 8 5 11 13 11 13 8 17 8 "/><rect x="5" y="13" width="8" height="2"/><rect x="5" y="17" width="8" height="1"/></svg>\
                              <span> ' + $.lang[LANG]['dashbord.toolbar.upgrade-site'] + '</span>\
                            </a>\
                        </div>-->\
        ';
        link_content += '\
                  </div>\
                </div>\
            </li>\
        ';
    }

    if (type == 'image') {
        var popup_popover_str = (SERVICE.indexOf('gabia') > -1) ? $.lang[LANG]['editor.link.imagePopup.info.gabia'] : $.lang[LANG]['editor.link.imagePopup.info'];
        var popup_info = prev_link.split('||');
        var popupLink = popup_info[0];
        var popupName = popup_info[1];

        link_content += '\
            <li class="link-type ' + isPopup + ' ' + link_disabled['imagePopup'] + ' imagePopup">\
                <div class="link-popup">\
                    ' + clSVG('checkbox_'+link_icon['imagePopup'],20,20,false) + '\
                    <h5>' + $.lang[LANG]['editor.link.imagePopup'] + '<svg class="cm-popover-info hand ' + LANG + '" viewBox="0 0 13 13" width="13" height="13" tabindex="0" data-toggle="popover" data-trigger="focus" data-html="true" data-placement="top" data-content="' + popup_popover_str + '">\
                        <path d="M6.5 0C2.91 0 0 2.91 0 6.5S2.91 13 6.5 13 13 10.09 13 6.5 10.09 0 6.5 0zM6.5 12C3.47 12 1 9.53 1 6.5S3.47 1 6.5 1 12 3.47 12 6.5 9.53 12 6.5 12z"/>\
                        <rect x="6" y="9" width="1" height="1"/>\
                        <path d="M6.66 3.01C5.61 3.01 4.58 3.5 4.5 4.8c0 0.06-0.01 0.12 0 0.2h1.02c0-0.07 0.01-0.15 0.02-0.23 0.08-0.62 0.52-0.76 1.08-0.76 0.63 0 1.02 0.37 1.02 0.95 -0.01 0.48-0.3 0.87-0.76 1.34C6.21 6.97 6.02 7.37 6 8h0.99C7 7.66 7.04 7.37 7.67 6.75 8.17 6.27 8.7 5.68 8.7 4.87 8.7 3.85 7.89 3.01 6.66 3.01z"/>\
                    </svg></h5>\
                    <div class="group-wrap">\
        ';

        link_content += (VALIDPLAN && VALIDTYPE != 'PK') ? '\
                        <div class="btn-group">\
                            <span class="btn btn-sm fileinput-button popupImage-add">\
                                ' + clSVG('file-image', '13', '13', false, '') + '\
                                <span> ' + $.lang[LANG]['editor.link.imagePopup.btn'] + '</span>\
                            </span>\
                        </div>\
                        <span class="prop-popup-ctrl ' + isPopup + '">\
                            <span class="popup-info" ' + ((isPopup) ? 'data-popup="' + prev_link + '"' : '') + '>\
                                <span class="popup-name">' + ((isPopup) ? popupName : '') + '</span>\
                            </span>\
                            <span class="hand popup-cancel"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="10" height="10"><path d="M8.71 8l7.15-7.15c0.2-0.2 0.2-0.51 0-0.71s-0.51-0.2-0.71 0L8 7.29 0.85 0.15c-0.2-0.2-0.51-0.2-0.71 0s-0.2 0.51 0 0.71L7.29 8l-7.15 7.15c-0.2 0.2-0.2 0.51 0 0.71C0.24 15.95 0.37 16 0.5 16s0.26-0.05 0.35-0.15L8 8.71l7.15 7.15c0.1 0.1 0.23 0.15 0.35 0.15s0.26-0.05 0.35-0.15c0.2-0.2 0.2-0.51 0-0.71L8.71 8z"></path></svg></span>\
                        </span>\
        ' : '\
                        <div class="btn-group">\
                            <span class="btn btn-sm btn-popup-upgrade">\
                                ' + clSVG('file-image', '13', '13', false, '') + '\
                                <span> ' + $.lang[LANG]['editor.link.imagePopup.btn'] + '</span>\
                            </span>\
                        </div>\
        ';
        link_content += '\
                  </div>\
                </div>\
            </li>\
        ';
    }

    if (type == 'menu') {
        link_content += '\
            <li class="link-type ' + isFolder + ' ' + link_disabled['submenu'] + '">\
                <div class="link-folder">' + clSVG('checkbox_'+link_icon['menu'],20,20,false) + '\
                    <h5>' + $.lang[LANG]['editor.link.folder'] + '</h5>\
                </div>\
            </li>\
        ';
    }
    if (type == 'editor') return { 'str': link_content, 'display': select_menu_str };
    else return link_content;
}

var makeMenuLinkList = function(s, type, id, prev_link) {
    // console.log(s);
    // console.log('type: '+type+', id: '+id+', prev_link: '+prev_link);
    var depth = 0,
        str = '',
        isActive = '';
    if (type == 'menu') {
        menu = function(level, depth) {
            $.each(level, function(idx, obj) {
                if (obj.name == id && obj.children.length > 0) menu(obj.children, depth + 1);
                if (depth != 0) {
                    isActive = (prev_link == obj.name) ? 'active' : '';
                    str = str + '<li data-userlink="' + obj.name + '" class="' + isActive + '"><a href="javascript:;">' + obj.name + '</a></li>';
                }
            });
            return str;
        }
        return menu(s, depth);
    }
    if ($.inArray(type, ['image', 'gallery', 'popup', 'popupbanner', 'bandbanner', 'fnav', 'showcase', 'editor']) > -1) {
        menu = function(level, depth) {
            $.each(level, function(idx, obj) {
                var check_menu_str = (type == 'editor') ? prev_link.replace(/^\//g, '') : prev_link;
                isActive = (check_menu_str.replace(/ /g, '-') == obj.name.replace(/ /g, '-')) ? 'active' : '';
                var onoff = (obj.display == 'on') ? '' : ' off';
                if (depth == 0) {
                    str = str + '<li data-userlink="' + obj.name + '" class="' + isActive + onoff + '"><a href="javascript:;">' + obj.name + '</a></li>';
                } else {
                    str = str + '\
                    <li data-userlink="' + obj.name + '" class="' + isActive + '">\
                        <a href="javascript:;"><i class="fa fa-level-up"></i>' + obj.name + '</a>\
                    </li>';
                }

                if (obj.children) menu(obj.children, depth + 1);
            });
            return str;
        }
        return menu(s, depth);
    }
};
$('.menu-edit-cancel').live('click', function() {
    menuEdit = false;
    menu_edit_cancel();
});

var menu_edit_cancel = function() {
    if ($('#nestable > .dd-list').children().last().prev().attr('data-id') == 'menu-added') {
        $('#nestable > .dd-list').children().last().prev().remove();
    } else {
        $('.menu-edit-cancel').parents('.menu-edit-text').hide();
    }
    $('#menu-add').show();
}

$(document)
    .on('click', '.flink-cancel', function(e) {
        var flinkConfig = $(this).closest('.prop-flink-ctrl');
        flinkConfig.removeClass('active');
        flinkConfig.find('.flink-info').removeAttr('data-id');
        flinkConfig.find('.flink-name,.flink-size').empty();
    })
    .on('click', '.flink-add', function(e) {
        var block_el = (typeof editEL == 'undefined') ? $.gallery.block_el : editEL;
    
        if(typeof editEL != 'undefined') {
            menuConfigToggle('close');
            siteConfigToggle('close');
        }
        var block_el = (typeof editEL == 'undefined') ? $.gallery.block_el : editEL;
        $('.g-body .text-menu').removeClass('active').addClass('hide');
        if (typeof fr_editor != 'undefined' && fr_editor != '') $(fr_editor.popups.get('link.insert')).addClass('allways');
        $('.resource-useit')
            .attr('data-property', 'flink-change')
            .attr('data-element', '.' + block_el)
            .attr('data-replace-count', 1)
            .removeAttr('data-ctrl')
            .removeAttr('data-idx')
            .removeAttr('data-seq')
            .removeAttr('data-col');
        selectCount = 1;

        $('#el-fileupload').modal('show');
    });

var setFileLink = function() {
    var selectedFlink = $('#filestorage .fitem.selected'),
        selected = (selectedFlink.length > 0) ? true : false,
        selected_count = (selected) ? 1 : 0,
        obj = (selected) ? {
            'name': selectedFlink.find('p.fitem-name').text(),
            'size': selectedFlink.find('p.fitem-size .size').attr('data-size'),
            'seq': selectedFlink.find('p.fitem-name').attr('data-seq'),
            'file': selectedFlink.find('p.fitem-name').attr('data-source'),
        } : {};

    var flinkConfig = $('.link-file .prop-flink-ctrl'),
        flink_s = Number(obj.size.replace(',', '')),
        flink_unit = (flink_s > 1024) ? 'unit_m' : '',
        flink_size = (flink_s > 1024) ? flink_s / 1024 : flink_s;

    flinkConfig.find('.flink-info .flink-name').text(obj.name);
    flinkConfig.find('.flink-info .flink-size').text(flink_size.toFixed(0));
    if (flink_unit) flinkConfig.find('.flink-info .flink-size').addClass('unit_m');
    else flinkConfig.find('.flinkflink-info .flink-size').removeClass('unit_m');
    flinkConfig.find('.flink-info').attr('data-id', obj.seq);
    flinkConfig.addClass('active');
    selectCount = 0;
    $('#el-fileupload').modal('hide');
}


$('.link-type').live({
    click: function(e) {
        if ($(e.target).is('a') && $(e.target).hasClass('upgrade-link')) return;
        if ($(this).hasClass('disabled')) {
            $('.link-type').find('.linkguidetext').remove();
            var link_type = $(this).children('div[class*="link-"]').attr('class').replace(/^link-/gi, ''),
                guide_str = (link_type == 'inner' || link_type == 'folder') ? $.lang[LANG]['editor.link.inner.guide'] : $.lang[LANG]['editor.link.bookmark.guide'];
            if (link_type == 'file') {
                guide_str = (SERVICE.indexOf('gabia') > -1) ? $.lang[LANG]['editor.link.file.upgrade.gabia'] : $.lang[LANG]['editor.link.file.upgrade'];
            } else if (link_type == 'popup') {
                if(!VALIDPLAN || VALIDTYPE == 'PK') {
                    guide_str = (SERVICE.indexOf('gabia') > -1) ? $.lang[LANG]['editor.link.imagePopup.upgrade.gabia'] : $.lang[LANG]['editor.link.imagePopup.upgrade'];
                } else {
                    guide_str = '' ;
                    return;
                }
            }

            $(this).append('<p class="linkguidetext edit-link-error">' + clSVG('info', 13, 13) + guide_str + '</p>');
            return;
        }

        if ($(this).closest('.link-content[data-type="popup"]').length > 0 && $(this).children('.link-default').length > 0) $('#popup-linktarget-onoff').removeAttr('checked');
        $('.link-type').find('.linkguidetext').remove();
        $(this).parent().children().removeClass('active');
        $(this).addClass('active');

        if($(this).children().attr('class') == 'link-default' || $(this).children().attr('class') == 'link-file' || $(this).children().attr('class') == 'link-popup') {
            $('#linktarget-onoff').prop('checked', false);
            $('#linktarget-onoff').closest('.newcheckbox').addClass('disabled');
        } else {
            $('#linktarget-onoff').closest('.newcheckbox').removeClass('disabled');
        }
    }
});

var getInputLink = function(type) {
    var link = '',
        isOkay = true,
        isActive = true,
        //regex = /([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w_\.-]*)/ig;
        regex = /^(((http(s?))\:\/\/||\/\/)?)([0-9a-zA-Z\-]+\.)+[a-zA-Z]{2,7}(\:[0-9]+)?(\/\S[^\{\}]*)?$/, //http://do doesn't
        regex2 = /^((http(s?))\:\/\/||\/\/)([0-9a-zA-Z\-\_]+\.)+[a-zA-Z]{2,7}(\:[0-9]+)?(\/\S[^\{\}]*)?$/; //http://do
        regex3 = /^(https?:\/\/||\/\/)?(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9][a-z0-9-]{0,61}[a-z0-9]/, // add punycode
        regexKR = /^(https?:\/\/||\/\/)?((([a-z\d](([a-z\d-]*[a-z\d]))|([ㄱ-힣])*)\.)+(([a-zㄱ-힣]{2,}))|((\d{1,3}\.){3}\d{1,3}))(\:\d+)?(\/[-a-z\d%_.~+]*)*(\?[;&a-z\d%_.~+=-]*)?(\#[-a-z\d_]*)?$/,
        regexTel = /^tel\:[0-9-+]+$/;

    function showInputLinkError(linktype, error) {
        $('.link-content').find('.linkguidetext').remove();
        var activeLinkConfig = $('.link-content').find('.' + linktype),
            error_class = 'linkguidetext edit-link-error',
            error_txt = '';

        if (error == 'empty') {
            error_txt = $.lang[LANG]['editor.link.empty.' + linktype.replace('link-', '')];
        } else {
            if (linktype == 'link-out') {
                $('.link-input').focus();
                if (error == 'config') error_class = 'linkguidetext modal-layout';
                error_txt = (error == 'emoji') ? $.lang[LANG]['config.unable.emoji'] : $.lang[LANG]['editor.menu.input-link.' + error];
            }
        }

        if (typeof error_txt == 'undefined' || error_txt.length == 0) return false;
        else activeLinkConfig.after('<p class="' + error_class + '">' + clSVG('info', 13, 13) + error_txt + '</p>');
    }

    switch (type) {
        case 'link-default':
            link = '';
            isActive = false;
            break;

        case 'link-out':
            link = $('.link-input').val().trim();
            isOkay = false;
            var error_str = '';

            if (link == '') { //input value empty
                showInputLinkError(type, 'info');

                // $('.link-input').focus();
                // if($('.link-out').find('.linkguidetext').length == 0) $('.link-out').prepend('<span class="linkguidetext"><i class="fa fa-exclamation-circle"></i>' + $.lang[LANG]['editor.menu.input-link.info'] + '</span>');
            } else if (link != '') {
                if (checkEmojis(link)) {
                    showInputLinkError(type, 'emoji');
                } else if (link.match('^(tel:|mailto:|sms:)') !== null) {
                    isOkay = true;
                } else if (!regex2.test(link)) {
                    if (regex.test(link)) {
                        isOkay = true;
                    } else if (regex3.test(link) || regexKR.test(link)) {
                        isOkay = true;
                        var check_protocol = /^(http(s?)\:\/\/|\/\/?)/;
                        if (!check_protocol.test(link)) link = '//' + link;
                    } else if (regexTel.test(link)) {
                        isOkay = true;
                    } else {
                        showInputLinkError(type, 'info');
                        // $('.link-input').focus();
                        // if($('.link-out').find('.linkguidetext').length == 0) $('.link-out').prepend('<span class="linkguidetext"><i class="fa fa-exclamation-circle"></i>' + $.lang[LANG]['editor.menu.input-link.info'] + '</span>');
                    }
                } else {
                    // if($('.link-out').find('.linkguidetext').length > 0) $('.link-out').find('.linkguidetext').remove();
                    isOkay = true;
                }
            }

            if (isOkay) {
                if (link.match(/\/config/gi) !== null && link.match(/creatorlink/gi) !== null) {
                    isOkay = false;
                    showInputLinkError(type, 'config');
                } else {
                    $('.linkguidetext').remove();
                }

                if(checkBase64Encode(decodeURIComponent(link))) link = Base64.decode(decodeURIComponent(link));
                link = encodeURIComponent(Base64.encode(link));

            }
            break;

        case 'link-inner':
        case 'link-menu':
            var select_menu = $('.link-innerlist').find('.active');
            isOkay = false;
            if (select_menu.length > 0) {
                link = select_menu.first().attr('data-userlink');
                isOkay = true;

                $('.linkguidetext').remove();
            } else {
                showInputLinkError(type, 'empty');
            }
            break;

        case 'link-bookmark':
            var select_bookmark = $('.link-bookmarklist').find('.active');
            isOkay = false;
            if (select_bookmark.length > 0) {
                link = select_bookmark.first().attr('data-bookmark').replace('bookmark', '\@');
                isOkay = true;

                $('.linkguidetext').remove();
            } else {
                showInputLinkError(type, 'empty');
            }
            break;

        case 'link-folder':
            link = 'folder-menu';
            break;

        case 'link-file':
            var ctrl_flink = $('.link-file').find('.prop-flink-ctrl'),
                select_flink = ctrl_flink.find('.flink-info');
            isOkay = false;
            if (typeof select_flink.attr('data-id') != 'undefined' && select_flink.attr('data-id')) {
                link = 'flink@' + select_flink.attr('data-id');
                isOkay = true;

                $('.linkguidetext').remove();
            } else {
                showInputLinkError(type, 'empty');
            }
            break;
        case 'link-popup':
            var ctrl_popup = $('.link-popup').find('.prop-popup-ctrl'),
                select_popup = ctrl_popup.find('.popup-info');
            isOkay = false;
            if (typeof select_popup.attr('data-popup') != 'undefined' && select_popup.attr('data-popup')) {
                link = select_popup.attr('data-popup');
                isOkay = true;

                $('.linkguidetext').remove();
            } else {
                showInputLinkError(type, 'empty');
            }
            break;
        default:
            break;
    }

    var result = [link, isOkay, isActive];
    return result;
}

var getElementType = function() {
    var type = '',
        block_el = (typeof selectEL == 'undefined') ? $.gallery.block_el : selectEL;
    switch (block_el) {
        case 'el-menu':
            type = 'MENU';
            break;
        case 'el-footer':
            type = 'FOOT';
            break;
        default:
            type = 'ELEM';
            break;
    }
    return type;
}

$('.link-innerlist li').live({
    click: function(e) {
        $('.link-innerlist li').removeClass('active');
        $(this).addClass('active');
        var select_userlink = $(this).attr('data-userlink');
        $('.link-content .dropdown-toggle .select-link').text(select_userlink).attr('data-link-val', select_userlink);
    }
});


var fixedConfigBtn = function() {
    var parentDocument = $(window.parent.document),
        $detail_modal = parentDocument.find('.product-detail-modal');
    
    if (typeof selectEL == 'undefined' || !selectEL || $('header.navbar').length == 0 && $detail_modal.length == 0) return false;
    var $configEl = $('.' + selectEL + '_ctrl > .config-element');
    var $configTmp = $('.' + selectEL + '_ctrl > .config-template');
    var $galleryDetail = $('.' + selectEL + '_ctrl > .galleryDetail');
    var $navbar = ($detail_modal.length) ? $('.dsgn-body') : $('header.navbar');
    var checkSidebar = $('.dsgn-body').hasClass('sidebar');
    var headerOffset = (!checkSidebar) ? $navbar.outerHeight() + Math.ceil($navbar.offset().top) : Math.ceil($navbar.offset().top) + 15;
    var btnOffset = (typeof $('.' + selectEL + '_ctrl').offset() != 'undefined') ? $('.' + selectEL + '_ctrl').offset().top : 0;
    var topPos = (!checkSidebar) ? headerOffset + 15 : Math.ceil($navbar.offset().top) + 15;
    var distance = (headerOffset - btnOffset) / 2;
    var remain = $('.' + selectEL).height() + btnOffset - headerOffset;

    $configEl.removeClass('fixed-ctrl').attr('style', '');
    $configTmp.removeClass('fixed-ctrl').attr('style', '');
    $galleryDetail.removeClass('fixed-ctrl').attr('style', '');

    if($detail_modal.length) {
        topPos = $('.openBandBanner').length ? 163 : 23;
        distance = 0;
    }

    $('body').find(`.addElementButton, .config-element-section`).removeClass('zindex19');
    if (selectEL != 'el-menu' && selectEL != 'el-footer') {
        var checkHTMLScroll = ($('body').is('.off-config[data-gjs="fixedscroll2"]')) ? true : false;
        if (distance > 0 && remain >= 37 || checkHTMLScroll) {
            var s_top = ($('body').hasClass('off-config')) ? $('html').scrollTop() : $('.dsgn-body').scrollTop(),
                unset_top = (checkHTMLScroll) ? $('html').scrollTop() : 0;
            if (s_top == 0 && $navbar.hasClass('transparent') && selectEL == 'el_0') {
                var config_t = headerOffset + 10;
                config_t -= unset_top;
                $configEl.css('top', config_t + 'px');
                $configTmp.css('top', config_t + 'px');
            } else {
                topPos -= unset_top;
                $configEl.addClass('fixed-ctrl').css('top', topPos + 'px');
                $configTmp.addClass('fixed-ctrl').css('top', topPos + 'px');
                $galleryDetail.addClass('fixed-ctrl').css('top', topPos + 'px');
            }
        } else {
            $configEl.removeClass('fixed-ctrl').attr('style', '');
            $configTmp.removeClass('fixed-ctrl').attr('style', '');
            $galleryDetail.removeClass('fixed-ctrl').attr('style', '');

            if( selectEL != 'el-menu' &&
                $('html').scrollTop() == 0 && 
                $('.el-menu .cl-menu-option[data-moption="ntoggle"]').hasClass('open')
            ) {
                $('body').find(`.addElementButton.add${selectEL}, .${selectEL}_ctrl.config-element-section`).addClass('zindex19');
            }
        }
    }
}

var educationModal = function(edu_seq,type,data='') {
    var row = '', temp_cont = '', temp_review = '';
    var popup_svg = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 14 10" width="14" height="10"><path d="m5.77 9.49-5-5 1.42-1.41 3.58 3.59L12.36.08l1.41 1.41z"/></svg>';

    if(type=='list') {
        $.ajax({
            url:'/main/eduData/type/getData',
            type:'post',
            dataType:'json',
            async: false,
            data:{ 'seq' : edu_seq,'type':'list' },
            success:function(data) {
                row = data.data;
                temp_cont = JSON.parse(data.modal_data.replace('\\', ''));
                temp_review =  JSON.parse(data.review_data.replace('\\', ''));
            }
        });
    } else {
        $.ajax({
            url:'/adm/edu/eduEvent/type/getData',
            type:'post',
            dataType:'json',
            async: false,
            data:{ 'seq' : data.edu_temp_idx,'type':'update',data:data },
            success:function(data) {
                row = data.data;
                temp_cont = JSON.parse(data.modal_data.replace('\\', ''));
                temp_review =  JSON.parse(data.review_data.replace('\\', ''));
            }
        });
    }

    var tp_review = (typeof temp_review == 'undefined' || !temp_review) ? false : true ,
        tp_target = (typeof temp_cont.target_cont == 'undefined' || !temp_cont.target_cont) ? false : true ,
        tp_curri = (typeof temp_cont.curri_cont == 'undefined' || !temp_cont.curri_cont) ? false : true;
    var edu_url = "", edu_btn_text = "", btn_active = "active";
    if(row.edu_list_closed) {
        edu_url = "";
        edu_btn_text = "접수마감";
        btn_active = "disabled";
    } else {
        edu_url = "window.open('"+ row.edu_url +"')";
        edu_btn_text = row.edu_btn_text;
    }

    var help_url = 'https://www.creatorlink.net/help';

    var edu_level = ($.isNumeric(temp_cont.guide_level)) ? '<li class="level" data-level="'+temp_cont.guide_level+'">난이도 : <span><span class="level1">입문</span> - <span class="level2">초급</span> - <span class="level3">중급</span> - <span class="level4">고급</span></span></li>'
    : '<li class="level" data-level="">난이도 : '+temp_cont.guide_level+'</li>';

    var edu_header = '\
        <div class="edu_head_wrap">\
            <div class="edu_head_img only-pc" style="background-image: url(\''+temp_cont.head_pc+'\');"></div>\
            <div class="edu_head_img not-pc" style="background-image: url(\''+temp_cont.head_m+'\');"></div>\
            <div class="main-title">\
                '+temp_cont.pc_title+'\
            </div>\
            <div class="edu_head_m not-pc">\
                <div class="guide">\
                    <ul class="note">\
                        <li>일시 : '+ row.edu_popupDate +'</li>\
                        <li>강의 시간 : '+temp_cont.guide_time+'</li>\
                        '+edu_level+'\
                        <li>가격 : '+temp_cont.guide_pay+'</li>\
                        <li>강의 종류 : '+temp_cont.guide_cate+'</li>\
                    </ul>\
                    <ul class="notice">\
                        <li>접속 링크는 신청 메일 및 <span>교육 1일 전 개별 알림톡</span> 전달</li>\
                        <li>강의실 입장 링크는 <span>수강 신청 시 입력하신 메일 주소로 발송</span>됩니다.</li>\
                    </ul>\
                </div>\
            </div>\
        </div>\
    ';

    var summary_list = '';
    $.each(temp_cont.intro_summary,function(i,v) {
        summary_list += '<p>'+popup_svg+' '+v+'</p>';
    });

    var edu_intro = '\
        <section id="intro" class="">\
            <div class="teacher">\
                    <div class="text not-pc">\
                        <p class="title">'+ temp_cont.intro_title +'</p>\
                    </div>\
                    <div class="photo">\
                        <img src="'+ temp_cont.intro_pc_img +'" class="img-responsive only-pc">\
                        <img src="'+ temp_cont.intro_m_img +'" class="img-responsive not-pc">\
                    </div>\
                    <div class="text">\
                        <p class="title small only-pc">'+ temp_cont.intro_title +'</i></p>\
                        <p class="text">'+ temp_cont.intro_text +'</p>\
                        <p class="text name">'+ temp_cont.intro_name +'</p>\
                    </div>\
            </div>\
            <div class="line">\
                <p class="title">'+ temp_cont.intro_summary_title +'</p>\
                <div class="content">\
                    '+summary_list+'\
                </div>\
            </div>\
        </section>\
    ';

    var target_list = '';

    if(tp_target) {
    $.each(temp_cont.target_cont,function(i,v) {
        target_list += '<p>'+popup_svg+' '+v+'</p>';
    });
    }

    var edu_target = (tp_target) ? '\
        <section id="target" class="">\
            <div class="">\
                <p class="title">'+temp_cont.target_title+'</i></p>\
                <div class="content">\
                    '+target_list+'\
                </div>\
            </div>\
        </section>\
        ' : '' ;

    if(tp_curri) {
    var curri_list = '';
    $.each(temp_cont.curri_cont,function(i,v) {
        var collapse = (i==0) ? '' : 'collapsed';
        var col_in = (i==0) ? 'in' : '';
        var col_toggle = 'collapse';
        var curri_svg = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16"><path d="m14.3 5.21-.7-.71-5.3 5.3-5.29-5.3-.71.71 5.3 5.29.7.71.71-.71z"/></svg>';
        var curri_cont_list = '';
        $.each(v.content,function(i,v) {
            curri_cont_list += '<p>'+v+'</p>';
        });

        if((temp_cont.curri_cont.length-1 == i)) {
            curri_svg ='';
            col_toggle = '';
        }

        curri_list += '\
            <div class="panel-heading '+collapse+'" data-toggle="'+col_toggle+'" href="#collapse'+i+'" aria-expanded="false" aria-controls="collapse'+i+'">\
                <h4 class="panel-title">\
                    '+v.title+'\
                    '+curri_svg+'\
                </h4>\
            </div>\
            <div id="collapse'+i+'" class="panel-collapse collapse '+col_in+' multi-collapse">\
                <div class="panel-body">\
                    '+curri_cont_list+'\
                </div>\
            </div>\
        ';
    });
    }
    
    var edu_curri = (tp_curri) ? '\
        <section id="curriculum" class="">\
            <div class="">\
                <p class="title">'+temp_cont.curri_title+'</p>\
                <div class="panel-group" id="curriaccordion">\
                    <div class="panel panel-default">\
                    '+curri_list+'\
                    </div>\
                </div>\
            </div>\
        </section>\
        ' : '' ;

    var edu_etc = '\
        <section id="etc" class="">\
            <div class="" id="info1">\
                <p class="title">강의를 위해 필요한 <i>준비물</i></p>\
                <div class="content">\
                    <p>'+popup_svg+' 데스크탑 PC <span class="red">(권장)</span> / 노트북</p>\
                    <p>'+popup_svg+' 크롬 브라우저</p>\
                    <p>'+popup_svg+' 필기도구</p>\
                </div>\
            </div>\
            <div class="line" id="info2">\
                <p class="title">온라인 교육 안내 사항</p>\
                <div class="content">\
                    <p>'+popup_svg+' 강의실 입장 링크는 수강 신청하며 <b>입력하신 메일 주소로 발송</b>됩니다.</p>\
                    <p>'+popup_svg+' 교육 시간 <b>20분 전부터 입장이 가능</b>합니다.</p>\
                    <p>'+popup_svg+' 1개 아이디로 <b>중복 참여는 불가능</b>합니다.</p>\
                    <p>'+popup_svg+' 강의 관련 문의는 <a href="'+help_url+'"><u>1:1 문의</u></a>에 남겨주세요.</p>\
                </div>\
            </div>\
        </section>\
        ';
    var edu_review = (tp_review) ? '\
        <section id="review" class="">\
            <div class="">\
                <p class="point">New</p>\
                <p class="title">먼저 수강한 분들의<br><i>후기를 들어보세요!</i></p>\
                <div class="review-list">\
                </div>\
                <div class="review-btn hand">\
                  <span>수강평 더보기</span>\
                </div>\
            </div>\
        </section>\
        ' : '' ;

    var edu_sticky = '\
        <div class="edu_content_right sticky">\
            <div class="sticky">\
                <div class="btn-order hand '+ btn_active +'" onclick="' + edu_url + '">'+ edu_btn_text +'</div>\
                <div class="guide">\
                    <ul class="note">\
                        <li>일시 : '+ row.edu_popupDate +'</li>\
                        <li>강의 시간 : '+temp_cont.guide_time+'</li>\
                        '+edu_level+'\
                        <li>가격 : '+temp_cont.guide_pay+'</li>\
                        <li>강의 종류 : '+temp_cont.guide_cate+'</li>\
                    </ul>\
                    <ul class="notice">\
                        <li>접속 링크는 신청 메일 및 <span>교육 1일 전 개별 알림톡</span> 전달</li>\
                        <li>강의실 입장 링크는 <span>수강 신청 시 입력하신 메일 주소로 발송</span>됩니다.</li>\
                    </ul>\
                </div>\
            </div>\
        </div>\
    ';
    var edu_review_tab = (tp_review) ? '<li class="hand" data-menulink="review">후기<span class="point">New</span></li>' : '';
    var edu_target_tab = (tp_target) ? '<li class="hand" data-menulink="target">강의 대상</li>' : '<li class="hand" data-menulink="info1">준비물</li>';
    var edu_curri_tab = (tp_curri) ? '<li class="hand" data-menulink="curriculum">커리큘럼</li>' : '<li class="hand" data-menulink="info2">교육안내</li>';


    var edu_html = '\
        <div class="education_detail">\
            <div class="edu_wrap">\
                '+edu_header+'\
                <div class="edu_content">\
                    <div class="edu_content_left">\
                        <div class="edu_tab">\
                            <ul>\
                                <li class="hand active" data-menulink="intro">강의소개</li>\
                                '+edu_target_tab+'\
                                '+edu_curri_tab+'\
                                '+edu_review_tab+'\
                            </ul>\
                        </div>\
                        <div class="edu_section">\
                            '+edu_intro+'\
                            '+edu_target+'\
                            '+edu_curri+'\
                            '+edu_etc+'\
                            '+edu_review+'\
                        </div>\
                    </div>\
                    '+edu_sticky+'\
                </div>\
            </div>\
        </div>\
    ';
    
    var modal = $(this).showModalFlat('', edu_html, true, false, '', 'close', '', 'guidePopup cl-cmmodal cl-s-btn cover education-modal', false, '', function() {
        $.guidePopup.scrollevent(); 

        modal.find('.edu_tab li').off('click').on('click', function(e) {
        var target = $(this).attr('data-menulink');

        var top = ($(this).index())+1,
            hsize = (window.innerWidth <= 768) ? 34 : 55,
            tab_pos = (window.innerWidth <= 768) ? $('#'+target).position().top + $('.edu_head_wrap').outerHeight() : $('#'+target).position().top;
            move = tab_pos - hsize;

            modal.find('.guidePopup .modal-content').animate({scrollTop: move},1000, 'easeInOutExpo');
        });

        modal.find('.guidePopup .modal-content').bind('scroll', function () {
        var hsize = (window.innerWidth <= 768) ? 38 : 55,
            scrollValue = $('.guidePopup .modal-content').scrollTop() + hsize,
            tab_pos = (window.innerWidth <= 768) ? $('.edu_head_wrap').outerHeight() : 0;

            if(tp_review) {
                if( scrollValue >= $("#target").position().top + tab_pos && scrollValue < $("#curriculum").position().top + tab_pos) {
                    $('.edu_tab li').eq(1).addClass('active').siblings().removeClass('active');
                } else if( scrollValue >= $("#curriculum").position().top + tab_pos && scrollValue < $("#review").position().top + tab_pos) {
                    $('.edu_tab li').eq(2).addClass('active').siblings().removeClass('active');
                } else if( scrollValue >= $("#review").position().top + tab_pos) {
                    $('.edu_tab li').eq(3).addClass('active').siblings().removeClass('active');
                } else {
                    $('.edu_tab li').eq(0).addClass('active').siblings().removeClass('active');
                }
            } else {
                if(tp_target) {
                    if( scrollValue >= $("#target").position().top + tab_pos && scrollValue < $("#curriculum").position().top + tab_pos) {
                        $('.edu_tab li').eq(1).addClass('active').siblings().removeClass('active');
                    } else if( scrollValue >= $("#curriculum").position().top + tab_pos) {
                        $('.edu_tab li').eq(2).addClass('active').siblings().removeClass('active');
                    } else {
                        $('.edu_tab li').eq(0).addClass('active').siblings().removeClass('active');
                    }
                } else {
                    if( scrollValue >= $("#info1").position().top + tab_pos && scrollValue < $("#info2").position().top + tab_pos) {
                        $('.edu_tab li').eq(1).addClass('active').siblings().removeClass('active');
                    } else if( scrollValue >= $("#info2").position().top + tab_pos) {
                        $('.edu_tab li').eq(2).addClass('active').siblings().removeClass('active');
                    } else {
                        $('.edu_tab li').eq(0).addClass('active').siblings().removeClass('active');
                    }
                }
            }
        });
        if(tp_review) {
            $.each(temp_review,function(i,v) {
                modal.find('.review-list').append('<li><p class="review">'+v.review+'</p><p class="name">'+v.name+' 님</p></li>');
            });
            var targets = modal.find('.review-list').children();
            for(var i=0; i<targets.length; i+=4){
                $('<ul class="hide"></ul>').append(targets.slice(i, i+4)).appendTo('.review-list');
            }
            modal.find('.review-list').find('ul:eq(0)').removeClass('hide');
            modal.find('.review-list').find('ul:eq(1)').removeClass('hide');

            modal.find('.review-btn').off('click').on('click', function(e) {
                modal.find('.review-list').find('ul.hide:eq(0)').removeClass('hide');
                if(modal.find('.review-list').find('ul.hide').length < 1) $(this).addClass('hide');
            });
        }
    });
}

var getColorisHtml = function(val,clr,input_options,input_layout,iswrap,class_obj,tooltip_title) {
    if(typeof val == 'undefined' || val == '') val = 'transparent';
    if(typeof mode == 'undefined') mode = '';
    if(typeof layout == 'undefined') layout = '';
    if(typeof iswrap == 'undefined') iswrap = true;
    if(typeof class_obj == 'undefined') class_obj = {'wrap':'', 'input':''};
    if(typeof class_obj['element'] == 'undefined') class_obj['element'] = 'span';
    if(typeof class_obj['wrap'] == 'undefined') class_obj['wrap'] = '';
    if(typeof class_obj['wrap_attr'] == 'undefined') class_obj['wrap_attr'] = '';
    if(typeof class_obj['input'] == 'undefined') class_obj['input'] = '';

    if(Array.isArray(val)) val = val[val.length - 1];

    var clr_options = '';
    $.each(input_options, function(k,v) {
        if(v) clr_options += ` ${k}="${v}"`;
    });

    var clr_input_class = (class_obj['input']) ? class_obj['input'] + ' ' : '';
    switch(input_layout) {
        case 'thumbnail': clr_input_class += 'clr-thumbnail '; break;
        default: break;
    }

    var colorValueRegex = Coloris.getColorRegex(),
        colorWithImportantRegex = /!important$/g,
        checkWithImportant = (val.match(colorWithImportantRegex) !== null) ? true : false;
    if(checkWithImportant) {
        var tmp_match = val.match(colorValueRegex);
        val = (tmp_match) ? tmp_match[0] : 'transparent';
    }

    if(/(none|inherit|initial)\b/gi.exec(val)) val = val.replace(/(none|inherit|initial)\b/gi, 'transparent');

    if(class_obj['input'].indexOf('clr-alphaoff') > -1) val = Coloris.getChangeColorVal(val,'a',1);

    var clr_tooltip_title = (tooltip_title) ? tooltip_title : 'editor.color';

    var clr_tooltip = (clr_input_class.indexOf('clr-tooltipoff') > -1) ? '' : `data-toggle="tooltip" data-placement="top" title="${$.lang[LANG][clr_tooltip_title]}"`,
        clr_html = `<input type="text" value="${val}" class="coloris ${clr_input_class}" data-clr="${clr}" ${clr_options} ${clr_tooltip} readonly>`;
    if(iswrap) {
        var clr_wrap_class = class_obj['wrap'];
        var clr_wrap_attr = class_obj['wrap_attr'];
        var element_type = class_obj['element'];
        
        clr_html = `<${element_type} class="coloris-picker ${clr_wrap_class}" ${clr_wrap_attr}>${clr_html}</${element_type}>`;
    }

    return clr_html;
}