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

	'use strict';

	$(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 ) {
							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').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('ti-plus')) {
						$this.siblings().slideDown( "fast", function() {
							$icon.removeClass('ti-plus').addClass('ti-minus');
						});
					} else {
						$this.siblings().slideUp( "fast", function() {
							$icon.removeClass('ti-minus').addClass('ti-plus');
						});
					}
				});
				
			}
		};

		$('#content, .maintab').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
		});

		// 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() {
			showAlert();
			var data = $themify.serialize();
			$.post(
				ajaxurl,
				{
					'action': 'themify_save',
					'data': data,
					'nonce' : themify_js_vars.nonce
				},
				function() {
					hideAlert();
					$( '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 styling,settings
		 */
		$( '#reset-styling, #reset-setting' ).on( 'click', function( e ) {
			e.preventDefault();

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

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

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

		// For FW updates, receive a message from themify.me and show it
		if ( $( 'p.update:has(a.upgrade-framework, a.upgrade-theme)' ).length ) {
			$.ajax( {
				url : 'https://themify.me/public-api/update-message/index.txt',
				success : function( message ) {
					$( '<span class="updater-message"></span>' ).text( message ).appendTo( 'p.update:has(a.upgrade-framework, a.upgrade-theme)' );
				}
			} );
		}

		$('.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);
			if ( $( '.prompt-box iframe' ).length < 1 ) {
				$('.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();
		} );

		/*******************************************************************************/
		/* Style Module Events */

		//
		// Padding / Margin
		//
		$('.padding-switch, .margin-switch').on('click',function(){
			var parent = $(this).parent().parent().parent();
			var num = 0;
			if($(this).is(":checked")){
				if(parent.find(".individuals input:first").val() != ''){
					num = parent.find(".individuals input:first").val();
				}
				parent.find(".individuals").fadeOut(200, function(){
					parent.find(".same").fadeIn(200).find("input").val(num);
				}).find("input").val('');
			} else {
				if(parent.find(".same input").val() != ''){
					num = parent.find(".same input").val();
				}
				parent.find(".same").fadeOut(200, function(){
					parent.find(".individuals").fadeIn(200).find("input").val(num);
				}).find("input").val('');
			}
		});
		//
		// Border
		//
		$('.border-switch').on('click',function(){
			var parent = $(this).parent().parent(),
				color = '',
				num = 0,
				true_color = '';
			if($(this).is(":checked")){
				if(parent.parent().find(".individuals input[type='text']:nth-child(1)").val() != ''){
					color = parent.parent().find(".individuals input[type='text']:nth-child(1)").val();
				}
				if(parent.parent().find(".individuals input:nth-child(2)").val() != ''){
					num = parent.parent().find(".individuals input:nth-child(2)").val();
				}
				true_color = parent.parent().find(".individuals .colorSelect").css('background-color');
				parent.parent().find(".individuals .colorSelect").css('background-color','#ffffff');
				parent.parent().find(".individuals input[type='text']").val('');
				parent.parent().find(".individuals").fadeOut(200, function(){
					parent.parent().find(".same input[type='text']:nth-child(1)").val(color);
					parent.parent().find(".same .colorSelect").css("background-color",true_color);
					parent.parent().find(".same").fadeIn(200).find("input[type=text]:nth-child(2)").val(num);
					parent.parent().find(".same select").val(parent.parent().find('.individuals select:first option:selected').val());
				});

			} else {
				if(parent.parent().find(".same input[type='text']:nth-child(1)").val() != ''){
					color = parent.parent().find(".same input[type='text]:nth-child(1)").val();
				}
				if(parent.parent().find(".same input:nth-child(2)").val() != ''){
					num = parent.parent().find(".same input:nth-child(2)").val();
				}
				true_color = parent.parent().find(".same .colorSelect").css('background-color');
				parent.parent().find(".same .colorSelect").css('background-color','#ffffff');
				parent.parent().find(".same input").val('');
				parent.parent().find(".same").fadeOut(200, function(){
					parent.parent().find(".individuals select").val(parent.parent().find('.same select:first option:selected').val());
					parent.parent().find(".individuals").fadeIn(200).find("input[type='text']:nth-child(2)").val(num);
					parent.parent().find(".individuals .borders input[type='text']:nth-child(1)").val(color);
					parent.parent().find(".individuals .borders .colorSelect").css("background-color",true_color);
				});
			}
		});
		//
		// Background-Color Transparent
		//
		$('.colorTransparent').on('click',function(){
			var $parent = $(this).parent();
			if($(this).is(":checked")){
				$parent.find("input[type='text']").attr('disabled', true).val('').addClass('opacity-7');
				$parent.find('.colorSelect').minicolors('value', '');
				$('.clearColor, .minicolors', $parent).hide();
			} else {
				$parent.find("input[type=text]").removeAttr('disabled').removeClass('opacity-7');
				$('.minicolors', $parent).show();
			}
		});
		//
		// Background-Image No BG Image
		//
		var $noBgImage = $('.noBgImage');
		$noBgImage.each(function(){
			if($(this).is(":checked")){
				var $parent = $(this).parent();
				$parent.find("input[type='text']").attr('disabled', true).val('').addClass('opacity-7');
				$('.plupload-button', $parent).hide();
			}
		}).click(function(){
			var $parent = $(this).parent();
			if($(this).is(":checked")){
				$parent.find("input[type='text']").attr('disabled', true).val('').addClass('opacity-7');
				$('.plupload-button', $parent).hide();
			} else {
				$parent.find("input[type='text']").removeAttr('disabled').removeClass('opacity-7');
				$('.plupload-button', $parent).show();
			}
		});
		//
		// Background-Position
		//
		$('.background_position.positionX').on('change',function(){
			$(this).parent().find('.valueX').val($('option:selected', this).val());
		});
		$('.background_position.positionY').on('change',function(){
			$(this).parent().find('.valueY').val($('option:selected', this).val());
		});
		//
		// Background-Image Thumb
		//
		var $bgPreset = $('.preset');
		$bgPreset.on('click', '.backgroundThumb', function(e){
			e.preventDefault();
			var alt = $(this).attr("alt");
			$(this).parent().parent().find('.backgroundThumb.selected').removeClass('selected');
			$(this).addClass('selected');
			$(this).parent().parent().parent().find('.background_image input[type=text]').removeAttr('disabled').val(alt);
			$(this).parent().parent().parent().find('.background_image input:checkbox').attr('checked', false);
		});
		//
		// Background-Image Remove Selection on Blur
		//
		$('.background_image .upload-file').on('blur', function(){
			if($(this).val() == ''){
				$(this).parent().parent().find('.backgroundThumb.selected').removeClass('selected');
			}
		});
		//
		// Background-Image None
		//
		$('.background_image input:checkbox').on('click',function(){
			if($(this).is(":checked")){
				$(this).parent().parent().find('.backgroundThumb.selected').removeClass('selected');
				$(this).parent().parent().find('.background_image input[type=text]').attr('disabled', true).val('');
			} else {
				$(this).parent().parent().find('.background_image input[type=text]').removeAttr('disabled');
			}
		});
		//
		// Delete Image
		//
		$bgPreset.on('click', 'span', function(e){
			e.preventDefault();
			var el = $(this);
			var reply = confirm(themify_lang.confirm_delete_image);
			// Check if it has an attachment ID
			if(reply){
				$.post(
					ajaxurl,
					{
						'action': 'themify_delete_preset',
						'file': el.attr('title'),
						'nonce' : themify_js_vars.nonce
					},
					function() {
						if(el.parent().parent().parent().find('.background_image input[type="text"]').val() == el.parent().find("img").attr("alt")){
							el.parent().parent().parent().find('.background_image input[type="text"]').val('');
						}
						el.parent().remove();
						$('.preset a[title="'+el.parent().attr('title')+'"]').remove();
						$('.upload-file').each(function(){
							if($(this).val() == el.parent().find('img').attr('alt')){
								$(this).val('');
							}
						});
					}
				);
			}
		});
		//
		// Position
		//
		$('.select_position').on('change',function(){
			var val = $('option:selected', this).val();
			if(val === 'absolute' || val === 'fixed'){
				$(this).parent().parent().find('.position_display').show(200);
			} else {
				$(this).parent().parent().find('.position_display').hide(200);
			}
		});

		//
		// Font-Family
		//
		$('.fontFamily').on('change',function(){
			if($('option:selected', this).val() === 'custom'){
				$(this).parent().find('.value').show();
				$(this).parent().find('.value input').val('');
			} else {
				$(this).parent().find('.value').hide();
				$(this).parent().find('.value input').val($('option:selected', this).val());
			}
		});
		//
		// Site-Logo
		//
		$("input[name='setting-site_logo'], input[name='setting-footer_logo']").on('change',function(){
			if($(this).val() === "image"){
				$(this).parent().parent().find(".image").fadeIn(200).css("display","block");
			} else {
				$(this).parent().parent().find(".image").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.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.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').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);
			}
		}).change();

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

		//
		// Skins Load
		//
		$("#skins .skin-preview").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' ) );
		});

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

		function showAlert(){
			$(".tb_alert").addClass("busy").fadeIn(800);
		}
		function hideAlert(status){
			if(status === 'error'){
				status = 'error';
				showErrors();
			} else {
				status = 'done';
			}
			$(".tb_alert").removeClass("busy").addClass(status).delay(800).fadeOut(800, function(){
				$(this).removeClass(status);
			});
		}
		function showErrors(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();
		}

		/*******************************************************************************/
		/*	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.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
					$('#social-links-wrapper').append(data);

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

					// 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);
					}

					if ( $colorPicker.length > 0 ) {
						// Initialize color pickers for this new field
						$colorPicker.minicolors( {
							defaultValue: '#ffffff',
							letterCase: 'lowercase',
							change: function(hex) {
								$(this).parent().next().val(hex.replace( '#', '' ));
							}
						} );
					}

					// 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;
				}
			});
		});

		$themify.on('click', '.refresh-webfonts', function(event){
			event.preventDefault();
			var reply = confirm(themify_lang.confirm_refresh_webfonts);
			if(reply){
				var data = $themify.serialize();
				$.post(
					ajaxurl,
					{
						'action': 'themify_save',
						'data': data,
						'nonce' : themify_js_vars.nonce
					},
					function() {
						showAlert();
						$.post(
							ajaxurl,
							{
								'action': 'themify_refresh_webfonts',
								'nonce' : themify_js_vars.nonce
							},
							function(){
								hideAlert();
								window.location.reload(true);
							}
						);
					}
				);
			}
		});
		$themify.on('change', '.google_font_subset, .themify_multiselect', function(){
			var $vals = $(this).val();
			if($vals){
				$vals= $vals.join(',');
			}
			$(this).next().val($vals);
						
		});

		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 .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>');
			var $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();
			var field_ids = JSON.parse( $('#themify-hooks-field-ids').val() ),
                            $item = $(this).closest('.social-link-item').fadeOut('fast', function(){
				var removeId = $item.attr('data-id');
				for( var key in field_ids ) {
					if ( field_ids.hasOwnProperty(key) ) {
						if ( field_ids[key] == removeId ) {
							field_ids.splice(key, 1);
						}
					}
				}
				$('#themify-hooks-field-ids').val( JSON.stringify( field_ids ) );
				$('.themify-admin-lightbox-' + removeId).remove();
			});
		}).
                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>');
			var 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){
					var 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
		var $hookContentList = $('#hook-content-list');
		$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 ) );
			}
		});
		var $seeHookLocations = $('.see-hook-locations');
		if( $seeHookLocations.length > 0 ) {
			$seeHookLocations.magnificPopup({
				type: 'iframe',
				iframe: {
					markup: '<div class="mfp-iframe-scaler" style="max-width: 100% !important; height: 100%;">'+
					'<div class="mfp-close"></div>'+
					'<iframe class="mfp-iframe" frameborder="0" allowfullscreen></iframe>'+
					'</div>'
				}
			});
		}

		$('#setting-editor-gfonts-list').on('change',function(){
			var fonts = $(this).val();
			$(this).next().val( JSON.stringify( fonts ) );
		}).change();

		$( '.required-addons.themify-modal' ).appendTo( 'form#themify' );

		// 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' ).click( function(){
			$( '#skins .skin-preview.selected .skin-demo-import' ).click();
		} );

		/**
		 * Import sample images in demo content.
		 * First import post thumbnails, then 'gallery_shortcode' field types
		 */
		function 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;
				}
				var 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 ( var i = 0; i < max_query; i++ ) {
				make_request();
			}
		}

		$body.on( 'click', '#skins .skin-demo-import', function(e){
			e.preventDefault();
			var $this = $( this ),
				$preview = $this.closest( '.skin-preview' ).find( '.skin-demo-content' ),
				skin_name = $preview.data( 'skin' ),
                    do_import = function( import_images ) {
	                    $.ajax({
                            url: ajaxurl,
                            data: {
                                action: 'themify_import_sample_content',
                                skin : skin_name,
								import_images : import_images ? 'yes' : 'no',
                                nonce: themify_js_vars.nonce
                            },
                            type: 'POST',
                            success: function( response ) {
								var callback = function() {
									hideAlert();
									window.location = themify_js_vars.admin_url;
								};
								if ( response.success ) {
									import_assets( response, callback );
								} else {
									hideAlert();
									alert( response.data.error );
								}
                            },
                            beforeSend: function(){
                                showAlert();
                            },
                            complete: function(){
                                
                            }
	                    } );
                    };
			
			var requirements = $( '#themify .required-addons[data-skin="' + skin_name + '"]:first' );
			if( requirements.length ) {
				requirements.fadeIn()
					.find( '.proceed-import' ).off().on( 'click', function(e){
						e.preventDefault();
						do_import( $( this ).parent().find( '.tf_import_images input:checkbox' ).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' );
					} );
			}
		}).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(){
					showAlert();
				},
				complete: function(){
					hideAlert();
				}
			} );
		});

		// 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' ).click();
		} );

		// Import Demo button in main tab
		$( '#demo-import .import-sample-content' ).on('click',function(){
			var $button = $(this),
				required_addons = $( '#themify' ).find( '.required-addons' );

			if( $button.hasClass( 'disabled' ) ) {
				return false;
			}

			var do_import = function( import_images ) {
				$.ajax({
					url: ajaxurl,
					dataType : 'json',
					data: {
						action: 'themify_import_sample_content',
						import_images : import_images ? 'yes' : 'no',
						nonce: themify_js_vars.nonce
					},
					type: 'POST',
					success: function( response ) {
						var callback = function() {
							$button
								.find('span').text( $button.attr('data-success') );
							hideAlert();
							// reload the page so settings are updated with their new values
							window.location = themify_js_vars.admin_url;
						};
						if ( response.success ) {
							import_assets( response, callback );
						} else {
							hideAlert();
							alert( response.data.error );
						}
					},
					beforeSend: function(){
						$button
							.find('span').text( $button.attr('data-importing') );
						showAlert();
					},
					complete: function(){
					}
				});
			};

			if( required_addons.length ) {
				required_addons.fadeIn()
				.find( '.proceed-import' ).off().on( 'click', function(e){
					e.preventDefault();
					
					do_import( $( this ).parent().find( '.tf_import_images input:checkbox' ).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' );
					} );
			}
			return false;
		});

		// Erase Demo button
		$('.erase-sample-content').on('click',function(){
			var $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') );
					showAlert();
				},
				complete: function(){
					$button
						.find('span').text( $button.attr('data-success') );
					hideAlert();
				}
			});
			return false;
		});
		$( '.themify-modal .dismiss-import-notice' ).on('click',function(){
			$( this ).closest( '.themify-modal' ).fadeOut();
			return false;
		});
		// Dismiss the big notice and save a flag.
		$('.notice-dismiss').on('click', function(){
			var $close = $(this),
				noticeName = $close.data('notice');
			$.post(ajaxurl,
				{
					action: 'themify_notice_dismiss',
					notice: noticeName,
					nonce: themify_js_vars.nonce
				},
				function(){
					$('.js-' + noticeName + '-notice').fadeOut(300, function(){
						$(this).remove();
					});
				}
			);
			return false;
		});

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

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

		// Clear cache builder
		$('.js-clear-builder-cache').on('click', function( event ){
			event.preventDefault();
			var $this = $(this);
			if ( $this.hasClass('disabled') ) return;
			if ( ! window.confirm( $this.data('confim')) ) return;
			$this.addClass('disabled');
			$.ajax({
				url: ajaxurl,
				data: {
					action:$this.data('action'),
					nonce: themify_js_vars.nonce
				},
				type: 'POST',
				beforeSend: function(){
					$this.find('span').text( $this.data('clearing-text') ).end()
					.find('i').removeClass().addClass('fa fa-cog fa-spin');
				},
				success: function(){
					$this.find('span').text( $this.data('done-text') ).end()
					.find('i').removeClass().addClass('fa fa-check-square');

					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(){
		  var $this = $(this),
			$input = $this.next(),
			value = $input.val(),
			values = value.split('-'),
			isRange = $input.data('range') ? true: false;
		  $this.slider({
			range: isRange,
			min: $input.data('min'),
			max: $input.data('max'),
			values: values,
			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 ] );
			  }
			}
		  });
		});


		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 ){
				var row = $( '#post_image' ).closest( '.themify_field_row' );
				if( id == -1 ) {
					row.find( '.themify_featimg_remove a' ).click();
				} else {
					themifyMediaLib.setPreviewIcon( row, $( html ).find( '#set-post-thumbnail img' ).attr( 'src' ) );
				}
			} );
			$( '#post_image' ).closest( '.themify_field_row' ).find( '.themify_featimg_remove a' ).click(function(){
				$( '#remove-post-thumbnail' ).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();
	});

	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 = $.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').click(function(){
                    var $this = $(this);
			$this.attr({'value':'Regenerating ...','disabled':'disabled'});
                        $.ajax({
                                url: ajaxurl,
                                type: 'post',
                                data: {
                                        action: 'themify_regenerate_css_files_ajax',
                                        nonce: themify_js_vars.nonce
                                },
                                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').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(){
		var pagesDropdown = document.getElementById('setting-page_builder_maintenance_page');
		if( null === pagesDropdown ){
			return;
		}
		pagesDropdown.addEventListener('click',tb_load_maintenance_pages);
		function tb_load_maintenance_pages(){
			pagesDropdown.removeEventListener('click',tb_load_maintenance_pages);
			var self = this;
			$.ajax( {
				url: ajaxurl,
				type:'POST',
				data: {
					'action': 'tb_load_maintenance_pages',
					'nonce' : themify_js_vars.nonce
				},
				success: function( data ) {
					self.innerHTML = data;
				}
			});
		}
	}

	// Tooltip helper		
	$(function() {
		var 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>' );		
			} );		
		}
	} );
})(jQuery);
