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

	'use strict';

	/* decode HTML entities */
	var decodeEntities = function( string ) {
		var textarea = document.createElement( 'textarea' );
		textarea.innerHTML = string;
		return textarea.innerText;
	}

	$(function() {

		// Themify Directory
		var $body = $('body'),
                    $themify = $('#themify'),
                    $panel = $('#setting>.subtabnav'),
                    inputAuto = $( '#themify_404_page_autocomplete' ),
                    $panelTop;

		/*******************************************************************************/
		/* Tab Events */

		//
		// Get Subtab height based on Navigation height
		//
		$themify.find('.maintab').not('[aria-expanded="false"]').each(function(){
			$(this).find('.subtab').css('minHeight', $(this).find('.subtabnav').outerHeight());
		});

		if( inputAuto.length>0) {
			var cache = {},
				inputWrapper = inputAuto.closest( '.themify_404_autocomplete_wrap' );

			inputAuto.autocomplete( {
				minLength: 2,
				autoFocus: true,
				classes: {
					"ui-autocomplete": "highlight"
				},
				source: function( request, response ) {
					var term = request.term;

					inputWrapper.addClass( 'themify_autocomplete_run' );

					if ( term in cache ) {
						response( cache[ term ] );
						inputWrapper.removeClass( 'themify_autocomplete_run' );
						return;
					}

					$.ajax( {
						url: ajaxurl,
						dataType: "json",
						type:'POST',
						data: {'term': term, 'action': 'themify_get_404_pages'},
						success: function( data ) {
							for ( const i in data ) {
								data[ i ]['label'] = decodeEntities( data[ i ]['label'] );
							}
							cache[ term ] = data;
							response( data.length ? data : [themify_js_vars.page_not_found] );
							inputWrapper.removeClass( 'themify_autocomplete_run' );
						}
					});
				},
				select: function( event, ui ) {
					event.preventDefault();
					if( ui.item.value === themify_js_vars.page_not_found ) return;
					inputAuto.val( ui.item.label ).next( 'input[type="hidden"]' ).val( ui.item.value );
				},
				change: function( event, ui ) {
					if( ! ui.item && ! event.target.value ) {
						inputAuto.next( 'input[type="hidden"]' ).val( '' );
					}
				}
			} ).focus( function () {
				$(this).autocomplete( 'search' );
			} );
		}
		if ($panel.length > 0) {
			$panelTop =  $panel.offset().top - 32;
		}

		var expandableOptionsInit = false;
		//
		// Create Tabs
		// Update address URL when Themify sub tab is clicked
		var updateTabURL = function( e, ui ) {

			$('.search-setting-holder .clear-search').trigger( 'click' );
			var el = e.type === 'tabscreate' ? window.location : ui.newTab.find('a')[0];
			if ( 'replaceState' in history ) {
				history.replaceState( null, null, el.hash || null );
			}
			if (e.type === 'tabscreate' && !expandableOptionsInit) {
				expandableOptionsInit = true;
				var subtabs = $('#themify div#setting div.subtab');
				subtabs.each(function() {
					var $this = $(this),
					fieldset = $this.find('fieldset');
					if (fieldset.length > 2) {
						fieldset.children('.themify_panel_fieldset_wrap').hide();
					} else {
						fieldset.find('legend').addClass('themify_panel_fieldset_nocollapse');
					}
				});
				subtabs.find('legend:not(.themify_panel_fieldset_nocollapse)').on('click', function() {
					var $this = $(this),
						$icon = $this.children('i');
					if ($icon.hasClass('tf_plus_icon')) {
						$this.siblings().slideDown( "fast", function() {
							if(this.getElementsByClassName('CodeMirror').length<1){
								const editors = this.getElementsByClassName('tf_code_editor');
								for(let i=editors.length-1;i>-1;--i){
									themify_code_editor(editors[i]);
								}
							}
							$icon.removeClass('tf_plus_icon').addClass('ti-minus');
						});
					} else {
						$this.siblings().slideUp( "fast", function() {
							$icon.removeClass('ti-minus').addClass('tf_plus_icon');
						});
					}
				});

			}
		};

		$('.maintab, #content').tabs({
			fx: { opacity: 'toggle', duration: 200 },
			cache: true,
			select: function() {
				$(this).css({
					'height': $(this).height(),
					'overflow': 'hidden'
				});
			},
			show: function() {
				$(this).css({
					'height': 'auto',
					'overflow': 'visible'
				});
				if ($panel.length > 0) {
					$panelTop =  $panel.offset().top - 32;
				}
			},
			beforeActivate: updateTabURL,
			create: updateTabURL
		});

		/* fix deep linking to sub tabs in theme settings page */
		let link = window.location.hash && document.querySelector( 'a[href="' + window.location.hash + '"]' );
		if ( link && link.closest( '.subtabnav' ) ) {
			let maintab_id = link.closest( '.maintab' ).getAttribute( 'id' );
                        if(maintab_id){
                            maintab_id=document.getElementById( 'maintabnav' ).querySelector( 'a[href="#' + maintab_id + '"]' );
                            if(maintab_id){
                                maintab_id.click();
                            }
                        }
		}

		// fixed themify panel while scrolling
		if ($panel.length > 0) {
			$(window).on('scroll',function() {
				if ($(this).scrollTop() > $panelTop) {
					if (!$panel.hasClass('themify_settings_fixed')){
						$panel.addClass('themify_settings_fixed');
					}
				} else {
					$panel.removeClass('themify_settings_fixed');
				}
			});
		}

		/*******************************************************************************/
		/* Global Events  */

		/**
		 *Search in settings
		 *
		 */
		var mark = function() {

			var keyword = $("#search-setting").val();

			if ( keyword.length <= 0 ){

				clearButtonStatus();
				$(".subtab",'#setting').unmark({
					"done": function () {
						$('.searching').removeClass('searching');
						$('.contain-result').removeClass('contain-result');
						$('#setting').removeClass('not-found');
					}
				});
				return;

			}else if ( keyword.length ){

				if (!$('.search-setting-holder .clear-search').hasClass('show')){
					//show clear button
					clearButtonStatus();
				}
			}
			$(".subtab",'#setting').unmark({
				done: function() {
					$('.searching').removeClass('searching');
					$('.contain-result').removeClass('contain-result');
					$('#setting').removeClass('not-found');

					$("*:not(:input):contains('"+ keyword + "')","#setting .subtab").mark(keyword,{
						diacritics: true,
						separateWordSearch: true,
						"exclude": [
							"option",
							".tm-option-title-fw"
						],
						"filter": function(textNode, foundTerm, totalCounter, counter){

							if ( textNode.nodeName === "#text" ){
								if ( $(textNode).parent().parent().css('display') === 'none' ){
									return false
								}
							} else {
								if ( $(textNode).parent().css('display') === 'none' ){
									return false
								}
							}
							return true; // must return either true or false
						},
						"each": function(element) {

							$(element).closest('fieldset').addClass('contain-result');
							$(element).closest('.subtab').addClass('contain-result');
						},
						"done": function () {
							$('#setting').addClass('searching');
						},
						"noMatch" : function () {
							$('#setting').addClass('not-found');
						}
					});
				}
			});
		};

		$("#search-setting").on("input", mark);

		$('.search-setting-holder .clear-search').on('click',function () {
			var $input = $(this).prev();
			$input.val('');
			mark();
		});

		/**
		 *  Based on input value it shows or hide
		 *  clear button
		 */
		function clearButtonStatus() {

			var button = $('.search-setting-holder .clear-search');
			if( button.prev().val().length <= 0 ){
				button.removeClass('show')
			}else{
				button.addClass('show')
			}
		}


		//
		// Validation of Numbers
		//
		$('.valid_num').on('keyup input paste',function(){
			if(!is_numeric($(this).val())){
				$(this).val($(this).val().substring(0,($(this).val().length-1)));
			}
		});

		function themify_save_settings() {
			themify_show_alert();
			var data = $themify.serialize();
			$.post(
				ajaxurl,
				{
					'action': 'themify_save',
					'data': data,
					'nonce' : themify_js_vars.nonce
				},
				function() {
					themify_hide_alert();
					$( 'body' ).triggerHandler( 'themify_save' );
				}
			);
		}

		/**
		 * Save user settings
		 * Uses nonces for security
		 */
		$('.save-button').on('click',function(e){
			themify_save_settings();
			return false;
		});

		/**
		 * Save user settings when pressing Shift+Enter
		 */
		if($themify.length > 0){
			$(document).on('keydown', function(event){
				if (83 == event.which && (true == event.ctrlKey || true == event.metaKey)) {
					event.preventDefault();
					themify_save_settings();
				}
			});
		}
		/**
		 * Reset user settings
		 */
		$( '#reset-setting' ).on( 'click', function( e ) {
			e.preventDefault();

			var actionType = $( this ).prop( 'id' ) !== 'reset-setting' ? 'styling' : 'settings';

			if( confirm( themify_lang[ 'confirm_reset_' + actionType ] ) ) {
				themify_show_alert();

				$.post( ajaxurl,{
					action: 'themify_reset_' + actionType,
					data  : $themify.serialize(),
					nonce : themify_js_vars.nonce
				}, function() {
						themify_hide_alert();
						window.location.reload( true );
					}
				);
			}
		});

		/* TF Message, displayed above theme settings */
		( function() {
			let el = document.getElementById( 'tf_message' ),
				message = localStorage.getItem( 'tf_message' ),
				dismiss = localStorage.getItem( 'tf_message_dismiss' ),
				show = function() {
					el.className = 'show';
					el.innerHTML = message + ' ';

					let dis = document.createElement( 'a' );
					dis.href = '#';
					dis.textContent = el.dataset.dismiss;
					dis.addEventListener( 'click', function( e ) {
						e.preventDefault();
						el.style.display = 'none';
						localStorage.setItem( 'tf_message_dismiss', 1 );
					} );
					el.appendChild( dis );
				};
			if ( el && ! dismiss ) {
				if ( message === null ) {
					$.ajax( {
						url : 'https://themify.me/public-api/update-message/index.txt',
						success : function( response ) {
							message = response;
							localStorage.setItem( 'tf_message', message );
							if ( message.trim() !== '' ) {
								show();
							}
						}
					} );
				} else if ( message !== '' ) {
					show();
				}
			}
		} )();

		$('.themify_changelogs').on('click', function(e){
			e.preventDefault();
			var $self = $(this),
				url = $self.data('changelog');
			$('.show-login, .show-error').hide();
			$('.overlay, .prompt-box').fadeIn(300);
			$( '.prompt-box iframe' ).remove();
			$('.tb_alert').addClass('busy').fadeIn(300);
			var $iframe = $('<iframe src="'+url+'" />');
			$iframe.on('load', function(){
				$('.tb_alert').removeClass('busy').fadeOut(300);
			}).prependTo( '.prompt-box' );
			$('.prompt-box').addClass('show-changelog');

		});
		$( '.overlay' ).on( 'click', function() {
			$( this ).add( '.prompt-box' ).fadeOut();
		} );

		//
		// Feature Box Image / Posts Display
		//
		$(".feature-box-display").on('click',function(){
			if($(this).val() === "images"){
				$(this).parent().parent().find(".feature_box_posts").fadeOut(200, function(){
					$(this).parent().parent().find(".feature_box_images").fadeIn(200);
				});
			} else {
				$(this).parent().parent().find(".feature_box_images").fadeOut(200, function(){
					$(this).parent().parent().find(".feature_box_posts").fadeIn(200);
				});
			}
		});
		//
		// Generic show/hide block for radio buttons
		// Requires the value="x" and a data-hide="y" where y is the suffix of the block to hide
		//
		$(".block-toggle").on('click',function(){
			var $self = $(this),
				val = $self.val(),
				hide = $self.data('hide');
			$self.parent().parent().find('.feature_box_' + hide).fadeOut(200, function(){
				$self.parent().parent().find('.feature_box_' + val).fadeIn(200);
			});
		});
		//
		// Feature Box Enabled Display
		//
		$(".feature_box_enabled_check").on('change',function(){
			if('on' === $(this).val()){
				$(this).closest('fieldset').find(".feature_box_enabled_display").fadeIn(200);
			} else {
				$(this).closest('fieldset').find(".feature_box_enabled_display").fadeOut(200);
			}
		});

		/**
		 * Display box if checkbox is checked
		 * Markup required
		 * 	<div class="row">
		 * 		<input type="checkbox" class="box_enabled_check" />
		 * 		<*tag* class="box_enabled_display">
		 * 			<select>
		 */
		var $boxEnabledCheck = $('.box_enabled_check');
		$boxEnabledCheck.on( 'click', function(){
			if($(this).is(":checked")){
				$(this).parent().find(".box_enabled_display").fadeIn(200);
			} else {
				$(this).parent().find(".box_enabled_display").fadeOut(200);
			}
		});
		if($boxEnabledCheck.is(":checked")){
			$boxEnabledCheck.parent().find(".box_enabled_display").show();
		}

		/**
		 * Display matched boxes if checkbox is checked
		 * Markup required
		 * <input type="checkbox" class="box_enabled_check" />
		 * <span class="box_enabled_display">
		 */
		var $disableImgPhp = $('.disable_img_php');
		$disableImgPhp.on( 'click', function(){
			if($disableImgPhp.is(":checked")){
				$( '.show_if_disabled_img_php' ).fadeIn(200);
				$( '.show_if_enabled_img_php' ).fadeOut(200);
			} else {
				$( '.show_if_disabled_img_php' ).fadeOut(200);
				$( '.show_if_enabled_img_php' ).fadeIn(200);
			}
		});
		if($disableImgPhp.is(":checked")){
			$(".show_if_disabled_img_php").show();
		} else {
			if($disableImgPhp.not(":checked")){
				$(".show_if_enabled_img_php").show();
			}
		}

		$('.gallery_lightbox_type').on( 'change', function(){
			var lightboxIndex = $('.gallery_lightbox_type').prop('selectedIndex');
			if(lightboxIndex != 1){
				$( '.show_if_photoswipe_enabled' ).fadeOut(200);
			} else {
				$( '.show_if_photoswipe_enabled' ).fadeIn(200);
			}
		}).trigger( 'change' );

		/*******************************************************************************/
		/* Skin CSS Load */

		//
		// Skins Load
		//
		$("#skins .skin-preview").on( 'click', function(e){
			if( ! $( e.target ).parent().hasClass( 'view-demo' ) ) {
				e.preventDefault();
			}
			$("#skins .skin-preview").removeClass( 'selected' );
			$(this).addClass('selected');
			$( "input[name='skin']" ).val( $(this).attr( 'data-skin' ) );
		});

		/*******************************************************************************/
		/*	Is Numeric Function */

		function is_numeric(string){
			var ValidChars = " 0123456789.+-",
                            IsNumber = true,
                            Char;
			for (var i = 0; i < string.length && IsNumber === true; i++){
				Char = string.charAt(i);
				if(ValidChars.indexOf(Char) === -1){
					IsNumber = false;
				}
			}
			return IsNumber;
		}

		/**
		 * Group drop down containing Featured Image sizes with the Featured Image field
		 * .featimgdropdown
		 */
		var $featImgControl = $('.featimgcontrol');
		if( $featImgControl.length > 0 && $('.featimgdropdown').length > 0 ) {
			$featImgControl.each( function() {
				$(this).append($(this).next('.featimgdropdown'));
			});
		}

		/**
		 * Social Links Panel
		 */
		var $socialType = $('#social-link-type' ),
			$socialLinksWrapper = $('#social-links-wrapper'),
			$socialLinkIDs = $('#setting-link_field_ids'),
			$socialLinkHash = $('#setting-link_field_hash');

		/**
		 * Link type selector
		 */
		if($('input[value="font-icon"]', $socialType).prop('checked')) {
			$('.image-icon', $socialLinksWrapper).fadeOut();
			$('.font-icon', $socialLinksWrapper).fadeIn();
		} else {
			$('.font-icon', $socialLinksWrapper).fadeOut();
			$('.image-icon', $socialLinksWrapper).fadeIn();
		}
		$('input', $socialType).on('click', function(){
			var $self = $(this);
			if($self.prop('checked')) {
				$('.' + $self.data('hide'), $socialLinksWrapper).fadeOut();
				$('.' + $self.val(), $socialLinksWrapper).fadeIn();
			}
		});

		/**
		 * Links settings page
		 */
		// Set up drag & drop
		$socialLinksWrapper.length && $socialLinksWrapper.sortable({
			placeholder: 'social-link-placeholder',
			handle: '.social-drag',
			update: function() {
				var field_ids = {};
				$('.social-link-item').each(function(){
					field_ids[$(this).attr('id')] = $(this).attr('id');
				});
				$socialLinkIDs.val(JSON.stringify(field_ids));
			}
		})

		// Remove Link
		.on('click', '.remove-item', function(event) {
			event.preventDefault();
			var field_ids = JSON.parse($socialLinkIDs.val()),
				removeId = $(this).data('removelink');

			$('#' + removeId).remove();
			delete field_ids[removeId];
			$socialLinkIDs.val(JSON.stringify(field_ids))
		});

		// Add Link
		$('.add-social-link a').on('click',function(e) {
			var field_ids = JSON.parse($socialLinkIDs.val()),
				hash = parseInt($socialLinkHash.val()),
				type = 'image-icon';
			e.preventDefault();
			if($('input[value=font-icon]', $socialType).prop('checked')) {
				type = 'font-icon';
			}
			$.post(
				ajaxurl,
				{
					'action': 'themify_add_link_field',
					'nonce' : themify_js_vars.nonce,
					'fid'   : hash,
					'type'  : type
				},
				function(data){
					// Insert new link block
					let $container = $('#social-links-wrapper'),
						$data = $( data );
					$container.append( $data );

					var $plupload = $('#themify-link-' + $socialLinkHash.val() + ' .plupload-upload-uic');

					// Add new key/element to JSON object
					field_ids['themify-link-' + $socialLinkHash.val()] = 'themify-link-' + $socialLinkHash.val();
					$socialLinkIDs.val(JSON.stringify(field_ids));

					if ( $plupload.length > 0 ) {
						// Initialize plupload in this new field
						themify_create_pluploader($plupload);
					}

					window.Themify_Metabox.color_picker( $data );

					// Increase hash number
					$socialLinkHash.val(hash + 1);
				}
			);

		});

		// Validate slug input
		$('.slug-rewrite').each(function(){
			$(this).on('keypress', function (event) {
				var regex = new RegExp("^[a-z0-9_\-]+$"),
					key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
				if (!regex.test(key)) {
					event.preventDefault();
					return false;
				}
			});
		});
		var Themify_Visibility = {
			target: '',

			getDocHeight: function() {
				var D = document;
				return Math.max(
					Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
					Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
					Math.max(D.body.clientHeight, D.documentElement.clientHeight)
				);
			},

			showLightbox: function(id) {
				var top = $(document).scrollTop() + 80,
					$lightbox = $(".themify-admin-lightbox-" + id);

				if (! $lightbox.length) {
					$('.themify-admin-lightbox:first').clone().removeClass('themify-admin-lightbox-1').addClass('themify-admin-lightbox-' + id).data('item', id).insertAfter('.themify-admin-lightbox:last');
					if ($('.themify-admin-lightbox').length > 1) {
						$('.lightbox_container', '.themify-admin-lightbox-' + id).html('');
					}
					$lightbox = $(".themify-admin-lightbox-" + id);
					$lightbox.removeClass('is-loaded');
				}

				$('#themify_lightbox_overlay').show();
				if (! $lightbox.hasClass('is-loaded')) {
				$.ajax({
					'type' : 'POST',
					url: ajaxurl,
					data: {
						action: 'themify_get_visibility_options',
						selected: Themify_Visibility.target.val(),
						nonce: themify_js_vars.nonce
					},
					success: function(data){
						$( '.lightbox_container', $lightbox ).append(data);
						$lightbox
						.show()
						.css('top', Themify_Visibility.getDocHeight())
						.animate({
							'top': top
						}, 800 );
						$('#visibility-tabs', $lightbox).tabs();
						$('#visibility-tabs .themify-visibility-inner-tabs', $lightbox).tabs();
							$('.themify-visibility-toggle').html($('.themify-visibility-toggle').data('text'));
					}
				});
				} else {
					$lightbox
						.show()
						.css('top', Themify_Visibility.getDocHeight())
						.animate({
							'top': top
						}, 800);
					$('.themify-visibility-toggle').html($('.themify-visibility-toggle').data('text'));
				}
			},
			closeLightbox: function( id, callback ){
				$('.themify-admin-lightbox-' + id).animate({
					'top': Themify_Visibility.getDocHeight()
				}, 800, function() {
					$('#themify_lightbox_overlay').hide();
					$('.themify-admin-lightbox-' + id).hide();
					if( typeof(callback) === 'function' ) {
						callback();
					}
				}).addClass('is-loaded');
			},
			clearOptions: function(){
				$('#themify_lightbox_visibility').find('.lightbox_container').empty();
			}
		};


		$body.on('click', '.themify-visibility-toggle', function(){
			var $this = $(this),
                            toggle_text = $this.html();
			$this.html('<span class="tb_slider_loader_wrapper"><span class="tb_slider_loader"></span></span>' + toggle_text);
			Themify_Visibility.target = $(this).next();
			Themify_Visibility.showLightbox($(this).data('item'));
			return false;
		}).on('click', '.themify_lightbox_visibility .close_lightbox, #themify_lightbox_overlay', function(){
			Themify_Visibility.closeLightbox($(this).parents('.themify_lightbox_visibility').data('item'));
			return false;
		});

		// Generate inner page for tab
		function getPaginationPages(e) {
			e.preventDefault();
			var $this = $(this),
				$originalInput = $('#themify-original-conditions');
			if ($this.data('active')) {
				return;
			}
			var type = $this.data('type'),
                            tab = $this.parents('#visibility-tabs').find('.themify-visibility-type-options[data-type=' + type + ']'),
                            id = $this.parents('.themify_lightbox_visibility').data('item'),
                            selected = $('#setting-hooks-' + id + '-visibility').val();
			$.ajax({
				url: ajaxurl,
				type: 'post',
				data: {
					action: 'themify_create_inner_page',
					type: type,
					selected: selected,
					nonce: themify_js_vars.nonce,
					original_values: $originalInput.val(),
				},
                beforeSend: function() {
					tab.html('<div class="tb_slider_loader"></div>');
				},
				success: function(data){
					data = JSON.parse(data);
					tab.html(data.html);
					$this.data('active', 'on');
					$originalInput.val(data.original_values);
				}
		});
		}

		// Generate pagination for tab
		function showPaginationPage(e) {
			e.preventDefault();
			var $this = $(this),
                            tab = $this.parents('.themify-visibility-options'),
                            items_inner = $this.parents('.themify-visibility-items-inner'),
                            pagination = $('.themify-visibility-pagination', items_inner),
                            current_page = parseFloat($('.themify-visibility-pagination .current', items_inner).text()),
                            go_to_page = 1;
			if ($this.hasClass('next')) {
				go_to_page = current_page + 1;
			} else if ($this.hasClass('prev')) {
				go_to_page = current_page - 1;
			} else if($this.hasClass('page-numbers')) {
				go_to_page = parseFloat($this.text());
			}
			var inner_item = $('.themify-visibility-items-inner', tab);

			$.ajax({
				url: ajaxurl,
				type: 'post',
				data: {
					action: 'themify_create_page_pagination',
					current_page: go_to_page,
					num_of_pages: items_inner.data('pages'),
					nonce: themify_js_vars.nonce
				},
                beforeSend: function() {
					$('.tb_slider_loader', tab).remove();
					pagination.hide();
					inner_item.append('<div class="tb_slider_loader"></div>');
				},
				success: function(data){
					$('.tb_slider_loader', tab).remove();
					$('.themify-visibility-items-page', items_inner).addClass('is-hidden');
					$('.themify-visibility-items-page-' + go_to_page, items_inner).removeClass('is-hidden');
					pagination.html(data).show();
				}
			});

		}

		$body.on('click', '.themify-visibility-pagination a.page-numbers', showPaginationPage)
                    .on('click', '#visibility-tabs .themify-visibility-tab', getPaginationPages)

                .on('click', '.visibility-save', function(){
		    var $lightbox = $(this).parents('.themify_lightbox_visibility'),
				id = $lightbox.data('item'),
				data = $('form', $lightbox).serialize(),
				originalValues = $('#themify-original-conditions',$lightbox).val();
					// Merge with original value (because maybe some checked items dose not load yet)
					originalValues = '' === originalValues ? [] : originalValues.split('&');
					var selectedData = '' === data ? [] : data.split('&');
					data = originalValues.concat(selectedData).concat();
					for(var i=0; i<data.length; ++i) {
						for(var j=i+1; j<data.length; ++j) {
							if(data[i] === data[j])
								data.splice(j--, 1);
						}
					}
					data = data.join('&');
			$('.setting-hooks-' + id + '-visibility').val(data);
			Themify_Visibility.target.val( data );
			Themify_Visibility.closeLightbox($(this).parents('.themify_lightbox_visibility').data('item'));
			return false;
		}).on('click', '.themify_lightbox_visibility .uncheck-all', function(){
			$(this).before('<span class="tb_slider_loader_wrapper"><span class="tb_slider_loader"></span></span>');
			const $this = $(this),
                            $lightbox = $this.parents('.themify_lightbox_visibility'),
                            id = $lightbox.data('item');
			$('#setting-hooks-' + id + '-visibility').val('');
			$('#themify-original-conditions',$lightbox).val('');
			$('input:checkbox', $lightbox).removeAttr( 'checked' );
                        $this.parent().find('.tb_slider_loader_wrapper').remove();
			return false;
		});

		$('#setting-hooks').on('click', '.remove-item', function(e){
                        e.preventDefault();
			const field_ids = JSON.parse( $('#themify-hooks-field-ids').val() ),
                            $item = $(this).closest('.social-link-item').fadeOut('fast', function(){
				const removeId = $item.attr('data-id');
				for( let key in field_ids ) {
					if ( field_ids.hasOwnProperty(key) && field_ids[key] == removeId  ) {
                                                field_ids.splice(key, 1);

					}
				}
				$('#themify-hooks-field-ids').val( JSON.stringify( field_ids ) );
				$('.themify-admin-lightbox-' + removeId).removeClass('is-loaded').find('.lightbox_container').html('');
			});
		}).
                on('click', '.themify-add-hook a', function(e){
                        e.preventDefault();
			$(this).before('<span class="tb_slider_loader_wrapper"><span class="tb_slider_loader"></span></span>');
			let field_ids = JSON.parse( $('#themify-hooks-field-ids').val() ),
				new_field_id = 1;
			if( field_ids.length > 0 ) {
				new_field_id = Math.max.apply(null, field_ids) + 1;
			} else {
				field_ids = [];
			}
			$.ajax({
				url: ajaxurl,
				type: 'post',
				data: {
					action: 'themify_hooks_add_item',
					field_id : new_field_id,
					nonce: themify_js_vars.nonce
				},
				success: function(data){
					const hook_list = $('#hook-content-list');
					field_ids.push( new_field_id );
					$('#themify-hooks-field-ids').val( JSON.stringify( field_ids ) );
					$('#setting-hooks .tb_slider_loader_wrapper').remove();
					hook_list.append(data);
					$('textarea[name=setting-hooks-' + new_field_id + '-code]', hook_list).html('');
					$('select[name=setting-hooks-' + new_field_id + '-location] optgroup:first-child option[value=themify_body_start]', hook_list).attr('selected', true);
					if (hook_list.find('li').length > 1) {
					$('.themify-admin-lightbox:first').clone().removeClass('themify-admin-lightbox-1').addClass('themify-admin-lightbox-' + new_field_id).data('item', new_field_id).insertAfter('.themify-admin-lightbox:last');
					}
						$('.lightbox_container', '.themify-admin-lightbox-' + new_field_id).html('');
					$('#setting-hooks-' + new_field_id + '-visibility', hook_list).val('');
					$('.themify-admin-lightbox:last').removeClass('is-loaded');
				}
			});
		});

		// Set up drag & drop
		const $hookContentList = $('#hook-content-list');
		$hookContentList.length && $hookContentList.sortable({
			placeholder: 'social-link-placeholder',
			handle: '.social-drag',
			update: function() {
				var field_ids = [];
				$hookContentList.find('li').each(function(){
					field_ids.push( parseInt( $(this).attr('data-id') ) );
				});
				$('#themify-hooks-field-ids').val( JSON.stringify( field_ids ) );
			}
		});
		$( 'body' ).on( 'click', '.see-hook-locations', function( e ) {
			e.preventDefault();
			window.tf_hook_target = this.closest( 'li' ).querySelector( 'select' ); /* used by hook-locations-urlfix.js */
			$.magnificPopup.open({
				items : [ this ],
				type: 'iframe',
				iframe: {
					markup: '<div class="mfp-iframe-scaler" style="max-width: 100% !important; height: 100%;">'+
					'<div role="button" class="tf_close mfp-close"></div>'+
					'<iframe id="tf_hook_location_iframe" class="mfp-iframe" frameborder="0" allowfullscreen></iframe>'+
					'</div>'
				}
			});
		} );

		$('#setting-editor-gfonts-list').on('change',function(){
			$(this).next().val( JSON.stringify( $(this).val() ) );
		}).trigger( 'change' );
		
		// Skin selection in the Demo Import notice box
		$body.on( 'click', '#demo-import-notice .skin-preview', function(e){
			if( ! $( e.target ).parent().hasClass( 'view-demo' ) ) {
				e.preventDefault();
			}
			$("#demo-import-notice .skin-preview").removeClass( 'selected' );
			$(this).addClass('selected');
			$( '#skins .skin-preview[data-skin="' + $(this).data( 'skin' ) + '"]' ).trigger( 'click' );
		} );

		$( '#demo-import-notice .skin-demo-import' ).on( 'click', function(){
			$( '#skins .skin-preview.selected .skin-demo-import' ).trigger( 'click' );
		} );

		

		$body.on( 'click', '#skins .skin-demo-import', themify_import_modal).on( 'click', '#skins .skin-erase-demo', function(e){
			e.preventDefault();
			var $this = $( this ),
				$preview = $this.closest( '.skin-demo-content' );
			$.ajax({
				url: ajaxurl,
				data: {
					action: 'themify_erase_sample_content',
					skin : $preview.data( 'skin' ),
					nonce: themify_js_vars.nonce
				},
				type: 'POST',
				success: function( response ){
					if ( ! response.success ) {
						alert( response.data.error );
					}
				},
				beforeSend: function(){
					themify_show_alert();
				},
				complete: function(){
					themify_hide_alert();
				}
			} );
		});

		// Map controls in Import Demo notice box to the options under main tab
		$( '#demo-import-notice .import-sample-content' ).on('click', function(){
			$( '#demo-import .import-sample-content' ).trigger( 'click' );
		} );


		// Import Demo button in main tab
		$( '#demo-import .import-sample-content' ).on('click',themify_import_modal);

		// Erase Demo button
		$('.erase-sample-content').on('click',function(){
			const $button = $(this);
			if( $button.hasClass( 'disabled' ) ) {
				return false;
			}
			$button.addClass( 'disabled' );
			$.ajax({
				url: ajaxurl,
				data: {
					action: 'themify_erase_sample_content',
					nonce: themify_js_vars.nonce
				},
				type: 'POST',
				success: function( response ){
					if ( ! response.success ) {
						alert( response.data.error );
					}
				},
				beforeSend: function(){
					$button
						.find('span').text( $button.attr('data-erasing') );
					themify_show_alert();
				},
				complete: function(){
					$button
						.find('span').text( $button.attr('data-success') );
					themify_hide_alert();
				}
			});
			return false;
		});
		$( '.themify-modal .dismiss-import-notice' ).on('click',function(){
			$( this ).closest( '.themify-modal' ).fadeOut();
			themify_modal_action('close');
			return false;
		});

		// <select> Wrapper
		themify_select_wrapper($themify);

		// New general show/hide elements toggle.
		themify_init_show_if( $('#themify, .toplevel_page_themify-builder #wpbody-content') );

		// Clear cache builder
		$('.js-clear-cache').on('click', function( e ){
			e.preventDefault();
			const $this = $(this);
			if ( $this.hasClass('disabled') ) return;
			$this.addClass('disabled');
			$.ajax({
				url: ajaxurl,
				data: {
					action:$this.data('action'),
                                        data:$this.data('send')==='all'?$themify.serialize():'',
					nonce: themify_js_vars.nonce
				},
				type: 'POST',
				dataType:'json',
				beforeSend: function(){
					$this.find('span').text( $this.data('clearing-text') ).end()
					.find('i').removeClass().addClass('tf_loader');
				},
                                error:function(){
                                    $this.removeClass('disabled');
                                },
				success: function(resp){
					if(resp && resp['error']){
						alert(resp['error']);
					}
					$this.find('span').text( $this.data('done-text') ).end()
						.find('i').removeClass();

                                        if(resp && resp['remove_after']){
                                            setTimeout(function(){$this.closest('.pushlabel').remove();}, 3000);
                                            return;
                                        }
					setTimeout(function(){

                                            $this.find('span').text( $this.data('default-text') ).end()
                                            .find('i').removeClass().addClass( $this.data('default-icon')).end()
                                            .removeClass('disabled');
					}, 5000);
				}
			});
		});

		$('.input-range .range-slider').each(function(){
		  let $this = $(this),
			$input = $this.next(),
			isRange = $input.data('range') ? true: false;
		  $this.slider({
			range: isRange,
			min: $input.data('min'),
			max: $input.data('max'),
			values: $input.val().split('-'),
			slide: function( event, ui ) {
			  if ( ui.values[0] == ui.values[ 1 ] || ! isRange ) {
				$input.val( ui.values[ 0 ] );
			  } else {
				$input.val( ui.values[ 0 ] + '-' + ui.values[ 1 ] );
			  }
			}
		  });
		  $input.on('keyup',function(){
			  const $el = $(this),
				  val = parseInt($el.val());
			  // Update min
			  if(val < parseInt($el.data('default-min'))){
				  $this.slider( "option", "min", val );
			  }
			  // Update max
			  if(val > parseInt($el.data('default-max'))){
				  $this.slider( "option", "max", val );
			  }
			  $this.slider( "values", [val] );
		  });
		});


		if( window['wp'] !== undefined  && window['wp']['media'] !== undefined && typeof wp.media.featuredImage !== 'undefined' ) {
			// Featured Image option sync with WP Panel
			$( 'body' ).on( 'themify_metabox_lib_selected', function( e, $el, attachment, file_frame ){
				var data = $el.data( 'submit' );
				if( data.featured ) {
					wp.media.featuredImage.set( attachment.id );
				}
			} ).on( 'themify_plupload_selected', function( e, $el, json ){
				if( $el.data( 'featured' ) ) {
					wp.media.featuredImage.set( json.id );
				}
			} ).on( 'themify_wp_media_featured_image_set', function( e, id, html ){
				const row = $( '#post_image' ).closest( '.themify_field_row' );
				if( id == -1 ) {
					row.find( '.themify_featimg_remove a' ).trigger( 'click' );
				} else {
					themifyMediaLib.setPreviewIcon( row, $( html ).find( '#set-post-thumbnail img' ).attr( 'src' ) );
				}
			} );
			$( '#post_image' ).closest( '.themify_field_row' ).find( '.themify_featimg_remove a' ).on( 'click', function(){
				$( '#remove-post-thumbnail' ).trigger( 'click' );
			});

			/**
			 * Originally located in wp-includes/js/media-editor.js
			 */
			wp.media.featuredImage.set = function(id){
				var settings = wp.media.view.settings;

				settings.post.featuredImageId = id;

				wp.media.post( 'get-post-thumbnail-html', {
					post_id:      settings.post.id,
					thumbnail_id: settings.post.featuredImageId,
					_wpnonce:     settings.post.nonce
				}).done( function( html ) {
					if ( html == '0' ) {
						window.alert( window.setPostThumbnailL10n.error );
						return;
					}
					$( '.inside', '#postimagediv' ).html( html );

					// custom event trigger
					$( 'body' ).triggerHandler( 'themify_wp_media_featured_image_set', [ id, html ] );
				});
			};
		}

		themify_regenerate_css_files();
		tb_find_and_replace();
		tb_maintenance_mode();
		// license Modal Event
		themify_license_modal(document.getElementsByClassName('license-link'));
		const tw=document.getElementById( 'tb_option_flush_twitter' );
		if(tw){
			tw.addEventListener( 'click', function( e ) {
				e.preventDefault();
				themify_show_alert();
				$.ajax( {
					url : ajaxurl,
					type : 'POST',
					data : { action : 'themify_twitter_flush', nonce : themify_js_vars.nonce },
					success : function() {
						themify_hide_alert();
					}
				} );
			} );
		}
		const font_import = document.getElementById( 'tf_font_import' );
		if ( font_import ) {
			$( font_import ).insertAfter( '.wp-header-end' );
			document.getElementById( 'tf_font_import_submit' ).addEventListener( 'click', function() {
				themify_show_alert();
				jQuery.ajax( {
					type : 'POST',
					url : ajaxurl,
					data : {
						action : 'tf_import_font',
						nonce : themify_js_vars.nonce,
						font_name : font_import.querySelector( 'select' ).value
					},
					success : function( response ) {
						themify_hide_alert();
						if ( response.success ) {
							location.reload();
						} else {
							console.log( response.data );
						}
					}
				} );
			} );

			$( "#tf_font_size_slider_wrap" ).appendTo( 'th#font_preview' );
			let style = document.getElementById( 'tf_font_preview_style' ),
				size = localStorage.getItem( 'tf_font_preview_size' ) || 1,
				update_preview = function( size ) {
					style.innerText = '.font_preview span { font-size: ' + size + 'em; }';
				};
			update_preview( size );

			$( "#tf_font_size_slider" ).slider({
				value : size,
				min : 0.5,
				max : 4,
				step : .1,
				slide : function( event, ui ) {
					update_preview( ui.value );
					localStorage.setItem( 'tf_font_preview_size', ui.value );
				}
			});
		}

		let child_theme_generate_btns = document.getElementsByClassName( 'generate-child-theme' );
		for ( let i = 0; i < child_theme_generate_btns.length; i++ ) {
			child_theme_generate_btns[ i ].addEventListener( 'click', (e) => {
				e.preventDefault();
				if ( window.confirm( child_theme_generate_btns[ i ].dataset.confirm ) ) {
					themify_show_alert();
					$.ajax( {
						url : ajaxurl,
						type : 'POST',
						data : {
							action : 'themify_generate_child_theme',
							nonce : themify_js_vars.nonce,
							import_customizer : child_theme_generate_btns[ i ].closest( 'div' ).querySelector('input[type="checkbox"]').checked ? 1 : 0
						},
						success : ( response ) => {
							themify_hide_alert();
							if ( response.success ) {
								child_theme_generate_btns[ i ].classList.add( 'disabled' );
								child_theme_generate_btns[ i ].closest( '.tf_generate_child_theme' ).classList.add( 'tf_done' );
							} else {
								window.alert( response.data[0].message ); // oof
							}
						}
					} );
				}
			} );
		}

		// Ajax Install & Activate the Themify Updater
		$('.themify-ajax-installer').on('click', themify_ajax_installer);

		function themify_init_show_if( $context ){
			var selectors = $context.find('[data-show-if-element]').map(function(){
				return $(this).data('show-if-element');
			}).get().filter(function(itm, i, selectors){

				return i === selectors.indexOf( itm );
			});

			$.each(selectors, function(i, selector){
				var $source_element_selector = selector;

				themify_apply_show_if( $source_element_selector );

				$( document ).on( 'change', $source_element_selector, function(e){
					themify_apply_show_if( $source_element_selector );
				});
			});
		}

		function themify_apply_show_if( $source_element_selector_new ){

			$( '[data-show-if-element="' + $source_element_selector_new + '"]' ).each(function(){

				var $target_element = $(this),
					$target_value   = $target_element.data( 'show-if-value' ),
					$source_element = $( $target_element.data( 'show-if-element' ).toString() ),
					$source_element_value = '';

				/* Check the reason */
				if ($source_element.length <= 0)
					return;

				if ( $source_element.is(':checkbox') ) {
					$source_element_value = $source_element.is(':checked') ? 'true' : 'false' ;
				} else if( $source_element.is(':radio') ) {
					$source_element_value = $source_element.filter( ':checked' ).val();
				} else {
					$source_element_value = $source_element.val().trim();
				}

				$target_value = Array.isArray($target_value) ? $target_value : [$target_value.toString()];

				if( 'undefined' !== typeof( $source_element_value ) && $.inArray($source_element_value,$target_value)!==-1){
					// Show
					$target_element.slideDown( { duration: 550 } );
				} else {
					// Hide
					$target_element.slideUp( { duration: 550 } );
				}
			});
		}

		function themify_regenerate_css_files(){
			$('#builder-regenerate-css-files').on( 'click', function(){
				const $this = $(this).attr({'value':'Regenerating ...','disabled':'disabled'});
				$.ajax({
					url: ajaxurl,
					type: 'post',
					data: {
						action: 'themify_regenerate_css_files_ajax',
						nonce: themify_js_vars.nonce,
                                                all:$('#tmp_regenerate_all_css').is( ':checked' )?1:0
					},
					success: function(data){
						$this.removeAttr('disabled').attr('value','Regenerate CSS Files');
						if('finished' !== data){
							alert(data);
						}
					}
				});
			});
		}

		// Get builder posts and make data ready to send find and replace ajax request
		function tb_get_builder_posts(){
			$.ajax({
				url: ajaxurl,
				type: 'post',
				data: {
					action: 'themify_get_builder_posts',
					from_ajax: true,
					nonce: themify_js_vars.nonce
				},
				success: function(result){
					result = JSON.parse(result);
					if('' == result['posts']){
						alert('No builder data found!');
						$('#builder-find-and-replace-btn').removeAttr('disabled').attr('value','Replace');
						return;
					}
					var originalString = $('#original_string').val(),
						replaceString = $('#replace_string').val();
					for (var i = 1; i <= result['groups']; ++i) {
						tb_send_find_replace_ajax_request({
							'group': i,
							'total': result['groups'],
							'originalString': originalString,
							'replaceString': replaceString
						});
					}
				}
			});
		}

		// Handle find and replace string functionality tools
		function tb_find_and_replace(){
			$('#builder-find-and-replace-btn').on( 'click', function(){
				if('' === $('#original_string').val()){
					alert('Please fill original value for search!');
					return;
				}
				if (!confirm("WARNING: This will replace all data in your database. It can not be undone. Please backup your database before proceeding.")) {
					return;
				}
				$(this).attr({'value':'Replacing ...','disabled':'disabled'});
				tb_get_builder_posts();
			});
		}

		// Send find and replace ajax request
		function tb_send_find_replace_ajax_request(vars){
			$.ajax({
				url: ajaxurl,
				type: 'post',
				data: {
					action: 'themify_find_and_replace_ajax',
					group_number : vars.group,
					total_groups : vars.total,
					original_string : vars.originalString,
					replace_string : vars.replaceString,
					nonce: themify_js_vars.nonce
				},
				success: function(result){
					if( -1 !== result.indexOf('finished-')){
						$('#builder-find-and-replace-btn').removeAttr('disabled').attr('value','Replace');
						alert('Replace operation was completed successfully. ' + result.replace('finished-', '') + ' strings found and replaced.');
					}
				}
			});
		}

		// Handle maintenance functionality tool
		function tb_maintenance_mode(){
			const pagesDropdown = document.getElementById('setting-page_builder_maintenance_page');
			if( null === pagesDropdown ){
				return;
			}
			pagesDropdown.addEventListener('mousedown',function(e){
				var self = this;
				$.ajax( {
					url: ajaxurl,
					type:'POST',
					data: {
						'action': 'themify_load_maintenance_pages',
						'nonce' : themify_js_vars.nonce
					},
					success: function( data ) {
						self.innerHTML = data;
						// Fix safari bug - Safari does not update the select after HTML is changed
						if(/^((?!chrome|android).)*safari/i.test(navigator.userAgent)){
							self.blur();
							self.dispatchEvent(e);
						}
					}
				});
			},{once:true,passive:true});

		}

		function themify_code_editor(el){
			if(wp && wp.codeEditor && themify_js_vars.code_editor){
				let ed = wp.codeEditor.initialize( el,themify_js_vars.code_editor);
				ed.codemirror.on( 'change', function() {
					ed.codemirror.save();
				} );
				ed.codemirror.refresh();
			}
		}

		// Tooltip helper
		$(function() {
			const previewIcon = $( '#themify .preview-icon' );
			if( previewIcon.length ) {
				previewIcon.each( function() {
					var $item = $( this ),
						title = $item.attr( 'title' );
					$item.removeAttr( 'title' ).append( '<span class="tm-option-title-fw">' + title + '</span>' );
				} );
			}
		} );

		// Custom Posts in RSS option, this multiselect option is stored as a string
		$( '#themify_feed_settings select' ).on( 'change', function() {
			$( this ).next().val( $( this ).val().join( ',' ) );
		} );

		/**
		 * Import sample images in demo content.
		 * First import post thumbnails, then 'gallery_shortcode' field types
		 */
		function themify_import_assets( res, callback ) {
			var queue = [],
				max_query = 5, // maximum number of requests to send simultaneously
				count = 0; // keep track of how many requests are ongoing simultaneously

			if ( res.data.actions !== undefined ) {
				$.each( res.data.actions, function( action_name, actions_list ) {
					$.each( actions_list, function( i, data ) {
						queue.push( {
							action: 'themify_import_sample_actions',
							_action : action_name, // action name, used by themify_import_sample_actions()
							nonce: themify_js_vars.nonce,
							data : data
						} );
					} );
				} );
			}

			if ( queue.length === 0 ) {
				callback();
				return;
			}

			function make_request() {
				if ( queue.length === 0 )
					return;
				if ( count > max_query ) {
					return;
				}
				const data = queue.shift();
				++count;
				$.ajax( {
					url : ajaxurl,
					dataType : 'json',
					type: 'POST',
					data : data,
					complete : function( response ) {
						--count;
						make_request();
						if ( count < 1 ) {
							callback();
							return;
						}
					}
				} );
			}
			for ( let i = 0; i < max_query; ++i ) {
				make_request();
			}
		}

		/*******************************************************************************/
		/*	Display Alerts */

		function themify_show_alert(){
			$(".tb_alert").addClass("busy").fadeIn(800);
		}
		function themify_hide_alert(status){
			if(status === 'error'){
				status = 'error';
				themify_show_errors();
			} else {
				status = 'done';
			}
			$(".tb_alert").removeClass("busy").addClass(status).delay(800).fadeOut(800, function(){
				$(this).removeClass(status);
			});
		}
		function themify_show_errors(verbose){
			$(".overlay, .prompt-box").delay(900).fadeIn(500);
			$('.prompt-box .show-error').show();
			$('.prompt-box .show-error p').remove();
			$('.prompt-box .error-msg').after('<p class="prompt-error">' + verbose + '</p>');
			$('.prompt-box .show-login').hide();
		}

		function themify_import_modal(e){
			e.preventDefault();
			const target = this,
				modal = document.querySelector('.required-addons.themify-modal');
			let reload = false;
			if(modal){
				if(target.dataset.id && modal.dataset.skin!==target.dataset.id){
					modal.remove();
				}else if(modal.classList.contains('reload')){
					modal.classList.remove('reload');
					reload=modal;
				}else{
					$(modal).fadeIn();
					themify_modal_action();
					return;
				}
			}
			const data = new FormData();
			data.append('action', 'themify_required_plugins_modal');
			data.append('nonce', themify_js_vars.nonce);
			if(document.getElementById('license-modal')===null){
				data.append('license', '1');
			}
			if(target.dataset.plugins && ''!==target.dataset.plugins){
				data.append('plugins', target.dataset.plugins);
			}
			if(target.dataset.id && ''!==target.dataset.id){
				data.append('skin', target.dataset.id);
			}
			$('.tb_alert').addClass('busy').fadeIn(300);
			fetch(ajaxurl, {method: 'POST', headers: new Headers({
					'Accept': 'application/json',
					'X-Requested-With': 'XMLHttpRequest'
				}), body: data})
				.then(res=>res.text())
				.then(function (html) {
					let modal = (new DOMParser()).parseFromString(html, 'text/html').getElementsByClassName('themify-modal')[0];
					if(reload!==false){
						reload.innerHTML = modal.innerHTML;
						modal=reload;
					}else{
						document.getElementById('themify').appendChild(modal);
					}
					const $modal = $(modal);
					if(reload===false){
						$modal.fadeIn();
						themify_modal_action();
					}
					$('.tb_alert').removeClass('busy').fadeOut(300);
					// Close Modal Event
					modal.querySelector('.dismiss-import-notice').addEventListener('click',function(e){
						e.preventDefault();
						$modal.fadeOut(300);
						themify_modal_action('close');
					});
					// license Modal Event
					themify_license_modal(modal.getElementsByClassName('license-link'));
					if(target.classList.contains('import-sample-content')){
						themify_import_sample_content($modal, $(target));
					}else if(target.classList.contains('skin-demo-import')){
						themify_import_skin(target,$modal);
					}
					// Ajax Install
					$modal.find('.themify-ajax-installer').on('click', themify_ajax_installer);
				});
		}

		function themify_modal_action(act='open'){
			if('open'===act){
				document.body.classList.add('themify-modal-active');
			}else{
				document.body.classList.remove('themify-modal-active');
			}
		}

		function themify_license_modal(links){
			const len = links.length;
			if(len===0){
				return
			}
			const modal = document.getElementById('license-modal');
			if(modal === null){
				return;
			}
			for(let i = len - 1; i>-1;--i){
				links[i].addEventListener('click',function(e){
					e.preventDefault();
					modal.dataset.src=this.dataset.src;
					$(modal).fadeIn();
					themify_modal_action();
				});
			}
			if(modal.dataset.init){
				return;
			}
			modal.dataset.init=true;
			// Close Modal Event
			modal.getElementsByClassName('close')[0].addEventListener('click',function(e){
				e.preventDefault();
				$(modal).fadeOut(300);
				themify_modal_action('close');
			});
			// Update license Event
			modal.getElementsByClassName('update-license')[0].addEventListener('click',function(e){
				e.preventDefault();
				const u = modal.querySelector('[name="themify_username"]').value,
					l = modal.querySelector('[name="updater_licence"]').value,
					src = e.target.closest('.themify-modal').dataset.src;
				if(u==='' || l===''){
					alert(themify_js_vars.empty_li);
					return;
				}
				const data = new FormData();
				data.append('action', 'themify_update_license');
				data.append('nonce', themify_js_vars.nonce);
				data.append('src', src);
				data.append('themify_username', u);
				data.append('updater_licence', l);
				$('.tb_alert').addClass('busy').fadeIn(300);
				fetch(ajaxurl, {method: 'POST', headers: new Headers({
						'Accept': 'application/json',
						'X-Requested-With': 'XMLHttpRequest'
					}), body: data})
					.then(res=>res.json())
					.then(function (res) {
						if(res.result===true){
							if('import'===src){
								const skin = document.getElementsByClassName('required-addons')[0].dataset.skin;
								document.querySelector('.required-addons.themify-modal[data-skin="'+skin+'"]').classList.add('reload');
								$(''===skin?'a.import-sample-content':'.skin-demo-import[data-id="'+skin+'"]').trigger( 'click' );
							}
							const wrap = document.getElementById('update-main');
							wrap.innerHTML=(new DOMParser()).parseFromString(res.html, 'text/html').body.innerHTML;
							themify_select_wrapper($(wrap));
							ThemifyUpdater.updateThemeBtn();
							modal.remove();
							if('import'!==src){
								$('.tb_alert').removeClass('busy').fadeOut(300);
							}
						}else{
							$('.tb_alert').removeClass('busy').fadeOut(300);
							alert(res.err);
						}
					});
			});
		}

		function themify_import_sample_content($modal,$button){
			const do_import = function( import_images, clear_old_imports ) {
				$.ajax({
					url: ajaxurl,
					dataType : 'json',
					data: {
						action: 'themify_import_sample_content',
						import_images : import_images ? 'yes' : 'no',
						clear_old_imports : clear_old_imports ? 'yes' : 'no',
						nonce: themify_js_vars.nonce
					},
					type: 'POST',
					success: function( response ) {
						const callback = function() {
							$button
								.find('span').text( $button.attr('data-success') );
							themify_hide_alert();
							// reload the page so settings are updated with their new values
							window.location = themify_js_vars.admin_url;
						};
						if ( response.success ) {
							themify_import_assets( response, callback );
						} else {
							themify_hide_alert();
							alert( response.data.error );
						}
					},
					beforeSend: function(){
						$button
							.find('span').text( $button.attr('data-importing') );
						themify_show_alert();
					}
				});
			};
			$modal.find( '.proceed-import' ).off().on( 'click', function(e){
				e.preventDefault();
				do_import( $( this ).parent().find( '.tf_import_images input:checkbox' ).is( ':checked' ), $( this ).closest( 'div' ).find( '.erase-demo' ).is( ':checked' ) );
			} )
				// patch up the issue of links not working inside the modal box
				.end()
				.find( 'a.external-link' ).on( 'click', function(){
				window.location = $( this ).attr( 'href' );
			} );
		}

		function themify_import_skin(target,$modal){
			const $this = $( target ),
				$preview = $this.closest( '.skin-preview' ).find( '.skin-demo-content' ),
				skin_name = $preview.data( 'skin' ),
				do_import = function( import_images, clear_old_imports ) {
					$.ajax({
						url: ajaxurl,
						data: {
							action: 'themify_import_sample_content',
							skin : skin_name,
							import_images : import_images ? 'yes' : 'no',
							clear_old_imports : clear_old_imports ? 'yes' : 'no',
							nonce: themify_js_vars.nonce
						},
						type: 'POST',
						success: function( response ) {
							const callback = function() {
								themify_hide_alert();
								window.location = themify_js_vars.admin_url;
							};
							if ( response.success ) {
								themify_import_assets( response, callback );
							} else {
								themify_hide_alert();
								alert( response.data.error );
							}
						},
						beforeSend: function(){
							themify_show_alert();
						}
					} );
				};
			$modal.fadeIn()
				.find( '.proceed-import' ).off().on( 'click', function(e){
				e.preventDefault();
				do_import( $( this ).parent().find( '.tf_import_images input:checkbox' ).is( ':checked' ), $( this ).closest( 'div' ).find( '.erase-demo' ).is( ':checked' ) );
			} )
				// patch up the issue of links not working inside the modal box
				.end()
				.find( 'a.external-link' ).on( 'click', function(){
				window.location = $( this ).attr( 'href' );
				themify_modal_action();
			} );
		}

		function themify_ajax_installer(e){
			if ( this.dataset.loading ) {
				return;
			}
			e.preventDefault();
			const link = this,
				modal = link.classList.contains('themify-updater');
			link.dataset.loading=true;
			if(true===modal){
				link.dataset.ajax=document.querySelector('#update-main .themify-ajax-installer').dataset.ajax;
			}
			themify_show_alert();
			fetch(link.dataset.ajax, {headers:new Headers({'X-Requested-With': 'XMLHttpRequest'})})
				.then(res=>res.text())
				.then(function (html) {
					delete link.dataset.loading;
					if(link.dataset.required){
						const chk = document.createElement('span');
						chk.className='ti-check';
						link.parentNode.replaceChild(chk,link);
					}else if(true===modal){
						document.querySelector('.required-addons.themify-modal[data-skin="'+link.dataset.skin+'"]').classList.add('reload');
						$(''===link.dataset.skin?'a.import-sample-content':'.skin-demo-import[data-id="'+link.dataset.skin+'"]').trigger( 'click' );
					}else{
						window.location.reload();
					}
					themify_hide_alert('done');
				}).catch(function (err) {
				themify_hide_alert('error');
				delete link.dataset.loading;
			});
		}

		function themify_select_wrapper($el){
			$el.find('select').not('[multiple]').wrap('<div class="selectwrapper"></div>');
			$el.find('.selectwrapper').on('click',function(){
				$(this).toggleClass('clicked');
			});
		}



	});

})(jQuery);
