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

	'use strict';

	$(document).ready(function($){

		// Themify Directory
		var blog_url = themify_js_vars.blog_url,
			$body = $('body'),
			$wpbody = $('#wpbody'),
			$themify = $('#themify');

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

		//
		// Get Subtab height based on Navigation height
		//
		$themify.find('.maintab').not('[aria-expanded="false"]').each(function(){
			var $this = $(this).find('.subtabnav'),
			h = $this.outerHeight();
			$(this).find('.subtab').css('minHeight', h);
		});
                
                
                if($.fn.tooltipster){
                    $('.themify_builder_lite').each(function(){
                        $('<div class="themify_builder_lite_modal"></div>').appendTo($(this)).tooltipster({
                            contentAsHTML:true,
                            side:$(this).data('position'),
                            debug:false,
                            repositionOnScroll:true,
                            content:'Upgrade to premium version to get this feature'
                        });
                    });
                }

		// fixed themify panel while scrolling (variables)
		var $panel = $('#setting>.subtabnav');
		var $panelTop;
		if ($panel.length > 0) {
			$panelTop =  $panel.offset().top - 32;
		}

		//
		// Create Tabs
		//
		$('#maintabnav').find('a').click(function(e){
			e.preventDefault();
			if ( 'replaceState' in history ) {
				history.replaceState( null, null, this.hash );
			}
		});
		$('#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;
				}
			}
		});

		// fixed themify panel while scrolling
		if ($panel.length > 0) {
			$(window).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  */

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

		/**
		 * Save user settings
		 * Uses nonces for security
		 */
		$('.save-button').click(function(e){
			e.preventDefault();
			showAlert();
			var data = $themify.serialize();
			$.post(
				ajaxurl,
				{
					'action': 'themify_save',
					'data': data,
					'nonce' : themify_js_vars.nonce
				},
				function() {
					hideAlert();
					$( 'body' ).trigger( 'themify_save' );
				}
			);
			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();
					$('.save-button').trigger('click');
				}
			});
		}
		/**
		 * Reset user styling
		 */
		$("#reset-styling").on('click', function(e){
			e.preventDefault();
			var reply = confirm(themify_lang.confirm_reset_styling);
			if(reply){
				showAlert();
				var data = $themify.serialize();
				$.post(
					ajaxurl,
					{
						'action': 'themify_reset_styling',
						'data'  : data,
						'nonce' : themify_js_vars.nonce
					},
					function(){
						hideAlert();
						window.location.reload(true);
					}
				);
			}
		});
		/**
		 * Reset user settings
		 */
		$("#reset-setting").on('click', function(e){
			e.preventDefault();
			var reply = confirm(themify_lang.confirm_reset_settings);
			if(reply){
				showAlert();
				var data = $themify.serialize();
				$.post(
					ajaxurl,
					{
						'action': 'themify_reset_setting',
						'data'  : data,
						'nonce' : themify_js_vars.nonce
					},
					function(){
						hideAlert();
						window.location.reload(true);
					}
				);
			}
		});

		//
		// Upgrade Theme / Framework
		//
		$wpbody.on('click', '.upgrade-framework, .upgrade-theme', function(e){
			e.preventDefault();
			var reply = confirm(themify_lang.check_backup),
				type = '',
				themeversion = '';
			if($(this).hasClass('upgrade-theme')){
				type = 'theme';
				themeversion = "&themeversion=" + ( $('#themeversiontoreinstall').length == 1 ? $('#themeversiontoreinstall').val() : 'latest' );
			} else {
				type = 'framework';
			}
			if ( reply ) {
				if ( $(this).parent().hasClass('login') ) {
					showLogin();
				} else {
					//showAlert();
					window.location = blog_url + "wp-admin/admin.php?page=themify&action=upgrade&type=" + type + themeversion + "&login=false";
				}
			}
		});

		//
		// Login Validation
		//
		$wpbody.on('click', '.upgrade-login', function(e){
			e.preventDefault();
			if ( ! $('.prompt-box').hasClass( 'update-plugin' ) ) {
				var el = $(this),
					username = el.parent().parent().find('.username').val(),
					password = el.parent().parent().find('.password').val(),
					login = $(".upgrade-theme").parent().hasClass('login');
				if ( username != '' && password != '' ) {
					hideLogin();
					showAlert();
					$.post(
						ajaxurl,
						{
							'action':'themify_validate_login',
							'nonce': themify_js_vars.nonce,
							'type':'theme',
							'login':login,
							'username':username,
							'password':password
						},
						function(data){
							data = $.trim(data);
							if('subscribed' == data){
								hideAlert();
								$('#themify_update_form').submit();
							} else if('invalid' == data) {
								hideAlert('error');
								showLogin('error');
							} else if('unsuscribed' == data) {
								hideAlert('error');
								showLogin('unsuscribed');
							}
						}
					);
				} else {
					hideAlert('error');
					showLogin('error');
				}
			} else if ( $('.prompt-box').hasClass( 'update-plugin' ) ) {
				e.preventDefault();
				var el = $(this),
					username = el.parent().parent().find('.username').val(),
					password = el.parent().parent().find('.password').val(),
					_updater_el = $('.themify-builder-upgrade-plugin')
					login = _updater_el.closest( '.notifications' ).find( '.update' ).hasClass('login');
				if ( username !== '' && password !== '' ) {
					hideLogin();
					showAlert();
					$.post(
						ajaxurl,
						{
							'action':'themify_builder_validate_login',
							'type':'plugin',
							'login':login,
							'username':username,
							'password':password,
							'nicename_short': _updater_el.data( 'nicename_short' ),
							'update_type': _updater_el.data( 'update_type' )
						},
						function(data){
							data = $.trim(data);
							if ( data === 'true' ) {
								hideAlert();
								$('#themify_update_form').append( '<input type="hidden" name="plugin" value="'+ _updater_el.data( 'plugin' ) +'" /><input type="hidden" name="package_url" value="'+ _updater_el.data( 'package_url' ) +'" />' ).submit();
							} else if ( data === 'false' || 'invalid' === data ) {
								hideAlert('error');
								showLogin('error');
							}
						}
					);
				} else {
					hideAlert('error');
					showLogin('error');
				}
			}
		});
		//
		// Hide Overlay
		//
		$('.overlay').on('click', function(){
			hideLogin();
		});

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

		});

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

		//
		// Padding / Margin
		//
		$('.padding-switch, .margin-switch').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').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').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();
			}
		});
		$noBgImage.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').change(function(){
			$(this).parent().find('.valueX').val($('option:selected', this).val());
		});
		$('.background_position.positionY').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').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').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']").change(function(){
			if($(this).val() == "image"){
				$(this).parent().parent().find(".image").fadeIn(200);
				$(this).parent().parent().find(".image").css("display","block");
			} else {
				$(this).parent().parent().find(".image").fadeOut();
			}
		});
		//
		// Feature Box Image / Posts Display
		//
		$(".feature-box-display").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").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").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).find("img").attr('id'));
		});

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

		function showLogin(status){
			var version = $('#themeversiontoreinstall').length == 1 ? $('#themeversiontoreinstall').val() : 'latest',
				action = $('.prompt-box form').attr('action');
			action = action.replace(/(themeversion=.*$)/ig, 'themeversion='+version);
			$('.prompt-box form').attr('action', action);

			$('.prompt-box .show-login').show();
			$('.prompt-box .show-error').hide();
			if('error' == status){
				if($('.prompt-box .prompt-error').length == 0){
					$('.prompt-box .prompt-msg').after('<p class="prompt-error">' + themify_lang.invalid_login + '</p>');
				}
			} else if ('unsuscribed' == status) {
				if($('.prompt-box .prompt-error').length == 0) {
					$('.prompt-box .prompt-msg').after('<p class="prompt-error">' + themify_lang.unsuscribed + '</p>');
				}
			} else {
				$('.prompt-box .prompt-error').remove();
			}
			$('.prompt-box').removeClass( 'update-plugin' );
			$(".overlay, .prompt-box").fadeIn(500);
		}
		function hideLogin(){
			$('.overlay, .prompt-box').fadeOut(500, function(){
				var $prompt = $('.prompt-box'), $iframe = $prompt.find('iframe');
				if ( $iframe.length > 0 ) {
					$iframe.remove();
				}
				$prompt.removeClass('show-changelog');
			});
		}
		function showAlert(){
			$(".alert").addClass("busy").fadeIn(800);
		}
		function hideAlert(status){
			if(status == 'error'){
				status = 'error';
				showErrors();
			} else {
				status = 'done';
			}
			$(".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.+-";
			var IsNumber = true;
			var 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
		$socialLinksWrapper.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').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', 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() {
				var top = $(document).scrollTop() + 80,
					$lightbox = $("#themify_lightbox_visibility");

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

			closeLightbox: function( callback ){
				$('#themify_lightbox_visibility').animate({
					'top': Themify_Visibility.getDocHeight()
				}, 800, function() {
					$('#themify_lightbox_overlay').hide();
					$('#themify_lightbox_visibility').hide();
					if( typeof(callback) === 'function' ) {
						callback();
					}
					Themify_Visibility.clearOptions();
				});
			},

			clearOptions: function(){
				$('#themify_lightbox_visibility').find('.lightbox_container').empty();
			}
		};

		var $lightbox = $('#themify_lightbox_visibility');

		$body.on('click', '.themify-add-hook a', function(){
			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){
					field_ids.push( new_field_id );
					$('#themify-hooks-field-ids').val( JSON.stringify( field_ids ) );
					$('#hook-content-list').append(data);
				}
			});
			return false;
		});

		$body.on('click', '.themify-visibility-toggle', function(){
			Themify_Visibility.target = $(this).next();
			Themify_Visibility.showLightbox();
			return false;
		});

		$body.on('click', '#themify_lightbox_visibility .close_lightbox, #themify_lightbox_overlay', function(){
			Themify_Visibility.closeLightbox();
		});

		$lightbox.on('click', '.visibility-save', function(){
			var data = $( 'form', $lightbox ).serialize();
			Themify_Visibility.target.val( data );
			Themify_Visibility.closeLightbox();
			return false;
		});

		$lightbox.on('click', '.uncheck-all', function(){
			$('input:checkbox', $lightbox).removeAttr( 'checked' );
			return false;
		});

		$body.on('click', '#setting-hooks .remove-item', function(){
			var field_ids = JSON.parse( $('#themify-hooks-field-ids').val() );
			var $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 ) );
			});
			return false;
		});

		// 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').change(function(){
			var fonts = $(this).val();
			$(this).next().val( JSON.stringify( fonts ) );
		}).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' );
		} );

		$( 'body' ).on( 'click', '.skin-demo-import', function(e){
			e.preventDefault();
			var $this = $( this ),
				$preview = $this.closest( '.skin-demo-content' );
			var do_import = function(){
				$.ajax({
					url: ajaxurl,
					data: {
						action: 'themify_import_sample_content',
						skin : $preview.data( 'skin' ),
						nonce: themify_js_vars.nonce
					},
					type: 'POST',
					success: function(data){
					},
					beforeSend: function(){
						$preview.addClass( 'busy' );
					},
					complete: function(){
						$preview.removeClass( 'busy' );
						window.location.reload();
					}
				} );
			}
			if( $this.closest( '.skin-preview' ).find( '.required-addons' ).length ) {
				$this.closest( '.skin-preview' ).find( '.required-addons' ).fadeIn()
					.find( '.skin-demo-import-proceed' ).off().on( 'click', do_import )
					// 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' );
					} )
			} else {
				do_import();
			}
		}).on( 'click', '.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(data){
				},
				beforeSend: function(){
					$preview.addClass( 'busy' );
				},
				complete: function(){
					$preview.removeClass( 'busy' );
				}
			} );
		});

		var $demo_import_buttons = $('.import-sample-content'),
			$demo_erase_buttons = $('.erase-sample-content');

		$demo_import_buttons.click(function(){
			var $button = $(this);
			if( $button.hasClass( 'disabled' ) ) {
				return false;
			}
			if( ! window.confirm( themify_lang.confirm_demo ) ) {
				return false;
			}
			$demo_import_buttons.addClass( 'disabled' );
			$.ajax({
				url: ajaxurl,
				data: {
					action: 'themify_import_sample_content',
					nonce: themify_js_vars.nonce
				},
				type: 'POST',
				success: function(data){
				},
				beforeSend: function(){
					$button
					.find('span').text( $button.attr('data-importing') ).end()
					.find('i').removeClass().addClass( 'fa fa-cog fa-spin' );
				},
				complete: function(){
					$button.addClass('import-success').click(function(){
						$(this).parent().find('.dismiss-import-notice:first').click();
					})
					.find('span').text( $button.attr('data-success') ).end()
					.find('i').removeClass().addClass( 'fa fa-check-circle' );

					$demo_erase_buttons.removeClass( 'disabled' )
					.find('i').removeClass().addClass('fa fa-times').end()
					.find('span').text( $demo_erase_buttons.attr('data-default') );

					// reload the page so users can see the new settings
					window.location.reload();
				}
			});
			return false;
		});
		$demo_erase_buttons.click(function(){
			var $button = $(this);
			if( $button.hasClass( 'disabled' ) ) {
				return false;
			}
			$demo_erase_buttons.addClass( 'disabled' );
			$.ajax({
				url: ajaxurl,
				data: {
					action: 'themify_erase_sample_content',
					nonce: themify_js_vars.nonce
				},
				type: 'POST',
				success: function(data){
				},
				beforeSend: function(){
					$button
					.find('span').text( $button.attr('data-erasing') ).end()
					.find('i').removeClass().addClass('fa fa-cog fa-spin');
				},
				complete: function(){
					$button
					.find('span').text( $button.attr('data-success') ).end()
					.find('i').removeClass().addClass( 'fa fa-check-circle' );

					$demo_import_buttons.removeClass( 'disabled' ).removeClass( 'import-success' )
					.find('i').removeClass().addClass('fa fa-arrow-down').end()
					.find('span').text( $demo_import_buttons.attr('data-default') );
				}
			});
			return false;
		});
		$( '.themify-modal .close' ).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');
		});

		// Return a specific variable in the url
		function getUrlVar( sParam ) {
			var sPageURL = window.location.search.substring(1),
				sURLVariables = sPageURL.split('&'),
				out = false;
			for ( var i = 0; i < sURLVariables.length; i ++ ) {
				var sParameterName = sURLVariables[i].split('=');
				if ( sParameterName[0] == sParam ) {
					out = sParameterName[1];
					break;
				}
			}
			return out;
		}

		// Redirect to Update tab if url has update=check variable
		var isThemify = getUrlVar('page');
		if ( isThemify && 'themify' == isThemify ) {
			var hash = window.location.hash;
			if ( ! hash ) {
				var isUpdate = getUrlVar('update');
				if ( isUpdate && 'check' === isUpdate ) {
					$themify.find('a[href="#update-check"]').trigger('click');
				}
			}
		}

		// If image in Featured Image meta box is removed, remove image in #post_image
		var themifyCustomPostImageRemove = $( '#post_image' ).closest( '.themify_field' ).find( '.themify_featimg_remove a' );
		if ( themifyCustomPostImageRemove.length > 0 ) {
			$body.on( 'click.themify', '#remove-post-thumbnail', function () {
				themifyCustomPostImageRemove.trigger( 'click' );
			} );
		}

		// New general show/hide elements toggle.
		themify_init_show_if( $('#themify') );

		// Clear cache builder
		$('.js-clear-builder-cache').on('click', function( event ){
			event.preventDefault();
			var $this = $(this);
			if ( $this.hasClass('disabled') ) return;
			if ( ! window.confirm( themify_lang.confirm_clear_builder_cache ) ) return;
			$this.addClass('disabled');
			$.ajax({
				url: ajaxurl,
				data: {
					action: 'themify_builder_clear_all_caches',
					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 ] );
			  }
			}
		  });
		});
	});

	function themifySetCookie(name,value) {
		'use strict';
		document.cookie = name+"="+value+"; path=/";
	}
	function themifyGetCookie(name) {
		'use strict';
		name = name + "=";
		var ca = document.cookie.split(';');
		for(var i=0; i < ca.length; i++) {
			var c = ca[i];
			while (' ' == c.charAt(0)) c = c.substring(1,c.length);
			if (0 == c.indexOf(name)) return c.substring(name.length,c.length);	}
		return null;
	}

	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);
			var $target_value   = $target_element.data( 'show-if-value' );
			var $source_element = $( $target_element.data( 'show-if-element' ).toString() );

			if ( $source_element.attr('type') == 'checkbox' ) {
				var $source_element_value = ( $source_element.is(':checked') ) ? 'true' : 'false' ;
			}
			else {
				var $source_element_value = $source_element.val();
			}
			$target_value = $.isArray($target_value)?$target_value:[$target_value];
			
			if( 'undefined' !== typeof( $source_element_value ) && $.inArray($source_element_value.trim(),$target_value)!==-1){
				// Show
				$target_element.slideDown( { duration: 550 } );
			} else {
				// Hide
				$target_element.slideUp( { duration: 550 } );
			}
		});
	}
})(jQuery);