/***************************************************************************
 *
 *  ----------------------------------------------------------------------
 *                      DO NOT EDIT THIS FILE
 *  ----------------------------------------------------------------------
 *
 *                       Copyright (C) Themify
 *
 *  ----------------------------------------------------------------------
 *
 ***************************************************************************/

/**
 * Common shared code between backend and frontend Builder.
 */

var ThemifyBuilderCommon;
if (window.top !== window.self) {
    //use top iframe js files
    window.wp.media = window.top.wp.media;
    MediaElementPlayer = window.top.MediaElementPlayer;
    jQuery.fn.mediaelementplayer = window.top.jQuery(window.top.document).mediaelementplayer;
    jQuery.ui = window.top.jQuery.ui;
    jQuery.fn.sortable = window.top.jQuery(window.top.document).sortable;
    window.wp.mediaelement = window.top.wp.mediaelement;
    window.tinyMCE = window.top.tinyMCE;
    window.tinyMCEPreInit = window.top.tinyMCEPreInit;
    window.tinymce = window.top.tinymce;
    window.switchEditors = window.top.switchEditors;
    window.self.wp === undefined && (window.self.wp = window.top.wp);
    window.self._ === undefined && (window.self._ = window.top._);
}

(function ($,Themify, topWindow, document,undefined) {

    'use strict';

    ThemifyBuilderCommon = {
        loader: null,
        is_template_support: 'content' in document.createElement('template'),
        showLoader: function (stats) {
            if (this.loader === null) {
                this.loader = $(topWindow.document.getElementById('tb_alert'));
            }
            if (stats === 'show') {
                this.loader[0].classList.add('tb_busy');
                this.loader[0].style['display'] = 'block';
            }
            else if (stats === 'spinhide') {
                this.loader.fadeOut(300, function () {
                    this.classList.remove('tb_busy');
                });
            }
            else {
                if (stats !== 'error') {
                    stats = 'done';
                }
                this.loader[0].classList.remove('tb_busy');
                this.loader[0].classList.add('tb_' + stats);
                this.loader.delay(500).fadeOut(500, function () {
                    this.classList.remove('tb_' + stats);
                });
            }
        },
        clone: function (el) {
            if(el[0]!==undefined){
                el = el[0];
            }
            var node = el.cloneNode(true);
            $(node).find('#tb_component_bar').empty().attr('id','').closest('.tb_clicked').removeClass('tb_clicked');
            if (tb_app.mode === 'visual') {
                //after cloning dom the video is playing in bg
                var v = node.getElementsByTagName('video');
                if (v.length > 0) {
                    var bg = node.getElementsByClassName('big-video-wrap');
                    for (var i = v.length-1; i > -1; --i) {
                        v[i].pause();
                    }
                    for (var i =bg.length-1; i>-1; --i) {
                        if (bg[i]) {
                            bg[i].parentNode.removeChild(bg[i]);
                        }
                    }
                }
            }
            return $(node);
        },
        /**
         * Clipboard-like functionality. Wraps localStorage with a Themify key. Supports one copied item per time.
         */
        Clipboard: {
            key: 'themify_builder_clipboard_',
            set: function (type, content) {
                    var data = {};
                    data[type] = content;
                    localStorage.setItem(this.key + 'content', JSON.stringify(data));
            },
            get: function (type) {
                var savedContent = JSON.parse(localStorage.getItem(this.key + 'content'));
                return savedContent[type] !== undefined ? savedContent[type] : false;
            }
        },
        alertWrongPaste: function () {
            alert(themifyBuilder.i18n.text_alert_wrong_paste);
        },
        autoComplete: function ($container) {
            var tax_el = $('.themify_tax_autocomplete', $container);
            if (tax_el.length > 0) {
                var $data = [];
                tax_el.each(function () {
                    var $this = $(this),
                            $input = $this.closest('.tb_input').find('input.query_category_multiple'),
                            $val = $input.val();
                    $(this).autocomplete({
                        minLength: 2,
                        source: function (request, response) {
                            var term = $.trim(request.term);
                            $.getJSON(themifyBuilder.ajaxurl, {
                                term: $.trim(term),
                                tax: $this.data('tax'),
                                action: $this.data('action')
                            },
                            function (data, status, xhr) {
                                response(data);
                            });
                        },
                        select: function (event, ui) {
                            $input.val(ui.item.value);
                            this.value = ui.item.label;
                            return false;
                        }
                    }).focus(function () {
                        $(this).autocomplete("search");
                        return false;
                    });
                    if ($val && $val !== 'undefined') {
                        var object = {};
                        object[$this.data('tax')] = $val;
                        $data.push(object);
                    }
                    else {
                        $input.val('');
                    }
                });
                if ($data.length > 0) {
                    $.ajax({
                        url: themifyBuilder.ajaxurl,
                        type: 'POST',
                        dataType: 'json',
                        data: {'data': $data, 'action': 'themify_builder_get_tax_data'},
                        success: function (resp) {
                            if (resp) {
                                for (var $i in resp) {
                                    $('#themify_search_cat_' + resp[$i].tax, $container).val(resp[$i].val);
                                }
                            }
                        }
                    });
                }
            }
        },
        Lightbox: {
            $lightbox: null,
            lightboxStorageKey:topWindow.document !== document ? 'themify_builder_lightbox_frontend_pos_size' : 'themify_builder_lightbox_backend_pos_size',
            setup: function () {
                if (ThemifyBuilderCommon.is_template_support) {
                    topWindow.document.body.appendChild(document.getElementById('tmpl-builder_lightbox').content);
                }
                else {
                    topWindow.document.body.insertAdjacentHTML('beforeend', ThemifyBuilderCommon.templateCache.get('tmpl-builder_lightbox'));
                }
                this.$lightbox = $('#tb_lightbox_parent', topWindow.document);
                this.bindEvents();
            },
            bindEvents: function () {
                SimpleBar.removeObserver();
                this.responsiveTabs();
                this.$lightbox.one('themify_opened_lightbox',function(){
                    this.resizable.init();
                    if (tb_app.mode === 'visual') {
                        // Cancel docked mode
                        this.$lightbox[0].getElementsByClassName('builder_cancel_docked_mode')[0].addEventListener('click', function (e) {
                            e.preventDefault();
                            e.stopPropagation();
                            topWindow.document.body.classList.add('themify_lightbox_drag');
                            ThemifyBuilderCommon.Lightbox.dockMode.close();
                            $(document).triggerHandler('mouseup');
                            setTimeout(function(){
                                topWindow.document.body.classList.remove('themify_lightbox_drag');
                            },300);
                        });   
                    }
                    this.$lightbox[0].getElementsByClassName('tb_close_lightbox')[0].addEventListener('click',function(){
                        this.close();
                    }.bind(this),{passive:true});
                }.bind(this));
                if (!themifyBuilder.disableShortcuts) {
                    this.controlByKeyInput();
                }
            },
            getLightboxStorage: function () {
                var lightboxStorage = localStorage.getItem(this.lightboxStorageKey);
                return lightboxStorage?JSON.parse(lightboxStorage):{};
            },
            updateLightboxStorage: function (obj) {
                localStorage.setItem(this.lightboxStorageKey, JSON.stringify(_.extend(this.getLightboxStorage(), obj)));
            },
            resizable: {
                $el:null,
                w: '',
                h: '',
                x: '',
                y: '',
                axis: '',
                overlay: false,
                minWidth: 350,
                maxWidth: 880,
                minHeight: 320,
                maxHeight: topWindow.document.documentElement.clientHeight * 0.9, // 90vh
                update:true,
                init: function () {
                    var self = this,
                        lightbox = ThemifyBuilderCommon.Lightbox,
                        body = topWindow.document.body.classList,
                        draggableCallback = function (e, ui) {
                                if (ui !== undefined && e && e.target.classList.contains('builder-lightbox')) {
                                    switch (e.type) {
                                        case 'dragstart' :
                                            if(lightbox.dockMode.get() && !body.contains('tb_standalone_lightbox') && e.originalEvent.target.closest('li')===null){
                                                self.$el[0].getElementsByClassName('builder_cancel_docked_mode')[0].click();
                                            }
                                            body.add('themify_lightbox_drag');
                                            document.body.classList.add('tb_start_animate');
                                            lightbox.fixContainment();
                                            break;
                                        case 'dragstop':
                                            body.remove('themify_lightbox_drag');
                                            document.body.classList.remove('tb_start_animate');
                                            lightbox.fixContainment();
                                            self.remember();
                                            if(tb_app.mode === 'visual'){
                                                $(document).triggerHandler('mouseup');
                                            }
                                        case 'drag':
                                            lightbox.dockMode.drag(e,ui);
                                            break;
                                    }
                                }
                            };

                    this.$el = lightbox.$lightbox;
                    self.$el.draggable({
                        handle: self.$el.find('.tb_lightbox_top_bar'),
                        scroll: false,
                        start: draggableCallback,
                        drag: draggableCallback,
                        stop: draggableCallback
                    });
                    var items = this.$el[0].getElementsByClassName('tb_resizable');
                    for (var i =items.length-1; i>-1; --i) {
                        items[i].addEventListener('mousedown', function (e) {
                            if (e.which === 1) {
                                e.preventDefault();
                                self.maxHeight=topWindow.document.documentElement.clientHeight * 0.9;
                                self.x = e.clientX;
                                self.y = e.clientY;
                                self.w = parseInt(self.$el.outerWidth(), 10);
                                self.h = parseInt(self.$el.outerHeight(), 10);
                                self.axis = this.dataset['axis'];
                                self.$el[0].classList.add('tb_resizing');
                                topWindow.document.addEventListener('mousemove', self.resize, {passive: true});
                                topWindow.document.addEventListener('mouseup', self.stop, {passive: true});
                                body.add('tb_start_animate');
                                Themify.body.addClass('tb_start_animate');
                                topWindow.document.body.classList.add('tb_panel_resize');
                                if(self.axis === 'se' || self.axis === 'x' || self.axis==='sw' || self.axis==='ne' || self.axis==='nw'){
                                    self.setupLightboxSizeClass();
                                }
                            }

                        }, false);
                    }
                    self.setupLightboxSizeClass();
                },
                remember: function () {
                    if(!topWindow.document.body.classList.contains('tb_standalone_lightbox')){
                        var self = ThemifyBuilderCommon.Lightbox.resizable,
                            pos = self.$el.position(),
                            posSizeObj = {
                                top: pos.top,
                                left: pos.left,
                                width: self.$el.outerWidth(),
                                height: self.$el.outerHeight()
                            };

                        ThemifyBuilderCommon.Lightbox.updateLightboxStorage(posSizeObj);
                        Themify.body.triggerHandler('themify_builder_resize_lightbox');
                    }
                },
                setupLightboxSizeClass: function (w) {
                    var self = ThemifyBuilderCommon.Lightbox.resizable;
                    if(self.$el!==null){
                        if(!w){
                            w=parseInt(self.$el.width());
                        }
                        var cl = self.$el[0].classList;
                        if(w > 750){
                            cl.add('larger-lightbox');
                        }
                        else{
                            cl.remove('larger-lightbox'); 
                        }
                        if(w<540){
                            cl.add('tb_lightbox_small'); 
                        }
                        else{
                            cl.remove('tb_lightbox_small'); 
                        }
                    }
                },
                resize: function (e) {
                    var self = ThemifyBuilderCommon.Lightbox.resizable,
                        w;
                    if (self.axis === 'w') {
                        w = self.x + self.w - e.clientX;
                        if( w > self.maxWidth){
                            w=self.maxWidth;
                        }
                        if (w >= self.minWidth && w <= self.maxWidth) {
                            var old_w=self.$el[0].style['width'];
                            self.$el[0].style['width']=w+'px';
                           
                            self.$el[0].style['left']=(parseInt(self.$el[0].style['left'])+parseInt(old_w)-w)+'px';
                            self.setupLightboxSizeClass(w);
                        }
                    } else {
                        var h =self.axis==='-y' || self.axis==='ne' || self.axis==='nw'?(self.y+self.h-e.clientY):( self.h + e.clientY - self.y);
                            w = self.axis==='sw' || self.axis==='nw' ?(self.x + self.w - e.clientX):(self.w + e.clientX - self.x);
                            if( w > self.maxWidth){
                                w=self.maxWidth;
                            }
                        if ((self.axis === 'se' || self.axis === 'x' || self.axis==='sw' || self.axis==='nw' || self.axis==='ne') && w >= self.minWidth && w <= self.maxWidth) {
                            var old_w=self.$el[0].style['width'];
                            self.$el[0].style['width']=w+'px';
                            if(self.axis==='sw' || self.axis==='nw'){
                                self.$el[0].style['left']=(parseInt(self.$el[0].style['left'])+parseInt(old_w)-w)+'px';
                            }
                            self.setupLightboxSizeClass(w);
                        }
                        if ((self.axis === 'se' || self.axis === 'y' || self.axis === '-y' || self.axis==='sw' || self.axis==='nw' || self.axis==='ne') && h >= self.minHeight && h <= self.maxHeight) {
                            if(self.axis === '-y' || self.axis === 'nw' || self.axis === 'ne' ){
                                self.$el[0].style['top']=(parseInt(self.$el[0].style['top'])+parseInt(self.$el[0].style['height'])-h)+'px';
                            }
                            self.$el[0].style['height']=h+'px';
                        }
                    }

                    Themify.body.triggerHandler('themify_builder_resize_lightbox');
                },
                stop: function (e) {
                    var lightbox = ThemifyBuilderCommon.Lightbox,
                        self = lightbox.resizable;
                    self.$el.removeClass('tb_resizing');
                    topWindow.document.removeEventListener('mousemove', self.resize, {passive: true});
                    topWindow.document.removeEventListener('mouseup', self.stop);
                    lightbox.fixContainment();
                    self.remember();
                    var $body = $('body', topWindow.document);
                        $body = $body.add('body');
                        $body.removeClass('tb_start_animate');
                    topWindow.document.body.classList.remove('tb_panel_resize');
                    if(tb_app.mode==='visual'){
                        $(document).triggerHandler('mouseup');
                    }
                    tb_app.ActionBar.disable=true;
                    setTimeout(function(){
                        tb_app.ActionBar.disable=null;
                    },7);
                }
            },
            fixContainment: function () {
                
                var self = ThemifyBuilderCommon.Lightbox,
                        el_w = self.$lightbox.outerWidth(),
                        $w = $(topWindow),
                        w2 =  $w.width() - 20,
                        w3 = $w.height() - 30,
                        positions = self.$lightbox.position(),
                        left = positions.left,
                        top = positions.top,
                        new_pos = {};
                        if(left<0){
                            new_pos.left = 20;
                        }
                        else if((left+el_w)>w2){
                             new_pos.left = w2-el_w;
                        }
                        if(top<0){
                            new_pos.top = 0;
                        }
                        else if(top > w3){
                             new_pos.top = w3;
                        }
                        for(var i in new_pos){
                            self.$lightbox[0].style[i] = new_pos[i]+'px';
                        }
            },
            setStandAlone:function(left,top,inTop){
                var w =this.$lightbox.outerWidth(),
                    h=this.$lightbox.outerHeight(),
                    clW = topWindow.document.documentElement.clientWidth,
                    clH=topWindow.document.documentElement.clientHeight;
                if(!inTop && tb_app.mode==='visual'){
                    if(this.dockMode.get()){
                        tb_app.toolbar.$el.find('.tb_toolbar_add_modules').click();
                        if(!topWindow.document.body.classList.contains('tb_panel_minimized')){
                            if(tb_app.activeBreakPoint!=='desktop'){
                                left+=this.dockMode.isLeft?150:-150;
                            }
                            else if(this.dockMode.isLeft){
                                left+=300;
                            }
                        }
                    }
                    if(tb_app.activeBreakPoint!=='desktop'){
                        left+=(((clW-tb_app.iframe.width())/2)+8);
                    }
                }
                left-=(w/2);
                if(left<=5){
                    left=5;
                }
                else if((left+w)>clW){
                    left=clW-w-20;
                }
                top+=50;
                if((top+h)>clH){
                    top=clH-h-5;
                }
                if(top<0){
                    top=5;
                }
                this.$lightbox.css({left:left,top:top}).one('themify_opened_lightbox',function(){
                    tb_app.Utils.addViewPortClass(this);
                });
                
            },
            open: function (options, beforeCallback, afterCallback) {
                var self = ThemifyBuilderCommon.Lightbox,
                    doc =  topWindow.document,
                    lightboxContainer = doc.getElementById('tb_lightbox_container'),
                    callback = function (response) {
                            self.$lightbox[0].style['display'] = 'none';
                            if (typeof beforeCallback === 'function') {
                                beforeCallback.call(self, response);
                            }
                            while (lightboxContainer.firstChild) {
                                lightboxContainer.removeChild(lightboxContainer.firstChild);
                            }
                            
                            if(typeof response==='string'){
                                lightboxContainer.innerHTML = response;
                            }
                            else{
                                lightboxContainer.appendChild(response);
                            }
                            
                            var isStandAlone = doc.body.classList.contains('tb_standalone_lightbox'),
                                posSizeObj,
                                isCalled=null;
                            if(isStandAlone===false){
                                posSizeObj = {
                                    top: 100,
                                    left: Math.max(0, (($(topWindow).width() / 2) - 300)),
                                    width: 600,
                                    height: 500
                                };
                                _.extend(posSizeObj, self.getLightboxStorage());
                            }
                            else{
                                posSizeObj = {
                                    top: '',
                                    left: '',
                                    width: '',
                                    height: ''
                                };
                            }
                            for(var s in posSizeObj){
                                self.$lightbox[0].style[s] =posSizeObj[s]!==''? posSizeObj[s]+'px':'';
                            }
                            if(isStandAlone===false){
                                if(self.dockMode.get()===true){
                                   self.dockMode.setDoc();
                                   isCalled=true;
                                }
                                else{
                                    self.fixContainment();
                                }
                            }
                            if (typeof afterCallback === 'function') {
                                afterCallback.call(self, lightboxContainer);
                            }
                            if(isCalled===null){
                                self.resizable.setupLightboxSizeClass(posSizeObj.width);
                            }
                            self.$lightbox[0].style['display'] = 'block';
                            self.$lightbox.triggerHandler('themify_opened_lightbox');
                            if ('inline' !== options.loadMethod){
                                var tabs = lightboxContainer.getElementsByClassName('tb_tabs');
                                for(var i=tabs.length-1;i>-1;--i){
                                    var a = tabs[i].getElementsByTagName('a');
                                    for(var j=a.length-1;j>-1;--j){
                                         a[j].addEventListener('click', tb_app.Constructor.switchTabs);
                                    }
                                }
                                tabs =a= null;
                            }
                            tb_app.undoManager.disable();
                            if(tb_app.mode==='visual'){
                                $(document).triggerHandler('mouseup');
                            }
                            tb_app.Instances.Builder[tb_app.builderIndex].lastRowShowHide();
                        };
                        if ('inline' === options.loadMethod) {
                            Themify.body.triggerHandler('themify_builder_lightbox_close');
                            doc.body.classList.remove('tb_standalone_lightbox');
                            callback(tb_app.Constructor.run(options.templateID));
                        }
                        else if (options.loadMethod === 'html') {
                            tb_app.autoSaveCid = null;
                            self.close(true);
                            if(options.contructor===true){
                                callback(tb_app.Constructor.run(options.data,options.save));
                            }
                            else{
                                 callback(options.data);
                            }
                        }
                        else {
                            ThemifyBuilderCommon.showLoader('show');
                            tb_app.autoSaveCid = null;
                            self.close(true);
                            options.data['nonce'] = themifyBuilder.tb_load_nonce;
                            options = _.defaults(options || {}, {
                                type: 'POST',
                                url: themifyBuilder.ajaxurl
                            });

                           $.ajax(options)
                            .done(function (response) {
                                if(options.contructor===true){
                                    callback(tb_app.Constructor.run(response));
                                }
                                else{
                                    callback(response);
                                }
                                ThemifyBuilderCommon.showLoader('spinhide');
                                var container = lightboxContainer.getElementsByClassName('tb_options_tab_wrapper');
                                if (container.length > 0) {
                                    new SimpleBar(container[0]);
                                }
                            });
                        }
            },
            close: function (auto) {
                var self = ThemifyBuilderCommon.Lightbox;
                Themify.body.triggerHandler('themify_builder_lightbox_before_close');
                if (tb_app.mode === 'visual') {
                    // Trigger parent iframe
                    topWindow.jQuery('body').trigger('themify_builder_lightbox_close',auto);
                }
                if (!auto) {
                    self.$lightbox[0].style['display']='none';
                    tb_app.autoSaveCid = null;
                }
                self._cleanLightBoxContent();
                if (!auto) {
                    tb_app.undoManager.updateUndoBtns();
                    tb_app.toolbar.Panel.setFocus();
                    if (tb_app.mode === 'visual') {
                        $(document).triggerHandler('mouseup');
                    }
                    tb_app.Instances.Builder[tb_app.builderIndex].lastRowShowHide(true);
                    tb_app.Utils.removeViewPortClass(self.$lightbox[0]);
                }
                Themify.body.triggerHandler('themify_builder_lightbox_close',auto);
            },
            dockMode: {
                key: 'themify_builder_docked',
                leftKey:'themify_builder_docked_left',
                workspace: topWindow.document.body.getElementsByClassName('tb_workspace_container')[0],
                minEl:null,
                width:322,
                isDocked: null,
                isLeft:null,
                set: function (isDocked) {
                    this.isDocked = isDocked;
                    if(isDocked){
                        localStorage.setItem(this.key, isDocked);
                        if(this.isLeft){
                            localStorage.setItem(this.leftKey, true);
                        }
                        else{
                            localStorage.removeItem(this.leftKey);
                        }
                    }
                    else{
                        localStorage.removeItem(this.key);
                        localStorage.removeItem(this.leftKey);
                    }
                    Themify.body.triggerHandler('themify_builder_resize_lightbox');
                },
                get: function () {
                    if(tb_app.mode === 'visual'){
                        if(this.isDocked===null){
                            this.isDocked = localStorage.getItem(this.key) === 'true';
                        }
                        if(this.isDocked===true){
                            this.isLeft = localStorage.getItem(this.leftKey)=== 'true';
                            return true;
                        }
                    }
                    return false;
                },
                minimize:function(e){
                    e.stopPropagation();
                    var cl = topWindow.document.body.classList;
                    cl.contains('tb_panel_minimized') ?cl.remove('tb_panel_minimized'):cl.add('tb_panel_minimized');
                    tb_app.Utils._onResize(true);
                },
                setDoc: function () {
                    if (this.get()){
                        var cl = topWindow.document.body.classList;
                        if(!cl.contains('tb_panel_docked')){
                            cl.add('tb_panel_docked');
                            if(this.isLeft){
                                cl.add('tb_panel_left_dock');
                                cl.remove('tb_panel_right_dock');
                            }
                            else{
                                cl.add('tb_panel_right_dock');
                                cl.remove('tb_panel_left_dock');
                            }
                            tb_app.Utils._onResize(true);
                            ThemifyBuilderCommon.Lightbox.resizable.setupLightboxSizeClass(this.width);
                            Themify.body.triggerHandler('themify_builder_resize_lightbox');
                            this.minEl = tb_app.toolbar.el.getElementsByClassName('tb_docked_minimize')[0];
                            this.minEl.addEventListener('click',this.minimize, {passive: true});
                            tb_app.Views.Toolbar.prototype.removeFloat();
                            tb_app.Views.Toolbar.prototype.openFloat();
                            tb_app.Views.Toolbar.prototype._setResponsiveTabs();
                        }else{
                            ThemifyBuilderCommon.Lightbox.resizable.setupLightboxSizeClass(this.width);
                        }
                    }
                },
                drag: function (e,ui) {
                    if (tb_app.mode === 'visual' && !this.get()) {
                        var cl= topWindow.document.body.classList;
                        if(!cl.contains('tb_standalone_lightbox')){
                            var check = e.pageX + 20 >= topWindow.innerWidth,
                                type=e.type;
                                this.isLeft =!check && ui.offset.left<0;
                            if((check || this.isLeft) && type === 'drag'){
                                cl.add('tb_dock_highlight');
                                if(this.isLeft){
                                   cl.add('tb_dock_left_highlight');
                                }
                                else{
                                    cl.remove('tb_dock_left_highlight');
                                }
                            }
                            else{
                                cl.remove('tb_dock_highlight');
                                cl.remove('tb_dock_left_highlight');
                            }
                            if ((check || this.isLeft) && type === 'dragstop') {
                                this.set(true);
                                this.setDoc();
                            } 
                        }
                    }
                },
                close: function (onlyClose) {
                    if (tb_app.mode === 'visual' && this.get()) {
                        var self = ThemifyBuilderCommon.Lightbox,
                            cl = topWindow.document.body.classList,
                            lightboxStorage = self.getLightboxStorage(),
                            props = {
                                width: lightboxStorage.width ? lightboxStorage.width : self.resizable.minWidth,
                                height: lightboxStorage.height ? lightboxStorage.height : self.resizable.minHeight,
                                top:topWindow.innerHeight / 2 - self.$lightbox.innerHeight() / 2,
                                left:topWindow.innerWidth / 2 - self.$lightbox.innerWidth() / 2
                            };
                        self.$lightbox.css(props);
                        if(onlyClose && topWindow.document.body.classList.contains('tb_panel_closed')){
                            tb_app.Views.Toolbar.prototype.openFloat();
                        }
                        if(this.isLeft || !onlyClose){
                            if(!onlyClose){
                                cl.remove('tb_panel_left_dock');
                                cl.remove('tb_panel_right_dock');
                                cl.remove('tb_panel_docked');
                                if(this.minEl!==null){
                                    this.minEl.removeEventListener('click',this.minimize, {passive: true});
                                    this.minEl=null;
                                }
                                if(tb_app.activeModel!==null && localStorage.getItem('tb_panel_closed') ){
                                    tb_app.Views.Toolbar.prototype.closeFloat();
                                }
                                tb_app.Views.Toolbar.prototype.setFloat();
                                if(!cl.contains('tb_standalone_lightbox')){
                                    this.set(null);
                                }
                            }
                            else{
                                if(this.isLeft){
                                    cl.remove('tb_panel_right_dock');
                                }
                                else{
                                     cl.remove('tb_panel_left_dock');
                                }
                                
                            }
                        }
                        self.resizable.setupLightboxSizeClass(props.width);
                        tb_app.Utils._onResize(true);
                    }
                }
            },
            _cleanLightBoxContent: function () {
                var item = this.$lightbox.find('#tb_lightbox_container')[0];
                while (item.firstChild) {
                    item.removeChild(item.firstChild);
                }
                item = this.$lightbox[0].getElementsByClassName('tb_options_tab')[0];
                while (item.firstChild) {
                    item.removeChild(item.firstChild);
                }
                item = this.$lightbox[0].getElementsByClassName('tb_lightbox_actions_wrap')[0];
                while (item.firstChild) {
                    item.removeChild(item.firstChild);
                }
            },
            controlByKeyInput: function () {
                function save(e) {
                    if (e.keyCode === 27  && tb_app.activeModel) {
                        e.preventDefault();
                        ThemifyBuilderCommon.Lightbox.close();
                    }
                     // Ctrl + s | Cmd + s - Save Builder
                    else if (83 === e.which && document.activeElement.tagName !== 'INPUT' && document.activeElement.tagName !== 'TEXTAREA' && (true === e.ctrlKey || true === e.metaKey)) {
                        e.preventDefault();
                        e.stopPropagation();
                        var save = tb_app.activeModel?$('.builder_save_button', ThemifyBuilderCommon.Lightbox.$lightbox):null;
                        if (save===null || save.length===0) {
                            save = tb_app.toolbar.$el.find('.tb_toolbar_save');
                        }
                        save.click();
                    }
                }
                $(document).on('keydown.tb_shortcut', save);
                if (tb_app.mode === 'visual') {
                    $(topWindow.document).on('keydown.tb_shortcut', save);
                }
            },
            responsiveTabs: function () {
                    var tabs=null,ul,tabsWidth,
                        label=null,
                        watchResize = function (context) {
                            if(tabs===null){
                                tabs = context.getElementsByClassName('tb_tabs')[0];
                            }
                            if (tabs!==undefined) {
                                if (!tabsWidth) {
                                    ul= tabs.getElementsByTagName('ul')[0]; 
                                    if(ul!==undefined){
                                        var last = ul.getElementsByTagName('li');
                                        last = last[last.length-1];
                                        last = $(last);
                                        tabs = $(tabs);
                                        tabsWidth = last.offset().left + last.outerWidth() - tabs.offset().left;
                                    } 
                                    else{
                                        return;
                                    }
                                }
                                if(tabs.innerWidth() <= tabsWidth){
                                    tabs[0].classList.add('tb_compact_tabs');
                                    ul.classList.add('tb_ui_dropdown_items');
                                    if(label===null){
                                        label = document.createElement('span');
                                        label.className = 'tb_ui_dropdown_label';
                                        label.tabIndex='-1';
                                        label.textContent = ul.getElementsByClassName('current')[0].textContent;
                                        ul.parentNode.insertBefore(label, ul);
                                    }
                                }
                                else{
                                    tabs[0].classList.remove('tb_compact_tabs');
                                    ul.classList.remove('tb_ui_dropdown_items');
                                }
                            }
                        },
                        callback = function (e, id, container) {
                            setTimeout(function(){
                                if(tb_app.Constructor.clicked==='styling'){
                                    watchResize(tabs===null?topWindow.document.getElementById('tb_options_styling'):null);
                                    if(e.type==='themify_builder_tabsactive' && label!==null){
                                        label.textContent = ul.getElementsByClassName('current')[0].textContent;
                                    }
                                }
                            },4);
                        };

                    Themify.body.on('themify_builder_tabsactive themify_builder_resize_lightbox', callback)
                    .on('themify_builder_lightbox_close', function () {
                        tabs =ul= tabsWidth =label= null;
                    });
                    this.$lightbox.on('themify_opened_lightbox',callback);
            }
        },
        LiteLightbox: {
            modal: new wp.media.view.Modal({
                controller: {trigger: function () {
                    }}
            }),
            confirmView: Backbone.View.extend({
                template: wp.template('builder_lite_lightbox_confirm'),
                className: 'tb_lite_lightbox_content',
                initialize: function (options) {
                    this.options = options || {};
                },
                render: function () {
                    this.el.innerHTML = this.template({message: this.options.message, buttons: this.options.buttons});
                },
                events: {
                    'click button': 'buttonClick'
                },
                buttonClick: function (e) {
                    e.preventDefault();
                    this.trigger('litelightbox:confirm', $(e.currentTarget).data('type'));
                }
            }),
            promptView: Backbone.View.extend({
                template: wp.template('builder_lite_lightbox_prompt'),
                className: 'tb_lite_lightbox_content',
                initialize: function (options) {
                    this.options = options || {};
                },
                render: function () {
                    this.$el.html(this.template(this.options));
                },
                events: {
                    'click button': 'buttonClick',
                    'keypress .tb_litelightbox_prompt_input': 'keyPress'
                },
                buttonClick: function (e) {
                    e.preventDefault();
                    this.trigger('litelightbox:prompt', $(e.currentTarget).data('type'), this.$el.find('.tb_litelightbox_prompt_input').val());
                },
                keyPress: function (e) {
                    if (e.which === 13) { // on enter
                        this.trigger('litelightbox:prompt', 'ok', $(e.currentTarget).val());
                    }
                }
            }),
            confirm: function (message, callback, options) {
                options = _.defaults(options || {}, {
                    buttons: {
                        no: {
                            label: 'No'
                        },
                        yes: {
                            label: 'Yes'
                        }
                    }
                });
                options.message = message;
                var contentView = new ThemifyBuilderCommon.LiteLightbox.confirmView(options);
                ThemifyBuilderCommon.LiteLightbox.modal.content(contentView);
                ThemifyBuilderCommon.LiteLightbox.modal.open();
                contentView.on('litelightbox:confirm', function (type) {
                    ThemifyBuilderCommon.LiteLightbox.modal.close();
                    // load callback
                    if ($.isFunction(callback)) {
                        callback.call(this, type);
                    }
                });
            },
            prompt: function (message, callback, options) {
                options = _.defaults(options || {}, {
                    buttons: {
                        cancel: {
                            label: 'Cancel'
                        },
                        ok: {
                            label: 'OK'
                        }
                    }
                });
                options.message = message;
                var promptView = new ThemifyBuilderCommon.LiteLightbox.promptView(options);
                ThemifyBuilderCommon.LiteLightbox.modal.content(promptView);
                ThemifyBuilderCommon.LiteLightbox.modal.open();
                promptView.on('litelightbox:prompt', function (type, value) {
                    ThemifyBuilderCommon.LiteLightbox.modal.close();
                    // load callback
                    if ($.isFunction(callback)) {
                        value = 'cancel' === type ? null : value;
                        callback.call(this, value);
                    }
                });
            },
            alert: function (message) {
                ThemifyBuilderCommon.LiteLightbox.confirm(message, null, {
                    buttons: {
                        yes: {
                            label: 'OK'
                        }
                    }
                });
            }
        },
        templateCache: {
            templates: [],
            get: function (selector) {
                if (this.templates[selector] === undefined) {
                    var el = document.getElementById(selector);
                    this.templates[selector] = el.innerHTML;
                    setTimeout(function () {
                        el.parentNode.removeChild(el);
                    }, 6000);
                }
                return this.templates[selector];
            }
        },
        setToolbar:function(){
            var fragment = document.getElementById('tb_toolbar_template'),
                tmp =this.is_template_support?fragment.content: fragment.firstElementChild;
                if(tb_app.mode==='visual'){
                    document.body.appendChild(tmp);  
                }
                else{
                    fragment.parentNode.insertBefore(tmp,fragment);
                }  
                fragment.parentNode.removeChild(fragment);
        },
        isImageUrl: function (link) {

            if (typeof link === 'undefined' || link == '') {
                return false;
            }
            var parts = link.split('?')[0].split('.');
            return  ['jpg', 'jpeg', 'tiff', 'png', 'gif', 'bmp', 'svg'].indexOf(parts[parts.length - 1]) !== -1;
        }

    };

}(jQuery,Themify, window.top, document,undefined));
