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

(function() { 

    if (typeof $ === 'undefined') $ = jQuery;
    // $(document).ready(function() {
    $(function() {
        icons.init();
        composer.init();
        announcement.init();
        
        console.log('Admin Scripts: loaded');
    } );

} )(jQuery);

/**
 * lottie icons
 * deprecated and moved to Plugin.
 * Plugin duplicates but checks these functions, so this is used until removed here.
 */
var icons = new function() {

    this.anims = {};

    this.init = function() {
        if (typeof $ === 'undefined') $ = jQuery;
        $(document).on('ajaxComplete ajaxCompleteJSON', icons.get);
        $(document).on('click', '.attachment-preview.type-application.subtype-json', icons.getfull);
    }
    this.get = function() {
        if (typeof bodymovin === 'undefined') return;
        icons.initThumbs();
        icons.initIcons();
    }
    this.getfull = function() {
        $('.edit-attachment-frame .thumbnail.thumbnail-application').each(function() {
            var icon_path = $(this).children('img').attr('src');
            if (icon_path) {
                // console.log(icon_path);
                var icon_id = Math.random().toString(36).substr(2, 16);
                var html = "<div class='bm_icon details-image' id='"+icon_id+"' data-src='"+icon_path+"' data-anim='auto'></div>";
                $(this).html(html);
            }
        });
        icons.initIcons();
    }

    this.initThumbs = function() {
        $('.attachment-preview.type-application.subtype-json .thumbnail .centered').each(function() {
            // console.log(this);
            var icon_path = $(this).children(':first').attr('src');
            if (icon_path) {
                // console.log(icon_path);
                var icon_id = Math.random().toString(36).substr(2, 16);
                var icon_style = "display:inline-block; width:auto;";
                var html = "<div class='bm_icon' style='"+icon_style+"' id='"+icon_id+"' data-src='"+icon_path+"' data-anim='auto'></div>";
                $(this).html(html);
                $(this).removeClass('centered');
            }
        });
    }
    this.initIcons = function() {
        // get json icons
        $('.bm_icon').each(function(index) {
            // console.log($(this));
            var id = $(this).attr('id');
            // var src = $(this).data('src');
            // var anim = $(this).data('anim');
            var src = $(this)[0].dataset.src;
            var anim = $(this)[0].dataset.anim;
            var auto = false;
            if (anim == "auto") auto = true;
            if (id != "" && src != "")
                icons.addIcon(id, src, auto);
        });
    }
    this.addIcon = function(icon, icon_path, autoplay) {
        if (autoplay == undefined) autoplay = false;
        // console.log(icon+', '+icon_path+', '+autoplay);
        if (!this.anims[icon]) {
            this.anims[icon] = bodymovin.loadAnimation( {
                                    container: document.getElementById(icon),
                                    renderer: 'svg',
                                    loop: true,
                                    autoplay: autoplay,
                                    path: icon_path
                                } );
        }
        this.anims[icon].setSubframe(false);
    }

}

//
// visual composer extensions
var composer = new function() {
    
    this.init = function() {
        if (typeof root === 'undefined') return;
        if (typeof vc === 'undefined') return;
        if (typeof vc.shortcode_view === 'undefined') return;

        composer.vc_templates();
        composer.vc_forms();
        composer.vc_content_box();
        composer.vc_row();
        
        // frontendeditor & preview only for pages
        // if (post_type != "page") {
            $('.vc_control-preview').remove();
            vc_frontend_enabled = false;
        // }

        // rename WPBakery Editor
        $('#wpb_visual_composer .hndle').text('Backend Editor');

        // fire events after backend editor is ready
        vc.events.on("vc:access:backend:ready", function(access){
            // console.log("Backend editor ready");
            setTimeout( function(){
                composer.editorReady();
            }, 0 );
        });
    }

    this.init_content = "";

    this.alertOnLeave = function() {
        if ( composer.init_content !== vc.storage.getContent() )
            return 'Are you sure you want to leave?';
    }

    this.editorReady = function() {
        
        if (
            typeof vc.storage !== 'undefined' &&
            typeof vc !== 'undefined' &&
            typeof vc.app !== 'undefined'
        ) {
            // save content to compare later on
            this.init_content = vc.storage.getContent();
        
            // alert on leave when composer is changed
            $(window).on('beforeunload', composer.alertOnLeave);

            // don't alert on submit
            $('[type="submit"]').on("click", function(){
                $(window).off('beforeunload', composer.alertOnLeave);
            });

            // always init backend editor
            if ( vc.app.status !== 'shown' ) {
                vc.app.switchComposer();
                // vc.app.save(); // otherwise onbeforeunload message is always triggered
                this.init_content = vc.storage.getContent();
            }
        }

        // edit triggers for conditional fields
        $('a#vc_cond_content').on("click", function(){
            // setTimeout(function(){ composer.addCondTrigger(); },0);
            composer.addCondTrigger();
        });
        composer.addCondTrigger();
    }

    this.callback = function() {
        console.log('called');
    }
    
    // vc_templates view
    this.vc_templates = function() {
        // console.log('vc_list enabled!');
        // https://gist.github.com/AngeIII/b7948f5951755e8ddcd2
        window.VcTemplateView = vc.shortcode_view.extend( {
            changeShortcodeParams: function ( model ) {
                window.VcTemplateView.__super__.changeShortcodeParams.call( this, model );
                var wrapper = this.$el.find( '.wpb_element_wrapper' );
                // console.log(this);
                $(wrapper).find('.template').each(function() {
                    // console.log($(this));
                    var holder = $(this).html().replace("<p>", "").replace("</p>", "").trim();
                    for (var i=0; i<dynamic_templates.length; i++) {
                        if (dynamic_templates[i].id == holder || dynamic_templates[i].slug == holder) {
                            $(this).html('<strong>: </strong><span>'+dynamic_templates[i].title+'</span>');
                            break;
                        }
                    }
                });
            }
        } );
    }
    
    // forms view
    this.vc_forms = function() {
        // console.log('vc_list enabled!');
        // https://gist.github.com/AngeIII/b7948f5951755e8ddcd2
        window.VcFormsView = vc.shortcode_view.extend( {
            changeShortcodeParams: function ( model ) {
                window.VcTemplateView.__super__.changeShortcodeParams.call( this, model );
                var wrapper = this.$el.find( '.wpb_element_wrapper' );
                var label = $(wrapper).find('.vc_admin_label.admin_label_id');
                label.children().remove();
                var id = label.html().replace(':', '').trim();
                if ( typeof greyd_forms !== 'undefined' && typeof greyd_forms[id] !== 'undefined'  ) {
                    label.html( '<strong>: </strong>'+greyd_forms[id] );
                } else {
                    label.html(' ');
                }
            }
        } );
    }
    // vc_content_box view
    this.vc_content_box = function() {
        // console.log('vc_content_box enabled!');
        window.VcCbView = VcColumnView.extend( {
            changeShortcodeParams: function ( model ) {
                window.VcColumnView.__super__.changeShortcodeParams.call( this, model );
                // console.log(model);
                var $column_toggle = this.$el.find('> .vc_controls .column_add')[0];
                var params = this.model.get('params');
                var grid = "<span class='vc_row_bg_grid'></span>";
                var pre = "vc_content_box";

                // background
                if (params[pre+'_type'] != undefined && params[pre+'_type'] != "") {
                    // console.log(params);
                    // main color
                    var color = composer.getColor(params, pre);
                    // opacity
                    var opacity = composer.getOpacity(params, pre);
                    // background type
                    var title = "";
                    var content = "";
                    if (params[pre+'_type'] == pre+'_color') {
                        // render blip
                        title = theme_wordings.vc.bg_color;
                        content = '<span style="background-color: '+color+'; opacity: '+opacity+'"></span>';
                    }
                    else if (params[pre+'_type'] == pre+'_gradient2') {
                        var gradient = composer.getGradient2(params, pre);
                        // render blip
                        title = theme_wordings.vc.bg_gradient;
                        content = '<span style="background-image: '+gradient+'; opacity: '+opacity+'"></span>';
                    }
                    else if (params[pre+'_type'] == pre+'_image') {
                        // composer.getImage(params, pre);
                        if (params[pre+'_image'] != undefined && params[pre+'_image'] != "") {
                            var img_id = params[pre+'_image'];
                            var img_that = this;
                            wp.media.attachment(img_id).fetch().then(function (data) {
                                // preloading finished
                                var img_src = wp.media.attachment(img_id).get('url');                       
                                var img_div = img_that.$el.find('> .vc_controls .vc_row_bg_color');
                                $(img_div).append('<span style="background-image: url('+img_src+'); opacity: '+opacity+'"></span>');
                            });
                        }
                        // render blip
                        title = theme_wordings.vc.bg_image;
                        content = '<span style="background-color: '+color+'; opacity: '+opacity+'"></span>';
                    }
                    else if (params[pre+'_type'] == pre+'_animation') {
                        // render blip
                        title = theme_wordings.vc.bg_animation;
                        var color_span = '<span style="background-color: '+color+'; opacity: '+opacity+'"></span>';
                        var image_span = '<span style="background-image: url('+themeurl+'/assets/icon/animation.png); background-size: contain; background-repeat: no-repeat; opacity: '+opacity+'"></span>';
                        content = color_span+image_span;
                    }
                    else if (params[pre+'_type'] == pre+'_video') {
                        // render blip
                        title = theme_wordings.vc.bg_video;
                        var color_span = '<span style="background-color: '+color+'; opacity: '+opacity+'"></span>';
                        var image_span = '<span style="background-image: url('+themeurl+'/assets/icon/video.png); background-size: contain; background-repeat: no-repeat; opacity: '+opacity+'"></span>';
                        content = color_span+image_span;
                    }
                    // render blip
                    if (content != "") {
                        this.$el.find('> .vc_controls .vc_row_bg_color').remove();
                        $('<div class="vc_row_bg_color" title="'+title+'">'+grid+content+'</div>').insertBefore($column_toggle);
                    }
                }
            }
        } );
    }
    // vc_row view
    this.vc_row = function() {
        // console.log('vc_row enabled!');
        var Shortcodes = vc.shortcodes;
        window.VcRowView = vc.shortcode_view.extend({
            // vc defaults
            change_columns_layout:!1,
            events:{'click > .vc_controls [data-vc-control="delete"]':"deleteShortcode",
                    "click > .vc_controls .set_columns":"setColumns",
                    'click > .vc_controls [data-vc-control="add"]':"addElement",
                    'click > .vc_controls [data-vc-control="edit"]':"editElement",
                    'click > .vc_controls [data-vc-control="clone"]':"clone",
                    'click > .vc_controls [data-vc-control="move"]':"moveElement",
                    'click > .vc_controls [data-vc-control="toggle"]':"toggleElement",
                    "click > .wpb_element_wrapper .vc_controls":"openClosedRow"
            },
            convertRowColumns:function(layout){var layout_split=layout.toString().split(/_/),columns=Shortcodes.where({parent_id:this.model.id}),new_columns=[],new_layout=[],new_width="";return _.each(layout_split,function(value,i){var new_column_params,new_column,column_data=_.map(value.toString().split(""),function(v,i){return parseInt(v,10)});new_width=3<column_data.length?column_data[0]+""+column_data[1]+"/"+column_data[2]+column_data[3]:2<column_data.length?column_data[0]+"/"+column_data[1]+column_data[2]:column_data[0]+"/"+column_data[1],new_layout.push(new_width),new_column_params=_.extend(_.isUndefined(columns[i])?{}:columns[i].get("params"),{width:new_width}),vc.storage.lock(),new_column=Shortcodes.create({shortcode:this.getChildTag(),params:new_column_params,parent_id:this.model.id}),_.isObject(columns[i])&&_.each(Shortcodes.where({parent_id:columns[i].id}),function(shortcode){vc.storage.lock(),shortcode.save({parent_id:new_column.id}),vc.storage.lock(),shortcode.trigger("change_parent_id")}),new_columns.push(new_column)},this),layout_split.length<columns.length&&_.each(columns.slice(layout_split.length),function(column){_.each(Shortcodes.where({parent_id:column.id}),function(shortcode){vc.storage.lock(),shortcode.save({parent_id:_.last(new_columns).id}),vc.storage.lock(),shortcode.trigger("change_parent_id")})}),_.each(columns,function(shortcode){vc.storage.lock(),shortcode.destroy()},this),this.model.save(),this.setActiveLayoutButton(""+layout),new_layout},
            changeShortcodeParams:function(model){window.VcRowView.__super__.changeShortcodeParams.call(this,model),this.buildDesignHelpers(),this.setRowClasses(),this.makeBlip()},
            setRowClasses:function(){var disable=this.model.getParam("disable_element"),disableClass="vc_hidden-xs vc_hidden-sm  vc_hidden-md vc_hidden-lg";this.disable_element_class&&this.$el.removeClass(this.disable_element_class),_.isEmpty(disable)||(this.$el.addClass(disableClass),this.disable_element_class=disableClass)},
            designHelpersSelector:"> .vc_controls .column_toggle",
            buildDesignHelpers:function(){var css,$elementToPrepend,image,color,rowId,matches;css=this.model.getParam("css"),$elementToPrepend=this.$el.find(this.designHelpersSelector),this.$el.find("> .vc_controls .vc_row_color").remove(),this.$el.find("> .vc_controls .vc_row_image").remove(),(matches=css.match(/background\-image:\s*url\(([^\)]+)\)/))&&!_.isUndefined(matches[1])&&(image=matches[1]),(matches=css.match(/background\-color:\s*([^\s\;]+)\b/))&&!_.isUndefined(matches[1])&&(color=matches[1]),(matches=css.match(/background:\s*([^\s]+)\b\s*url\(([^\)]+)\)/))&&!_.isUndefined(matches[1])&&(color=matches[1],image=matches[2]),rowId=this.model.getParam("el_id"),this.$el.find("> .vc_controls .vc_row-hash-id").remove(),_.isEmpty(rowId)||$('<span class="vc_row-hash-id"></span>').text("#"+rowId).insertAfter($elementToPrepend),image&&$('<span class="vc_row_image" style="background-image: url('+image+');" title="'+window.i18nLocale.row_background_image+'"></span>').insertAfter($elementToPrepend),color&&$('<span class="vc_row_color" style="background-color: '+color+'" title="'+window.i18nLocale.row_background_color+'"></span>').insertAfter($elementToPrepend)},
            addElement:function(e){e&&e.preventDefault&&e.preventDefault(),Shortcodes.create({shortcode:this.getChildTag(),params:{},parent_id:this.model.id}),this.setActiveLayoutButton(),this.$el.removeClass("vc_collapsed-row")},
            getChildTag:function(){return"vc_row_inner"===this.model.get("shortcode")?"vc_column_inner":"vc_column"},
            sortingSelector:"> [data-element_type=vc_column], > [data-element_type=vc_column_inner]",
            sortingSelectorCancel:".vc-non-draggable-column",
            setSorting:function(){if(vc_user_access().partAccess("dragndrop")){var _this=this;1<this.$content.find(this.sortingSelector).length?this.$content.removeClass("wpb-not-sortable").sortable({
                forcePlaceholderSize:!0,
                placeholder:"widgets-placeholder-column",
                tolerance:"pointer",
                cursor:"move",
                items:this.sortingSelector,
                cancel:this.sortingSelectorCancel,
                distance:.5,
                start:function(event,ui){$("#visual_composer_content").addClass("vc_sorting-started"),ui.placeholder.width(ui.item.width())},
                stop:function(event,ui){$("#visual_composer_content").removeClass("vc_sorting-started")},
                update:function(){var $columns=$(_this.sortingSelector,_this.$content);$columns.each(function(){var model=$(this).data("model"),index=$(this).index();model.set("order",index),$columns.length-1>index&&vc.storage.lock(),model.save()})},
                over:function(event,ui){ui.placeholder.css({maxWidth:ui.placeholder.parent().width()}),ui.placeholder.removeClass("vc_hidden-placeholder")},
                beforeStop:function(event,ui){}
            }):(this.$content.hasClass("ui-sortable")&&this.$content.sortable("destroy"),this.$content.addClass("wpb-not-sortable"))}},
            validateCellsList:function(cells){var b,return_cells=[],split=cells.replace(/\s/g,"").split("+");return 12===_.reduce(_.map(split,function(c){if(c.match(/^(vc_)?span\d?$/)){var converted_c=vc_convert_column_span_size(c);return!1===converted_c?1e3:(b=converted_c.split(/\//),return_cells.push(b[0]+""+b[1]),12*parseInt(b[0],10)/parseInt(b[1],10))}return c.match(/^[1-9]|1[0-2]\/[1-9]|1[0-2]$/)?(b=c.split(/\//),return_cells.push(b[0]+""+b[1]),12*parseInt(b[0],10)/parseInt(b[1],10)):1e4}),function(num,memo){return memo+=num},0)&&return_cells.join("_")},
            setActiveLayoutButton:function(column_layout){column_layout||(column_layout=_.map(vc.shortcodes.where({parent_id:this.model.get("id")}),function(model){var width=model.getParam("width");return width?width.replace(/\//,""):"11"}).join("_")),this.$el.find("> .vc_controls .vc_active").removeClass("vc_active");var $button=this.$el.find('> .vc_ [data-cells-mask="'+vc_get_column_mask(column_layout)+'"] [data-cells="'+column_layout+'"], > .vc_controls [data-cells-mask="'+vc_get_column_mask(column_layout)+'"][data-cells="'+column_layout+'"]');$button.length?$button.addClass("vc_active"):this.$el.find("> .vc_controls [data-cells-mask=custom]").addClass("vc_active")},
            layoutEditor:function(){return _.isUndefined(vc.row_layout_editor)&&(vc.row_layout_editor=new vc.RowLayoutUIPanelBackendEditor({el:$("#vc_ui-panel-row-layout")})),vc.row_layout_editor},
            setColumns:function(e){_.isObject(e)&&e.preventDefault();var $button=$(e.currentTarget);if("custom"===$button.data("cells"))this.layoutEditor().render(this.model).show();else{if(vc.is_mobile){var $parent=$button.parent();$parent.hasClass("vc_visible")||($parent.addClass("vc_visible"),$(document).off("click.vcRowColumnsControl").on("click.vcRowColumnsControl",function(e){$parent.removeClass("vc_visible")}))}$button.is(".vc_active")||(this.change_columns_layout=!0,_.defer(function(view,cells){view.convertRowColumns(cells)},this,$button.data("cells")))}this.$el.removeClass("vc_collapsed-row")},
            sizeRows:function(){var max_height=45;$("> .wpb_vc_column, > .wpb_vc_column_inner",this.$content).each(function(){var content_height=$(this).find("> .wpb_element_wrapper > .wpb_column_container").css({minHeight:0}).height();max_height<content_height&&(max_height=content_height)}).each(function(){$(this).find("> .wpb_element_wrapper > .wpb_column_container").css({minHeight:max_height})})},
            ready:function(e){return window.VcRowView.__super__.ready.call(this,e),this},
            checkIsEmpty:function(){window.VcRowView.__super__.checkIsEmpty.call(this),this.setSorting()},
            changedContent:function(view){if(this.change_columns_layout)return this;this.setActiveLayoutButton()},
            moveElement:function(e){e&&e.preventDefault&&e.preventDefault()},
            toggleElement:function(e){e&&e.preventDefault&&e.preventDefault(),this.$el.toggleClass("vc_collapsed-row")},
            openClosedRow:function(e){this.$el.removeClass("vc_collapsed-row")},
            remove:function(){this.$content&&(this.$content.data("uiSortable")&&this.$content.sortable("destroy"),this.$content.data("uiDroppable")&&this.$content.droppable("destroy")),delete vc.app.views[this.model.id],window.VcRowView.__super__.remove.call(this)},
            // extensions
            makeBlip: function() {
                // console.log('make blip!');
                var $column_toggle = this.$el.find('> .vc_controls .column_toggle');
                var params = this.model.get('params');
                var grid = "<span class='vc_row_bg_grid'></span>";
                var pre = "vc_bg";
                
                // backend description
                if (params[pre+'_description'] != undefined && params[pre+'_description'] != "") {
                    // render blip
                    var title = params[pre+'_description'];
                    this.$el.find('> .vc_controls .vc_row_bg_description').remove();
                    var html ='<div class="vc_row_bg_description"><span class="preview">';
                    html += title.length > 28 ? title.substr(0,25)+'...</span><span class="descr">'+title+'</span></div>' : title+'</span></div>';
                    $(html).insertAfter($column_toggle);
                }
                else this.$el.find('> .vc_controls .vc_row_bg_description').remove();

                // row type
                if (params[pre+'_type'] != undefined) {
                    // render blip
                    var title = params['row_type'];
                    var after = "";
                    if (title == undefined || title == "") {
                        // if (post_type == "dynamic_template" && template_type == "dynamic")
                        if (post_type == "dynamic_template" && template_type == "dynamic")
                            title = root['GRDrowtdefault']['value'];
                        else title = root['GRDrowdefault']['value'];
                        after = " "+theme_wordings.vc.bg_row_default;
                    }
                    if (title == 'row_l') title = "S";
                    else if (title == 'row_xl') title = "M";
                    else if (title == 'row_xxl') title = "L";
                    else if (title == 'row_xxxl') title = "XL";
                    this.$el.find('> .vc_controls .vc_row_bg_type').remove();
                    var t = theme_wordings.vc.bg_row.replace('%s', title)+after;
                    $('<div class="vc_row_bg_type" title="'+t+'">'+title+'</div>').insertAfter($column_toggle);
                }
                
                // background
                if (params[pre+'_type'] != undefined && params[pre+'_type'] != "") {
                    // console.log(params);
                    // main color
                    var color = composer.getColor(params, pre);
                    // opacity
                    var opacity = composer.getOpacity(params, pre);
                    // background type
                    var title = "";
                    var content = "";
                    if (params[pre+'_type'] == pre+'_color') {
                        // render blip
                        title = theme_wordings.vc.bg_color;
                        content = '<span style="background-color: '+color+'; opacity: '+opacity+'"></span>';
                    }
                    else if (params[pre+'_type'] == pre+'_gradient2') {
                        var gradient = composer.getGradient2(params, pre);
                        // render blip
                        title = theme_wordings.vc.bg_gradient;
                        content = '<span style="background-image: '+gradient+'; opacity: '+opacity+'"></span>';
                    }
                    else if (params[pre+'_type'] == pre+'_image') {
                        // composer.getImage(params, pre);
                        if (params[pre+'_image'] != undefined && params[pre+'_image'] != "") {
                            var img_id = params[pre+'_image'];
                            var img_that = this;
                            wp.media.attachment(img_id).fetch().then(function (data) {
                                // preloading finished
                                var img_src = wp.media.attachment(img_id).get('url');                       
                                var img_div = img_that.$el.find('> .vc_controls .vc_row_bg_color');
                                $(img_div).append('<span style="background-image: url('+img_src+'); opacity: '+opacity+'"></span>');
                            });
                        }
                        // render blip
                        title = theme_wordings.vc.bg_image;
                        content = '<span style="background-color: '+color+'; opacity: '+opacity+'"></span>';
                    }
                    else if (params[pre+'_type'] == pre+'_animation') {
                        // render blip
                        title = theme_wordings.vc.bg_animation;
                        var color_span = '<span style="background-color: '+color+'; opacity: '+opacity+'"></span>';
                        var image_span = '<span style="background-image: url('+themeurl+'/assets/icon/animation.png); background-size: contain; background-repeat: no-repeat; opacity: '+opacity+'"></span>';
                        content = color_span+image_span;
                    }
                    else if (params[pre+'_type'] == pre+'_video') {
                        // render blip
                        title = theme_wordings.vc.bg_video;
                        var color_span = '<span style="background-color: '+color+'; opacity: '+opacity+'"></span>';
                        var image_span = '<span style="background-image: url('+themeurl+'/assets/icon/video.png); background-size: contain; background-repeat: no-repeat; opacity: '+opacity+'"></span>';
                        content = color_span+image_span;
                    }
                    // render blip
                    if (content != "") {
                        this.$el.find('> .vc_controls .vc_row_bg_color').remove();
                        $('<div class="vc_row_bg_color" title="'+title+'">'+grid+content+'</div>').insertAfter($column_toggle);
                    }
                }
                else this.$el.find('> .vc_controls .vc_row_bg_color').remove();

                // overlay
                if (params[pre+'_overlay'] != undefined && params[pre+'_overlay'] != "") {
                    var overlay_type = params[pre+'_overlay_type'];
                    if (overlay_type == undefined) overlay_type = pre+'_color';
                    // color
                    var overlay_color = "";
                    if (overlay_type == pre+"_color") {
                        var overlay_color_opacity = composer.getOpacity(params, pre+'_overlay_color');
                        overlay_color = composer.getColor(params, pre+'_overlay');
                        if (overlay_color != '') 
                            overlay_color = '<span style="background-color: '+overlay_color+'; opacity: '+overlay_color_opacity+'"></span>';
                    }
                    // gradient
                    if (overlay_type == pre+"_gradient2") {
                        var overlay_color_opacity = composer.getOpacity(params, pre+'_overlay_color');
                        overlay_color = composer.getGradient2(params, pre+'_overlay');
                        overlay_color = '<span style="background-image: '+overlay_color+'; opacity: '+overlay_color_opacity+'"></span>';
                    }
                    // overlay pattern
                    var overlay_opacity = composer.getOpacity(params, pre+'_overlay');
                    var overlay_pattern = "";
                    if (params[pre+'_overlay_pattern'] != undefined && params[pre+'_overlay_pattern'] != "") {
                        if (params[pre+'_overlay_pattern'] == "pattern_custom") {
                            var pattern_id = params[pre+'_overlay_cpattern'];
                            var pattern_that = this;
                            wp.media.attachment(pattern_id).fetch().then(function (data) {
                                // preloading finished
                                var pattern_src = wp.media.attachment(pattern_id).get('url');                       
                                var pattern_div = pattern_that.$el.find('> .vc_controls .vc_row_bg_overlay');
                                $(pattern_div).append('<span style="background-image: url('+pattern_src+');background-size: 10px; opacity: '+overlay_opacity+'"></span>');
                            });
                        }
                        else {
                            overlay_pattern = patterns[params[pre+'_overlay_pattern']];
                            overlay_pattern = '<span style="background-image: url('+overlay_pattern+');background-size: 5px; opacity: '+overlay_opacity+'"></span>';
                        }
                    }
                    // render blip
                    var title = theme_wordings.vc.bg_overlay;
                    this.$el.find('> .vc_controls .vc_row_bg_overlay').remove();
                    $('<div class="vc_row_bg_overlay" title="'+title+'">'+grid+overlay_color+overlay_pattern+'</div>').insertAfter($column_toggle);
                }
                else this.$el.find('> .vc_controls .vc_row_bg_overlay').remove();

                // seperator
                if (params[pre+'_seperator'] != undefined && params[pre+'_seperator'] != "") {
                    // color
                    var seperator_opacity = composer.getOpacity(params, pre+'_seperator');
                    var seperator_color = composer.getColor(params, pre+'_seperator');
                    // overlay type
                    var seperator_type = "";
                    var seperator_div = "";
                    if (params[pre+'_seperator_type'] != undefined && params[pre+'_seperator_type'] != "") {
                        if (seperator_color == "" || seperator_color == "transparent") seperator_color = "#888";
                        seperator_type = getSeperator(params[pre+'_seperator_type'], "7px", seperator_color);
                        if (params[pre+'_seperator_position'] != undefined) {
                            if (params[pre+'_seperator_position'] == "") {
                                seperator_div = '<span style="opacity: '+seperator_opacity+'">'+seperator_type+'</span>';
                            }
                            else if (params[pre+'_seperator_position'] == "bottom") {
                                seperator_div = '<span class="sep_bottom" style="opacity: '+seperator_opacity+'">'+seperator_type+'</span>';
                            }
                            else if (params[pre+'_seperator_position'] == "top_bottom") {
                                seperator_div = '<span style="opacity: '+seperator_opacity+'">'+seperator_type+'</span>';
                                seperator_div += '<span class="sep_bottom" style="opacity: '+seperator_opacity+'">'+seperator_type+'</span>';
                            }
                            else if (params[pre+'_seperator_position'] == "top_bottom_asym") {
                                seperator_div = '<span style="opacity: '+seperator_opacity+'">'+seperator_type+'</span>';
                                seperator_div += '<span class="sep_bottom_mirror" style="opacity: '+seperator_opacity+'">'+seperator_type+'</span>';
                            }
                        }
                        
                    }
                    // render blip
                    var title = theme_wordings.vc.bg_seperator;
                    this.$el.find('> .vc_controls .vc_row_bg_seperator').remove();
                    $('<div class="vc_row_bg_seperator" title="'+title+'">'+grid+seperator_div+'</div>').insertAfter($column_toggle);
                }
                else this.$el.find('> .vc_controls .vc_row_bg_seperator').remove();

            },
        });
    }
    
    this.getColor = function(params, pre, post="") {
        var color = "transparent";
        if (params[pre+'_colorselect'+post] != undefined && params[pre+'_colorselect'+post] != "") {
            color = params[pre+'_colorselect'+post];
            if (color.indexOf('color_') == 0)  {
                color = root["--"+color.replace("_", "")];
                if (color) color = color['value'];
                else color = "transparent";
            }
        }
        else if (params[pre+'_color'+post] != undefined && params[pre+'_color'+post] != "") {
            var colormod = root["--"+params[pre+'_color'+post].replace("_", "")];
            if (colormod) color = colormod['value'];
            else if (params[pre+'_ccolor'+post] != undefined && params[pre+'_ccolor'+post] != "") color = params[pre+'_ccolor'+post];
        }
        return color;
    }
    this.getOpacity = function(params, pre, post="") {
        var opacity = 1;
        if (params[pre+'_opacity'+post] != undefined && params[pre+'_opacity'+post] != "") {
            var op = params[pre+'_opacity'+post];
            op = op.replace("%", "");
            opacity = op/100.0;
        }
        return opacity;
    }
    this.getPosition = function(params, pre, post="") {
        var pos = "0%";
        if (post == "2") pos = "100%";
        if (params[pre+'_gradient_pos'+post] != undefined && params[pre+'_gradient_pos'+post] != "") {
            pos = params[pre+'_gradient_pos'+post];
            if (pos.indexOf("%") == -1) pos = pos+"%";
        }
        return pos;
    }
    this.getGradient2 = function(params, pre) {
        // read value
        var gradient_raw = "scroll|angle|45|color_21:0|color_33:100"
        if (params[pre+'_gradient2'] != undefined && params[pre+'_gradient2'] != "") {
            gradient_raw = params[pre+'_gradient2'];
        }
        var tmp = gradient_raw.split('|');
        var gradient_array = { type: tmp[1], angle: tmp[2], scroll: tmp[0], colors: [] };
        // colors
        for (var i=3; i<tmp.length; i++) {
            var color = tmp[i].split(':');
            if (color[0].indexOf("color_") === 0) color[0] = root["--"+color[0].replace("_", "")]['value'];
            else if (color[0] == "") color[0] = 'transparent';
            gradient_array['colors'].push( { color: color[0], position: color[1] } );
        }
        // angle
        var angle = gradient_array['type'];
        if (angle == "" || angle == "top") angle = 180;
        else if (angle == "bottom") angle = 0;
        else if (angle == "left") angle = 90;
        else if (angle == "right") angle = 270;
        else angle = gradient_array['angle'];
        // make gradient
        var gradient = "";
        for (var i=0; i<gradient_array['colors'].length; i++) {
            gradient += ', '+gradient_array['colors'][i]['color']+' '+gradient_array['colors'][i]['position']+'%';
        }
        return 'linear-gradient('+angle+'deg'+gradient+')';
    }
    
    this.condTrigger;
    this.addCondTrigger = function () {
        this.condTrigger = $('.wpb_vc_cond_content .vc_tta-section-append');
        // console.log(this.condTrigger);
        this.condTrigger.removeClass('vc_tta-section-append').addClass('vc_cond_content_item-append');
        this.condTrigger.on("click", function(e){
            e.preventDefault();
            var newTabTitle= theme_wordings.new_condition;
            var params = {
                shortcode: "vc_cond_content_item",
                params: {
                    title: newTabTitle
                },
                parent_id: $(this).closest('.wpb_vc_cond_content').data('model-id'),
                order: vc.shortcodes.getNextOrder(),
                prepend: undefined
            };
            vc.shortcodes.create(params);
            //console.log('new condition');
        });
    }
    
    this.insertTagText = function(element) {
        var text = $(element).text(),
            wrapper = $(element).closest('.vc_description').siblings('.wp-editor-wrap'),
            textarea = wrapper.find('textarea.content'),
            tabs = wrapper.find('.wp-editor-tabs'),
            button1 = tabs.find('#wpb_tinymce_content-tmce'),
            button2 = tabs.find('#wpb_tinymce_content-html');

        button2.trigger("click");
        textarea.val( textarea.val()+' '+text );
        button1.trigger("click");
    }
}

//
// announcement media file picker
var announcement = new function() {
    
    this.init = function() {
        $('#announce_toggle').on('click', announcement.toggle);
        $('#announce_img_button').on('click', announcement.select);
        $('#announce_img_remove').on('click', announcement.remove);
    }

    this.toggle = function() {
        var newval = $(this).prop('checked');
        // console.log(newval);
        $(this).parent().parent().parent().find('.toggle_row').each(function(){
            // console.log(this);
            if (newval == true) $(this).show();
            else $(this).hide();
        });
    };

    this.select = function() {
        wp.media.editor.send.attachment = function( props, attachment ) {
            // console.log(attachment);
            if (attachment.url.indexOf('.json') > -1) {
                alert(theme_wordings.select_image);
                return false;
            }
            $('#announce_image').val(attachment.url);
            $('#announce_img_url').html(attachment.url);
            $('#announce_img_src').attr('src', attachment.url);
            $('.image_preview').css('display', 'block');
            $('#announce_img_button').addClass('hidden');
            $('#announce_img_remove').removeClass('hidden');
        }
        wp.media.editor.open( $('#announce_img_button') );
        return false;
    };

    this.remove = function() {
        $('#announce_image').val('');
        $('#announce_img_url').html('');
        $('#announce_img_src').attr('src', '');
        $('.image_preview').css('display', 'none');
        $('#announce_img_button').removeClass('hidden');
        $('#announce_img_remove').addClass('hidden');
        return false;
    };
};

//
// File Picker
var filepicker = new function() {
    
    this.custom_media = true;
    this.orig_send_attachment = false;

    this.init = function() {
        if (typeof $ === 'undefined') $ = jQuery;
        if (wp.media == undefined) return;
        filepicker.custom_media = true;
        filepicker.orig_send_attachment = wp.media.editor.send.attachment;
        // add events
        $(document).on('click', '.file_picker_block .file_picker_button', filepicker.chooseFile );
        $(document).on('click', '.file_picker_block .file_remover_button', filepicker.removeFile );
        $(document).on('click', '.add_media', function() { filepicker.custom_media = false; } );
    }
    
    this.chooseFile = function() {
        var file_picker_button = $(this);
        filepicker.custom_media = true;
        wp.media.editor.send.attachment = function( props, attachment ) {
            if (filepicker.custom_media) {
                // console.log("custom media");
                filepicker.setFile(file_picker_button, attachment);
            } 
            else {
                // console.log("original media");
                return filepicker.orig_send_attachment.apply(this, [props, attachment]);
            };
        }
        wp.media.editor.open();
        return false;
    }
    this.removeFile = function() {
        var file_remover_button = $(this);
        filepicker.unsetFile(file_remover_button);
        return false;
    }

    this.setFile = function(el, attachment) {
        var file_picker_button = $(el);
        var file_remover_button = $(el).parent().find( '.file_remover_button' );
        var img = $(el).parent().find( '.file_picker_img' );
        var anim = $(el).parent().find( '.file_picker_anim' );
        var url = $(el).parent().find( '.file_picker_url' );
        var input = $(el).parent().find( '.file_picker_input' );
        var filetype = $(el).parent().find( '.file_picker_type' );

        if (attachment.url != "") {
            var ft = JSON.parse(filetype.val());
            // console.log(ft);
            // make preview
            if (attachment.url.indexOf('.json') > -1) {
                if (ft == "image") {
                    alert(theme_wordings.select_image);
                    return false;
                }
                anim.html('');
                anim.data('src', attachment.url)
                anim.attr('id', 'bm_'+Math.random().toString(36).substr(2, 16));
                anim.removeClass( 'hidden' );
                img.addClass( 'hidden' );
                $(document).trigger('ajaxCompleteJSON');
            }
            else if (attachment.url.indexOf('.svg') > -1 ||
                    attachment.url.indexOf('.png') > -1 ||
                    attachment.url.indexOf('.jpg') > -1 ||
                    attachment.url.indexOf('.gif') > -1) {
                if (ft == "json") {
                    alert(theme_wordings.select_animation);
                    return false;
                }
                img.attr( 'src', attachment.url );
                img.removeClass( 'hidden' );
                anim.addClass( 'hidden' );
            }
            else {
                if (ft.includes("json") && ft.includes("image")) {
                    alert(theme_wordings.select_media);
                    return false;
                }
                else if (ft == "json" || ft.includes("json")) {
                    alert(theme_wordings.select_animation);
                    return false;
                }
                else if (ft == "image" || ft.includes("image")) {
                    alert(theme_wordings.select_image);
                    return false;
                }
            }
            // url and buttons
            url.html( attachment.url+'<br>' );
        }
        url.removeClass( 'hidden' );
        input.val( attachment.id );
        input.trigger("change");
        file_picker_button.addClass( 'hidden' );
        file_remover_button.removeClass( 'hidden' );
    }
    this.unsetFile = function(el) {
        var file_picker_button = $(el).parent().find( '.file_picker_button' );
        var file_remover_button = $(el).parent().find( '.file_remover_button' );
        var img = $(el).parent().find( '.file_picker_img' );
        var anim = $(el).parent().find( '.file_picker_anim' );
        var url = $(el).parent().find( '.file_picker_url' );
        var input = $(el).parent().find( '.file_picker_input' );
        var placeholder = $(el).parent().data( 'url-placeholder' );

        anim.html('');
        anim.data('src', '')
        anim.attr('id', '');
        anim.addClass( 'hidden' );
        img.attr( 'src', '' );
        img.addClass( 'hidden' );
        if (typeof(placeholder) ==='undefined' || placeholder == "") {
            url.html( '' );
            url.addClass( 'hidden' );
        }
        else {
            url.html( placeholder );
            url.removeClass( 'hidden' );
        }
        input.val( '' );
        input.trigger("change");
        file_picker_button.removeClass( 'hidden' );
        file_remover_button.addClass( 'hidden' );
    }
    
    this.setTag = function(el, tag) {
        var file_picker_button = $(el).parent().find( '.file_picker_button' );
        var file_remover_button = $(el).parent().find( '.file_remover_button' );
        var img = $(el).parent().find( '.file_picker_img' );
        var anim = $(el).parent().find( '.file_picker_anim' );
        var url = $(el).parent().find( '.file_picker_url' );
        var input = $(el).parent().find( '.file_picker_input' );

        img.addClass( 'hidden' );
        anim.addClass( 'hidden' );
        url.removeClass( 'hidden' );
        url.html( tag+'<br>' );
        input.val( tag );
        input.trigger("change");
        file_picker_button.addClass( 'hidden' );
        file_remover_button.removeClass( 'hidden' );
    }
    this.setURL = function(el, attachment) {
        var img = $(el).parent().find( '.file_picker_img' );
        var anim = $(el).parent().find( '.file_picker_anim' );
        var url = $(el).parent().find( '.file_picker_url' );

        // make preview
        if (attachment.url.indexOf('.json') > -1) {
            anim.html('');
            anim.data('src', attachment.url)
            anim.attr('id', 'bm_'+Math.random().toString(36).substr(2, 16));
            anim.removeClass( 'hidden' );
            img.addClass( 'hidden' );
            $(document).trigger('ajaxCompleteJSON');
        }
        if (attachment.url.indexOf('.svg') > -1 ||
            attachment.url.indexOf('.png') > -1 ||
            attachment.url.indexOf('.jpg') > -1 ||
            attachment.url.indexOf('.gif') > -1) {
            img.attr( 'src', attachment.url );
            img.removeClass( 'hidden' );
            anim.addClass( 'hidden' );
        }
        // url and buttons
        url.html( attachment.url+'<br>' );
    }
    this.setPlaceholder = function(el) {
        var url = $(el).parent().find( '.file_picker_url' );
        var input = $(el).parent().find( '.file_picker_input' );
        var placeholder = $(el).parent().data( 'url-placeholder' );

        if (input.val() == '') {
            if (typeof(placeholder) ==='undefined' || placeholder == "") {
                url.html( '' );
                url.addClass( 'hidden' );
            }
            else {
                url.html( placeholder );
                url.removeClass( 'hidden' );
            }
        }
    }

}