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

/**
 * Common shared code between backend and frontend Builder.
 */
var ThemifyBuilderCommon;
(function ($, Themify, topWindow, document) {
    'use strict';
    if (topWindow !== window.self) {
        window.wp.shortcode = topWindow.wp.shortcode;
    }
    ThemifyBuilderCommon = {
        loader: null,
        showLoader(stats) {
            if (this.loader === null) {
                this.loader = $(topWindow.document.getElementById('tb_alert'));
            }
			const l=this.loader[0];
            if (stats === 'show') {
                l.classList.add('tb_busy');
                l.style['display'] = 'block';
            } else if (stats === 'spinhide') {
                this.loader.fadeOut(300, function () {
                    this.classList.remove('tb_busy');
                });
            } else {
                if (stats !== 'error') {
                    stats = 'done';
                }
                l.classList.remove('tb_busy');
                l.classList.add('tb_' + stats);
                this.loader.delay(500).fadeOut(500, function () {
                    this.classList.remove('tb_' + stats);
                });
            }
        },
        clone(el) {
            if (el === null) {
                return el;
            }
            if (el[0] !== undefined) {
                el = el[0];
            }
            const 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
                const v = node.getElementsByTagName('video');
                if (v.length > 0) {
                    for (let i = v.length - 1; i > -1; --i) {
                        v[i].pause();
                    }
                    for (let items=node.getElementsByClassName('big-video-wrap'),i=items.length-1;i>-1;--i) {
                        if (items[i]) {
                            items[i].remove();
                        }
                    }
                }
				for (let items=node.getElementsByClassName('tb_dragger'),i=items.length-1; i>-1;--i) {
					items[i].remove();
				}
                for (let items=Themify.selectWithParent('tb_element_clicked',node),i=items.length-1; i>-1;--i) {
					items[i].classList.remove('tb_element_clicked');
				}
                for(let items=Themify.selectWithParent('[contenteditable]',node),i=items.length-1;i>-1;--i){
                    items[i].setAttribute('contenteditable','false');
                    let p=items[i].closest('.tb_editor_on');
                    if(p){
                        p.classList.remove('tb_editor_on','tb_editor_clicked');
                    }
                }
            }
            return $(node);
        },
        /**
         * Clipboard-like functionality. Wraps localStorage with a Themify key. Supports one copied item per time.
         */
        Clipboard: {
            key: 'themify_builder_clipboard_',
            set(type, content) {
                const data = {};
                data[type] = content;
                localStorage.setItem(this.key + 'content', JSON.stringify(data));
            },
            get(type) {
                const savedContent = JSON.parse(localStorage.getItem(this.key + 'content'));
                return savedContent[type] !== undefined ? savedContent[type] : false;
            }
        },
        alertWrongPaste() {
            alert(themifyBuilder.i18n.text_alert_wrong_paste);
        },
        autoComplete($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(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(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(resp) {
                            if (resp) {
                                for (var $i in resp) {
                                    $('#themify_search_cat_' + resp[$i].tax, $container).val(resp[$i].val);
                                }
                            }
                        }
                    });
                }
            }
        },
        Lightbox: {
            $lightbox: null,
            lightboxStorageKey: topWindow!== window.self? 'themify_builder_lightbox_frontend_pos_size' : 'themify_builder_lightbox_backend_pos_size',
            setup() {
                topWindow.document.body.appendChild(document.getElementById('tmpl-builder_lightbox').content);
                this.$lightbox = $('#tb_lightbox_parent', topWindow.document);
                ThemifyBuilderCommon.LiteLightbox.modal = new wp.media.view.Modal({
                    controller: {trigger() {}}
                });
                ThemifyBuilderCommon.LiteLightbox.modal.on('attach', function () {
                    this.el.classList.add('tb_lite_lightbox_modal');
                });
                this.bindEvents();
            },
            bindEvents() {
                const self=this;
                self.responsiveTabs();
                self.$lightbox.one('themify_opened_lightbox', function () {
                    self.resizable.init();
                    if (tb_app.mode === 'visual') {
                        // Cancel docked mode
                        self.$lightbox[0].getElementsByClassName('builder_cancel_docked_mode')[0].addEventListener('click', function (e) {
                            e.preventDefault();
                            e.stopPropagation();
							const cl=this.ownerDocument.body.classList;
                            cl.add('themify_lightbox_drag');
                            ThemifyBuilderCommon.Lightbox.dockMode.close();
							cl.remove('themify_lightbox_drag');
                        });
                    }
                    self.$lightbox[0].getElementsByClassName('tb_close_lightbox')[0].addEventListener('click', function () {
                        self.close();
                    }, {passive: true});
                });
                if (!themifyBuilder.disableShortcuts) {
                    self.controlByKeyInput();
                }
            },
            getLightboxStorage() {
                const lightboxStorage = localStorage.getItem(this.lightboxStorageKey);
                return lightboxStorage ? JSON.parse(lightboxStorage) : {};
            },
            updateLightboxStorage(obj) {
                localStorage.setItem(this.lightboxStorageKey, JSON.stringify(Object.assign(this.getLightboxStorage(), obj)));
            },
            resizable: {
                $el: null,
                init() {
					
                    const self = this,
						ev=tb_app.Utils.getMouseEvents(),
						lightbox = ThemifyBuilderCommon.Lightbox,
						body = topWindow.document.body.classList;
                    this.$el = lightbox.$lightbox;	
					
					const resizeHandler = this.$el[0].getElementsByClassName('tb_resizable'),
						dragHandler=this.$el[0].querySelectorAll('.tb_lightbox_top_bar,.tb_action_breadcrumb');
						
                    for (let i = resizeHandler.length - 1; i > -1; --i) {
                        resizeHandler[i].addEventListener(ev['mousedown'], function (e) {
                            if (e.type==='touchstart' || e.which === 1) {
                                e.stopImmediatePropagation();
								let timer;
								const doc=this.ownerDocument,
									minHeight=parseInt(self.$el.css('min-height')),
									maxHeight = doc.documentElement.clientHeight * .9,
									minWidth=350,
									maxWidth=880,
									axis = this.dataset['axis'],
									startH = parseInt(self.$el[0].offsetHeight, 10),
									startW = parseInt(self.$el[0].offsetWidth, 10),
									resizeX = e.touches?e.touches[0].clientX:e.clientX,
									resizeY = e.touches?e.touches[0].clientY:e.clientY,
									_resize=function(e){
										e.stopImmediatePropagation();
										if(timer){
											cancelAnimationFrame(timer);
										}
										timer=requestAnimationFrame(function(){
											let w;
											const el=self.$el[0],
												clientX=e.touches?e.touches[0].clientX:e.clientX,
												clientY=e.touches?e.touches[0].clientY:e.clientY;
											if (axis === 'w') {
												w = resizeX + startW - clientX;
												if (w > maxWidth) {
													w = maxWidth;
												}
												if (w >= minWidth && w <= maxWidth) {
													const old_w = el.style['width'];
													el.style['width'] = w + 'px';

													el.style['left'] = (parseInt(el.style['left']) + parseInt(old_w) - w) + 'px';
													self.setupLightboxSizeClass(w);
												}
											} 
											else {
												const h = axis === '-y' || axis === 'ne' || axis === 'nw' ? (resizeY + startH - clientY) : (startH + clientY - resizeY);
												w = axis === 'sw' || axis === 'nw' ? (resizeX + startW - clientX) : (startW + clientX - resizeX);
												if (w > maxWidth) {
													w = maxWidth;
												}
												if ((axis === 'se' || axis === 'x' || axis === 'sw' || axis === 'nw' || axis === 'ne') && w >= minWidth && w <= maxWidth) {
													const old_w = el.style['width'];
													el.style['width'] = w + 'px';
													if (axis === 'sw' || axis === 'nw') {
														el.style['left'] = (parseInt(el.style['left']) + parseInt(old_w) - w) + 'px';
													}
													self.setupLightboxSizeClass(w);
												}
												if ((axis === 'se' || axis === 'y' || axis === '-y' || axis === 'sw' || axis === 'nw' || axis === 'ne') && h >= minHeight && h <= maxHeight) {
													if (axis === '-y' || axis === 'nw' || axis === 'ne') {
														el.style['top'] = (parseInt(el.style['top']) + parseInt(el.style['height']) - h) + 'px';
													}
													el.style['height'] = h + 'px';
												}
											}

											Themify.body.triggerHandler('themify_builder_resize_lightbox');
										});
									},
									_stop=function(e){
										e.stopImmediatePropagation();
										this.removeEventListener(ev['mousemove'], _resize, {passive: true});
										if(timer){
											cancelAnimationFrame(timer);
										}
										timer=null;
										lightbox.fixContainment();
										self.remember();
										this.body.style['cursor']='';
										body.remove('tb_start_animate','tb_move_drag','tb_panel_resize');
									};
                                doc.addEventListener(ev['mousemove'], _resize, {passive: true});
                                doc.addEventListener(ev['mouseup'], _stop, {passive: true,once:true});
                                body.add('tb_start_animate','tb_move_drag','tb_panel_resize');
                                if (axis === 'se' || axis === 'x' || axis === 'sw' || axis === 'ne' || axis === 'nw') {
                                    self.setupLightboxSizeClass();
                                }
								doc.body.style['cursor']=$(this).css('cursor');
                            }

                        }, {passive:true});
                    }
					for(let i=dragHandler.length-1;i>-1;--i){
						dragHandler[i].addEventListener(ev['mousedown'],function(e){
							if (e.type==='touchstart' || e.which === 1) {
								const isDocked=lightbox.dockMode.get() && !body.contains('tb_standalone_lightbox') && (this.classList.contains('tb_action_breadcrumb') || e.target.classList.contains('tb_lightbox_top_bar'));
								if(!isDocked && !e.target.classList.contains('tb_lightbox_top_bar')){
									return;
								}
								e.stopImmediatePropagation();
								let timer,
								isDragged,
								el=self.$el[0];
								const doc=this.ownerDocument,
								dragX=el.offsetLeft-(e.touches?e.touches[0].clientX:e.clientX),
								dragY=el.offsetTop-(e.touches?e.touches[0].clientY:e.clientY),
								draggableCallback = function (e) {
									e.stopImmediatePropagation();
									if(timer){
										cancelAnimationFrame(timer);
									}
									timer=requestAnimationFrame(function(){
										const clientX=dragX+(e.touches?e.touches[0].clientX:e.clientX),
											clientY=dragY+(e.touches?e.touches[0].clientY:e.clientY);
											el.style['left']=clientX+'px';
											el.style['top']= clientY+'px';
										lightbox.dockMode.drag(e,clientX);
									});
								},
								startDrag=function(e){
									isDragged=true;
									e.stopImmediatePropagation();
									if(isDocked){
										const left=el.offsetLeft,
										top=el.offsetTop;
										el.getElementsByClassName('builder_cancel_docked_mode')[0].click();
										el.style['left']=left+'px';
										el.style['top']= top+'px';
									}
									body.add('tb_start_animate','tb_move_drag','themify_lightbox_drag');
								};
								doc.addEventListener(ev['mouseup'], function(e){
									this.removeEventListener(ev['mousemove'], startDrag,{passive: true,once:true});
									this.removeEventListener(ev['mousemove'], draggableCallback, {passive: true});
									if(isDragged){
										draggableCallback(e);
										requestAnimationFrame(function(){
											timer=el=isDragged=null;
											lightbox.fixContainment();
											body.remove('tb_start_animate','tb_move_drag','themify_lightbox_drag');
										});
                                        self.remember();
									}
								}, {passive: true,once:true});
								
								doc.addEventListener(ev['mousemove'], startDrag,{passive: true,once:true});
								doc.addEventListener(ev['mousemove'], draggableCallback, {passive: true});
							}
						},{passive:true});
					
					}
					
                    self.setupLightboxSizeClass();
                },
                remember() {
                    if (!topWindow.document.body.classList.contains('tb_standalone_lightbox')) {
                        const 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(w) {
                    if (this.$el !== null) {
                        if (!w) {
                            w = parseInt(this.$el.width());
                        }
                        const cl = this.$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');
                        }
                    }
                }
            },
            fixContainment() {
                 const box = this.$lightbox[0].getBoundingClientRect(),
						el_w=box.width,
                        w = topWindow.innerWidth - 20,
                        h = topWindow.innerHeight - 30,
                        left = box.left,
                        top = box.top,
						new_pos = {};
						
                if (left < 0) {
                    new_pos.left = 20;
                } else if ((left + el_w) > w) {
                    new_pos.left = w - el_w;
                }
                if (top < 0) {
                    new_pos.top = 0;
                } else if (top > h) {
                    new_pos.top = h;
                }
                for (let i in new_pos) {
                    this.$lightbox[0].style[i] = new_pos[i] + 'px';
                }
            },
            setStandAlone(left, top, inTop) {
                const 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(options, beforeCallback, afterCallback) {
                const self = ThemifyBuilderCommon.Lightbox,
                        doc = topWindow.document,
                        lightboxContainer = self.$lightbox[0].querySelector('#tb_lightbox_container'),
                        callback = function (response) {
                            self.$lightbox[0].style['display'] = 'none';
                            if (typeof beforeCallback === 'function') {
                                beforeCallback.call(self, response);
                            }
                            while (lightboxContainer.firstChild!==null) {
                                lightboxContainer.removeChild(lightboxContainer.firstChild);
                            }

                            if (typeof response === 'string') {
                                lightboxContainer.innerHTML = response;
                            } else {
                                lightboxContainer.appendChild(response);
                            }

                            const isStandAlone = doc.body.classList.contains('tb_standalone_lightbox');
                            let posSizeObj,
                                isCalled = null;
                            if (isStandAlone === false) {
                                posSizeObj = {
                                    top: 100,
                                    left: Math.max(0, (($(topWindow).width() / 2) - 300)),
                                    width: 600,
                                    height: 500
                                };
                               Object.assign(posSizeObj, self.getLightboxStorage());
                            } else {
                                posSizeObj = {
                                    top: '',
                                    left: '',
                                    width: '',
                                    height: ''
                                };
                            }
                            for (let 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) {
                                const tabs = lightboxContainer.getElementsByClassName('tb_tabs');
                                for (let i = tabs.length - 1; i > -1; --i) {
                                    let a = tabs[i].getElementsByTagName('a');
                                    for (let j = a.length - 1; j > -1; --j) {
                                        a[j].addEventListener('click', ThemifyConstructor.switchTabs);
                                    }
                                }
                            }
                            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(ThemifyConstructor.run(options.templateID));
                } else if (options.loadMethod === 'html') {
                    tb_app.autoSaveCid = null;
                    self.close(true);
                    if (options.contructor === true) {
                        callback(ThemifyConstructor.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(ThemifyConstructor.run(response));
                                } else {
                                    callback(response);
                                }
                                ThemifyBuilderCommon.showLoader('spinhide');
                            });
                }
            },
            close(auto) {
                const 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.Instances.Builder[tb_app.builderIndex].lastRowShowHide(true);
                    tb_app.Utils.removeViewPortClass(self.$lightbox[0]);
                }
                tb_app.ActionBar.hoverCid = null;
                tb_app.ActionBar.clearSelected();
                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(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() {
                    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(e) {
                    e.stopPropagation();
                    const 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() {
                    if(null===tb_app.toolbar.getStorage()){
                        localStorage.setItem(this.key, true);
                    }
                    if (this.get()) {
                        const cl = topWindow.document.body.classList,
                            api=tb_app;
                        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');
                            }
                            api.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});
                            api.Views.Toolbar.prototype.removeFloat();
                            api.Views.Toolbar.prototype.openFloat();
                            api.Views.Toolbar.prototype._setResponsiveTabs();
                        } else {
                            ThemifyBuilderCommon.Lightbox.resizable.setupLightboxSizeClass(this.width);
                        }
                    }
                },
                drag(e,left) {
                    if (tb_app.mode === 'visual' && !this.get()) {
                        const cl = topWindow.document.body.classList;
                        if (!cl.contains('tb_standalone_lightbox')) {
                            const check = e.clientX + 20 >= topWindow.innerWidth,
                                    type = e.type;
                            this.isLeft = !check && left < 0;
                            if ((check || this.isLeft) && (type === 'mousemove' || type==='touchmove')) {
                                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','tb_dock_left_highlight');
                            }
                            if ((check || this.isLeft) &&  (type === 'mouseup' || type==='touchend')) {
                                this.set(true);
                                this.setDoc();
                            }
                        }
                    }
                },
                close(onlyClose) {
                    if (tb_app.mode === 'visual' && this.get()) {
                        const 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','tb_panel_right_dock','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() {
                let item = this.$lightbox.find('#tb_lightbox_container')[0];
                while (item.firstChild !== null) {
                    item.removeChild(item.firstChild);
                }
                item = this.$lightbox[0].getElementsByClassName('tb_options_tab')[0];
                while (item.firstChild !== null) {
                    item.removeChild(item.firstChild);
                }
                item = this.$lightbox[0].getElementsByClassName('tb_lightbox_actions_wrap')[0];
                while (item.firstChild !== null) {
                    item.removeChild(item.firstChild);
                }
                item = this.$lightbox[0].getElementsByClassName('tb_action_breadcrumb')[0];
                while (item.firstChild !== null) {
                    item.removeChild(item.firstChild);
                }
            },
            controlByKeyInput() {
                function shortcutListener(e) {
                    if (e.keyCode === 27 && tb_app.activeModel) {
                        e.preventDefault();
                        e.stopPropagation();
                        ThemifyBuilderCommon.Lightbox.close();
                    } 
					else if (83 === e.which && (true === e.ctrlKey || true === e.metaKey) && topWindow.document.activeElement.tagName !== 'INPUT' && topWindow.document.activeElement.tagName !== 'TEXTAREA') {
                        // Ctrl + s | Cmd + s - Save Builder
                        e.preventDefault();
                        e.stopPropagation();
                        let 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', shortcutListener);
                if (tb_app.mode === 'visual') {
                    $(topWindow.document).on('keydown.tb_shortcut', shortcutListener);
                }
            },
            responsiveTabs() {
                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) {
                                        let last = ul.getElementsByTagName('li');
                                        last = last[last.length - 1];
                                        last = $(last);
                                        tabs = $(tabs);
                                        if(document.dir==='rtl'){
                                            const lastw=last.outerWidth(),
													wW=topWindow.innerWidth;
                                            tabsWidth = (wW - (last.offset().left + lastw)) + lastw - (wW - (tabs.offset().left + tabs.outerWidth()));
                                        }else{
                                            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 (ThemifyConstructor.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: null,
            confirmView: Backbone.View.extend({
                template: wp.template('builder_lite_lightbox_confirm'),
                className: 'tb_lite_lightbox_content',
                initialize(options) {
                    this.options = options || {};
                },
                render() {
                    this.el.innerHTML = this.template({message: this.options.message, buttons: this.options.buttons});
                },
                events: {
                    'click button': 'buttonClick'
                },
                buttonClick(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(options) {
                    this.options = options || {};
                },
                render() {
                    this.$el.html(this.template(this.options));
                },
                events: {
                    'click button': 'buttonClick',
                    'keypress .tb_litelightbox_prompt_input': 'keyPress'
                },
                buttonClick(e) {
                    e.preventDefault();
                    this.trigger('litelightbox:prompt', $(e.currentTarget).data('type'), this.$el.find('.tb_litelightbox_prompt_input').val());
                },
                keyPress(e) {
                    if (e.which === 13) { // on enter
                        this.trigger('litelightbox:prompt', 'ok', $(e.currentTarget).val());
                    }
                }
            }),
            confirm(message, callback, options) {
                options = _.defaults(options || {}, {
                    buttons: {
                        no: {
                            label: 'No'
                        },
                        yes: {
                            label: 'Yes'
                        }
                    }
                });
                options.message = message;
                const 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 ( typeof callback === 'function' ) {
                        callback.call(this, type);
                    }
                });
            },
            prompt(message, callback, options) {
                options = _.defaults(options || {}, {
                    buttons: {
                        cancel: {
                            label: 'Cancel'
                        },
                        ok: {
                            label: 'OK'
                        }
                    }
                });
                options.message = message;
                const 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 ( typeof callback === 'function' ) {
                        value = 'cancel' === type ? null : value;
                        callback.call(this, value);
                    }
                });
            },
            alert(message) {
                ThemifyBuilderCommon.LiteLightbox.confirm(message, null, {
                    buttons: {
                        yes: {
                            label: 'OK'
                        }
                    }
                });
            }
        },
        templateCache: {
            templates: [],
            get(selector) {
                if (this.templates[selector] === undefined) {
                    const el = document.getElementById(selector);
                    this.templates[selector] = el.innerHTML;
                    setTimeout(function () {
                        el.remove();
                    }, 6000);
                }
                return this.templates[selector];
            }
        },
        setToolbar() {
            const fragment = document.getElementById('tb_toolbar_template'),
                    tmp = fragment.content;
            if (tb_app.mode === 'visual') {
                document.body.appendChild(tmp);
            } else {
                fragment.parentNode.insertBefore(tmp, fragment);
            }
            fragment.remove();
        },
        isImageUrl(link) {
            if (!link) {
                return false;
            }
            const parts = link.split('?')[0].split('.');
            return  ['jpg', 'jpeg', 'tiff', 'png', 'gif', 'bmp', 'svg'].indexOf(parts[parts.length - 1]) !== -1;
        }

    };

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