/**
 * File default_admin.js.
 * Theme Backend scripts.
 */

(function() { 

    if (typeof $ === 'undefined') $ = jQuery;
    $(function() {

        popup.init();
        
        console.log('Popup Admin Scripts: loaded');
    } );

} )(jQuery);

//
// popups
var popup = new function() {
    // events
    this.changed = false;
    this.init = function() {
        $(document).on('click', '#menu-posts-greyd_popup a[href*="post-new.php?post_type=greyd_popup"]', popup.redirectToNew);
        $(document).on('click', '#wp-toolbar a[href*="post-new.php?post_type=greyd_popup"]', popup.redirectToNew);
        $(document).on('click', '#wpbody-content .page-title-action[href*="post-new.php?post_type=greyd_popup"]', popup.redirectToNew);

        // popup wizard
        if ($('#greyd-wizard.popup_wizzard').length > 0) {
            var name_input = $('#greyd-wizard #name');

            name_input.on('input change', function() { wizzard.checkExisting(popups); });
            name_input.on('keyup', function() { name_input.addClass('changed'); });

            $('#greyd-wizard .content_option').on('click', function() {
                wizzard.selectContent(this);
                if ( !name_input.hasClass('changed') ){
                    $('#greyd-wizard #name').val( $(this).children('p').text() );
                    name_input.trigger('change');
                }
            });

            $('#greyd-wizard .double_reset').on('click', function() { popup.createPopup(this) });
            $('#greyd-wizard .create').on('click', function() { popup.createPopup(this) });

            // console.log(location.search);
            if (location.search == '?post_type=greyd_popup&wizzard=add') wizzard.initnew();
        }

        // popup design
        if ($('.design_input').length > 0) {
            
            // inputs
            $('.design_input .settings_input_value').each(function() {
                var that = this;
                $.each([ 'position' ], function() {
                    // custom grid input from select
                    if ($(that).hasClass(this)) popup.customSelect(that, 'grid'); 
                });
                $.each([ 'width', 'height', 'align', 'mobile_width', 'mobile_height', 'mobile_align' ], function() {
                    // custom line input from select
                    if ($(that).hasClass(this)) popup.customSelect(that, 'line'); 
                });
                $(this).on('input change', function() {
                    // input events
                    popup.checkDependencies();
                    popup.makeValue();
                    
                    // auto-preview animation
                    if ( $(this).hasClass('anim_type') ) popup.closePreview();
                    
                    // mobile preview
                    if ( $(this).hasClass('mobile_enable') ) {
                        
                        $( '.popup_design_preview .popup_switch .' + ($(this).prop('checked') ? 'mobile' : 'desktop') ).trigger("click");
                    }
                });
            });
            $('.design_input .input_item').on('click', function() {
                // click events for custom inputs
                popup.setSelect(this);
            });
            $('.design_input input[type="range"]').each(function() {
                // input events for range
                popup.setRange(this);
                $(this).on('input change', function() {
                    popup.setRange(this);
                });
            });
            popup.checkDependencies();
            popup.makeValue();
            $('.popup_design_data').on('change', function() {
                popup.renderPreview();
            });
            $('.popup_design_preview .popup_switch .dashicons').on('click', function() {
                popup.switchPreview(this);
            });
            $('.popup_design_preview .close_popup_wrapper').on('click', function() {
                popup.closePreview();
            });

            // console.log("popup design events added ...");
        }

        if ($('.settings_input').length > 0) {
            
            $('.settings_input_switch .greyd_switch input').each(function() {
                // input events for switch slider
                popup.setSlider(this);
                $(this).on('input change', function() {
                    popup.setSlider(this);
                });
            });
            
            $('.settings_input_switch .settings_options select').each(function() {
                popup.customSelect(this, 'line');
                $(this).parent().find('.input_item').on('click', function() {
                    // click events for custom inputs
                    popup.setSelect(this);
                });
                // input events for switch buttons
                popup.setSwitch(this);
                $(this).on('input change', function() {
                    popup.setSwitch(this);
                });
            });
            
            $('.settings_input_option.checkbox').each(function() {
                
                $(this).find('input[type="checkbox"]').on('click', function () {
                    // console.log($(this).prop('name')+": "+$(this).prop('checked'));
                    var new_value = [];
                    $(this).closest('.settings_input_option').find('input[type="checkbox"]').each(function() {
                        if ($(this).prop('checked')) new_value.push($(this).prop('name'));
                    });
                    $(this).closest('.settings_input_option').find('input.settings_input_option_value').val(new_value.join(','));
                    $(this).closest('.settings_input_option').find('input.settings_input_option_value').trigger("change");
                });

            });

            $('.settings_input_option.autotags').each(function() {
                popup.setAutotags(this);
            });
            if ($('.tag_suggestions').length > 0) {
                popup.initAutotags();
            }

            $('.settings_input[data-param_type="info"]').each(function() {
                var wrapper = $(this);
                // console.log(wrapper);
                wrapper.find('.info_toggle').on('click', function() {
                    console.log('clicked');
                    wrapper.find('.settings_input_options').slideToggle('fast');
                });
                
            });

            popup.setUrlCondition($('.settings_input_options[data-param_name="urlparam"] select[name="condition"]'));
            $('.settings_input_options[data-param_name="urlparam"] select[name="condition"]').on('change', function() {
                popup.setUrlCondition(this);
            });
            popup.setTimeCheckbox($('.settings_input_options[data-param_name="time"] .settings_input_option[data-param_name="select"] input[name="custom"]'));
            $('.settings_input_options[data-param_name="time"] .settings_input_option[data-param_name="select"] input[name="custom"]').on('click', function() {
                popup.setTimeCheckbox(this);
            });

            // inputs
            $('.settings_input .settings_input_value, .settings_input .settings_input_option_value').each(function() {
                $(this).on('input change', function() {
                    // input events
                    popup.makeSettingsValue();
                });
            });
            popup.makeSettingsValue();

            // console.log("popup settings events added ...");
        }
        
        if ($('.design_input').length > 0 && $('.settings_input').length > 0) {

            // alert on leave if settings changed
            $(window).on('beforeunload', popup.alertOnLeave);
            // don't alert on submit
            $('input[type="submit"]').on("click", function(){
                $(window).off('beforeunload', popup.alertOnLeave);
            });
            
            setTimeout(function() {
                
                // show stuff
                $('.popup_design .maybe_active').removeClass('maybe_active').addClass('active');
                $('#popup_preview').removeClass('hidden');
                popup.changed = false;
    
            }, 0);

        }
    }
    
    this.alertOnLeave = function() {
        if (popup.changed) 
            return 'Are you sure you want to leave?';
    }

    // settings
    this.setSlider = function(el) {
        if ($(el).prop('checked')) {
            $(el).closest('.settings_input').removeClass('inactive');
            $(el).closest('.settings_input').find('.settings_input_value').val('on');
            $(el).closest('.settings_input').find('.settings_input_value').trigger("change");
            $(el).closest('.settings_input').find('.settings_input_option_value').prop('disabled', false);
            $(el).closest('.settings_input').find('.settings_input_options').slideDown('fast');
        }
        else {
            $(el).closest('.settings_input').addClass('inactive');
            $(el).closest('.settings_input').find('.settings_input_value').val('off');
            $(el).closest('.settings_input').find('.settings_input_value').trigger("change");
            $(el).closest('.settings_input').find('.settings_input_option_value').prop('disabled', true);
            $(el).closest('.settings_input').find('.settings_input_options').slideUp('fast');
        }
    }
    this.setSwitch = function(el) {
        if ($(el).val() == 'custom')
            $(el).closest('.settings_input').find('.settings_input_options').slideDown('fast');
        else
            $(el).closest('.settings_input').find('.settings_input_options').slideUp('fast');
        if ($(el).val() == 'off')
            $(el).closest('.settings_input').addClass('inactive');
        else
            $(el).closest('.settings_input').removeClass('inactive');
        $(el).closest('.settings_input').find('.settings_input_value').val($(el).val());
        $(el).closest('.settings_input').find('.settings_input_value').trigger("change");
    }
    this.setUrlCondition = function(el) {
        if ($(el).val() != 'empty' && $(el).val() != 'not_empty') {
            $('.settings_input_options[data-param_name="urlparam"] .settings_input_option[data-param_name="value"]').css('opacity', '1');
        }
        else {
            $('.settings_input_options[data-param_name="urlparam"] .settings_input_option[data-param_name="value"]').css('opacity', '0');
        }
    }
    this.setTimeCheckbox = function(el) {
        if ($(el).prop('checked')) {
            $('.settings_input_options[data-param_name="time"] .settings_input_option[data-param_name="custom"]').slideDown('fast');
        }
        else {
            $('.settings_input_options[data-param_name="time"] .settings_input_option[data-param_name="custom"]').slideUp('fast');
        }
    }

    this.setAutotags = function(el) {
        var wrapper = $(el);
        var data = wrapper.find('input').data('tags');
        // console.log(data);
        var value = wrapper.find('input').val().split(',');
        // console.log(value);

        var tags_data = {};
        var suggestions = "";
        $.each(data, function(key, values) {
            suggestions += '<span class="tag_suggest">'+key+'</span>';
            $.each(values, function(title, id) {
                title = decodeURIComponent(title).replace( /\+/g, ' ' );
                var display = "data-available='yes'";
                if (value.includes(id.toString())) display = "data-available='no' style='display:none'";
                suggestions += '<span class="tag_suggest option" data-value="'+id+'" '+display+'>'+title+'</span>';
                tags_data[id] = title;
            });
        });
        var tags = "";
        var new_value = [];
        $.each(value, function() {
            if (typeof tags_data[this] !== 'undefined') {
                new_value.push(this);
                var title = decodeURIComponent(tags_data[this]).replace( /\+/g, ' ' );
                tags += '<span class="tag" data-value="'+this+'">'+title+'<span class="tag_close dashicons dashicons-no-alt"></span></span>';
            }
        });
        wrapper.find('input').val(new_value.join(','));
        // console.log(tags_data);

        var markup = '<div class="tagarea">';
            markup +=   '<span class="tags">'+tags+'</span>';
            markup +=   '<input class="tag_input" type="text" size="3">';
            markup +=   '<span class="tag_suggestions">'+suggestions+'</span>';
            markup += '</div>';
        wrapper.append(markup);
    

        wrapper.find('.tagarea').on('click', function () {
            $(this).find('.tag_input').focus();
        });
        wrapper.find('.tag_input').on('focus', function () {
            var inputpos = $(this).offset();
            var inputheight = $(this).height();
            var parentpos = $(this).closest('.settings_input').offset();
            $(this).siblings('.tag_suggestions').css('top', (inputpos.top - parentpos.top + inputheight)+'px');
            $(this).siblings('.tag_suggestions').css('left', (inputpos.left - parentpos.left)+'px');
            $(this).siblings('.tag_suggestions').css('display', 'block');
        });

        wrapper.find('.tag_input').on("keypress", function (e) {
            var redExp = new RegExp("[a-zA-Z0-9- ]");
            var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
            if (!redExp.test(key)) return false; 
            return true;
        });
        wrapper.find('.tag_input').on("keyup", function (e) {
            var x = e || window.event;
            var key = (x.keyCode || x.which);
            console.log(key);
            switch (key) {
                // case 188: // comma
                //     // $(this).val('');
                //     break;
                // case 40:
                // case 38: //down/up arrow
                //     break;
                // case 13: //enter
                //     break;
                case 27: //esc 
                    $(this).siblings('.tag_suggestions').css('display', 'none');
                    break;
                default:
                    var val = $(this).val().toLowerCase().replace(' ', '');
                    $(this).siblings('.tag_suggestions').css('display', 'block');
                    $(this).siblings('.tag_suggestions').find('.tag_suggest.option').each(function() {
                        if ($(this).data('available') == 'yes') {
                            var option = $(this).html().toLowerCase().replace(' ', '');
                            option += $(this).data('value').toString();
                            if (option.indexOf(val) > -1) $(this).css('display', 'block');
                            else $(this).css('display', 'none');
                        }
                    });
                    $(this).attr('size', $(this).val().length + 1); //increase size
                    break;
            }
        });

        wrapper.find('.tag_suggest.option').on('click', function (e) {
            // console.log("add tag");
            // console.log($(this));
            var id = $(this).data('value');
            var title = decodeURIComponent( $(this).html() ).replace( /\+/g, ' ' );
            var tags = $(this).closest('.autotags').find('.tags');
            var input = $(this).closest('.autotags').find('.settings_input_option_value');

            var is_cat = (typeof id === 'string' && id.indexOf('cat_')) === 0 ? theme_wordings.vc.tags.category+": " : "";
            var new_tag = '<span class="tag" data-value="'+id+'">'+is_cat+title+'<span class="tag_close dashicons dashicons-no-alt"></span></span>';
            tags.append(new_tag);
            var new_value = []
            tags.find('.tag').each(function() {
                new_value.push($(this).data('value'));
            });
            input.val(new_value.join(','));
            input.trigger("change");

            $(this).parent().siblings('.tag_input').val('');
            $(this).parent().siblings('.tag_input').attr('size', 3);
            $(this).css('display', 'none');
            $(this).data('available', 'no');
            $(this).siblings('.tag_suggest.option').each(function() {
                if ($(this).data('available') == 'yes') {
                    $(this).css('display', 'block');
                }
            });
        });
    }
    this.initAutotags = function() {
        $(document).on("mouseup", function (e) {
            var suggestions = $(".tag_suggestions");
            if (!suggestions.is(e.target) && // if the target of the click isn't the container...
                suggestions.has(e.target).length === 0) { // ... nor a descendant of the container
                suggestions.css('display', 'none');
            }
        });
        $(document).on('click', '.tag_close', function (e) {
            // var val = $(this).parent().data('value');
            var tag = $(this).parent();
            var tags = $(this).closest('.autotags').find('.tags');
            var input = $(this).closest('.autotags').find('.settings_input_option_value');
            
            var val = tag.data('value');
            tag.parent().siblings(".tag_suggestions").find('.tag_suggest.option').each(function() {
                if ($(this).data('value') == val) {
                    $(this).css('display', 'block');
                    $(this).data('available', 'yes');
                }
            });
            tag.parent().siblings(".tag_suggestions").css('display', 'none');
            tag.remove();

            var new_value = []
            tags.find('.tag').each(function() {
                new_value.push($(this).data('value'));
            });
            input.val(new_value.join(','));
            input.trigger("change");
        });
        $(document).on('click', '.tag', function (e) {
            $(this).parent().siblings(".tag_suggestions").css('display', 'none');
        });
    }

    this.makeSettingsValue = function() {

        // console.log("make settings value ...");
        var data = {};
        $('.settings_input .settings_input_value').each(function() {
            var name = $(this).prop('name');
            var value = $(this).val();
            if ($(this).prop('type') == "checkbox") {
                value = 'false';
                if ($(this).prop('checked'))
                    value = 'true';
            }
            data[name] = { value: value };
            if ($(this).closest('.settings_input').find('.settings_input_option_value').length > 0) {
                var options = {};
                $(this).closest('.settings_input').find('.settings_input_option_value').each(function() {
                    var oname = $(this).prop('name');
                    var ovalue = $(this).val();
                    options[oname] = ovalue;
                });
                data[name].options = options;
            }
        });
        // console.log(data);
        // console.log(JSON.stringify(data));
        var old_data = $('.popup_settings_data').val();
        var new_data = JSON.stringify(data);
        if (new_data != old_data) {
            // console.log("new settings data found");
            popup.changed = true;
        }
        $('.popup_settings_data').val(new_data);
        $('.popup_settings_data').trigger("change");
    }


    // design
    this.customSelect = function(el, mode) {
        $(el).addClass('hidden');
        var value = $(el).val();
        var options = el.options;
        var markup = '<div class="'+mode+'_items">';
        if (mode == 'grid') {
            for (var i=0; i<options.length; i++) {
                if (i%3 == 0) markup += '<span>';
                var active = '';
                if (options[i].value == value) active = 'active';
                markup += '<span class="input_item '+active+'" title="'+options[i].label+'" data-index="'+options[i].value+'"></span>';
                if (i%3 == 2) markup += '</span>';
            }
        }
        else if (mode == 'line') {
            for (var i=0; i<options.length; i++) {
                var active = '';
                if (options[i].value == value) active = 'active';
                markup += '<span class="input_item '+active+'" data-index="'+options[i].value+'">'+options[i].label+'</span>';
            }
        }
        markup += '</div>';
        $(el).parent().append(markup);
    }

    this.switchDesignTab = function(el) {
        // console.log(el);
        var title = $(el).data('title');
        $('.tabcontent').each(function() {
            if ($(this).data('title') == title) $(this).addClass('active');
            else $(this).removeClass('active');
        });
        $('.tablink').each(function() {
            if ($(this).data('title') == title) $(this).addClass('active');
            else $(this).removeClass('active');
        });
    }
    
    this.setRange = function(el) {
        var value = $(el).val();
        //console.log( "Range Changed to: "+value );
        if ($(el).prev().data("label") != undefined) {
            var label = $(el).prev().data("label");
            var unit = $(el).prev().data("unit");
            $(el).prev().html(label+": "+value+unit);
        }
    }
    this.setSelect = function(el) {
        var value = $(el).data('index');
        // console.log("clicked on "+value);
        var parent = $(el).parent();
        if (!$(parent).hasClass('line_items')) parent = $(parent).parent();
        $(parent).find('.input_item').each(function() {
            $(this).removeClass('active');
        });
        $(el).addClass('active');
        $(parent).siblings('select').val(value);
        $(parent).siblings('select').trigger("change");
    }

    this.checkDependencies = function() {
        // console.log("check dependencies ...");
        $('.design_input').each(function() {
            if ($(this).data('dependency') != undefined) {
                var dependency = JSON.parse(decodeURIComponent($(this).data('dependency')));
                // console.log(dependency);
                $(this).css('display', 'inline-block');
                for (var i=0; i<dependency.length; i++) {
                    var value = $('.settings_input_value.'+dependency[i].element).val();
                    if ($('.settings_input_value.'+dependency[i].element).prop('type') == "checkbox") {
                        value = 'false';
                        if ($('.settings_input_value.'+dependency[i].element).prop('checked'))
                            value = 'true';
                    }
                    // console.log(value);
                    if (dependency[i].value != undefined) {
                        var part_enabled = false;
                        for (var j=0; j<dependency[i].value.length; j++) {
                            if (value == dependency[i].value[j]) {
                                part_enabled = true;
                                break;
                            }
                        }
                    }
                    if (dependency[i].not_value != undefined) {
                        var part_enabled = true;
                        for (var j=0; j<dependency[i].not_value.length; j++) {
                            if (value == dependency[i].not_value[j]) {
                                part_enabled = false;
                                break;
                            }
                        }
                    }
                    if (!part_enabled) {
                        $(this).css('display', 'none');
                        break;
                    }
                }
            }
        });
    }
    
    this.makeValue = function() {
        // console.log("make design value ...");
        var data = {};
        $('.design_input .settings_input_value').each(function() {
            var name = $(this).prop('name');
            var value = $(this).val();
            if ($(this).prop('type') == "checkbox") {
                value = 'false';
                if ($(this).prop('checked'))
                    value = 'true';
            }
            data[name] = value;
        });
        // console.log(data);
        // console.log(JSON.stringify(data));
        var old_data = $('.popup_design_data').val();
        var new_data = JSON.stringify(data);
        if (new_data != old_data) {
            // console.log("new design data found");
            popup.changed = true;
        }
        $('.popup_design_data').val(new_data);
        $('.popup_design_data').trigger("change");
    }
    
    // preview
    this.renderPreview = function() {
        // console.log("render preview ...");
        var design_value = JSON.parse($('.popup_design_data').val());
        // console.log(design_value);

        // position
        var p = design_value['position'];
        var jc = (p=='tl' || p=='ml' || p=='bl') ? 'flex-start' : ((p=='tc' || p=='mc' || p=='bc') ? 'center' : 'flex-end');
        var ai = (p=='tl' || p=='tc' || p=='tr') ? 'flex-start' : ((p=='ml' || p=='mc' || p=='mr') ? 'center' : 'flex-end');
        $('#popup_preview.popup').css({
            'justify-content': jc,
            'align-items': ai,
        });

        // width height align
        var width = this.getValue(design_value, 'width');
        var height = this.getValue(design_value, 'height');
        var align = "flex-start";
        var inner_width = "100%";
        var inner_height = "100%";
        if (height != 'auto') {
            align = (design_value['align'] == 'top') ? 'flex-start' : ((design_value['align'] == 'middle') ? 'center' : 'flex-end');
        }
        if (design_value['margin_lr'] > 0) inner_width = "calc(100% - "+(2*design_value['margin_lr'])+"px)";
        if (design_value['margin_tb'] > 0) inner_height = "calc(100% - "+(2*design_value['margin_tb'])+"px)";

        $('#popup_preview.popup .popup_content').css({
            'width': width,
            'height': height,
        });
        $('#popup_preview.popup .popup_wrapper').css({
            'justify-content': align,
            'width': inner_width,
            'height': inner_height,
            'margin': design_value['margin_tb']+'px '+design_value['margin_lr']+'px',
            'padding': design_value['padding_tb']+'px '+design_value['padding_lr']+'px',
            'border-radius': design_value['border_radius']+'px',
            'overflow': design_value['overflow'],
        });

        // mobile width height align
        if (design_value['mobile_enable'] == 'true') {
            var mobile_width = this.getValue(design_value, 'mobile_width');
            var mobile_height = this.getValue(design_value, 'mobile_height');
            var mobile_align = "flex-start";
            var mobile_inner_width = "100%";
            var mobile_inner_height = "100%";
            if (mobile_height != 'auto') {
                mobile_align = (design_value['mobile_align'] == 'top') ? 'flex-start' : ((design_value['mobile_align'] == 'middle') ? 'center' : 'flex-end');
            }
            if (design_value['mobile_margin_lr'] > 0) mobile_inner_width = "calc(100% - "+(2*design_value['mobile_margin_lr'])+"px)";
            if (design_value['mobile_margin_tb'] > 0) mobile_inner_height = "calc(100% - "+(2*design_value['mobile_margin_tb'])+"px)";

            $('#popup_preview.popup.mobile .popup_content').css({
                'width': mobile_width,
                'height': mobile_height,
            });
            $('#popup_preview.popup.mobile .popup_wrapper').css({
                'justify-content': mobile_align,
                'width': mobile_inner_width,
                'height': mobile_inner_height,
                'margin': design_value['mobile_margin_tb']+'px '+design_value['mobile_margin_lr']+'px',
                'padding': design_value['mobile_padding_tb']+'px '+design_value['mobile_padding_lr']+'px',
            });
        }

        // colors border shadow
        var color = this.getColor(design_value, 'text_color');
        var head = this.getColor(design_value, 'head_color');
        var background = this.getColor(design_value, 'bg_color');
        var border = "none";
        var shadow = "none";
        if (design_value['border_enable'] == 'true')
            border = design_value['border_width']+"px "+design_value['border_style']+" "+this.getColor(design_value, 'border_color');
        if (design_value['shadow_enable'] == 'true')
            shadow = shadowcontrol.makeValue(design_value['shadow']);

        $('#popup_preview.popup .popup_wrapper').css({
            'color': color,
            'background-color': background,
            'border': border,
            'box-shadow': shadow,
        });
        $('#popup_preview.popup .popup_wrapper h1, '+
          '#popup_preview.popup .popup_wrapper h2, '+
          '#popup_preview.popup .popup_wrapper h3, '+
          '#popup_preview.popup .popup_wrapper h4, '+
          '#popup_preview.popup .popup_wrapper h5, '+
          '#popup_preview.popup .popup_wrapper h6').css({
            'color': head,
        });
        
        document.documentElement.style.setProperty('--backPOPcolor', color);
        document.documentElement.style.setProperty('--backPOPcolor_hover', color);
        
        // hover colors border shadow
        if (design_value['hover_enable'] == 'true') {
            var hover_color = this.getColor(design_value, 'hover_text_color');
            var hover_head = this.getColor(design_value, 'hover_head_color');
            var hover_background = this.getColor(design_value, 'hover_bg_color');
            var hover_border = "none";
            var hover_shadow = "none";
            if (design_value['border_enable'] == 'true')
                hover_border = design_value['border_width']+"px "+design_value['border_style']+" "+this.getColor(design_value, 'hover_border_color');
            if (design_value['shadow_enable'] == 'true')
                hover_shadow = shadowcontrol.makeValue(design_value['hover_shadow']);

            $("#popup_preview.popup .popup_wrapper").off('mouseover').on('mouseover', function() {
                $(this).css({
                    'color': hover_color,
                    'background-color': hover_background,
                    'border': hover_border,
                    'box-shadow': hover_shadow,
                });
                $(this).find('h1, h2, h3, h4, h5, h6').css({
                    'color': hover_head,
                });
            });
            $("#popup_preview.popup .popup_wrapper").off('mouseout').on('mouseout', function() {
                $(this).css({
                    'color': color,
                    'background-color': background,
                    'border': border,
                    'box-shadow': shadow,
                });
                $(this).find('h1, h2, h3, h4, h5, h6').css({
                    'color': head,
                });
            });
            
            document.documentElement.style.setProperty('--backPOPcolor_hover', hover_color);
        }
        else {
            $("#popup_preview.popup .popup_wrapper").off('mouseover');
            $("#popup_preview.popup .popup_wrapper").off('mouseout');
        }

        // overlay effect click
        if (design_value['overlay_enable'] == 'true') {
            var overlay = this.getColor(design_value, 'overlay_color');
            var opacity = design_value['overlay_opacity']/100.0;
            $('#popup_preview.popup .popup_overlay').css({
                'top': '0', 'left': '0', 'width': '100%', 'height': '100%',
                'background-color': overlay,
                'opacity': opacity,
            });
            
            var effect = design_value['overlay_effect'];
            if (effect != 'none') {
                var value = design_value['overlay_effect_'+effect];
                var unit = "%";
                if (effect == 'blur') unit = "px";
                if (effect == 'brightness') unit = "";
                if (effect == 'hue-rotate') unit = "deg";
                effect += "("+value+unit+")";
            }
            $('.popup_design .popup_design_preview .popup_website > iframe').css({
                'filter': effect,
            });

            if (design_value['overlay_close'] == 'true') {
                $("#popup_preview.popup .popup_overlay").off('click').on('click', function() {
                    popup.closePreview();
                });
            }
            else $("#popup_preview.popup .popup_overlay").off('click');
        }
        else {
            $('#popup_preview.popup .popup_overlay').css({
                'top': '0', 'left': '0', 'width': '0', 'height': '0',
            });
            $('.popup_design .popup_design_preview .popup_website > iframe').css({
                'filter': 'none',
            });
            $("#popup_preview.popup .popup_overlay").off('click');
        }

        // animation
    }
    this.closePreview = function() {
        console.log("preview close animation ...");

        var popup_preview = $('#popup_preview.popup');
        var busy = popup_preview.data('busy');
        if (typeof busy !== 'undefined' && busy == 'yes') return;
        popup_preview.data('busy', 'yes');

        var overlay = popup_preview.find('.popup_overlay');
        var wrapper = popup_preview.find('.popup_content .popup_wrapper');
        var website = $('.popup_design .popup_design_preview .popup_website > iframe');
        
        var design_value = JSON.parse($('.popup_design_data').val());
        var anim = design_value['anim_type'];
        var time = design_value['anim_time']*1;
        var dur = (time/1000.0);
        var opacity = design_value['overlay_opacity']/100.0;
        // console.log(anim+" "+time+" "+opacity);

        if (anim == 'none') {
            time = 0; 
            dur = 0;
            popup_preview.addClass('hidden');
        }
        else if (anim == 'fade') {
            popup_preview.animate( {"opacity": '0'}, time, function() { popup_preview.addClass('hidden') } );
        }
        else if (anim.indexOf('slide_') == 0) {
            if (anim == 'slide_top') {
                overlay.animate( {"top": '100%', "opacity": '0'}, time );
                popup_preview.animate( {"top": '-100%'}, time, function() { popup_preview.addClass('hidden') } );
            }
            else if (anim == 'slide_bottom') {
                overlay.animate( {"top": '-100%', "opacity": '0'}, time );
                popup_preview.animate( {"top": '100%'}, time, function() { popup_preview.addClass('hidden') } );
            }
            else if (anim == 'slide_left') {
                overlay.animate( {"left": '100%', "opacity": '0'}, time );
                popup_preview.animate( {"left": '-100%'}, time, function() { popup_preview.addClass('hidden') } );
            }
            else if (anim == 'slide_right') {
                overlay.animate( {"left": '-100%', "opacity": '0'}, time );
                popup_preview.animate( {"left": '100%'}, time, function() { popup_preview.addClass('hidden') } );
            }
        }
        else {
            var dur_old = wrapper.css('transition-duration');
            if (anim == 'scale')
                wrapper.animate( {"transition-duration": dur+'s'}, 0, function() { wrapper.css('transform', 'scale(0)') } );
            else if (anim == 'flip_vertical')
                wrapper.animate( {"transition-duration": dur+'s'}, 0, function() { wrapper.css('transform', 'rotateY(-90deg)') } );
            else if (anim == 'flip_horizontal')
                wrapper.animate( {"transition-duration": dur+'s'}, 0, function() { wrapper.css('transform', 'rotateX(-90deg)') } );
            else if (anim == 'flip_3d')
                wrapper.animate( {"transition-duration": dur+'s'}, 0, function() { wrapper.css('transform', 'rotate3d(1,1,1,240deg) scale(0)') } );
            overlay.animate( {"opacity": '0'}, time, function() { popup_preview.addClass('hidden') } );
        }
        var filter_old = website.css('filter');
        website.animate( {"transition-duration": dur+'s'}, 0, function() { website.css('filter', 'none') } );


        var reopen = 500;
        setTimeout(function() {

            popup_preview.removeClass('hidden');

            if (anim == 'none') {
            } 
            else if (anim == 'fade') {
                popup_preview.animate( {"opacity": '1'}, time );
            }
            else if (anim.indexOf('slide_') == 0) {
                overlay.animate( {"top": '0', "left": '0', "opacity": opacity}, time );
                popup_preview.animate( {"top": '0', "left": '0'}, time );
            }
            else {
                var dur = (time/1000.0);
                if (anim == 'scale')
                    wrapper.animate( {"transition-duration": dur+'s'}, 0, function() { wrapper.css('transform', 'scale(1)') } );
                else if (anim == 'flip_vertical')
                    wrapper.animate( {"transition-duration": dur+'s'}, 0, function() { wrapper.css('transform', 'rotateY(0deg)') } );
                else if (anim == 'flip_horizontal')
                    wrapper.animate( {"transition-duration": dur+'s'}, 0, function() { wrapper.css('transform', 'rotateX(0deg)') } );
                else if (anim == 'flip_3d')
                    wrapper.animate( {"transition-duration": dur+'s'}, 0, function() { wrapper.css('transform', 'rotate3d(1,1,1,0) scale(1)') } );
                overlay.animate( {"opacity": opacity}, time, function() { wrapper.css('transition-duration', dur_old) } );
            }
            website.animate( {"transition-duration": dur+'s'}, 0, function() { website.css('filter', filter_old) } );

        }, reopen+time);

        setTimeout(function() {
            popup_preview.data('busy', 'no');
        }, reopen+time+time);
    }
    this.switchPreview = function(el) {
        if (!$(el).hasClass('active')) {
            if ($(el).hasClass('desktop')) {
                $(el).parent().siblings().removeClass('mobile');
            }
            else if ($(el).hasClass('mobile')) {
                $(el).parent().siblings().addClass('mobile');
            }
            $(el).siblings().removeClass('active');
            $(el).addClass('active');
            popup.renderPreview();
        }
    }

    this.getColor = function(data, key) {
        var color = data[key];
        if (color == "") color = 'transparent';
        if (color.indexOf('color_') > -1) {
            var tmp = color.split('color_');
            color = root['--color'+tmp[1]]['value'];
        }
        return color;
    }
    this.getValue = function(data, key) {
        var value = data[key];
        if (value == 'custom') value = data[key+'_custom'];
        if (value != 'auto') {
            if (value.indexOf('px') == -1 && value.indexOf('%') == -1) {
                if (value <= 100) value += "%";
                else value += "px";
            }
        }
        return value;
    }

    // Wizard
    this.redirectToNew = function(e) {
        e.preventDefault();
        var url = window.location.href.split('wp-admin');
        if (url[1].indexOf("/edit.php?post_type=greyd_popup") > -1) wizzard.initnew();
        else window.location.href = url[0]+"wp-admin/edit.php?post_type=greyd_popup&wizzard=add";
    }
    this.createPopup = function(el) {
        if ($(el).hasClass('disabled')) return;

        var result = {
            name: $('#greyd-wizard #name').val(),
            slug: $('#greyd-wizard #slug').val(),
            type: $('#greyd-wizard #ttype').val(),
            content: $('#greyd-wizard .content_option.active').attr('id'),
        }
        if ($(el).hasClass('double_reset')) {
            result['force'] = 'true';
            result['content'] = 'empty';
        }
        if (result.content == 'copy') {
            if ($('#greyd-wizard #copy_'+result.type).length == 0) result.content = 'empty';
            else {
                result.copy = $('#greyd-wizard #copy_'+result.type).val();
                if (result.copy == "0") {
                    alert(theme_wordings.wizard.no_copy.replace('%s', 'Popup'));
                    return;
                }
            }
        }
        if (result.name == "") {
            alert(theme_wordings.wizard.no_name.replace('%s', 'Popup'));
            return;
        }
        
        // create popup post
        // console.log(result);
        wizzard.createPost('create_popup', result);
    }

    // Backend
    this.prio_dec = function(id) {
        popup.prio(id, "minus");
    }
    this.prio_inc = function(id, ) {
        popup.prio(id, "plus");
    }
    this.prio = function(id, mode) {
        // console.log(mode+" priority for "+id);
        if ($('#popup_'+id+'_priority').parent().hasClass('blocked')) {
            // console.log("blocked");
            return;
        }
        var value = parseInt($('#popup_'+id+'_priority').html());
        if (mode == "plus") value++;
        else if (mode == "minus") value--;
        if (value < 1) console.log("minimum reached");
        else if (value > 9) console.log("maximum reached");
        if (value > 0 && value < 10) {
            // mod popup via ajax
            var result = {
                id: id,
                value: value,
            }
            $.post(
                wizzard_details.ajax_url, {
                    'action': 'greyd_ajax',
                    '_ajax_nonce': wizzard_details.nonce,
                    'mode': 'mod_popup',
                    'data': result,
                }, 
                function(response) {
                    if (response.indexOf('error::') > -1) {
                        console.warn(response);
                        var tmp = response.split('error::');
                        var message = tmp[1];
                        $('#popup_'+id+'_priority').parent().removeClass('blocked');
                    }
                    else {
                        console.info( response );
                        $('#popup_'+id+'_priority').html(value);
                        $('#popup_'+id+'_priority').parent().removeClass('blocked');
                        $('#popup_'+id+'_priority').siblings().removeClass('off');
                        if (value == 1) $('#popup_'+id+'_priority').prev().addClass('off');
                        else if (value == 9) $('#popup_'+id+'_priority').next().addClass('off');
                    }
                }
            );
            $('#popup_'+id+'_priority').parent().addClass('blocked');
        }
    }
}
