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

	'use strict';

	// Themify Directory
	var blog_url = themify_js_vars.blog_url,
		$body = $('body'),
		$wpbody = $('#wpbody'),
		$themify = $('#themify'),
		transitionEvents = 'webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend';

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

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

	/*******************************************************************************/
	/* 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();
			}
		);
		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 = '';
		if($(this).hasClass('upgrade-theme')){
			type = 'theme';
		} 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 + "&login=false";
			}
		}
	});

	//
	// Login Validation
	//
	$wpbody.on('click', '.upgrade-login', function(e){
		e.preventDefault();
		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');
		}
	});
	//
	// 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);
		}
	});
	//
	// Color Picker
	//
	$('.colorSelect').each(function(){
		var input = $(this).parent().parent().find('.colorSelectInput'),
				set_color = (input.val() == '') ? '' : input.val(),
				minicolors = $(this);

		minicolors.minicolors({
			defaultValue: set_color,
			textfield: false,
			change: function(hex) {
				// Generate text to show in console
				var text = hex ? hex : '', colorField = this.parent().parent();
				colorField.find('.colorSelectInput').val(text.replace('#', ''));
				$('.clearColor', colorField).show();
			}
		});
	});
	// Set or clear color swatch based on input value
	$(document).on('blur', '.colorSelectInput', function() {
		var $parent = $(this).parent();
		if('' == $(this).val()){
			$parent.find('.colorSelect').minicolors('value', '');
			$('.clearColor', $parent).hide();
		} else {
			$('.colorSelect', $parent).minicolors('value', '#' + $(this).val());
			$('.clearColor', $parent).show();
		}
	});
	// Clear swatch and input
	$(document).on('click', '.clearColor', function(){
		$(this).parent().find('.colorSelect').minicolors('value', '');
		$(this).parent().find('.colorSelectInput').val('');
		$(this).hide();
	});
	$('.themify_field-color').each(function(){
		if('' != $('.colorSelectInput', $(this)).val()){
			$('.clearColor', $(this)).show();
		}
		if($('.colorTransparent', $(this)).prop('checked')){
			$('.minicolors', $(this)).hide();
		}
	});
	$( '.colorSelectInput' ).on('keyup', function(){
		if ( $(this).val().indexOf( '#' ) !== -1 ) {
			$(this).val( $(this).val().replace( '#', '' ) );
		}
	});

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

	//
	// Toggle Active Layout Icons and Post Format Icons
	//
	var $enableToggle = $('.enable_toggle');
	if($enableToggle.length > 0){
		$enableToggle.each(function(){
			var context = $(this).closest('.themify_write_panel');
			$('.themify-toggle', context).hide().addClass('toggled-off');
		});
	}
	$('.enable_toggle .preview-icon').on('click', function(e){
		// toggle
		var img_alt = $(this).find("img").attr("alt"),
			toggle_class = ($.trim(img_alt) != '') ? '.'+img_alt+'-toggle' : '.default-toggle';
		$(this).closest('.inside').find('.themify-toggle').hide().addClass('toggled-off');
		$(this).closest('.inside').find( toggle_class ).show().removeClass('toggled-off');
		e.preventDefault();
	});
	$('.enable_toggle .preview-icon.selected').each(function(){
		var img_alt = $(this).find("img").attr("alt"),
			toggle_class = (img_alt != '' && img_alt != 'default') ? '.'+img_alt+'-toggle' : '.default-toggle';
		$( toggle_class ).show().removeClass('toggled-off');
	});

	// Toggle Post Format Fields by Radio Button
	$('.enable_toggle input[type=radio]').on('click', function() {
		var val = $(this).val(),
			toggle_class = (val != 0 && val != '') ? '.'+val+'-toggle' : '.default-toggle',
			$siblings = $(this).siblings('input[type=radio]');

		$siblings.each(function(){
			var sib_val = $(this).val();
			if ( sib_val != 0 && sib_val !== '' ) $( '.' + sib_val + '-toggle').hide().addClass('toggled-off');
		});

		$(toggle_class).each(function(){
			$(this).show().removeClass('toggled-off');
			if ( $(this).hasClass('enable_toggle_child') ) {
				var $child_siblings = $(this).find('input[type=radio]:checked').siblings('input[type=radio]');
				$child_siblings.each(function(){
					var sib_val = $(this).val();
					setTimeout(function(){
						if ( sib_val != 0 && sib_val !== '' ) $( '.' + sib_val + '-toggle').hide().addClass('toggled-off');
					}, 500);
				});
			}
		});
	});
	$enableToggle.each(function(){
		var $checked = $(this).find('input[type=radio]:checked'),
			val = $checked.val(),
			toggle_class = (val != 0 && val !== '') ? '.'+val+'-toggle' : '.default-toggle';
		$(toggle_class).show().removeClass('toggled-off');
	});

	// Toggle Post Format Fields by Checkbox.
	// Works with single checkbox selection, not yet with combinations.
	$('.enable_toggle input[type=checkbox]').on('click', function() {
		var val = $(this).data('val'),
			toggle_class = (val != 0 && val != '') ? '.'+val+'-toggle' : '.default-toggle';

		$(this).closest('.inside').find('.themify-toggle').hide().addClass('toggled-off');

		if($(this).prop('checked')){
			$(this).closest('.inside').find( toggle_class ).show().removeClass('toggled-off');
		}
	});
	$('.enable_toggle input[type=checkbox]:checked').each(function() {
		var val = $(this).data('val'),
			toggle_class = (val != 0 && val !== '') ? '.'+val+'-toggle' : '.default-toggle';
		$( toggle_class ).show().removeClass('toggled-off');
	});

	//
	// Layout Options
	//
	$('.preview-icon').each( function() {
		var $self = $(this),
			$parent = $self.parent(),
			$val = $parent.find('.val'),
			$dataHide,
			dataHide = '',
			context = '';

		if ( $self.closest('.group-hide').length > 0 ) {
			context = 'theme-settings';
			$dataHide = $self.closest('.group-hide');
			dataHide = $dataHide.data( 'hide' );
		} else if ( $self.closest('.themify_field_row').length > 0 ) {
			context = 'custom-panel';
			$dataHide = $self.closest('.themify_field_row');
			if ( 'undefined' !== typeof $dataHide.data( 'hide' ) ) {
				dataHide = $dataHide.data( 'hide' );
			}
		}

		$self.click(function(e){
			e.preventDefault();
			
			// Change value
			$parent.find('.selected').removeClass('selected');
			$self.addClass('selected');
			$val.val( $self.find('img').attr('alt') );

			// There are elements to show/hide so do it
			if ( '' !== dataHide ) {
				if ( 'custom-panel' == context ) {
					// All until next data-hide, minus toggled-off those are nested and handled by toggle code, minus items not in list to hide
					$dataHide.nextUntil('[data-hide]').not('.toggled-off').filter( '.' + dataHide.replace( /\s/g, ',.' ) ).show().filter( '.' + $val.val() ).hide();
				} else if ( 'theme-settings' == context ) {
					$dataHide.find('.hide-if').filter( '.' + dataHide.replace( /\s/g, ',.' ) ).show().filter( '.' + $val.val() ).hide();
				}
			}

		});

		// All until next data-hide, minus toggled-off those are nested and handled by toggle code, minus items not in list to hide
		if ( '' !== dataHide ) {
			if ( 'custom-panel' == context ) {
				$dataHide.nextUntil('[data-hide]').not('.toggled-off').filter( '.' + dataHide.replace( /\s/g, ',.' ) ).filter( '.' + $val.val() ).hide();
			} else if ( 'theme-settings' == context ) {
				$dataHide.find('.hide-if').filter( '.' + dataHide.replace( /\s/g, ',.' ) ).show().filter( '.' + $val.val() ).hide();
			}
		}

	});

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

	//
	// Skins Load
	//
	$(".skin-preview").click(function(e){
		e.preventDefault();
		$(".skin-preview img.selected").removeClass();
		$(this).find("img").addClass('selected');
		$("input[name='skin']").val($(this).find("img").attr('id'));
	});

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

	function showLogin(status){
		$('.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();
		}
		$(".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'));
		});
	}

	/**
	 * Map layout icons to values and bind clicks
	 */
	$(".themify_field .preview-icon").click(function(e){
        e.preventDefault();
        $(this).parent().find(".selected").removeClass("selected");
        $(this).addClass("selected");
        $(this).parent().find(".val").val($(this).find("img").attr("alt"));
    });
    /**
     * Bind categories select to value field
     */
    var $themifyField = $('.themify_field'),
	    $themifyInfoLink = $('.themify-info-link');

    $themifyField.find('.query_category').blur(function(){
	    var $self = $(this), value = $self.val();
        $(this).parent().find('.val').val( value );
	    toggleQueryCategoryFields( $self, value );
    }).keyup(function(){
	    var $self = $(this), value = $self.val();
    	$(this).parent().find('.val').val( value );
	    toggleQueryCategoryFields( $self, value );
    });

	$themifyField.find('.query_category_single').change(function() {
		var $self = $(this), value = $self.val();
    	$self.parent().find('.query_category, .val').val( value );
		toggleQueryCategoryFields( $self, value );
    }).closest('.themify_field_row').addClass('query-field-visible');
    $themifyInfoLink.closest('.themify_field_row').addClass('query-field-visible');

	$('.query_category_single, .query_category').each(function(){
		var $self = $(this), value = $self.val();
		toggleQueryCategoryFields( $self, value );
	});
	$themifyInfoLink.closest('.themify_field_row').removeClass('query-field-hide');

	function toggleQueryCategoryFields( $obj, value ) {
		if ( '' != value ) {
			$obj.closest('.inside').find('.themify_field_row').removeClass('query-field-hide');
		} else {
			$obj.closest('.inside').find('.themify_field_row').not('.query-field-visible').addClass('query-field-hide');
		}
	}

    /**
     * Dropdownbutton
     */
    $('.dropdownbutton-group').each(function(){
    	var $elf = $(this);
    	$elf.on('mouseenter mouseleave', '.dropdownbutton-list', function(event){
    		event.preventDefault();
    		var $a = $(this);
    		if($a.hasClass('disabled')) {
    			return false;
    		}
    		if(event.type == 'mouseenter') {
    			if(!$a.children('.dropdownbutton').is(':visible')) {
    				$a.children('.dropdownbutton').show();
    			}
    		}
    		if(event.type == 'mouseleave') {
    			if($a.children('.dropdownbutton').is(':visible')) {
    				$a.children('.dropdownbutton').hide();
    			}
    		}
    	});
    	$elf.on('click', '.first-ddbtn a', function(event){
    		event.preventDefault();
    	});
    	$elf.on('click', '.ddbtn a', function(event){
    		event.preventDefault();
    		var ddimgsrc = $(this).find('img').attr('src'),
                val = $(this).data('val'),
                parent = $(this).closest('.dropdownbutton-list'),
                inputID = parent.attr('id');
    		$(this).closest('.dropdownbutton-list').find('.first-ddbtn img').attr('src', ddimgsrc);
    		$(this).closest('.dropdownbutton').hide();
    		$('input#' + inputID).val(val);
    		if(parent.next().hasClass('ddbtn-all')) {
			    var $ddbtnList, $ddbtnInput;
				if($elf.hasClass('multi-ddbtn')) {
					$ddbtnList = $('.multi-ddbtn-sub', $elf.parent().parent());
					$ddbtnInput = $('.multi-ddbtn-sub + input', $elf.parent().parent());
				} else {
					var inputVal = parent.next();
					$ddbtnList = inputVal.prev().siblings('.dropdownbutton-list');
					$ddbtnInput = inputVal.siblings('input');
				}

				if(parent.next().val() == 'yes') {
					$ddbtnList.addClass('disabled opacity-5');
					$ddbtnList.each(function(){
						var defIcon = $(this).data('def-icon');
						$(this).find('.first-ddbtn img').attr('src', defIcon);
					});
					$ddbtnInput.val(''); // clear value
				} else {
					$ddbtnList.removeClass('disabled opacity-5');
				}

    		}
    	});
    	// disabled other options on dom load
    	var selectAll = $elf.find('input.ddbtn-all');
    	if( selectAll.val() == 'yes' ) {
    		if($elf.hasClass('multi-ddbtn')) {
    			$('.multi-ddbtn-sub', $elf.parent().parent()).addClass('disabled opacity-5');
    		} else {
    			selectAll.prev().siblings('.dropdownbutton-list').addClass('disabled opacity-5');
    		}
    	}
    });

    /**
     * Post meta checkboxes
     */
    $('.post-meta-group').each(function(){
    	var $elf = $(this);
    	if($('.meta-all', $elf).prop('checked')){
    		$('.meta-sub', $elf).prop('disabled', true).parent().addClass('opacity-7');
    	}
    	$elf.on('click', '.meta-all', function(){
    		var $all = $(this);
			if($all.prop('checked')){
				//$all.prop('checked', true);
				$('.meta-sub', $elf).prop('disabled', true).prop('checked', false).parent().addClass('opacity-7');
			} else {
				//$all.prop('checked', false);
				$('.meta-sub', $elf).prop('disabled', false).parent().removeClass('opacity-7');
			}
    	});
	});

	/**
    * Post meta checkboxes - Mostly the same than before, but adding hidden field update.
    */
    $('.custom-post-meta-group').each(function(){
    	var $elf = $(this),
		    states_str = $('input[type="text"]', $elf).val(),
		    states = {},
		    state = [],
		    states_arr = [];

    	// Backwards compatibility
    	if('yes' == states_str){
    		$('.meta-all', $elf).val('yes').prop('checked', true);
    		$('.meta-sub', $elf).val('yes').prop('disabled', true).parent().addClass('opacity-7');
    	} else {
			// Parse string
			states_arr = states_str.split('&');
			for (var i = 0; i < states_arr.length; i++) {
				state = states_arr[i].split('=');
				states[state[0]] = state[1];
			}
		    for ( var meta in states ) {
			    if ( states.hasOwnProperty(meta) ) {
				    if ( 'yes' == states[meta] ) {
					    $('#' + meta, $elf).val('yes').prop('checked', true);
				    }
				}
			}
			if($('.meta-all', $elf).prop('checked')){
	    		$('.meta-sub', $elf).prop('disabled', true).prop('checked', false).parent().addClass('opacity-7');
	    	}
    	}
    	$elf.on('click', '.meta-all', function(){
    		var $all = $(this);
			if($all.prop('checked')){
				$('.meta-sub', $elf).val('yes').prop('disabled', true).prop('checked', false).parent().addClass('opacity-7');
				$all.val('yes');
			} else {
				$('.meta-sub', $elf).val('no').prop('disabled', false).parent().removeClass('opacity-7');
				$all.val('no');
			}
			savePostMetaStates($elf);
    	});
    	$elf.on('click', '.meta-sub', function(){
    		var $sub = $(this);
    		if($sub.prop('checked')){
				$sub.val('yes');
			} else {
				$sub.val('no');
			}
			savePostMetaStates($elf);
    	});
	});
	function savePostMetaStates($et){
		var state = '';
		$('input[type="checkbox"]', $et).each(function(){
			state += $(this).attr('id') + '=' + $(this).val() + '&';
		});
		$('input[type="text"]', $et).val(state.slice(0,-1));
	}

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

	});

	/**
	 * Date Picker
	 */
	$('.themifyDatePicker').each(function(){
		var $self = $(this),
			label = $self.data('label'),
			close = $self.data('close' ),
			dateformat = $self.data('dateformat' ),
			timeformat = $self.data('timeformat' ),
			timeseparator = $self.data('timeseparator' );
		$self.datetimepicker({
			showOn: 'both',
			showButtonPanel: true,
			closeButton: close,
			buttonText: label,
			dateFormat: dateformat,
			timeFormat: timeformat,
			stepMinute: 5,
			separator: timeseparator,
			onClose: function( date ) {
				if ( '' != date ) {
					$( '#' + $self.data('clear') ).addClass('themifyFadeIn');
				}
			},
			beforeShow: function() {
				$('#ui-datepicker-div').addClass( 'themifyDateTimePickerPanel' );
			}
		});
		$self.next().addClass('button');
	});
	/**
	 * Clear Date Button
	 */
	$body.on('click', '.themifyClearDate', function(e){
		e.preventDefault();
		var $self = $(this);
		$( '#' + $self.data('picker') ).val('');
		$self.removeClass('themifyFadeIn');
	});

	// Tabs for Custom Panel
	var $ilcHTabsLi = $('.ilc-htabs li');
	if($ilcHTabsLi.length > 1) {
		ilcTabs({ilctabs  : '#themify-meta-box-tabs'});
	} else {
		$('.ilc-tab').show();
		$ilcHTabsLi.addClass('select');
	}

	// set tabs cookie
	$('.ilc-htabs a').on('click', function(){
		themifySetCookie('themify-builder-tabs', $(this).attr('id'));
	});

	// active tabs cookie
	if( typeof(themifyGetCookie('themify-builder-tabs')) != 'undefined' && themifyGetCookie('themify-builder-tabs') !== null ){
		$( '#' + themifyGetCookie('themify-builder-tabs')).trigger('click');
	}

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

	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();

	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') );
			}
		});
		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;
	});
	$('.dismiss-import-notice').click(function(){
		$.ajax({
			url: ajaxurl,
			data: {
				action: 'themify_dismiss_import_notice',
				nonce: themify_js_vars.nonce
			},
			type: 'POST',
			success: function(){
				$('#demo-import-notice').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');
			}
		}
	}
});


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