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

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

var ThemifyBuilderCommon;
if (window.top.document !== document) {
    //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;
    top_iframe = window.top.document;
}
else {
    top_iframe = document;
}

(function ($, window, document, undefined) {

    'use strict';

    ThemifyBuilderCommon = {
        fonts: [],
        safe_fonts: {},
        google_fonts: {},
        loaded_fonts: [],
        showLoader: function (stats) {
            var alert = $("#themify_builder_alert", top_iframe);
            if (stats === 'show') {
                alert.addClass('tb_busy').show();
            }
            else if (stats === 'spinhide') {
                alert.fadeOut(500, function () {
                    $(this).removeClass('tb_busy');
                });
            }
            else {
                if (stats !== 'error') {
                    stats = 'done';
                }
                alert.removeClass('tb_busy').addClass('tb_' + stats).delay(500).fadeOut(500, function () {
                    $(this).removeClass('tb_' + stats);
                });
            }
        },
        setUpTooltip: function () {
            if ($('.themify_is_premium_module,.themify_builder_lite', top_iframe).length > 0) {
                if ($('.themify_tooltip').length === 0) {
                    $('<div class="themify_tooltip">Upgrade to premium version to get this feature<div class="themify_tooltip_arrow"><div class="themify_tooltip_arrow_border"></div><div class="themify_tooltip_arrow_background"></div></div></div>').appendTo('body');
                }
                var width = ($('.themify_tooltip').outerWidth(true) / 2) + 10,
                        height = $('.themify_tooltip').outerHeight(true) + 10,
                        is_hover;
                $('.themify_builder_lite,.themify_is_premium_module').each(function () {
                    if ($(this).children('.themify_builder_lite_modal').length === 0) {
                        var $this = $(this);
                        $('<div class="themify_builder_lite_modal"></div>').appendTo($(this)).mouseenter(function (e) {
                            var is_input = $this.children('.themify_builder_input').length > 0,
                                    tooltip = $('.themify_tooltip'),
                                    $ofset = $(this).offset(),
                                    top = $ofset.top - height,
                                    $width = is_input ? 50 : ($(this).width() / 2) - width,
                                    is_hover = true;
                            $('.themify_builder_lite_active').removeClass('themify_builder_lite_active');
                            $(this).addClass('themify_builder_lite_active');
                            if(top<-10){
                                tooltip.addClass('themify_tooltip_arrow_top');
                            }
                            else{
                                tooltip.removeClass('themify_tooltip_arrow_top');
                            }
                            tooltip.css({top: Math.abs(top), left: $ofset.left + $width}).delay(500)
                                    .queue(function (next) {
                                        var $el = $(this);
                                        if ($('.themify_builder_lite_active').length > 0) {
                                            if (is_hover) {
                                                $el.stop().fadeIn('fast');
                                            }
                                            else {
                                                $('.themify_builder_lite_modal').each(function () {
                                                    if ($(this).is(':hover')) {
                                                        $el.stop().fadeIn('fast');
                                                        return false;
                                                    }
                                                });
                                            }
                                        }
                                        else {
                                            $el.hide();
                                        }
                                        next();
                                    });
                            setTimeout(function () {
                                if ($('.themify_builder_lite_active').length === 0) {
                                    tooltip.hide();
                                }
                                else {
                                    var check_hover = false;
                                    $('.themify_builder_lite_modal').each(function () {
                                        if ($(this).is(':hover')) {
                                            check_hover = true;
                                            return false;
                                        }
                                    });
                                    if (!check_hover) {
                                        $('.themify_builder_lite_active').removeClass('themify_builder_lite_active');
                                        tooltip.hide();
                                    }
                                }
                            }, 1000);
                        }).mouseleave(function () {
                            is_hover = false;
                            $('.themify_builder_lite_active').removeClass('themify_builder_lite_active');
                            $('.themify_tooltip').hide();
                        });
                    }
                });
                $(window).scroll(function () {
                    $('.themify_builder_lite_active').trigger('mouseenter');
                });
            }
        },
        /**
         * Clipboard-like functionality. Wraps localStorage with a Themify key. Supports one copied item per time.
         */
        Clipboard: {
            key: 'themify_builder_clipboard_',
            is_available: null,
            /**
             * Function that detects whether localStorage is both supported and available.
             */
            storageAvailable: function (type) {
                if (this.is_available === null) {
                    try {
                        var storage = window[type],
                                x = '__storage_test__';
                        storage.setItem(x, x);
                        storage.removeItem(x);
                        this.is_available = true;
                    }
                    catch (e) {
                        this.is_available = false;
                        alert(themifyBuilder.i18n.text_no_localStorage);
                    }
                }
                return this.is_available;
            },
            set: function (type, content) {
                if (this.storageAvailable('localStorage')) {
                    var data = {};
                    data[type] = content;
                    localStorage.setItem(this.key + 'content', JSON.stringify(data));
                    return true;
                }
                return false;
            },
            get: function (type) {
                if (this.storageAvailable('localStorage')) {
                    var savedContent = JSON.parse(localStorage.getItem(this.key + 'content'));
                    return savedContent[type] !== undefined ? savedContent[type] : false;
                }
                return false;
            }
        },
        confirmDataPaste: function () {
            return confirm(themifyBuilder.i18n.text_confirm_data_paste);
        },
        alertWrongPaste: function () {
            alert(themifyBuilder.i18n.text_alert_wrong_paste);
        },
        detectBuilderComponent: function ($component) {
            return $component.data('component') || $component.attr('data-component') || false;
        },
        /**
         * Returns the checked radio in a named group.
         *
         * @param {jQuery} $radioInGroup A radio in a named group.
         * @param {jQuery|undefined} $context Where should the radio group be searched in.
         * @returns {jQuery}
         */
        getCheckedRadioInGroup: function ($radioInGroup, $context) {
            if (typeof $context === 'undefined') {
                $context = null;
            }

            var radioGroupName = $radioInGroup.attr('name');

            return $('input:radio[name="' + radioGroupName + '"]:checked', $context);
        },
        /**
         * Loads Google Web Fonts.
         *
         * @param {Array} fontFamilies Array containing font family declarations with character sets and styles.
         *                             E.g., [ 'Open+Sans:400,700:latin,latin-ext' ]
         */
        loadGoogleFonts: function (fontFamilies, iframe) {
            iframe = iframe || false;
            var fontConfig = {
                google: {families: fontFamilies}
            };
            WebFont.load(fontConfig);
            if (iframe) {
                fontConfig['context'] = iframe;
                WebFont.load(fontConfig);
            }
        },
        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('.themify_builder_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);
                                }
                            }
                        }
                    });
                }
            }
        },
        fontPreview: function ($container) {
            var self = ThemifyBuilderCommon;
            setTimeout(function () {
                self.autoComplete($container);
            }, 1);
            var $safe_fonts_html = '',
                    $google_fonts_html = '';
            if (Object.keys(self.safe_fonts).length === 0) {
                var fonts = themifyBuilder.fonts.safe;
                for (var i = 0, len = fonts.length; i < len; ++i) {
                    if ('' !== fonts[i].value && 'default' !== fonts[i].value) {
                        self.safe_fonts[fonts[i].value] = fonts[i].name;
                    }
                }
                fonts = themifyBuilder.fonts.google;
                for (var i = 0, len = fonts.length; i < len; ++i) {
                    if ('' !== fonts[i].value && 'default' !== fonts[i].value) {
                        self.google_fonts[fonts[i].value] = fonts[i].name;
                    }
                }
                delete themifyBuilder['fonts'];
            }
            $container.find('.font-family-select').each(function () {
                var selected = $(this).data('selected'),
                        $optgroup = $(this).find('optgroup');

                $(this).parent('.themify_builder_font_preview_wrapper').focusin(function () {
                    $(this).unbind('focusin');
                    if (!$safe_fonts_html) {
                        for (var $i in self.safe_fonts) {
                            var $is_selected = selected === $i ? 'selected="selected"' : '';
                            $safe_fonts_html += '<option ' + $is_selected + ' data-type="webfont" value="' + $i + '">' + self.safe_fonts[$i] + '</option>';
                        }
                        for (var $i in self.google_fonts) {
                            var $is_selected = selected === $i ? 'selected="selected"' : '';
                            $google_fonts_html += '<option ' + $is_selected + ' value="' + $i + '">' + self.google_fonts[$i] + '</option>';
                        }
                    }
                    $optgroup[0].insertAdjacentHTML('beforeend',$safe_fonts_html);
                    $optgroup.last()[0].insertAdjacentHTML('beforeend',$google_fonts_html);
                    comboSelect($(this).children('select'));
                });
                if (selected) {
                    if (self.safe_fonts[selected]) {
                        $optgroup[0].insertAdjacentHTML('beforeend','<option selected="selected" data-type="webfont" value="' + selected + '">' + self.safe_fonts[selected] + '</option>');
                    }
                    else if (self.google_fonts[selected]) {
                        $optgroup.last()[0].insertAdjacentHTML('beforeend','<option selected="selected" value="' + selected + '">' + self.google_fonts[selected] + '</option>');
                    }
                }
            });
            if (self.fonts.length > 0) {
                var $first = $('.themify-combo-dropdown').first();
                for (var $i in self.fonts) {
                    var $index = $first.find('[data-value="' + self.fonts[$i] + '"]').index();
                    showFontPreview($index, self.fonts[$i]);
                }
            }
            function comboSelect($select) {
                var $combo = $select.comboSelect({
                    'comboClass': 'themify-combo-select',
                    'comboArrowClass': 'themify-combo-arrow',
                    'comboDropDownClass': 'themify-combo-dropdown',
                    'inputClass': 'themify-combo-input',
                    'disabledClass': 'themify-combo-disabled',
                    'hoverClass': 'themify-combo-hover',
                    'selectedClass': 'themify-combo-selected',
                    'markerClass': 'themify-combo-marker'
                }).parent('div');

                $combo.on('comboselect:close', function () {
                    $('.themify_builder_font_preview', top_iframe).hide();
                }).on('click.item', '.themify-combo-item', function (e) {
                    var value = $(this).data('value');
                    if (value && $.inArray(value, self.loaded_fonts) === -1 && $select.find('option[value="' + value + '"]').data('type') !== 'webfont') {
                        WebFont.load({
                            classes: false,
                            google: {
                                families: [value]
                            },
                            fontloading: function (familyName, fvd) {
                                self.loaded_fonts.push(value);
                            },
                            fontinactive: function (familyName, fvd) {
                                self.loaded_fonts.push(value);
                            }
                        });

                    }
                }).trigger('focusin');
                $('.themify-combo-item', $combo).unbind('hover').hover(function () {
                    var $value = $(this).data('value');
                    if ($value) {
                        if (!$(this).is(':visible')) {
                            return;
                        }
                        var $preview = $combo.next('.themify_builder_font_preview');
                        if ($value === 'default') {
                            $value = 'inherit';
                        }
                        $preview.css({'top': $(this).position().top + 30, 'font-family': $value, 'display': 'block'});
                        if ($value === 'inherit') {
                            return;
                        }
                        if (!$(this).hasClass('themify_builder_font_loaded')) {
                            var $this = $(this),
                                    $index = $this.index();
                            $this.addClass('themify_builder_font_loaded');
                            $preview = $preview.children('span');
                            if ($.inArray($value, self.fonts) === -1) {
                                $preview.addClass('themify_show_wait');
                                if ($select.find('option[value="' + $value + '"]').data('type') !== 'webfont') {
                                    WebFont.load({
                                        classes: false,
                                        context: window.top,
                                        google: {
                                            families: [$value]
                                        },
                                        fontloading: function (familyName, fvd) {
                                            self.fonts.push($value);
                                            $preview.removeClass('themify_show_wait');
                                        },
                                        fontinactive: function (familyName, fvd) {
                                            self.fonts.push($value);
                                            $preview.removeClass('themify_show_wait');
                                        }
                                    });
                                }
                                else {
                                    self.fonts.push($value);
                                    $preview.removeClass('themify_show_wait');
                                }
                            }
                            showFontPreview($index, $value, $preview);
                        }
                    }
                });
            }
            function showFontPreview($index, familyName) {
                $('.themify-combo-dropdown', top_iframe).find('li:eq(' + $index + ')').addClass('themify_builder_font_loaded').css('font-family', familyName);
            }
            $('.themify-combo-arrow', top_iframe).unbind('click').click(function () {
                $('.themify_builder_font_preview', top_iframe).hide();
            });
        },
        Lightbox: {
            $lightbox: null,
            rememberedRow: null,
            rememberedCid: null,
            setup: function () {
                var isThemifyTheme = 'true' === themifyBuilder.isThemifyTheme ? 'is-themify-theme' : 'is-not-themify-theme',
                    lightbox_func = wp.template('builder_lightbox'),
                    markup = lightbox_func({is_themify_theme: isThemifyTheme});
                top_iframe.body.insertAdjacentHTML('beforeend',markup);
                this.$lightbox = $('#themify_builder_lightbox_parent', top_iframe);
                this.bindEvents();
            },
            bindEvents: function () {
                var self = ThemifyBuilderCommon.Lightbox,
                    actionEvent = 'true' === themifyBuilder.isTouch ? 'touchend' : 'click';
                SimpleBar.removeObserver();
                // Top bar actions
                self.$lightbox
                        .on(actionEvent, '.themify_builder_options_tab li,.themify_builder_tabs>ul li', self.switchTabs)
                        .on(actionEvent, '.builder_cancel_lightbox', self.cancel)
                        .on(actionEvent, '.reset-styling', self.resetStyling)
                        // Content actions
                        .on('change', '.tb-option-radio-enable input', self.clickRadioOption)
                        .on('change', '.tb-option-checkbox-enable input', self.clickCheckboxOption)
                        .on('change','.border_style',self.hideShowBorder)
                        .on(actionEvent,'.tb-icon-radio label',self.bindStylingToggles)
                        .on(actionEvent,'.tb-style-toggle',self.bindStylingRows)
                        .on('change', '#tb_module_settings .query_category_single', function () {
                            $(this).closest('.themify_builder_input').find('.query_category_multiple').val($(this).val());
                        })
                        .one( 'themify_opened_lightbox', self.resizable.init.bind( self.resizable ) );
                        document.body.insertAdjacentHTML('beforeend','<div id="themify_builder_overlay"></div>');
                        if (!themifyBuilder.disableShortcuts) {
                                self.controlByKeyInput();
                        }
                        if(themifybuilderapp.mode === 'visual'){
                            // Cancel docked mode
                            self.$lightbox.on(actionEvent,'.builder_cancel_docked_mode', function( e ) {
								e.preventDefault();
								e.stopPropagation();
								self.dockMode.close(true);
								$(document).trigger('mouseup');
                            } );
                        }
            },
            adjustHeight: function (newLightboxHeight) {
				this.$lightbox.find('#themify_builder_lightbox_container').css('height', newLightboxHeight - 55);
            },
            getLightboxStorageKey:function(){
                    return themifybuilderapp.mode === 'visual' ? 'themify_builder_lightbox_frontend_pos_size' : 'themify_builder_lightbox_backend_pos_size';
			},
			getLightboxStorage: function() {
				var lightboxStorage = localStorage.getItem( this.getLightboxStorageKey() ) || '{}';
				return JSON.parse( lightboxStorage );
			},
			updateLightboxStorage: function( obj ) {
				var lightboxStorage = this.getLightboxStorage(),
					newObj;

				( newObj = _.extend( lightboxStorage, obj ) )
					&& localStorage.setItem( this.getLightboxStorageKey(), JSON.stringify( newObj ) );
			},
            resizable:{
                $el:'',
                w:'',
                h:'',
                x:'',
                y:'',
                axis:'',
                overlay:false,
                minWidth: 500,
                maxWidth: 880,
                minHeight: 320,
                maxHeight: 800,
                init:function(){
					var self = this,
						lightbox = ThemifyBuilderCommon.Lightbox,
						$body = $('body',top_iframe),
						draggableCallback = function( e, ui ) {
							if( ui !== undefined && e && e.target.classList.contains('builder-lightbox') ) {
								switch( e.type ) {
									case 'dragstart' :
										$body.addClass('themify_lightbox_drag');
										lightbox.fixContainment();
									break;
									case 'dragstop':
										$body.removeClass('themify_lightbox_drag');
										lightbox.fixContainment();
										themifybuilderapp.mode === 'visual' && $(document).trigger('mouseup');
										self.remember();
									case 'drag':
										lightbox.dockMode.drag(e);
									break;
								}
							}
						};
						
					this.$el = lightbox.$lightbox;
					self.$el.draggable({
						handle: self.$el.find('.themify_builder_lightbox_top_bar'),
						scroll: false,
						start: draggableCallback,
						drag: draggableCallback,
						stop: draggableCallback
					});

                    if(themifybuilderapp.mode==='visual'){
                        //create fix overlay on top iframe,mouse position will be always on top iframe on resizing
                        this.tb_resizable_overlay = this.$el.prev('.tb_resizable_overlay');
                    }
                    var items = this.$el[0].getElementsByClassName('tb_resizable');
                    for( var i = 0, len = items.length; i < len; ++i ) {
                        items[i].addEventListener('mousedown', function(e) {
                            if( e.which === 1 ){
                                e.preventDefault();
                                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.classList.contains( 'tb_resizable-se' ) ? 'both': (this.classList.contains('tb_resizable-s')? 'y': (this.classList.contains('tb_resizable-w')? 'w' : 'x'));
                                self.tb_resizable_overlay && self.tb_resizable_overlay.show();
								self.$el.addClass('tb_resizing');
                                top_iframe.addEventListener('mousemove', self.resize, false);
								top_iframe.addEventListener('mouseup', self.stop, false);
                                if(self.axis==='w'){
                                    $body.addClass('tb_start_animate');
                                    $('body').addClass('tb_start_animate');
                                }
                            }
                            
                        }, false);
                    }
                    $('body').on('editing_module_option', self.setupLightboxSizeClass);
                },
                remember: function(){
					var self = ThemifyBuilderCommon.Lightbox.resizable,
						pos = self.$el.position(),
						isDocked = ThemifyBuilderCommon.Lightbox.dockMode.get(),
						lStorage = ThemifyBuilderCommon.Lightbox.getLightboxStorage(),
						posSizeObj = {
							top: pos.top,
							left: pos.left,
							width: isDocked && lStorage ? lStorage.width : self.$el.outerWidth(),
							height: isDocked && lStorage ? lStorage.height : self.$el.outerHeight()
						};
						
					isDocked && ( posSizeObj.dockedWidth = self.$el.outerWidth() );
					ThemifyBuilderCommon.Lightbox.updateLightboxStorage( posSizeObj );
				},
				setupLightboxSizeClass: function () {
					var self = ThemifyBuilderCommon.Lightbox.resizable;
					self.$el.toggleClass( 'larger-lightbox', parseInt( self.$el.width() ) > 750 );
				},
				resize:function(e){
					var self = ThemifyBuilderCommon.Lightbox.resizable,
						w = self.w + e.clientX - self.x,
						h = self.h + e.clientY - self.y;
						
					if( self.axis === 'w' ) {
						w = self.x + self.w - e.clientX;
						if( w >= 300 && w <= self.maxWidth ) {
							self.$el.width(w);
							self.setupLightboxSizeClass();
							ThemifyBuilderCommon.Lightbox.dockMode.resize(e);
						}
					} else {
						if((self.axis==='both' || self.axis==='x') && w>=self.minWidth && w<=self.maxWidth) {
							self.$el.width(w);
							self.setupLightboxSizeClass();
						}
						if((self.axis==='both' || self.axis==='y') && h>=self.minHeight && h<=self.maxHeight) {
							self.$el.height(h);
							ThemifyBuilderCommon.Lightbox.adjustHeight(self.$el.height());
						}
					}
				},
				stop: function(e) {
					var lightbox = ThemifyBuilderCommon.Lightbox,
						self = lightbox.resizable;
					
					self.tb_resizable_overlay && self.tb_resizable_overlay.hide();
                    self.$el.removeClass('tb_resizing');
                    top_iframe.removeEventListener('mousemove', self.resize, false);
                    top_iframe.removeEventListener('mouseup', self.stop, false);
					lightbox.fixContainment();
                    self.remember();
					lightbox.dockMode.resize('stop');
                    $('body').trigger('themify_builder_lightbox_resize');
                    if(self.axis === 'w'){
						var $body = $('body',top_iframe);
						$body = $body.add( 'body' )
						$body.removeClass('tb_start_animate');
                    }
                }
            },
            fixContainment: function () {
                var self = ThemifyBuilderCommon.Lightbox,
					el_w = self.$lightbox.outerWidth(),
					container_w = $(window.top).width(),
					container_h = $(window.top).height(),
					containment = [-el_w + 20, 0, container_w - 20, container_h - 30],
					positions = self.$lightbox.position(),
					new_positions = {};

				positions.left < containment[0] && (new_positions.left = containment[0]),
				0 > positions.top && (new_positions.top = 0),
				positions.left > containment[2] && (new_positions.left = containment[2]),
				positions.top > containment[3] && (new_positions.top = containment[3]),
				self.$lightbox.css(new_positions);
            },
            open: function (options, beforeCallback, afterCallback) {
                var self = ThemifyBuilderCommon.Lightbox,
					$lightboxContainer = $('#themify_builder_lightbox_container', self.$lightbox);
				themifybuilderapp.toolbar.Panel.hide();
                $('#themify_builder_overlay').show();
                ThemifyBuilderCommon.showLoader('show');

                if ('inline' === options.loadMethod) {
                    var response = ThemifyBuilderCommon.templateCache.get('tmpl-' + options.templateID);
                    self.openCallback(response, $lightboxContainer, beforeCallback, afterCallback);
                } 
                else if(options.loadMethod==='html'){
                    self.openCallback(options.data, $lightboxContainer, beforeCallback, afterCallback);
                }
                else {
                    options.data = _.extend(options.data || {}, {nonce: themifyBuilder.tb_load_nonce});
                    options = _.defaults(options || {}, {
                        type: 'POST',
                        url: themifyBuilder.ajaxurl
                    });

                    var jqxhr = $.ajax(options);
                    jqxhr.done(function (response) {
                        self.openCallback(response, $lightboxContainer, beforeCallback, afterCallback);
                        var container = $($lightboxContainer).find('.themify_builder_options_tab_wrapper');
                        if (container.length > 0) {
                            new SimpleBar(container[0]);
                        }
                    });
                }
            },
            openCallback: function (response, $lightboxContainer, beforeCallback, afterCallback) {
                themifybuilderapp.toolbar.undoManager.disable();
                var self = ThemifyBuilderCommon.Lightbox,
                    posSizeObj = {
						top: 100,
						left: Math.max( 0, ( ( $( window.top ).width() / 2 ) - 300 ) ),
						width: 600,
						height: 500
					};
					
				_.extend( posSizeObj, self.getLightboxStorage() );
				
                var $response = $(response),
                    $optionsTabItemsContainer = $response.find('#themify_builder_lightbox_options_tab_items');
					
                if ($optionsTabItemsContainer.length > 0 ) {
                    self.$lightbox[0].getElementsByClassName('themify_builder_options_tab')[0].insertAdjacentHTML('beforeend',$optionsTabItemsContainer[0].innerHTML);
                    $optionsTabItemsContainer.remove();
                }

                var $actionButtonsContainer = $response.find('#themify_builder_lightbox_actions_items');
                if ($actionButtonsContainer.length > 0) {
                    self.$lightbox[0].getElementsByClassName('themify_builder_lightbox_actions')[0].insertAdjacentHTML('beforeend',$actionButtonsContainer[0].innerHTML);
                    $actionButtonsContainer.remove();
                }
                if (typeof beforeCallback==='function') {
                    beforeCallback.call(self, $response[0]);
                }
                $lightboxContainer.html($response[0]);
                if (typeof afterCallback==='function') {
                    afterCallback.call(self, $response[0]);
				}
                self.$lightbox
					.addClass('themify_builder_show_start')
					.show()
					.css( posSizeObj );
                self.dockMode.setDoc();
                self.fixContainment();
                ThemifyBuilderCommon.showLoader('spinhide');
                if (!themifyBuilder.disableShortcuts) {
                    $(document).off('keyup', self.cancelKeyListener).on('keyup', self.cancelKeyListener);
                }
                self.adjustHeight(posSizeObj.height);
                ThemifyBuilderCommon.setUpTooltip();
                self.$lightbox.removeClass('themify_builder_show_start').trigger( 'themify_opened_lightbox' );
                
            },
            close: function () {
                var self = ThemifyBuilderCommon.Lightbox;

                $('body').trigger('themify_builder_lightbox_before_close');
                self.$lightbox.fadeOut(function (e) {
                    $(this).removeClass('animated fadeOut');
                    // Animation complete.
                    self._cleanLightBoxContent();
                    $('#themify_builder_overlay').hide();
                    $('#themify_builder_lightbox_parent', top_iframe).hide();
                    themifybuilderapp.toolbar.Panel.resetPanel();
                    if(themifybuilderapp.activeModel){
                        themifybuilderapp.activeModel.unset('styleClicked', {silent: true});
                        themifybuilderapp.activeModel.unset('visibileClicked', {silent: true});
                    }
                    themifybuilderapp.toolbar.undoManager.updateUndoBtns();
                    $('body').trigger('themify_builder_lightbox_close');
                    // Update docked mode
                    self.dockMode.close( false, true );
                });
            },
            dockMode: {
                key: 'themify_builder_docked',
                workspace: $('.themify_builder_workspace_container', top_iframe.body),
				isDocked: null,
				defaultWidth: 380,
				dockOut: 0,
                checkIsVisual: function () {
                    return themifybuilderapp.mode === 'visual';
                },
                set: function (isDocked, noStorage) {
					! noStorage && localStorage.setItem(this.key, isDocked);
                    this.isDocked = isDocked;
                },
                get: function () {
					return this.isDocked || localStorage.getItem(this.key) === 'true';
                },
                setStyleRowToggle:function(){
					var self = ThemifyBuilderCommon.Lightbox,
						tabs = self.$lightbox.find('.themify_builder_tab');
					
					if(tabs.length > 0){
						tabs.each(function(){
							var toggles = $(this).find( '.tb-style-toggle' ),
								rows = $(this).find('.themify_builder_field');
								
								if(toggles.length && toggles.length>1){
									toggles.addClass( 'tb-closed' );
									rows.addClass( 'tb-field-expanded' );
								}
							
						});
					} else {
						var toggles = self.$lightbox.find( '.tb-style-toggle' ),
							rows = self.$lightbox.find('#themify_builder_options_styling .themify_builder_field');
						rows = rows.filter( function() {
							return ! $( this ).find( '.reset-styling, #custom_css_column' ).length;
						} );

						toggles.addClass( 'tb-closed' );
						rows.addClass( 'tb-field-expanded' );
					}
                },
                setDoc: function () {
                    if (this.checkIsVisual() && this.get()) {
                        top_iframe.body.classList.add('tb_module_panel_docked');
						this.setDefaultWidth();
                        this.setWidth();
                        this.onResize();
                        $(window.top).off('tfsmartresize.docked').on('tfsmartresize.docked', function () {
                            this.resize();
                            this.onResize();
                        }.bind(this));
                        $('body').off( 'themify_builder_change_mode.docked').on('themify_builder_change_mode.docked',function(e,prevBreakPoint, breakpoint){
							this.setWidth();
							if(breakpoint!=='desktop' && prevBreakPoint==='desktop'){
								setTimeout(function(){
									if(themifybuilderapp.toolbar.$el.width()!==top_iframe.documentElement.clientWidth){
										this.setWidth();
										this.onResize();
									}
								}.bind(this),500);
							}
                        }.bind(this));
					}
					this.setStyleRowToggle();
				},
				setDefaultWidth: function() {
					var self = ThemifyBuilderCommon.Lightbox,
						lightboxStorage = self.getLightboxStorage(),
						defaultWidth = this.defaultWidth;

					if( lightboxStorage && lightboxStorage.dockedWidth ) {
						defaultWidth = lightboxStorage.dockedWidth;
					}
					
					self.$lightbox.css( 'width', defaultWidth );
				},
                setWidth: function () {
                    var docWidth = top_iframe.documentElement.clientWidth || top_iframe.body.clientWidth,
                        cWidth = docWidth - ThemifyBuilderCommon.Lightbox.$lightbox.css('height', '').width();
                    themifybuilderapp.toolbar.$el.css('width', cWidth);
                    this.workspace.css('width', cWidth);
                },
                resize: function (e) {
                    if (this.checkIsVisual() && this.get()) {
						this.setWidth();
						e === 'stop' && this.onResize();
                    }
                },
                onResize: function () {
                    themifybuilderapp.Utils._onResize(true);
                },
                drag: function (e) {
                    if (this.checkIsVisual()) {
						top_iframe.body.classList.toggle( 'themify-dock-highlight', e.type === 'drag' && e.pageX + 20 >= window.top.innerWidth );
						if (e.pageX + 20 >= window.top.innerWidth && e.type === 'dragstop') {
							this.set(true);
							this.setDoc();
						} else if ( this.get() ) {
							if( ! this.dockOut ) {
								this.dockOut = e.clientX;
							} else if( this.dockOut && e.type === 'dragstop' ) {
								this.dockOut = 0;
							} else if( this.dockOut - e.clientX > 50 ) {
								this.close();
								this.dockOut = 0;
								$(document).trigger('mouseup');
							}
						}
					}
				},
				close: function (center, onlyClose) {
					if (this.checkIsVisual() && this.get()) {
						var self = ThemifyBuilderCommon.Lightbox,
							lightboxStorage = self.getLightboxStorage(),
							props = {
								width: lightboxStorage.width ? lightboxStorage.width : self.resizable.minWidth,
								height: lightboxStorage.height ? lightboxStorage.height : self.resizable.minHeight
							};
						
						if (center) {
							props.top = window.top.innerHeight / 2 - self.$lightbox.innerHeight() / 2;
							props.left = window.top.innerWidth / 2 - self.$lightbox.innerWidth() / 2;
						}

						self.$lightbox.css(props);
						this.set(false, onlyClose);
						top_iframe.body.classList.remove('tb_module_panel_docked');
						themifybuilderapp.toolbar.$el.css('width', '');
						this.workspace.css('width', '');
						this.onResize();
						$(window.top).off('tfsmartresize.docked');
						$('body').off('themify_builder_change_mode.docked');
                    }
                }
            },
            _cleanLightBoxContent: function () {
                this.forgetRow();
                this.$lightbox.find('.themify_builder_options_tab').empty();
                this.$lightbox.find('.themify_builder_lightbox_actions')
					.children()
					.not('.builder_cancel_lightbox, .builder_cancel_docked_mode')
					.remove();
            },
            controlByKeyInput: function () {
                function save(e){
                    // Ctrl + s | Cmd + s - Save Builder
                    if (83 === e.which && document.activeElement.tagName !== 'INPUT' && document.activeElement.tagName !== 'TEXTAREA' && (true === e.ctrlKey || true === e.metaKey)) {
                        e.preventDefault();
                        e.stopPropagation();
                        var $settings = $('.builder_save_button',top_iframe);
                        if ($settings.length > 0) {
                            $settings.trigger('click');
                        }
                        else{
                            themifybuilderapp.toolbar.$el.find('.tb_toolbar_save').trigger('click');
                        }
                    }
                }
                $(document).on('keydown',save );
                if(themifybuilderapp.mode==='visual'){
                    $(top_iframe).on('keydown',save);
                }
            },
            clone: function (el) {
                var node = el.clone(true);
                if (themifybuilderapp.mode === 'visual') {
                    //after cloning dom the video is playing in bg
                    node.find('video').trigger('pause');
                    node.find('.big-video-wrap').remove();
                }
                return node;
            },
            rememberRow: function () {
                this.rememberedRow = this.clone($('.tb_element_cid_' + themifybuilderapp.activeModel.cid));
                this.rememberedCid = themifybuilderapp.activeModel.cid;
            },
            revertToRememberedRow: function () {
                var model = themifybuilderapp.Models.Registry.lookup(this.rememberedCid);
                if (model) {
                    var type = model.get('elType');
                    if (type !== 'subrow' && type !== 'column') {
                        model.trigger('custom:restorehtml', this.rememberedRow);
                    }
                }
                this.forgetRow();
            },
            forgetRow: function () {
                this.rememberedRow = this.rememberedCid = null;
            },
            clickRadioOption: function (e, item) {
                var item = item ? item : $(this),
                        context = item.hasClass('themify-builder-radio-dnd') ? item.closest('.tb_repeatable_field_content') : ThemifyBuilderCommon.Lightbox.$lightbox,
                        selected_item = ThemifyBuilderCommon.getCheckedRadioInGroup(item, context),
                        selected_group = context.find('input[name="' + selected_item.prop('name') + '"]');
                selected_item = selected_item.data('selected');

                selected_group.each(function () {
                    context.find('.tb-group-element-' + $(this).val()).hide();
                });
                $('.' + selected_item, context).show();
                context.find( '[data-binding]:visible').each( function () {
                    themifybuilderapp.Mixins.Common.doTheBinding($(this),$(this).val());
                });
            },
            clickCheckboxOption: function (e, item) {
                var item = item ? item : $(this),
                        el = item.hasClass('themify-builder-radio-dnd') ? item.closest('.tb_repeatable_field_content') : ThemifyBuilderCommon.Lightbox.$lightbox;
                el.find('.tb-checkbox-element').hide();
                var parent = item.parent('.themify-checkbox'),
                    items = parent.hasClass('tb-option-checkbox-revert')?parent.find('input:not(:checked)'):parent.find('input:checked');
                items.each(function () {
                    el.find('.tb-checkbox-element.' + $(this).data('selected')).show();;
                });
            },
            bindStylingToggles: function(e) {
                var input = $(this).prev('input');
                if(input.is(':checked')){
                    e.stopPropagation();
                    e.preventDefault();
                    input.prop('checked',false).trigger('change');
                }
            },
            bindStylingRows:function(e){
                e.preventDefault();
				var rows = $(this).nextUntil('.tb-style-toggle');

				rows = rows.filter( function() {
					return ! $( this ).find( '.reset-styling, #custom_css_column' ).length;
				} );

                if(this.classList.contains('tb-closed')){
                    this.classList.remove('tb-closed');
                    rows.removeClass('tb-field-expanded');
                }
                else{
                    this.classList.add('tb-closed');
                    rows.addClass('tb-field-expanded');
                }
            },
            hideShowBorder: function (e,el) {
                if(e && e.isTrigger){
                    return;
                }
                if(!el){
                    el = $(this);
                }
                var item = el.closest('.selectwrapper').siblings('.tb_border_wrapper');
                if(el.val()==='none'){
                    item.hide();
                }
                else{
                    item.show();
                }
            },
            cancelKeyListener: function (e) {
                var self = ThemifyBuilderCommon.Lightbox;
                if (e.keyCode === 27) {
                    e.preventDefault();
                    self.cancel(e);
                }
            },
            cancel: function (e) {
                e.preventDefault();
                var self = ThemifyBuilderCommon.Lightbox;
                if (self.rememberedCid !== null) {
                    self.revertToRememberedRow();
                }
                self.close();
            },
            resetStyling: function (e) {
                e.preventDefault();
                var $context = $('#themify_builder_options_styling', top_iframe),
                        radioGroupNames = [];
                $context.find('.tb_lb_option:not(.exclude-from-reset-field)').each(function () {
                    if ($(this).prop('type') === 'radio') {
                        var radioGroupName = $(this).prop('name');
                        if (radioGroupNames.indexOf(radioGroupName) === -1) {
                            $context.find('[name="' + radioGroupName + '"]:first').prop('checked', true).trigger('change');
                        }
                    }
                    else if ($(this).hasClass('themify-builder-uploader-input')) {
                        $(this).val('').trigger('change').parent().find('.img-placeholder').empty();
                    } else if ($(this).hasClass('font-family-select')) {
                        $(this).val('default').trigger('change');
                    } else if ($(this).hasClass('minicolors-input')) {
						var $el = $(this).val('');
						if (themifybuilderapp.mode === 'visual') {
							$('body').trigger('themify_builder_color_picker_change', [$el.attr('id'), $el, '']);
						} else {
							$el.trigger('change').parent().next('.color_opacity').val('');
						}
                    }
                    else {
						if($(this).hasClass('tb_unit')){
							$(this).val('px').trigger('change');
						} else {
							$(this).val('').prop('selected', false).trigger('change');
						}
                    }
                });
            },
            switchTabs: function (e) {
                var self = ThemifyBuilderCommon.Lightbox;
                e.preventDefault();
                e.stopPropagation();
                var id = $(this).find('a').attr('href'),
                    container = self.$lightbox.find(id);
                if (container[0] === undefined) {
                    return;
                }
                $(this).addClass('current').siblings().removeClass('current');
                if (container[0].SimpleBar === undefined && $(this).closest('.themify_builder_options_tab').length > 0) {
                    new SimpleBar(container[0]);
                }
                container.show().siblings('.themify_builder_options_tab_wrapper,.themify_builder_tab').hide();
                $('body').trigger('themify_builder_tabsactive', [id, container]);
                if(themifybuilderapp.mode==='visual'){
                    $(document).trigger('mouseup');
                }
            }
        },
        LiteLightbox: {
            modal: new wp.media.view.Modal({
                controller: {trigger: function () {
                    }}
            }),
            confirmView: Backbone.View.extend({
                template: wp.template('builder_lite_lightbox_confirm'),
                className: 'themify_builder_lite_lightbox_content',
                initialize: function (options) {
                    this.options = options || {};
                },
                render: function () {
                    this.$el.html(this.template({message: this.options.message, buttons: this.options.buttons}));
                },
                events: {
                    'click button': 'buttonClick'
                },
                buttonClick: function (event) {
                    event.preventDefault();
                    var type = $(event.currentTarget).data('type');
                    this.trigger('litelightbox:confirm', type);
                }
            }),
            promptView: Backbone.View.extend({
                template: wp.template('builder_lite_lightbox_prompt'),
                className: 'themify_builder_lite_lightbox_content',
                initialize: function (options) {
                    this.options = options || {};
                },
                render: function () {
                    this.$el.html(this.template(this.options));
                },
                events: {
                    'click button': 'buttonClick',
                    'keypress .themify_builder_litelightbox_prompt_input': 'keyPress'
                },
                buttonClick: function (event) {
                    event.preventDefault();
                    var type = $(event.currentTarget).data('type'),
                            value = this.$el.find('.themify_builder_litelightbox_prompt_input').val();
                    this.trigger('litelightbox:prompt', type, value);
                },
                keyPress: function (event) {
                    if (event.which === 13) { // on enter
                        var value = $(event.currentTarget).val();
                        this.trigger('litelightbox:prompt', 'ok', value);
                    }
                }
            }),
            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) {
                    this.templates[selector] = document.getElementById(selector).innerHTML;
                }
                return this.templates[selector];
            }
        }

    };

}(jQuery, window, document));
