/**
 * File vc.js.
 * Visual Composer extensions for module views.
 */
// if (typeof $ === 'undefined') $ = jQuery;

//
// Backgrounds
var backgrounds = new function() {

    this.init = function() {
        //
        // overlay
        $(".vc_bg_overlay_pattern").each( function() {
            var wrapper = document.createElement("div");
            wrapper.setAttribute("class", "pattern_wrapper");
            // wrapper.innerHTML = "pattern preview ...";
            for (i = 0; i < this.length; i++) {
                var thumb = document.createElement("div");
                if (this.selectedIndex == i)
                    thumb.setAttribute("class", "pattern_thumb selected");
                else
                    thumb.setAttribute("class", "pattern_thumb");
                thumb.setAttribute("data-pattern", i);
                var val = this.options[i].getAttribute('value');
                if (val && val != "" && val != "pattern_custom") thumb.setAttribute("style", "background:url("+patterns[val]+")");
                else thumb.innerHTML = "<span>"+this.options[i].innerHTML+"</span>";
                thumb.title = this.options[i].innerHTML;
                // thumb.innerHTML = this.options[i].innerHTML;

                // click event
                thumb.addEventListener("click", function(e) {
                    var index = this.getAttribute("data-pattern");
                    // console.log("click pattern "+index);
                    // update thumbs
                    var thumbs = this.parentNode;
                    $(thumbs).children().each( function() {
                        $(this).removeClass("selected");
                    } );
                    $(this).addClass("selected");
                    // update original select
                    var select = this.parentNode.previousSibling;
                    select.selectedIndex = index;
                    $(select).trigger("change");
                });
                wrapper.appendChild(thumb);
            }
            this.parentNode.insertBefore(wrapper, this.nextSibling);
        }); 
        //
        // seperator
        $(".vc_bg_seperator_type").each( function() {
            var wrapper = document.createElement("div");
            wrapper.setAttribute("class", "seperator_wrapper");
            // wrapper.innerHTML = "seperator preview ...";
            for (i = 0; i < this.length; i++) {
                var thumb = document.createElement("div");
                if (this.selectedIndex == i)
                    thumb.setAttribute("class", "seperator_thumb selected");
                else
                    thumb.setAttribute("class", "seperator_thumb");
                thumb.setAttribute("data-seperator", i);
                var val = this.options[i].getAttribute("value");
                if (val != "") thumb.innerHTML = getSeperator(val, "20px", "#888");
                else thumb.innerHTML = "<span>"+this.options[i].innerHTML+"</span>";
                thumb.title = this.options[i].innerHTML;

                // click event
                thumb.addEventListener("click", function(e) {
                    var index = this.getAttribute("data-seperator");
                    // console.log("click seperator "+index);
                    // update thumbs
                    var thumbs = this.parentNode;
                    $(thumbs).children().each( function() {
                        $(this).removeClass("selected");
                    } );
                    $(this).addClass("selected");
                    // update original select
                    var select = this.parentNode.previousSibling;
                    select.selectedIndex = index;
                    $(select).trigger("change");
                });
                wrapper.appendChild(thumb);
            }
            this.parentNode.insertBefore(wrapper, this.nextSibling);
        });
    }

}

//
// Social Media Modul
var socialmedia = new function() {

    this.init = function() {
        $('div').find(".vc_shortcode-param[data-param_type='checkbox']").each( function(e) {
            if ($(this).data('param_settings').class == "vc_sms_check") {
                var check = function(checkbox) {
                    var settings_element = $(checkbox).parent().parent().parent().next();
                    if (!$(checkbox).prop('checked')) {
                        settings_element.css('opacity','0');
                        settings_element.css('pointer-events','none');
                        if ($(checkbox).attr('name') == 'mail') {
                            settings_element = settings_element.next();
                            settings_element.css('opacity','0');
                            settings_element.css('pointer-events','none');
                        }
                    }
                    else {
                        settings_element.css('opacity','1');
                        settings_element.css('pointer-events','all');
                        if ($(checkbox).attr('name') == 'mail') {
                            settings_element = settings_element.next();
                            settings_element.css('opacity','1');
                            settings_element.css('pointer-events','all');
                        }
                    }
                };
                var checkbox = $(this).find('input');
                if (!$(checkbox).prop('checked')) { check(checkbox); }
                $(checkbox).on("click",  function(e) { check(this); } );
            }
        });
    }

}

//
// Switch Button
var switchcontrol = new function() {

    this.init = function() {
        $('.vc_wrapper-param-type-switch input[type="checkbox"]').on('change', function() {
            var val = $(this).data('off');
            if ($(this).prop('checked') == true) val = $(this).data('on');
            $(this).closest('.edit_form_line').find('.wpb_vc_param_value').val(val);
            $(this).closest('.edit_form_line').find('.wpb_vc_param_value').trigger("change");
        });
    }

}

//
// Dynamic Templates
var dyncontrol = new function() {

    this.init = function() {
        if (typeof vc === 'undefined') return;
        if (typeof post_type === 'undefined') return;
        dyncontrol.addVClink();
        
        // post overview module
        // -> add dynamic tags
        var post_overview_control = $('.vc_ui-panel-window[data-vc-shortcode="vc_posts_overview"] .vc_shortcode-param[data-vc-shortcode-param-name="pt"] select');
        var maps_checkbox = $('.vc_ui-panel-window[data-vc-shortcode="vc_posts_overview"] .vc_shortcode-param[data-vc-shortcode-param-name="enable_map"] input');
        var maps_control = $('.vc_ui-panel-window[data-vc-shortcode="vc_maps"] .vc_shortcode-param[data-vc-shortcode-param-name="pt"] select');
        if ( post_overview_control.length > 0 ) {
            // console.log("post_overview - add dynamic tags");
            // on init
            dyncontrol.updateDynamicTags( post_overview_control.val() );
            dyncontrol.addMapTags();
            
            $('.wpb_el_type_param_group .dynamic_single_field').each(function(){
                dyncontrol.addParamGroupTags($(this), 'single');
            });
            vc.events.on('vc-param-group-add-new', function() {
                $('.wpb_el_type_param_group ul li:nth-last-child(2) .dynamic_single_field').each(function(){
                    dyncontrol.addParamGroupTags($(this), 'single');
                });
            });
            
            // change trigger
            post_overview_control.on('change', function() {
                // console.log("select new dynamic tags ... "+$(this).val());
                
                dyncontrol.updateDynamicTags( $(this).val() );
                dyncontrol.addMapTags();
                if (maps_checkbox[0].checked)
                    dynamic_tags.push({ label: 'focus google maps', name: 'focus', type: 'text_long' });
                
                $('.wpb_el_type_param_group .dynamic_single_field').each(function(){
                    dyncontrol.addParamGroupTags($(this), 'single');
                });
            });
        }
        if ( maps_control.length > 0 ) {
            // console.log("maps - add dynamic tags");
            dyncontrol.updateDynamicTags( maps_control.val() );
            dyncontrol.addMapTags();

            // change trigger
            maps_control.on('change', function() {
                // console.log("select new dynamic tags ... "+$(this).val());
                dyncontrol.updateDynamicTags( $(this).val() );
                dyncontrol.addMapTags();
            });
        }
        if (post_overview_control.length == 0 && maps_control.length == 0) {
            dyncontrol.updateDynamicTags();
        }

        // post overview module
        // -> add additional dependency to maps checkbox
        if ( maps_checkbox.length > 0 ) {
            var lat = '.vc_ui-panel-window[data-vc-shortcode="vc_posts_overview"] .vc_shortcode-param[data-vc-shortcode-param-name$="_lat"]';
            var lon = '.vc_ui-panel-window[data-vc-shortcode="vc_posts_overview"] .vc_shortcode-param[data-vc-shortcode-param-name$="_lon"]';
            // console.log(maps_checkbox);
            if (maps_checkbox[0].checked == false) {
                $(lat+', '+lon).addClass('hidden');
            }
            else {
                dynamic_tags.push({ label: 'focus google maps', name: 'focus', type: 'text_long' });
            }
            // change trigger
            maps_checkbox.on('change', function() {
                dyncontrol.updateDynamicTags( post_overview_control.val() );
                if ($(this)[0].checked == false) {
                    $(lat+', '+lon).addClass('hidden');
                }
                else {
                    dyncontrol.addMapTags();
                    dynamic_tags.push({ label: 'focus google maps', name: 'focus', type: 'text_long' });
                    $(lat+', '+lon).removeClass('hidden');
                }
            });
        }
        
        // editing dynamic templates
        // -> init switch
        if (post_type == "dynamic_template" && template_type == "dynamic") {
            // console.log("dynamic template - add dynamic options");
            $('.vc_wrapper-param-type-dynamic .dynamic_type').each(function() {
                dyncontrol.toggleType(this, true);
            });
            $('.vc_wrapper-param-type-dynamic .dynamic_type').on('change', function() {
                dyncontrol.toggleType(this);
            });
            $('.vc_wrapper-param-type-dynamic .dynamic_type_checkbox').on('change', function() {
                var val = 'static';
                if ($(this).prop('checked') == true) val = 'dynamic';
                $(this).closest('.edit_form_line').find('.dynamic_type').val(val);
                $(this).closest('.edit_form_line').find('.dynamic_type').trigger("change");
            });
            $('.vc_wrapper-param-type-dynamic .dynamic_name_input').on('change input', function() {
                dyncontrol.toggleType($(this).closest('.edit_form_line').find('.dynamic_type'));
                if (typeof template_log !== 'undefined' && template_log > 0) {
                    // show changed alert on keyup
                    $(this).on('keyup', function() {
                        var input = $(this);
                        var val = input.val();
                        var old_val = input.data("val");
                        var alert = input.next('.change_name_alert');
                        if (alert.length !== 0) {
                            if (val !== old_val)
                                alert.addClass("open");
                            else
                                alert.removeClass("open");
                        }
                    });
                    $(this).on('blur', function() {
                        var alert = $(this).next('.change_name_alert');
                        if (alert.length !== 0)
                            alert.removeClass("open");
                    });
                }
            });
        }
        // editing post-templates
        // -> add dynamic tags
        else if ((post_type == "dynamic_template" && template_type == "single") ||
                 (post_type == "dynamic_template" && template_type == "archives") ||
                 (post_type == "dynamic_template" && template_type == "search") ||
                 (post_type == "dynamic_template" && template_slug == "woo-product")) {
            // console.log("single/archive/search template - add dynamic tags");

            /**
             * Get the current posttype. We basically have 4 scenarios:
             * 
             * (1) single | archive | search                --> posttype = 'post'
             * (2) single-category | archive-category ...   --> posttype = 'post'
             * (3) single-myposttype-category ...           --> posttype = 'myposttype'
             * (4) woo-product                              --> posttype = 'product'
             */
            var posttype = template_slug.split('-');
            // (3)+(4): the second part is the posttype    (1): otherwise it's 'post'
            posttype = typeof posttype[1] !== 'undefined' ? posttype[1] : 'post';
            // we verify if the posttype exists            (2): otherwise the second part is a category
            posttype = typeof all_dynamic_tags[posttype] !== 'undefined' ? posttype : 'post';

            // update the dynamic tags accordingly
            dyncontrol.updateDynamicTags(posttype);
            
            // add tags to normal fields
            $('.vc_wrapper-param-type-dynamic').each(function() {
                dyncontrol.addTags(this);
            });
            // remove dynamic control
            $('.vc_wrapper-param-type-dynamic').remove();
            
            // add custom tags inside param groups (template post overview)
            if ( $('.wpb_el_type_param_group[data-vc-shortcode-param-name="table_setup"]').length > 0 ) {
                
                // set variable tags
                variable_tags = all_variable_tags[posttype];
                
                // add tags
                $('.wpb_el_type_param_group .dynamic_single_field').each(function(){
                    dyncontrol.addParamGroupTags($(this), 'single');
                });

                // new row added
                vc.events.on('vc-param-group-add-new', function() {
                    $('.wpb_el_type_param_group ul li:nth-last-child(2) .dynamic_single_field').each(function(){
                        dyncontrol.addParamGroupTags($(this), 'single');
                    });
                });
            }
        }
        // default: remove dynamic controls
        else {
            $('.vc_wrapper-param-type-dynamic').remove();
        }
        
        // render dynamic content
        // -> inside template & post-overview VC modules
        $('.vc_wrapper-param-type-dynamic_content').each(function() {
            var params = $(this).data('param_settings').params;
            var dc = $(this).find('.dynamic_content_src');
            var vc_field = $('.vc_shortcode-param[data-vc-shortcode-param-name="'+params.field+'"] select');
            // console.log("Init dynamic content with slug: "+vc_field.val());
            dyncontrol.renderContent(dc, vc_field.val());
            setTimeout(function(){
                vc_field.on('change', function(e) {
                    // console.log(e);
                    // console.log("Change dynamic content with slug: "+$(this).val());
                    dyncontrol.renderContent(dc, $(this).val());
                });
            },0);
            $(this).find('.reload').on('click', function() {
                var slug = $(this).closest('.dynamic_content_block').find('input.dynamic_template').val();
                // console.log("Reload dynamic content with slug: "+slug);
                dyncontrol.renderContent(dc, slug);
            });
        }); 
               
        $(document).off("input change propertychange", ".vc_wrapper-param-type-dynamic_content .dynamic_content_src .wpb_vc_param_value")
                    .on("input change propertychange", ".vc_wrapper-param-type-dynamic_content .dynamic_content_src .wpb_vc_param_value" , function() {
            if (!$(this).hasClass('dynamic_value')) dyncontrol.set(this);
            if ($(this).hasClass('vc_link_field')) dyncontrol.setVClink(this);
        });
        
        // before saving the vc-panel -> insert the textarea_html contents
        $("[data-vc-ui-element='button-save']").off('click').on('click', function(e) {
            dyncontrol.saveEditors();
        });
        
        // add insert trigger for dynamic tags
        $(document).off("click", ".vc_shortcode-param .dtag .insert")
                    .on("click", ".vc_shortcode-param .dtag .insert" , function() {
            dyncontrol.insertTag(this);
        });
        
        // add toggle trigger for dynamic tags
        $(document).off("click", ".vc_shortcode-param .dtag .more")
                    .on("click", ".vc_shortcode-param .dtag .more" , function() {
            dyncontrol.toggleTagParams(this);
        });
        
        // set default row within dynamic templates
        if (post_type == "dynamic_template" && template_type == "dynamic") {
            if ($('.vc_shortcode-param[data-vc-shortcode-param-name="row_type"]').length > 0) {
                var optionold = $('.vc_shortcode-param[data-vc-shortcode-param-name="row_type"] select option').first().html().split('(');
                var newval = root['GRDrowtdefault']['value'];
                if (newval == 'row_l') newval = "(S)";
                else if (newval == 'row_xl') newval = "(M)";
                else if (newval == 'row_xxl') newval = "(L)";
                else if (newval == 'row_xxxl') newval = "(XL)";
                $('.vc_shortcode-param[data-vc-shortcode-param-name="row_type"] select option').first().html(optionold[0]+newval);
            }
        }
    }
    
    // update dynamic tags according to posttype
    this.updateDynamicTags = function(posttype) {
        // default
        if (typeof(default_dynamic_tags) !== 'undefined') dynamic_tags = default_dynamic_tags;
        else dynamic_tags = [];
        
        if (typeof(default_variable_tags) !== 'undefined') variable_tags = default_variable_tags;
        else variable_tags = [];
        
        // posttype defined
        if ( typeof posttype !== 'undefined' && posttype && posttype.length > 0 ) {
            
            if (typeof all_dynamic_tags !== 'undefined' && typeof all_dynamic_tags[posttype] !== 'undefined')
                dynamic_tags = JSON.parse(JSON.stringify(all_dynamic_tags[posttype]));
            
            if (typeof all_variable_tags !== 'undefined' && typeof all_variable_tags[posttype] !== 'undefined')
                variable_tags = JSON.parse(JSON.stringify(all_variable_tags[posttype]));
        }
    }
    
    // add tags to normal dynamic fields
    this.addTags = function(el) {
        var params = $(el).data('param_settings').params;
        var field = $('#vc_ui-panel-edit-element').find('div[data-vc-shortcode-param-name="'+params.field+'"]');
        
        if (field.length > 0) {
            dyncontrol.apendTags(field, template_type, params.type);
        }
    }
    this.addMapTags = function() {
        dynamic_tags.push({ label: 'google maps link', name: 'route', type: 'text_long' });
        dyncontrol.apendMapTags('header_content');
        dyncontrol.apendMapTags('body_content');
    }
    this.apendMapTags = function(param_name) {
        var field = $('#vc_ui-panel-edit-element').find('div[data-vc-shortcode-param-name="'+param_name+'"]');
        
        if (field.length > 0) {
            dyncontrol.apendTags(field, 'single', 'textarea');
        }
    }
    this.apendTags = function(field, type, param_type) {
        var tags = dyncontrol.getTags(type, param_type);
        var input_wrapper = $(field).find('.edit_form_line');
        var first_child = input_wrapper.children().first();
        
        if (tags.length != "" && first_child.length > 0 && !first_child.hasClass('embed_template') && !first_child.hasClass('dynamic_content_block')) {
            input_wrapper.find('.dtag_wrapper').remove();
            input_wrapper.append('<div class="dtag_wrapper"><small>'+theme_wordings.vc.dynamic_tags+'</small><br>'+tags+'</div>');
        }
    }
    
    // add tags to fields inside param groups
    this.addParamGroupTags = function(field, posttype) {
        if (field.length > 0) {
            var type            = field.data('param_type');
            var tags            = dyncontrol.getTags(posttype, type);
            var input_wrapper   = field.find('.edit_form_line');
            var first_child     = input_wrapper.children().first();
            
            input_wrapper.children('.dtag_wrapper').remove();

            if (tags.length != "" && first_child.length > 0 && !first_child.hasClass('embed_template') && !first_child.hasClass('dynamic_content_block')) {
                input_wrapper.append('<div class="dtag_wrapper"><small>'+theme_wordings.vc.dynamic_tags+'</small><br>'+tags+'</div>');
                field.find('.vc_description').remove();
            }
        }
    }
    
    // get all dynamic tags as html
    this.getTags = function(template_type, param_type) {
        // console.log(template_type);
        // console.log(param_type);
        // console.log(variable_tags);
        // default tags
        // var tags = ['title', 'content', 'post-type', 'author', 'date', 'categories', 'tags'];
        // var tags_var = [ 'content', 'excerpt', 'categories', 'tags' ];
        var tags_default = [ 'post-type', 'title', 'author', 'date' ];
        var tags = [ ];
        var tags_var = [ ];
        var tags_custom = [];
        
        // default dynamic tags
        if (typeof(all_default_dynamic_tags) !== 'undefined') {
            tags_default = all_default_dynamic_tags;
        }
        
        // default variable tags
        if (typeof(variable_tags) === 'undefined' && typeof(default_variable_tags) !== 'undefined') {
            variable_tags = default_variable_tags;
        }

        // for posts
        if (template_type == "single" || template_type == "woo") {
            if (param_type == 'textfield') {
                tags = tags_var = [];
            }
            else if (param_type == 'textarea_html' || param_type == 'textarea') {
                tags = tags_default;
                if (typeof(variable_tags) !== 'undefined') {
                    for (var i=0; i<variable_tags.length; i++) {
                        if (variable_tags[i] == 'content' ||
                            variable_tags[i] == 'excerpt' ||
                            variable_tags[i] == 'categories' ||
                            variable_tags[i] == 'tags' ||
                            String(variable_tags[i]).indexOf("customtax-") == 0 ) tags_var.push(variable_tags[i]);
                    }
                }
                if (typeof(dynamic_tags) !== 'undefined') {
                    for (var i=0; i<dynamic_tags.length; i++) {
                        if (dynamic_tags[i].type != 'url' && dynamic_tags[i].type != 'file') 
                            tags_custom.push(dynamic_tags[i].name);
                    }
                }
            }
            else if (param_type == 'emailfield') {
                tags = [ "author-email" ];
                tags_var = [ ];
                if (typeof(dynamic_tags) !== 'undefined') {
                    for (var i=0; i<dynamic_tags.length; i++) {
                        if (dynamic_tags[i].type == 'email') 
                            tags_custom.push(dynamic_tags[i].name);
                    }
                }
            }
            else if (param_type == 'vc_link') {
                // tags = [ "post-link", "image-link", "author-link", ];
                tags = [ "post-link", "author-link", ];
                // tags_var = [ "image-link" ];
                if (typeof(variable_tags) !== 'undefined') {
                    for (var i=0; i<variable_tags.length; i++) {
                        if (variable_tags[i] == 'thumbnail') tags_var.push('image-link');
                    }
                }
                if (typeof(dynamic_tags) !== 'undefined') {
                    for (var i=0; i<dynamic_tags.length; i++) {
                        if (dynamic_tags[i].type == 'file') 
                            tags_custom.push(dynamic_tags[i].name+"-link");
                        if (dynamic_tags[i].type == 'url') 
                            tags_custom.push(dynamic_tags[i].name);
                    }
                }
            }
            // if (param_type == 'file_picker' || param_type == 'file_picker_image') {
            else if (param_type.indexOf('file_picker') == 0) {
                // tags = [ "image" ];
                tags = [ ];
                // tags_var = [ "image" ];
                if (typeof(variable_tags) !== 'undefined') {
                    for (var i=0; i<variable_tags.length; i++) {
                        if (variable_tags[i] == 'thumbnail') tags_var.push('image');
                    }
                }
                if (typeof(dynamic_tags) !== 'undefined') {
                    for (var i=0; i<dynamic_tags.length; i++) {
                        if (dynamic_tags[i].type == 'file') 
                            tags_custom.push(dynamic_tags[i].name);
                    }
                }
            }
        }
        
        // for post archives
        else if (template_type == "archives") {
            if (param_type == 'textarea_html' || param_type == 'textarea') {
                // tags = [ "post-type", "category", "tag", "post-count", "posts-per-page", "page-num", "page-count", ];
                tags = [ "post-type", "post-count", "posts-per-page", "page-num", "page-count", ];
                // tags_var = [ "category", "tag" ];
                if (typeof(variable_tags) !== 'undefined') {
                    for (var i=0; i<variable_tags.length; i++) {
                        if (variable_tags[i] == 'categories') tags_var.push('category');
                        if (variable_tags[i] == 'tags') tags_var.push('tag');
                    }
                }
            }
        }
        
        // for search pages
        else if (template_type == "search") {
            if (param_type == 'textarea_html' || param_type == 'textarea') {
                // tags = [ "query", "post-type", "category", "tag", "post-count", "posts-per-page", "page-num", "page-count", ];
                tags = [ "query", "filter", "post-type", "post-count", "posts-per-page", "page-num", "page-count", ];
                // tags_var = [ "category", "tag" ];
                if (typeof(variable_tags) !== 'undefined') {
                    for (var i=0; i<variable_tags.length; i++) {
                        if (variable_tags[i] == 'categories') tags_var.push('category');
                        if (variable_tags[i] == 'tags') tags_var.push('tag');
                    }
                }
            }
        }

        var final_tags = [];
        
        // add html structure
        $.each(tags, function( i, key ) {
            final_tags[i] = dyncontrol.getTagHtml(key);
        });
        $.each(tags_var, function( i, key ) {
            final_tags.push(dyncontrol.getTagHtml(key));
        });
        $.each(tags_custom, function( i, key ) {
            final_tags.push(dyncontrol.getTagHtml(key, "dpt"));
        });
        // $.each(tags_woo, function( i, key ) {
        //     final_tags[i] = dyncontrol.getTagHtml(key, "woo");
        // });
        
        // return tags;
        if (final_tags.length > 0) return '<span class="dtag_container" data-type="'+param_type+'">'+final_tags.join('')+'</span>';
        else return "";
    }
    // add html structure for dynamic tags
    this.getTagHtml = function(type, css) {
        type = typeof type === 'undefined' ? 'content' : type;
        css  = typeof css === 'undefined' ? '' : css;
        
        if (type.length === 0) return "";
        
        var mode = 'simple';
        // advanced mode
        if (type === 'content' || 
            type === 'author' || 
            type === 'date' || 
            type === 'categories' || 
            type === 'tags' || 
            type === 'price' || 
            type === 'woo_ajax' ||
            type.indexOf("customtax-") == 0
           ) mode = 'advanced';
        // extra css class
        if (type === 'woo_ajax' || 
            type === 'price' || 
            type === 'vat' || 
            type === 'cart' || 
            type === 'cart-excerpt'
           ) css += ' woo';
        else if ( type.indexOf("customtax-") == 0 ) css += ' dpt';
        
        var wording = (typeof theme_wordings.vc.tags[type] !== "undefined") ? theme_wordings.vc.tags[type] : type;
        var html = "<span class='dtag "+mode+" "+css+"' data-tag='"+type+"'>";
        
        html += "<span class='insert' title='"+theme_wordings.vc.insert+"'>"+wording+"</span>";
        if (mode === 'advanced'){
            var content = "";
            var cat_seperators = [ '', 'semi', 'vert', 'hor', 'dot', 'space', 'br' ];
            var cat_options = "";
            cat_seperators.forEach(function(slug) {
                cat_options += "<option value='"+slug+"'>"+theme_wordings.vc.dividers[slug]+"</option>";
            });
            
            if (type === 'content') {
                content = "<span class='dtag_title'>"+theme_wordings.vc.chars+"</span>"+
                    "<input class='dtag_count' type='number' value='-1'>"+
                    "<span class='insert button small'>"+theme_wordings.vc.insert+"</span>";
            } 
            else if (type === 'author') {
                var author_options = "";
                ['name', 'email'].forEach(function(slug) {
                    author_options += "<option value='"+slug+"'>"+theme_wordings.vc[slug]+"</option>";
                });
                content = "<span class='dtag_title'>"+theme_wordings.vc.type+"</span>"+
                    "<select class='dtag_author'>"+author_options+"</select>"+
                    "<label><input class='dtag_link' type='checkbox'>"+theme_wordings.vc.link+"</label>"+
                    "<span class='insert button small'>"+theme_wordings.vc.insert+"</span>";
            } 
            else if (type === 'author-email') {
                content = "<label><input class='dtag_link' type='checkbox'>"+theme_wordings.vc.link+"</label>"+
                    "<span class='insert button small'>"+theme_wordings.vc.insert+"</span>";
            } 
            else if (type === 'date') {
                var date_formats = [ '', 'dmY', 'dmy', 'dm', 'ldmY', 'ldmy', 'ldm', 'jFY', 'jFy', 'jF', 'ljFY', 'ljFy', 'ljF', 'mY', 'my', 'm', 'FY', 'Fy', 'F', 'Y', 'y', 'Gi', 'His', 'G', 'm', 's' ];
                var date_options = "";
                date_formats.forEach(function(slug) {
                    date_options += "<option value='"+slug+"'>"+theme_wordings.vc.date_formats[slug]+"</option>";
                });
                content = "<span class='dtag_title'>"+theme_wordings.vc.date_format+"</span>"+
                    "<select class='dtag_date'>"+date_options+"</select>"+
                    "<span class='insert button small'>"+theme_wordings.vc.insert+"</span>";
            } 
            else if (type === 'categories' || type === 'tags' || type.indexOf("customtax-") == 0 ) {
                content = "<span class='dtag_title'>"+theme_wordings.vc.divider+"</span>"+
                    "<select class='dtag_seperator'>"+cat_options+"</select>"+
                    "<label><input class='dtag_link' type='checkbox'>"+theme_wordings.vc.link+"</label>"+
                    "<span class='insert button small'>"+theme_wordings.vc.insert+"</span>";
            }
            else if (type === 'price') {
                var symbol_options = "";
                ['', 'after', 'before', 'afterh', 'beforeh', 'hide'].forEach(function(slug) {
                    var title = theme_wordings.vc.symbols[slug];
                    if (typeof(title) == 'undefined') title = slug;
                    symbol_options += "<option value='"+slug+"'>"+title+"</option>";
                });
                var format_options = "";
                ['', 'comma', 'none'].forEach(function(slug) {
                    var title = theme_wordings.vc.formats[slug];
                    if (typeof(title) == 'undefined') title = slug;
                    format_options += "<option value='"+slug+"'>"+title+"</option>";
                });
                content = "<span class='dtag_title'>"+theme_wordings.vc.symbol+"</span>"+
                    "<select class='dtag_symbol'>"+symbol_options+"</select>"+
                    "<span class='dtag_title'>"+theme_wordings.vc.format+"</span>"+
                    "<select class='dtag_format'>"+format_options+"</select>"+
                    "<span class='insert button small'>"+theme_wordings.vc.insert+"</span>";
            }
            else if (type === 'woo_ajax') {
                var redirect_options = "";
                ['default', 'cart', 'checkout', 'shop', 'false'].forEach(function(slug) {
                    redirect_options += "<option value='"+slug+"'>"+theme_wordings.vc.redirects[slug]+"</option>";
                });
                content = "<span class='dtag_title'>"+theme_wordings.vc.redirect+"</span>"+
                    "<select class='dtag_redirect'>"+redirect_options+"</select>"+
                    "<label><input class='dtag_not_twice' type='checkbox'>"+theme_wordings.vc.not_twice+"</label>"+
                    "<label><input class='dtag_clear' type='checkbox'>"+theme_wordings.vc.clear+"</label>"+
                    "<span class='insert button small'>"+theme_wordings.vc.insert+"</span>";
            }
            
            html += "<span class='popup dtag_params'>"+content+"</span>";
            // add toggle
            html += "<span class='more dtag_toggle' title='"+theme_wordings.vc.more+"'><span class='dashicons dashicons-arrow-down-alt2'></span></span>";
        }
        html += "</span>";
        
        return html;
    }
    this.toggleTagParams = function(el) {
        $(el).siblings('.popup').toggle();
        $(el).closest('.dtag_container').children().each(function() {
            if ($(this).find('.more')[0] != el) {
                $(this).find('.popup').hide();
            }
        });
    }
    // insert dynamic placeholder into input
    this.insertTag = function(el) {
        
        var tag = $(el).closest('.dtag').data('tag');
        
        // if more options are clicked
        if ($(el).parent().hasClass('dtag_params')) {
            // link
            var link = $(el).parent().find('.dtag_link').prop('checked');
            if (tag == 'content') {
                // content count
                var count = $(el).parent().find('.dtag_count').val();
                if (typeof count !== 'undefined' && count > -1) tag += "|"+count;
            }
            if (tag == 'date') {
                // date format
                var date = $(el).parent().find('.dtag_date').val();
                if (typeof date !== 'undefined' && date != "") tag += "|"+date;
            }
            if (tag == 'author') {
                // date format
                var type = $(el).parent().find('.dtag_author').val();
                if (type === 'email') tag += "-email";
            }
            if (tag == 'categories' || tag == 'tags' || tag.indexOf("customtax-") == 0 ) {
                // cat/tag seperator
                var seperator = $(el).parent().find('.dtag_seperator').val();
                if (typeof seperator !== 'undefined' && seperator != "") tag += "|"+seperator;
                else if (link) tag += "|";
            }
            if (tag == 'price') {
                var symbol = $(el).parent().find('.dtag_symbol').val();
                var format = $(el).parent().find('.dtag_format').val();
                if (symbol != "" || format != "") tag += "|"+symbol+"|"+format;
            }
            if (tag == 'woo_ajax') {
                var redirect = $(el).parent().find('.dtag_redirect').val();
                var not_twice = $(el).parent().find('.dtag_not_twice').is(':checked') ? '1' : '0';
                var clear = $(el).parent().find('.dtag_clear').is(':checked') ? '1' : '0';
                tag += "|"+redirect+"|"+not_twice+"|"+clear;
            }
            // add link
            if (link) tag += "|1";
        }
        tag = '_'+tag+"_";
        
        // hide popup
        $(el).closest('.dtag_container').children().each(function() {
            $(this).find('.popup').hide();
        });
        
        // get input type
        var type = $(el).closest('.dtag_container').data('type');
        var container = $(el).closest('.edit_form_line');
        // console.log(type);
        
        if (type == "textarea_html") {
            // default vc tinymce editor
            if (typeof tinyMCE !== 'undefined' && typeof tinyMCE.editors !== 'undefined' && typeof tinyMCE.editors.wpb_tinymce_content !== 'undefined') {
                var elem = tinyMCE.editors.wpb_tinymce_content;
                var val = elem.getContent();
                var newval = (val == '') ? tag : val+' '+tag;
                elem.setContent(newval);
            }
            else {
                var tmce_wrapper = container.children('.wp-editor-wrap');
                // dynamic content tinymce editor
                if (tmce_wrapper.length > 0 && tmce_wrapper.hasClass('tmce-active') ) {
                    var switch_html = tmce_wrapper.find('button.switch-html');
                    var switch_tmce = tmce_wrapper.find('button.switch-tmce');
                    switch_html.trigger('click');
                }
                var elem = container.find('textarea');
                var val = elem.val();
                var newval = (val == '') ? tag : ( val.match(/.*\<\/\p\>$/) ? val.replace(/\<\/\p\>$/, ' '+tag+'</p>') : val+' '+tag );
                elem.val(newval);
                elem.trigger("change");
                if (typeof switch_tmce !== 'undefined') switch_tmce.trigger('click');
            }
        }
        else if (type == "textarea") {
            var elem = container.find('textarea');
            var val = elem.val();
            var newval = (val == '') ? tag : val+' '+tag;
            elem.val(newval);
            elem.trigger("change");
        }
        else if (type == "textfield" || type == "emailfield") {
            var elem = container.find('input');
            var val = elem.val();
            var newval = (val == '') ? tag : val+' '+tag;
            elem.val(newval);
            elem.trigger("change");
        }
        else if (type == "vc_link") {
            var val = container.find('input').val();
            var url = title = target = rel = newval = "";
            var values = dyncontrol.parseVClink(val);
            if (values) {
                url = values.url;
                title = values.title;
                target = values.target;
                rel = values.rel;
            }
            url = tag;
            newval = "url:"+encodeURIComponent(url)+"|title:"+encodeURIComponent(title)+"|target:"+encodeURIComponent(target)+"|rel:"+encodeURIComponent(rel);
            container.find('.title-label').html(title);
            container.find('.url-label').html(url+target);
            container.find('input').data('json', JSON.stringify( { url:url, title:title, target:target, rel:rel } ));
            container.find('input').val(newval);
            container.find('input').trigger("change");
        }
        // else if (type == 'file_picker' || type == 'file_picker_image') {
        else if (type.indexOf('file_picker') == 0) {
            // setFilePickerTag(container.find('input'), tag);
            filepicker.setTag(container.find('input'), tag);
        }
    }
    
    // dynamic switched on-off
    this.toggleType = function(el, init) {
        init = typeof init === 'undefined' ? false : init;
        
        //console.log(el);
        var time = 300;
        if (init) time = 0;
        
        var val = $(el).val();
        var container = $(el).closest('.vc_wrapper-param-type-dynamic');
        var params = container.data('param_settings').params;
        var name_container = container.find('.dynamic_name');
        var name_input = container.find('.dynamic_name_input');
        var field = container.siblings('.vc_shortcode-param[data-vc-shortcode-param-name="'+params.field+'"]');
        var field_label = field.find('.wpb_element_label');
        var label = " <u>"+theme_wordings.vc.placeholder+"</u>";
        
        //console.log(field);
        //console.log(field_label);
        
        if (val == 'static') {
            name_container.slideUp(time * 2 / 3);
            field.attr('disabled', false);
            if (field_label.length === 1) field_label.html(field_label.html().replace(label, ""));

            if (container.data('vc-shortcode-param-name') == 'dynamic_title') {
                var htag = container.siblings('.vc_shortcode-param[data-vc-shortcode-param-name="dynamic_h_tag"]');
                htag.slideUp(time * 2 / 3);
                if (!init)
                    htag.find('.dynamic_type_checkbox').each(function() {
                        $(this).prop('checked', false);
                        $(this).trigger("change");
                    });
            }
        }
        else if (val == 'dynamic') {
            val = params.field+'|'+params.type+'|';
            if (params.type == 'dynamic_content') {
                name_container.slideUp(time * 2 / 3);
                field.find('.dynamic_value.wpb_vc_param_value').val('');
                field.find('.dynamic_value.wpb_vc_param_value').trigger("change");
                field.attr('disabled', true);
                // console.log(params.field);
                var params2 = $('#vc_ui-panel-edit-element').find('div[data-vc-shortcode-param-name="'+params.field+'"]').data('param_settings').params;
                var val2 = $('.vc_shortcode-param[data-vc-shortcode-param-name="'+params2.field+'"] select').val();
                val += val2;
            }
            else {

                if (container.data('vc-shortcode-param-name') == 'dynamic_h_tag')
                    name_container.hide();
                else
                    name_container.slideDown(time);
                
                var name = name_input.val();
                if (typeof name === "undefined" || name == "") name = name_input.attr('placeholder').split('"')[1];
                
                val += encodeURIComponent(name);
                if (field_label.length > 0 && field_label.html().indexOf(label) == -1) field_label.html(field_label.html()+label);
                
                if (container.data('vc-shortcode-param-name') == 'dynamic_title') {
                    var htag = container.siblings('.vc_shortcode-param[data-vc-shortcode-param-name="dynamic_h_tag"]');
                    htag.slideDown(time);
                    if (!init) {
                        htag.find('.dynamic_name_input').each(function() {
                            $(this).val(name+" H-Tag");
                            $(this).trigger("change");
                        });
                    }
                }
            }
        }
        $(el).prev().val(val);
        $(el).prev().trigger("change");
    }
    this.toggleButtons = function(el, href) {
        href = typeof href === 'undefined' ? "" : href;
        
        var buttons = $(el).siblings('.edit_buttons');
        
        if (typeof href !== "undefined" && href.length > 0) {
            buttons.children().removeAttr('disabled');
            buttons.children('.template_link.edit').attr('href', href);
        } 
        else {
            buttons.children().attr('disabled', true);
            buttons.children('.template_link.edit').attr('href', "");
        }
    }
    
    this.changeContent = function(el, id) {
        // console.log($(el));
        // console.log(id);
        $(el).parent().parent().prev().val(id);
        $(el).parent().parent().prev().trigger("change");
        $(el).parent().parent().hide();
    }

    // render template inputs
    this.renderContent = function(el, slug) {
        
        // disable buttons
        dyncontrol.toggleButtons(el);
        
        // no template selected
        if (slug.length <= 0) {
            // show info message
            $(el).html('<div class="greyd_info_box info">'+
                         '<span class="dashicons dashicons-info"></span>'+
                         '<div><b>'+theme_wordings.vc.no_template+'</b><span>'+theme_wordings.vc.no_template_descr+'</span></div>'+
                     '</div>');
                     dyncontrol.setValue(el, "", "");
            return;
        }
        //console.log(slug);
        
        // append loading skeleton
        $(el).html("<div class='skeleton_loader'></div>");

        // ajax
        $.post(
            wizzard_details.ajax_url, {
                'action': 'greyd_ajax',
                '_ajax_nonce': wizzard_details.nonce,
                'mode': 'crawl_template',
                'data': { slug: slug, post_id: post_id }
            }, 
            function(response) {
                
                // collect all the editor ids needed for this template
                var editor_ids = [];

                // NO DYNAMIC CONTENT FOUND
                if (response.indexOf('error::') > -1) {
                    // console.warn(response);
                    var tmp = response.split('error::');
                    var mode = dashicon = 'info';
                    try {
                        var msg = JSON.parse(tmp[1]);
                        var post_id = msg.ID;
                        var href = 'post.php?post='+post_id+'&action=edit';
                        var result = msg.result;
                        var content = '<span>'+result+'</span>';
                        if ( typeof theme_wordings.vc[result] !== "undefined" && theme_wordings.vc[result].length > 0 )
                            content = '<b>'+theme_wordings.vc[result]+'</b><span>'+theme_wordings.vc[result+'_descr'].replace('%s', slug)+'</span>';
                        console.info(result); // logging
                    }
                    // error converting JSON
                    catch(e) {
                        mode = 'alert';
                        dashicon = 'warning';
                        var msg = tmp[1];
                        var result = msg;
                        var content = '<span>'+result+'</span>';
                        if ( typeof theme_wordings.vc[result] !== "undefined" && theme_wordings.vc[result].length > 0 )
                            content = '<b>'+theme_wordings.vc[result]+'</b><span>'+theme_wordings.vc[result+'_descr'].replace('%s', slug)+'</span>';
                        console.warn(result); // logging
                    }

                    // RENDER
                    // clear loading skeleton
                    $(el).html('');
                    // append info message
                    $(el).html('<div class="greyd_info_box '+mode+'">'+
                                 '<span class="dashicons dashicons-'+dashicon+'"></span>'+
                                 '<div>'+content+'</div>'+
                             '</div>');
                    // enable buttons
                    dyncontrol.toggleButtons(el, href);
                }

                // DYNAMIC CONTENT FOUND
                else {
                    // console.info(response);
                    var mode = 'success';
                    if (response.indexOf('info::') > -1) mode = 'info';
                    var tmp = response.split(mode+'::');

                    var dynamic_content = JSON.parse(tmp[1]);
                    var post_id = dynamic_content.ID;
                    var href = 'post.php?post='+post_id+'&action=edit';
                    // console.log(dynamic_content.result);

                    // collect rendered dynamic templates
                    var inner_dynamic_template_ids = {};

                    // clear loading skeleton
                    $(el).html('');
                    // enable buttons
                    dyncontrol.toggleButtons(el, href);
                    for (var i=0; i < dynamic_content.result.length; i++) {
                        if (dynamic_content.result[i].dynamic_field.value.indexOf("|") === -1) continue;
                        var atts = dynamic_content.result[i].dynamic_field.value.split('|');
                        var sfield = atts[0];
                        var dtype = atts[1];
                        var dtitle = atts[2];
                        var svalue = dynamic_content.result[i].static_field.value;
                        var id = dyncontrol.uniquid();
                        var shortcode = vc.getMapped(dynamic_content.result[i].shortcode).name;
                        var head_title = decodeURIComponent(dtitle);
                        var head = "<div class='flex'>"+
                                        "<div class='wpb_element_label'>"+head_title+" <u>("+shortcode+")</u></div>"+
                                        "<div class='duplicate' data-count='0'></div>"+
                                    "</div>";
                        var input = "";

                        // get the input structure
                        if (dtype == "textarea") {
                            input = "<textarea class='wpb_vc_param_value' placeholder='"+svalue+"'></textarea>";
                        }
                        else if (dtype == "emailfield") {
                            input = "<input class='wpb_vc_param_value' type='email' value='' placeholder='"+ encodeURIComponent(svalue)+"'>";
                        }
                        else if (dtype == "textfield") {
                            input = "<input class='wpb_vc_param_value' type='text' value='' placeholder='"+ encodeURIComponent(svalue)+"'>";
                        }
                        else if (dtype == "textarea_html") {
                            //console.log(svalue);
                            var svalue = svalue.replace(/[\u00A0-\u9999"'<>\&]/gim, function(i) { return '&#'+i.charCodeAt(0)+';'; });
                            // wp.editor API since WP 4.8
                            // https://make.wordpress.org/core/2017/05/20/editor-api-changes-in-4-8/
                            if (typeof wp.editor.getDefaultSettings === "function") {
                                // push editor-id to array to make it a wp_editor later on
                                editor_ids.push(id);
                                input = "<textarea class='wpb_vc_param_value wp-editor-area' placeholder='"+svalue+"' id='"+id+"' ></textarea>";
                            } 
                            else {
                                input = dynamic_content.result[i].markup.replace('<textarea ', '<textarea placeholder="'+svalue+'" ');
                            }
                        }
                        else if (dtype == "vc_link") {
                            input = dynamic_content.result[i].markup;
                            // console.log(svalue);
                            var svalues = dyncontrol.parseVClink(svalue);
                            if (svalues) {
                                var sdata = 'data-title-placeholder="'+svalues.title+'" data-url-placeholder="'+svalues.url+'"';
                                input = input.replace('class="vc_link"', 'class="vc_link" '+sdata);
                            }
                        }
                        else if (dtype.indexOf("dropdown") == 0) {
                            input = dynamic_content.result[i].markup;
                            // console.log(svalue);
                            if (svalue != "") {
                                var tmp = input.split('<option class="" value="" >');
                                var tmp2 = tmp[1].split('</option>');
                                // tmp2[0] = "Placeholder ("+svalue+")";
                                var title = svalue;
                                if (typeof theme_wordings.vc[svalue] !== "undefined")
                                    title = theme_wordings.vc[svalue];
                                tmp2[0] = title+" "+theme_wordings.vc.placeholder_dyn;
                                tmp2 = tmp2.join('</option>');
                                input = tmp[0]+'<option class="" value="" >'+tmp2;
                            }
                        }
                        else if (dtype.indexOf("file_picker") == 0) {
                            input = dynamic_content.result[i].markup;
                            // console.log(svalue);
                            input = input.replace("class='file_picker_block'", "class='file_picker_block' data-url-placeholder='"+svalue+"'");
                            /**
                             * Onclick event to reset the current TinyMCE & WP-Editor-Textarea selection node.
                             * This was causing errors, where the current TinyMCE range selection was removed when inserting media.
                             */
                            var onClickEvent = "setTimeout( function() {"+
                                "$(\"textarea.wpb_vc_param_value.wp-editor-area\").prop(\"selectionStart\", 0).prop(\"selectionEnd\", 0).blur().focus();"+
                            "}, 10 );";
                            if (typeof tinymce !== "undefined") {
                                onClickEvent += " tinymce.activeEditor.selection.getSel().removeRange(tinymce.activeEditor.selection.getRng());";
                            }
                            input = input.replace(/class='button file_picker_button( hidden)?/, "class='button file_picker_button$1' onclick='"+onClickEvent+"");
                        }
                        else if (dtype == "dynamic_content") {
                            // 'dtitle' usually is the post-ID, only in old setups it's the 'slug'
                            if ( inner_dynamic_template_ids[dtitle] !== "rendered" ) {
                                head = "<div class='embed_template'><p><i>"+theme_wordings.vc.embed_template.replace("%s", dtitle )+"</i></p>";
                                input = "<input type='hidden' value='' />"+
                                        "<div class='edit_buttons'><span class='duplicate' data-count='0'></span><a class='button small template_link edit' href='' target='_blank' disabled>"+theme_wordings.vc.edit+"&nbsp;<span class='dashicons dashicons-external'></span></a></div>"+
                                        "<div id='"+id+"' class='dynamic_dynamic_item'></div></div>";
                            }
                            else {
                                head = "";
                                input = "";
                            }
                        }
                        
                        // get dynamic tags
                        // var tags = $(el).closest('.vc_wrapper-param-type-dynamic_content').data('param_settings').params['tags'];
                        var tags = '';
                        var param_settings = $(el).closest('.vc_wrapper-param-type-dynamic_content').data('param_settings');
                        if (typeof param_settings !== 'undefined') var tags = param_settings.params['tags'];
                        if (typeof tags !== 'undefined')
                            tags = dyncontrol.getTags(tags, dtype);
                        else if (typeof template_type !== 'undefined')
                            tags = dyncontrol.getTags(template_type, dtype);

                        // add tags below input
                        if (typeof tags !== 'undefined' && tags.length > 0 && dtype !== "dynamic_content") {
                            input += '<div class="dtag_wrapper"><small>'+theme_wordings.vc.dynamic_tags+'</small><br>'+tags+'</div>';
                        }
                        
                        // check for duplicates
                        var duplicate_item = $(el).closest('.dynamic_content_src').find('.dynamic_item[data-atts="'+sfield+'|'+dtype+'|'+dtitle+'"]');

                        // no duplicate found
                        if (duplicate_item.length == 0) {
                            var div = "<div class='dynamic_item edit_form_line' data-atts='"+sfield+'|'+dtype+'|'+dtitle+"'>"+
                                            head+
                                            input+
                                        "</div>";
                        }
                        // duplicate found
                        else {
                            var div = "";
                            var duplicate_text = duplicate_item.find('.duplicate').first();
                            var count = parseInt(duplicate_text.data('count')) + 1;
                            var text = (count === 1) ? theme_wordings.vc.duplicate : theme_wordings.vc.duplicates;
                            var text = text.replace('%s', count);
                            var info = theme_wordings.vc.duplicate_info.replace('%1s', head_title ).replace('%2s', count+1);
                            duplicate_text.data('count', count);
                            duplicate_text.html(text+'&nbsp;<span class="greyd_popup_wrapper">'+
                                                    '<span class="toggle dashicons dashicons-info"></span>'+
                                                    '<span class="popup">'+
                                                        '<b>'+text+'</b><br>'+
                                                        '<small>'+info+'</small>'+
                                                    '</span>'+
                                                '</span>');
                            // remove from textarea_html array to prevent multiple calls
                            editor_ids = dyncontrol.arrayRemove(editor_ids, id);
                        }
                        // render  
                        if (div !== "") $(el).append(div);

                        // query contents of embedded templates
                        if (dtype == "dynamic_content") {
                            // 'dtitle' usually is the post-ID, only in old setups it's the 'slug'
                            if ( inner_dynamic_template_ids[dtitle] !== "rendered" ) {
                                dyncontrol.wait++;
                                dyncontrol.renderContent($(el).find('#'+id), dtitle);
                                inner_dynamic_template_ids[dtitle] = "rendered";
                            }
                        }
                    }
                    
                    /*
                     *  Append info message if no content was set
                     *  
                     *  happens, when dynamic contents are defined but not saved properly
                     *  the loop skips these fields via 'continue'
                     */ 
                    if ( $(el).html() == '' ) {
                        $(el).html('<div class="greyd_info_box info">'+
                             '<span class="dashicons dashicons-info"></span>'+
                             '<div><b>'+theme_wordings.vc['no_content']+'</b><span>'+theme_wordings.vc['no_content_descr'].replace('%s', slug)+'</span></div>'+
                         '</div>');
                    }
                }
                // greyd info popup
                $(".greyd_popup_wrapper").off('click').on('click', function(e){
                    greyd_backend.togglePopup(e, $(this));
                });
                
                // insert values
                dyncontrol.insertValues(el, slug);
                dyncontrol.renderEditors(editor_ids);
            }
        );
    }
    
    // render all textareas in the array 'dyncontrol.editor_ids' as wp_editors
    this.editor_ids = [];
    this.renderEditors = function(editor_ids) {
        editor_ids = typeof editor_ids === 'undefined' ? [] : editor_ids;
        
        // console.log(editor_ids);
        if (editor_ids.length > 0 && typeof wp.editor.getDefaultSettings === "function") {
            $.each(editor_ids, function(i, id) {
                var sets = {
                    "textarea_rows": 3,
                    "media_buttons": true,
                    "quicktags": true,
                    "default_editor": "tinymce",
                    "tinymce": {
                        "theme": 'modern',
                        "plugins": ' charmap,colorpicker,hr,lists,media,paste,tabfocus,textcolor,fullscreen,wordpress,wpautoresize,wpeditimage,wpemoji,wpgallery,wplink,wpdialogs,wptextpattern,wpview ',
                        "external_plugins": theme_wordings.tinymce.plugins,
                        "toolbar1": "formatselect,fontSizePicker,bold,italic,uppercase,bullist,numlist,blockquote,alignleft,aligncenter,alignright,foreColorPicker,backColorPicker,link,wp_adv",
                        "toolbar2": "fontFamilyPicker,strikethrough,hr,pastetext,removeformat,charmap,outdent,indent,undo,redo,wp_help",
                        // "fontsize_formats": '.85em 1em 1.2em 1.6em 2.4em 3em',
                        // "setup" : function(ed) {
                        //     ed.on('change',function(e) {
                        //         //console.log('the event object ', e);
                        //         //console.log('the editor object ', ed);
                        //         //console.log('the content ', ed.getContent());
                        //     if (ed.isDirty())
                        //         ed.save();
                        //     });
                        // }
                        content_style: theme_wordings.tinymce.styles,
                        textcolor_map: theme_wordings.tinymce.colors,
                        textcolor_cols: 9
                    }
                };
                if (typeof tinymce.PluginManager.get('table') === "function") {
                    sets.tinymce.plugins += ' table ';
                    sets.tinymce.toolbar2 += ',table ';
                }
                wp.editor.initialize(id, sets);
                dyncontrol.editor_ids.push(id);
            });
            // console.log(dyncontrol.editor_ids);
        }
        
        // VC Tinymce debugging
        if ( typeof window.tinyMCEPreInit === 'object' && typeof window.tinyMCEPreInit.mceInit === 'object' ) {
            var vc_editor_id = 'wpb_tinymce_content';
            if ( !( vc_editor_id in window.tinyMCEPreInit.mceInit ) ) {
                window.tinyMCEPreInit.mceInit[vc_editor_id] = window.tinyMCEPreInit.mceInit['content'];
            }
        }
        
    }
    // save value of tinyMCE-editor to textarea
    this.saveEditors = function() {
        // console.log(dyncontrol.editor_ids);
        if (dyncontrol.editor_ids.length > 0 && typeof wp.editor.getDefaultSettings === "function") {
            $.each(dyncontrol.editor_ids, function(i, id) {
                var textarea = $('#'+id);
                if ( window.tinymce ) {
                    var content = wp.editor.getContent(id);
                    // console.log(content);
                    textarea.val(content);
                }
                textarea.trigger("change"); // to trigger set();
            });
        }
        // console.log( window.tinyMCEPreInit.mceInit );
    }
    
    // insert values into inputs
    this.wait = 0;
    this.slugs = [];
    this.insertValues = function(el, slug) {
        // console.log(dyncontrol.wait);
        dyncontrol.slugs.push(slug);
        if (dyncontrol.wait == 0) {
            // console.log("inserting values ...");
            var firstslug = dyncontrol.slugs[0];
            dyncontrol.slugs = [];
            var wrapper = $(el).closest('.dynamic_content_block');
            
            // console.log('========================================');
            // console.log('slug: '+firstslug);
            // console.log('elem:');
            // console.log($(el));
            // console.log('wrapper:');
            // console.log(wrapper);
            // console.log('========================================');

            wrapper.find('.file_picker_block').each(function() {
                // console.log("setting default file_picker placeholder");
                if ($(this).data('url-placeholder') != "") {
                    var svalue = $(this).data('url-placeholder');
                    var cached_url = wp.media.attachment(svalue).get('url');
                    if (cached_url === undefined) {
                        cached_url = "";
                        var that = this, get_value = svalue;
                        wp.media.attachment(get_value).fetch().then(function() {
                            var url = wp.media.attachment(get_value).get('url');
                            $(that).data('url-placeholder', '<i style="color:#72777c">'+url+'</i>');
                            // setFilePickerPlaceholder($(that).find('.file_picker_button'));
                            filepicker.setPlaceholder($(that).find('.file_picker_button'));
                        });
                    }
                    else $(this).data('url-placeholder', '<i style="color:#72777c">'+cached_url+'</i>');
                }
            });
            
            var values = '';
            var val_field = wrapper.find('.dynamic_value.wpb_vc_param_value');
            if ( val_field.length > 0 ) {
                var val = val_field.val();
                values = val.indexOf('::') > -1 ? val.split('::') : '';
            }
            
            var lost_values = [];
            var cache_field = wrapper.find('.dynamic_content_src');
            if ( cache_field.length > 0 ) {
                var cachevalues = cache_field.data('cached-content');
            }
            if (cachevalues != undefined) {
                // console.log(cachevalues);
                var oldvalues = false;
                for (var i=0; i<cachevalues.length; i++) {
                    var tmp_values = cachevalues[i]['value'].split('::');
                    if (cachevalues[i]['template'] == firstslug) {
                        oldvalues = tmp_values;
                    }
                    else {
                        for (var j=0; j<tmp_values.length; j++) {
                            var atts = tmp_values[j].split('|');
                            if (atts.length == 4 && atts[3] != "")
                                lost_values.push( { title: decodeURIComponent(atts[2]), value: decodeURIComponent(atts[3]) } );
                        }
                    }
                }
                if (oldvalues !== false) values = oldvalues;
            }

            if (values.length > 0) { for (var i=1; i < values.length; i++) {
                var atts = values[i].split('|');
                var sfield = atts[0];
                var dtype = atts[1];
                var dtitle = atts[2];
                var value = decodeURIComponent(atts[3]);
                var key = sfield+'|'+dtype+'|'+dtitle;
                
                // console.log(atts);
                // console.log(value);
                // console.log(key);
                
                wrapper.find('.dynamic_item[data-atts="'+key+'"]').each(function() {
                    if (dtype == "textarea")
                        $(this).find('textarea').val(value);
                    else if (dtype == "textarea_html") {
                        
                        /*  to display the value in the tinymce-editor, we need to:
                         *  # swap to html-mode
                         *  # insert the content
                         *  # and then swap back to tmce-mode
                         *  
                         *  this is a little brutal...
                         *  but in the wp.editor api there is no access to a function to set a content by id
                         *  look here for details: ../wp-admin/js/editor.js
                         */
                        if ($(this).find('.switch-html').length > 0) $(this).find('.switch-html').trigger("click");
                        $(this).find('textarea').val(value);
                        if ($(this).find('.switch-tmce').length > 0) $(this).find('.switch-tmce').trigger("click");
                        
                    } else if (dtype == "textfield" || dtype == "emailfield")
                        $(this).find('input').val(value);
                    else if (dtype.indexOf("dropdown") == 0)
                        $(this).find('select').val(value);
                    else if (dtype == "vc_link") {
                        $(this).find('input').val(value);
                        var values = dyncontrol.parseVClink(value);
                        if (values) {
                            $(this).find('input').data('json', JSON.stringify( values ));
                            $(this).find('.title-label').html(values.title);
                            $(this).find('.url-label').html(values.url+values.target);
                            dyncontrol.setVClink($(this).find('input'));
                        }
                    }
                    else if (dtype.indexOf("file_picker") == 0) {
                        if (value == "") {
                            // unsetFilePicker($(this).find('.file_picker_button'));
                            filepicker.unsetFile($(this).find('.file_picker_button'));
                        }
                        else if (!isNaN(value) && (function(x) { return (x | 0) === x; })(parseFloat(value))) {
                            var cached_url = wp.media.attachment(value).get('url');
                            if (cached_url === undefined) {
                                cached_url = "";
                                var that = this, get_value = value;
                                wp.media.attachment(get_value).fetch().then(function() {
                                    filepicker.setURL($(that).find('.file_picker_button'), { url: wp.media.attachment(get_value).get('url') });
                                });
                            }
                            // console.log(cached_url);
                            filepicker.setFile($(this).find('.file_picker_button'), { url: cached_url, id: value });
                        }
                        else {
                            // console.log(value);
                            filepicker.setTag($(this).find('.file_picker_button'), value);
                        }
                    }
                });

                if (value != "") {
                    var lost = { title: decodeURIComponent(dtitle), value: value };
                    var found = [];
                    for (var j = 0; j < lost_values.length; j++) {
                        if (lost_values[j].title == lost.title && lost_values[j].value == lost.value) {
                            // console.log("found: "+lost.title+" => "+lost.value);
                            found.push(j);
                        }
                    }
                    if (wrapper.find('.dynamic_item[data-atts="'+key+'"]').length == 0) {
                        if (found.length == 0) {
                            // console.log("add value");
                            lost_values.push( lost );
                        }
                    }
                    else {
                        if (found.length > 0) {
                            // console.log("remove values");
                            for (var j = found.length-1; j >= 0; j--) 
                                lost_values.splice(found[j], 1);
                        }
                    }
                }
            } } // end if & for
            
            wrapper.find('.vc_link').each(function() {
                // console.log("setting default vc_link placeholder");
                dyncontrol.setVClink($(this).find('input'));
            });

            wrapper.find('.dynamic_template').val(firstslug);
            dyncontrol.set(el);
            filepicker.init();
            vc.atts.vc_link2.init(null, wrapper.find('.vc_link'));
            wrapper.find('.dynamic_html').each(function() {
                quicktags({ id: $(this).attr('id') });
            });

            if (lost_values.length > 0) {
                lost_values = Array.from(new Set(lost_values.map(JSON.stringify))).map(JSON.parse);
                // console.log(lost_values);
                var text = theme_wordings.vc.lost_values.title+"<br><ul style='list-style: disc'>";
                for (var i=0; i<lost_values.length; i++) {
                    text += "<li style='margin: 10px 15px'><b>"+lost_values[i].title+":</b><br>"+lost_values[i].value+"</li>";
                }
                text += "</ul>"+theme_wordings.vc.lost_values.info;
                wrapper.find('.dynamic_content_src').prepend("<div class='greyd_info_box info'><span class='dashicons dashicons-info'></span><div><span>"+text+"</span></div></div>");
            }
        }
        else dyncontrol.wait--;
    }
    
    // setup dynamic control
    this.set = function(el) {
        // var val = $(el).val();
        // console.log(val);
        var template = $(el).closest('.dynamic_content_block').find('.dynamic_template').val();
        var value = template;
        $(el).closest('.dynamic_content_block').find('.dynamic_item').each(function() {
            var key = $(this).data('atts');
            var atts = key.split('|');
            var sfield = atts[0], dtype = atts[1], dtitle = atts[2];
            var val = $(this).find('.wpb_vc_param_value').val();
            
            if (val != undefined) {
                val = encodeURIComponent(val);
                if (dtype != "dynamic_content") value += "::"+key+'|'+val;
            }
        });
        dyncontrol.setValue(el, template, value);
    }
    
    // set value of control
    this.setValue = function(el, template, value) {
        var template_id = template;
        if (typeof template_id !== 'number') {
            for (var i=0; i<dynamic_templates.length; i++) {
                if (dynamic_templates[i].slug == template_id) {
                    template_id = dynamic_templates[i].id;
                    break;
                }
            }
        }
        var values = $(el).closest('.dynamic_content_block').find('.dynamic_content_src').data('cached-content');
        if (values == undefined) values = [];
        var found = false;
        for (var i=0; i<values.length; i++) {

            if (values[i]['template'] == template_id) {
                values[i]['value'] = value;
                found = true;
                break;
            }
        }
        if (!found) values.push( { template: template_id, value: value } );
        // console.log(value);
        $(el).closest('.dynamic_content_block').find('.dynamic_content_src').data('cached-content', values);
        $(el).closest('.dynamic_content_block').find('.dynamic_value.wpb_vc_param_value').val(value);
        $(el).closest('.dynamic_content_block').find('.dynamic_value.wpb_vc_param_value').trigger("change");
        $(el).closest('.dynamic_content_block').find('.dynamic_template').val(template_id);
        $(el).closest('.dynamic_content_block').find('.dynamic_template').trigger("change");
    }
    
    // return a unique id
    this.uniquid = function() {
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
            var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
        });
    }
    this.arrayRemove = function(arr, value) {
        return arr.filter(function(ele) {
            return ele != value;
        });
    }
    
    //  modded VC Link
    this.setVClink = function(el) {
        // console.log("set vc link placeholder ...");
        var value = $(el).val();
        var values = dyncontrol.parseVClink(value);
        if (values) {
            if (values.title == "" || values.url == "") {
                var changed = false;
                if (values.url == "") {
                    values.url = $(el).parent().data('url-placeholder');
                    if (values.url != "") changed = true;
                }
                if (values.title == "") {
                    values.title = $(el).parent().data('title-placeholder');
                    if (values.title != "") changed = true;
                }
                if (changed) {
                    newval = "url:"+encodeURIComponent(values.url)+"|title:"+encodeURIComponent(values.title)+"|target:"+encodeURIComponent(values.target)+"|rel:"+encodeURIComponent(values.rel);
                    $(el).parent().find('.title-label').html(values.title);
                    $(el).parent().find('.url-label').html(values.url+values.target);
                    $(el).data('json', JSON.stringify( values ));
                    $(el).val(newval);
                    $(el).trigger("change");
                }
            }
        }
    }
    this.parseVClink = function(value) {
        var values = { url: "", title: "", target: "", rel: "" };
        value.split('|').forEach( function(item) {
            if ( item.indexOf(':') !== false ) {
                item = item.split(':');
                var key = item[0];
                var val = item[1];
                values[ key ] = decodeURIComponent( val );
            }
        } );
        return values;
    }
    this.addVClink = function() {
        if (typeof vc !== 'undefined') {
            vc.atts.vc_link2={
                init: function(param,$field) {
                    $(".vc_link-build",$field).on("click",function(e){
                        var $block,$input,$url_label,$title_label,value_object,$link_submit,$vc_link_submit,$vc_link_nofollow,dialog;
                        e&&e.preventDefault&&e.preventDefault(),
                        $block=$(this).closest(".vc_link"),
                        $input=$block.find(".wpb_vc_param_value"),
                        $url_label=$block.find(".url-label"),
                        $title_label=$block.find(".title-label"),
                        value_object=$input.data("json"),
                        $link_submit=$("#wp-link-submit"),
                        $vc_link_submit=$('<input type="submit" name="vc_link-submit" id="vc_link-submit" class="button-primary" value="'+theme_wordings.vc.set_link+'">'),
                        $link_submit.hide(),
                        $("#vc_link-submit").remove(),
                        $vc_link_submit.insertBefore($link_submit),
                        $vc_link_nofollow=$('<div class="link-target vc-link-nofollow"><label><span></span> <input type="checkbox" id="vc-link-nofollow"> '+theme_wordings.vc.no_follow+'</label></div>'),
                        $("#link-options .vc-link-nofollow").remove(),
                        $vc_link_nofollow.insertAfter($("#link-options .link-target")),
                        setTimeout(function(){var currentHeight=$("#most-recent-results").css("top");$("#most-recent-results").css("top",parseInt(currentHeight,10)+$vc_link_nofollow.height())},200),
                        dialog=!window.wpLink&&$.fn.wpdialog&&$("#wp-link").length?{
                            $link:!1,open:function(){
                                this.$link=$("#wp-link").wpdialog({title:wpLinkL10n.title,width:480,height:"auto",modal:!0,dialogClass:"wp-dialog",zIndex:3e5}),this.$link.addClass("vc-link-wrapper")
                            },
                            close:function(){
                                this.$link&&(this.$link.wpdialog("close"),this.$link.removeClass("vc-link-wrapper"))
                            }
                        }:window.wpLink;
                        var onOpen=function(e,wrap){
                            jQuery(wrap).addClass("vc-link-wrapper")
                        },
                        onClose=function(e,wrap){
                            jQuery(wrap).removeClass("vc-link-wrapper"),
                            jQuery(document).off("wplink-open",onOpen),
                            jQuery(document).off("wplink-close",onClose)
                        };
                        jQuery(document).off("wplink-open",onOpen).on("wplink-open",onOpen),
                        jQuery(document).off("wplink-close",onClose).on("wplink-close",onClose),
                        "admin_frontend_editor"===vc_mode?dialog.open("vc-hidden-editor"):dialog.open("content"),
                        _.isString(value_object.url)&&($("#wp-link-url").length?$("#wp-link-url").val(value_object.url):$("#url-field").val(value_object.url)),
                        _.isString(value_object.title)&&($("#wp-link-text").length?$("#wp-link-text").val(value_object.title):$("#link-title-field").val(value_object.title)),
                        $("#wp-link-target").length?$("#wp-link-target").prop("checked",!_.isEmpty(value_object.target)):$("#link-target-checkbox").prop("checked",!_.isEmpty(value_object.target)),
                        $("#vc-link-nofollow").length&&$("#vc-link-nofollow").prop("checked",!_.isEmpty(value_object.rel)),
                        $vc_link_submit.unbind("click.vcLink").on("click.vcLink",function(e){
                            var options,string;
                            e&&e.preventDefault&&e.preventDefault(),
                            e&&e.stopImmediatePropagation&&e.stopImmediatePropagation(),
                            (options={}).url=$("#wp-link-url").length?$("#wp-link-url").val():$("#url-field").val(),
                            options.title=$("#wp-link-text").length?$("#wp-link-text").val():$("#link-title-field").val();
                            var $checkbox=$("#wp-link-target").length?$("#wp-link-target"):$("#link-target-checkbox");
                            return options.target=$checkbox[0].checked?" _blank":"",
                            options.rel=$("#vc-link-nofollow")[0].checked?"nofollow":"",
                            string=_.map(options,function(value,key){
                                if(_.isString(value)&&0<value.length)return key+":"+encodeURIComponent(value)
                            }).join("|"),
                            $input.val(string),
                            $input.data("json",options),
                            $url_label.html(options.url+options.target),
                            $title_label.html(options.title),
                            $input.trigger("change"), // new
                            dialog.close(),
                            $link_submit.show(),
                            $vc_link_submit.unbind("click.vcLink"),
                            $vc_link_submit.remove(),
                            $("#wp-link-cancel").unbind("click.vcLink"),
                            window.wpLink.textarea="",
                            $checkbox.attr("checked",!1),
                            $("#most-recent-results").css("top",""),
                            $("#vc-link-nofollow").attr("checked",!1),!1
                        }),
                        $("#wp-link-cancel").unbind("click.vcLink").on("click.vcLink",function(e){
                            e&&e.preventDefault&&e.preventDefault(),
                            dialog.close(),
                            $vc_link_submit.unbind("click.vcLink"),
                            $vc_link_submit.remove(),
                            $("#wp-link-cancel").unbind("click.vcLink"),
                            window.wpLink.textarea=""
                        })
                    })
                }
            }
        }
    }

}

var searchcontrol = new function() {
    
    this.vc_wrapper;
    
    this.init = function() {
        
        // get wrapper
        this.vc_wrapper = $(".vc_ui-panel[data-vc-shortcode='vc_search'] .vc_edit_form_elements");
        if ( typeof this.vc_wrapper === "undefined" || this.vc_wrapper.length <= 0 ) return false;
        
        // get selects
        var filter_select = this.vc_wrapper.find("select[name='filter']");
        var layout_select = this.vc_wrapper.find("select[name='display']");
        
        // on load
        setTimeout( function(){
            searchcontrol.updateFilterControls(filter_select);
            searchcontrol.updateLayoutControls(layout_select);
        
            // remove clone button
            searchcontrol.vc_wrapper.find("a.vc_control.column_clone").remove();
        },0);
        
        // filter is changed
        filter_select.on("change", function() {
            searchcontrol.updateFilterControls(this);
        });
        
        // layout is changed
        layout_select.on("change", function() {
            searchcontrol.updateLayoutControls(this);
        });
        
        // new row added
        vc.events.on("vc-param-group-add-new", function() {
            searchcontrol.updateFilterControls(filter_select);
            searchcontrol.updateLayoutControls(layout_select);
        
            // remove clone button
            searchcontrol.vc_wrapper.find("a.vc_control.column_clone").remove();
        });
    }
    
    this.updateFilterControls = function(select) {
        var value = $(select).val().length > 0 ? $(select).val() : 'all';
        // hide all selects
        searchcontrol.vc_wrapper.find("select[name^='fields_filter_type_']").each( function(){
            $(this).closest(".vc_shortcode-param").addClass("hidden");
        });
        // show matching select
        searchcontrol.vc_wrapper.find("select[name='fields_filter_type_"+value+"']").each( function(){
            $(this).closest(".vc_shortcode-param").removeClass("hidden");
        });
    }
    
    this.updateLayoutControls = function (select) {
        var value = $(select).val().length > 0 ? $(select).val() : 'normal';
        console.log("VALUE: "+value);
        
        searchcontrol.vc_wrapper.find("select[name='fields_type']").each( function() {
            var field = $(this);
            field.find("option.br, option.space").each(function(){
                if ( value == 'custom' ) {
                    $(this).removeAttr('disabled'); // enable options
                } else {
                    $(this).attr('disabled', 'disabled'); // disable options
                }
            });
            
        });
    }
}

// jQuery(document).ready(function($) {
jQuery(function($) {
    if (typeof $ === 'undefined') $ = jQuery;
    
    // extended param_types
    filepicker.init();
    backgrounds.init();
    socialmedia.init();
    switchcontrol.init();
    dyncontrol.init();
    searchcontrol.init();
    $('.vc_param-animation-style-trigger').each(function() {
        $(this).html(theme_wordings.vc.animate_it);
    })

    console.log("VC Scripts: loaded");
     
});


