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

if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

/**
 * Theme and Themify Framework Path and URI
 * @since 1.2.2
 */
defined( 'THEME_DIR' ) || define( 'THEME_DIR', get_template_directory() );
defined( 'THEME_URI' ) || define( 'THEME_URI', get_template_directory_uri() );
defined( 'THEMIFY_DIR' ) || define( 'THEMIFY_DIR', THEME_DIR . '/themify' );
defined( 'THEMIFY_URI' ) || define( 'THEMIFY_URI', THEME_URI . '/themify' );
defined( 'THEMIFYMIN' ) || define( 'THEMIFYMIN', defined('SCRIPT_DEBUG') && SCRIPT_DEBUG ? '' : '.min' );

// Load new Themify image script
if ( is_file( THEMIFY_DIR . '/img.php' ) ) {
	require_once THEMIFY_DIR . '/img.php';
}

/*  Utilities
/***************************************************************************/

/**
 * Convert array key name with square bracket to valid array
 * @param array $inputArr
 * @return array
 */
function themify_convert_brackets_string_to_arrays( $inputArr ) {
	$result = array();

	foreach ($inputArr as $key => $val) {
		$keyParts = preg_split('/[\[\]]+/', $key, -1, PREG_SPLIT_NO_EMPTY);

		$ref = &$result;

		while ($keyParts) {
				$part = array_shift($keyParts);

			if (!isset($ref[$part])) {
				$ref[$part] = array();
			}

			$ref = &$ref[$part];
		}

		$ref = $val;
	}
	return $result;
}

///////////////////////////////////////////
// Get CSS
///////////////////////////////////////////
function themify_get_css() {
	$data = themify_get_data();
	$output = '';
	/**
	 * Stores CSS rules
	 * @var string
	 */
	$module_styling = '';
	if( is_array( $data ) ) {
		$new_arr = array();
		foreach( $data as $name => $value ) {
			$array = explode( '-', $name );
			$path = '';
			foreach($array as $part){
				$path .= "[$part]";
			}
			$new_arr[ $path ] = $value;
		}
		$themify_config = themify_convert_brackets_string_to_arrays( $new_arr );

		if( isset( $themify_config['styling'] ) && is_array( $themify_config['styling'] ) ) {
			foreach( $themify_config['styling'] as $nav => $value ) {
				foreach( $value as $element => $val ) {
					$temp = '';
					foreach( $val as $attribute => $v ) {
						$attribute = str_replace("_", "-", $attribute);
						if( isset( $v['value'] ) && $v['value'] != '' ) {
							switch( $attribute ) {
								case "border":
									foreach( $v['value'] as $key => $val ) {
										if( '' == $val ) {
											if( strpos( $key, 'style' ) === false ) {
												if ( strpos( $key, 'color' ) === false ) {
													$v['value'][$key] = 0;
												} else {
													$v['value'][$key] = '000000';
												}
											} else {
												$v['value'][$key] = 'solid';
											}
										}
									}
									if( isset( $v['value']['checkbox'] ) && $v['value']['checkbox'] ) {
										$temp .= "border: ".$v['value']['same']."px ".$v['value']['same_style']." #".$v['value']['same_color'].";\n";
									} else {
										if( isset( $v['value']['top'] ) && isset( $v['value']['top_style'] ) && isset( $v['value']['top_color'] ) && $v['value']['top'] != '' && $v['value']['top_style'] != '' && $v['value']['top_color'] != '' ) {
											$temp .= "border-top: ".$v['value']['top']."px ".$v['value']['top_style']." #".$v['value']['top_color'].";\n";
										}
										if ( isset( $v['value']['right'] ) && isset( $v['value']['right_style'] ) && isset( $v['value']['right_color'] ) && $v['value']['right'] != '' && $v['value']['right_style'] != '' && $v['value']['right_color'] != '' ) {
											$temp .= "border-right: ".$v['value']['right']."px ".$v['value']['right_style']." #".$v['value']['right_color'].";\n";
										}
										if ( isset( $v['value']['bottom'] ) && isset( $v['value']['bottom_style'] ) && isset( $v['value']['bottom_color'] ) && $v['value']['bottom'] != '' && $v['value']['bottom_style'] != '' && $v['value']['bottom_color'] != '' ) {

											$temp .= "border-bottom: ".$v['value']['bottom']."px ".$v['value']['bottom_style']." #".$v['value']['bottom_color'].";\n";
										}
										if ( isset( $v['value']['left'] ) && isset( $v['value']['left_style'] ) && isset( $v['value']['left_color'] ) && $v['value']['left'] != '' && $v['value']['left_style'] != '' && $v['value']['left_color'] != '' ) {
											$temp .= "border-left: ".$v['value']['left']."px ".$v['value']['left_style']." #".$v['value']['left_color'].";\n";
										}
									}
								break;
								case "background-position":
									if ( isset( $v['value']['x'] ) && isset( $v['value']['y'] ) && $v['value']['x'] != '' && $v['value']['y'] ) {
										foreach ( $v['value'] as $key => $val ) {
											if ( $val == '' ) {
												$v['value'][$key] = 0;
											}
										}
										$temp .= $attribute.": ";
										$temp .= $v['value']['x']." ".$v['value']['y'].";\n";
									}
								break;
								case "padding":
									if ( isset( $v['value']['checkbox'] ) && $v['value']['checkbox'] ) {
										$temp .= $attribute.": ";
										$temp .= $v['value']['same']."px".";\n";
									} else {
										if ( isset( $v['value']['top'] ) &&  $v['value']['top'] != '' ) {
											$temp .= "padding-top: ".$v['value']['top']."px;\n";
										}
										if ( isset( $v['value']['right'] ) &&  $v['value']['right'] != '' ) {
											$temp .= "padding-right: ".$v['value']['right']."px;\n";
										}
										if ( isset( $v['value']['bottom'] ) &&  $v['value']['bottom'] != '' ) {
											$temp .= "padding-bottom: ".$v['value']['bottom']."px;\n";
										}
										if ( isset( $v['value']['left'] ) &&  $v['value']['left'] != '' ) {
											$temp .= "padding-left: ".$v['value']['left']."px;\n";
										}
									}
								break;
								case "margin":
									if ( isset( $v['value']['checkbox'] ) && $v['value']['checkbox'] ) {
										$temp .= $attribute.": ";
										$temp .= $v['value']['same']."px".";\n";
									} else {
										if ( isset( $v['value']['top'] ) && $v['value']['top'] != '' ) {
											$temp .= "margin-top: ".$v['value']['top']."px;\n";
										}
										if ( isset( $v['value']['right'] ) && $v['value']['right'] != '' ) {
											$temp .= "margin-right: ".$v['value']['right']."px;\n";
										}
										if ( isset( $v['value']['bottom'] ) && $v['value']['bottom'] != '' ) {
											$temp .= "margin-bottom: ".$v['value']['bottom']."px;\n";
										}
										if ( isset( $v['value']['left'] ) && $v['value']['left'] != '' ) {
											$temp .= "margin-left: ".$v['value']['left']."px;\n";
										}
									}
								break;
								case "color":
									if ( isset( $v['value']['value'] ) && $v['value']['value'] != '' && $v['value']['value'] != ' ' ) {
										$temp .= $attribute.": ";
										$temp .= "#".$v['value']['value'].";\n";
									}
								break;
								case "background-color":
									if ( isset( $v['value']['transparent'] ) && $v['value']['transparent'] ) {
										$temp .= $attribute.": transparent;\n";
									} elseif ( isset( $v['value']['value'] ) && $v['value']['value'] != '' && $v['value']['value'] != ' ' ) {
										$temp .= $attribute.": ";
										$temp .= "#".$v['value']['value'].";\n";
									}
								break;
								case "background-image":
									if ( isset( $v['value']['value'] ) && $v['value']['value'] != '' && $v['value']['value'] != ' ' ) {
										$temp .= $attribute.": ";
										$temp .= "url(".$v['value']['value'].")".";\n";
									} elseif ( isset( $v['value']['none'] ) && 'on' == $v['value']['none'] ) {
										$temp .= $attribute.": ";
										$temp .= "none;\n";
									}
								break;
								case "background-repeat":
									if ( isset( $v['value']['value'] ) && $v['value']['value'] != '' && $v['value']['value'] != ' ' ) {
										$temp .= $attribute.": ";
										$temp .= $v['value']['value'].";\n";
									}
								break;
								case "font-family":
									if ( isset( $v['value']['value'] ) && $v['value']['value'] != '' && $v['value']['value'] != ' ' ) {
										$temp .= $attribute.": ";

										// check google fonts
										if ( themify_is_google_fonts( $v['value']['value'] ) ) {
											$temp .= '"' . $v['value']['value'] . '"' .";\n";
										} else {
											$temp .= $v['value']['value'] .";\n";
										}
									}
								break;
								case "line-height":
									if ( isset( $v['value']['value'] ) && $v['value']['value'] != '' && $v['value']['value'] != ' ' ) {
										$temp .= $attribute.": ";
										$temp .= $v['value']['value'].$v['value']['unit'].";\n";
									}
								break;
								case "position":
									if ( isset( $v['value']['value'] ) && $v['value']['value'] != '' && $v['value']['value'] != ' ' ) {
										$temp .= $attribute.": ";
										$temp .= $v['value']['value'].";\n";
										if($v['value']['value'] == 'absolute' || $v['value']['value'] == 'fixed'){
											if($v['value']['x_value'] != '' && $v['value']['x_value'] != ' '){
												$temp .= $v['value']['x'].": ".$v['value']['x_value']."px;\n";
											}
											if($v['value']['y_value'] != '' && $v['value']['y_value'] != ' '){
												$temp .= $v['value']['y'].": ".$v['value']['y_value']."px;\n";
											}
										}
									}
								break;
								default:
									if ( isset( $v['value']['value'] ) && $v['value']['value'] != '' && $v['value']['value'] != ' ' ) {
										$temp .= $attribute.": ";
										$temp .= $v['value']['value'];
										if(isset($v['value']['unit'])){
											$temp .= $v['value']['unit'];
										}
										$temp .= ";\n";
									}
								break;
							}
						}
					}
					if($temp != '' && $temp != ' '){

						$style_selector = themify_get_styling_selector('id', $element, $nav, true);
						if ( $style_selector != '' ) {
							$module_styling .= $style_selector." {\n";
							$module_styling .= $temp;
							$module_styling .= "}\n\n";
						}
					}
				}
			}
		}
	} else {
		$output = '<style type="text/css">/* ' . __('No Values in the Database', 'themify') . ' */</style>';
	}
	$module_styling_before = "<!-- modules styling -->\n<style type='text/css'>\n";
	$module_styling_after = "</style>";
	if( '' != $module_styling ){
		$output .= $module_styling_before . $module_styling . $module_styling_after;
	}
	echo "\n\n".$output;
}

///////////////////////////////////////////
// Strip
///////////////////////////////////////////
function themify_strip($startTag, $endTag, $text, $pos){
	if(!is_integer($pos)){
		$pos = false;
		return false;
	}
	$pos1 = strpos($text,$startTag,$pos);
	if(!is_integer($pos1)){
		$pos = false;
		return false;
	}
	$pos1 += strlen($startTag);
	$pos2 = strpos($text,$endTag,$pos1);
	if(!is_integer($pos2)){
		$pos = false;return false;
	}
	$res = substr($text,$pos1,$pos2-$pos1);
	$pos = $pos2 + strlen($endTag);
	return $res;
}

///////////////////////////////////////////
// Scrub Function
///////////////////////////////////////////
function themify_scrub_func($string=""){
	return str_replace(array(' ', '/', ','), array('_', '_', '-'), strtolower($string));
}

///////////////////////////////////////////
// Scrub
///////////////////////////////////////////
function themify_scrub($string=""){
	return str_replace(array('#','-',' ','.',':',',','[',']','=','<','>'), array('_id_','_dash_','_space_','_class_','_colon_','_comma_','_opensquare_','_closesquare_','_equal_','_openbracket_','_closebracket_'), $string);
}

///////////////////////////////////////////
// Scrub Decode
///////////////////////////////////////////
function themify_scrub_decode( $string = '' ) {
	return str_replace(array('_id_','_dash_','_space_','_class_','_colon_','_comma_','_opensquare_','_closesquare_','_equal_','_openbracket_','_closebracket_'), array('#','-',' ','.',':',',','[',']','=','<','>'), $string);
}

/**
 * Enqueue JS and CSS for Themify settings page and meta boxes
 * @param String $page
 * @since 1.1.1
 *******************************************************/
function themify_enqueue_scripts($page){
	$pagenow = isset( $_GET['page'] ) ? $_GET['page'] : '';

	// Don't do anything while updating the theme
	if ( 'themify' == $pagenow && isset( $_GET['action'] ) && 'upgrade' == $_GET['action'] ) {
		return;
	}

	global $typenow;

	$types = themify_post_types();
	$pages = apply_filters( 'themify_top_pages', array( 'post.php', 'post-new.php', 'toplevel_page_themify', 'nav-menus.php' ) );
	$pagenows = apply_filters( 'themify_pagenow', array( 'themify' ) );

	wp_register_script( 'meta-box-tabs', THEMIFY_URI . '/js/meta-box-tabs.js', array('jquery'), '1.0', true );
	wp_register_script( 'media-library-browse', THEMIFY_URI . '/js/media-lib-browse.js', array('jquery'), '1.0', true );
	wp_register_style( 'themify-ui',  THEMIFY_URI . '/css/themify-ui.css', array(), THEMIFY_VERSION );
	wp_register_style( 'themify-ui-rtl',  THEMIFY_URI . '/css/themify-ui-rtl.css', array(), THEMIFY_VERSION );
	wp_register_style( 'themify-colorpicker', THEMIFY_URI . '/css/jquery.minicolors.css', array(), THEMIFY_VERSION );
	wp_register_script( 'validate', THEMIFY_URI . '/js/jquery.validate.pack.js', array('jquery'), THEMIFY_VERSION );
	wp_register_script( 'themify-colorpicker', THEMIFY_URI . '/js/jquery.minicolors.js', array('jquery'), THEMIFY_VERSION );
	wp_register_script( 'themify-scripts', THEMIFY_URI . '/js/scripts.js', array('jquery'), THEMIFY_VERSION );
	wp_register_script( 'themify-plupload', THEMIFY_URI . '/js/plupload.js', array('jquery', 'themify-scripts'), THEMIFY_VERSION);
	wp_register_script( 'gallery-shortcode', THEMIFY_URI . '/js/gallery-shortcode.js', array('jquery', 'themify-scripts'), THEMIFY_VERSION, true );
	wp_register_style ( 'magnific', THEMIFY_URI . '/css/lightbox.css', array(), THEMIFY_VERSION );
	wp_register_script( 'magnific', THEMIFY_URI . '/js/lightbox.js', array('jquery'), THEMIFY_VERSION, true );

	// Custom Write Panel
	if( ($page == 'post.php' || $page == 'post-new.php') && in_array($typenow, $types) ){
		wp_enqueue_script( 'meta-box-tabs' );
		wp_enqueue_script( 'media-library-browse' );
	}

	// Register icon assets for later enqueueing.
	wp_register_style( 'themify-font-icons-css', THEMIFY_URI . '/fontawesome/css/font-awesome.min.css', array(), THEMIFY_VERSION );
	wp_register_script( 'themify-font-icons-js', THEMIFY_URI . '/js/themify.font-icons-select.js', array( 'jquery' ) );
	wp_localize_script( 'themify-font-icons-js', 'themifyIconPicker', array(
		'icons_list' => THEMIFY_URI . '/fontawesome/list.html',
	) );
	wp_register_style( 'themify-icons', THEMIFY_URI . '/themify-icons/themify-icons.css', array(), THEMIFY_VERSION );
	wp_register_style( 'google-fonts-admin', themify_https_esc('http://fonts.googleapis.com/css'). '?family=Open+Sans:400,300,600|Montserrat');

	// Settings Panel
	if( $page == 'toplevel_page_themify' ){
		wp_enqueue_script( 'jquery-ui-sortable' );
	}
	if( in_array( $page, $pages ) ) {
		//Enqueue styles
		wp_enqueue_style( 'themify-ui' );
		if ( is_rtl() ) {
			wp_enqueue_style( 'themify-ui-rtl' );
		}
		wp_enqueue_style( 'themify-colorpicker' );

		//Enqueue scripts
		wp_enqueue_script( 'jquery' );
		wp_enqueue_script( 'jquery-ui-core' );
		wp_enqueue_script( 'jquery-ui-tabs' );
		wp_enqueue_script( 'jquery-ui-slider' );
		wp_enqueue_script( 'json2' );
		wp_enqueue_script( 'plupload-all' );
		wp_enqueue_script( 'validate' );
		wp_enqueue_script( 'themify-colorpicker' );
		if( in_array($typenow, $types) || in_array( $pagenow, $pagenows ) ){
			//Don't include Themify JavaScript if we're not in one of the Themify-managed pages
			wp_enqueue_script( 'themify-scripts' );
			wp_enqueue_script( 'themify-plupload' );
		}
		// Enqueue font icon assets.
		themify_font_icons_admin_assets();
		wp_enqueue_style ( 'magnific' );
		wp_enqueue_script( 'magnific' );
	}
	//Inject variable values to scripts.js previously enqueued
	wp_localize_script('themify-scripts', 'themify_js_vars', array(
			'themify' 	=> THEMIFY_URI,
			'nonce' 	=> wp_create_nonce('ajax-nonce'),
			'admin_url' => admin_url( 'admin.php?page=themify' ),
			'ajax_url' 	=> admin_url( 'admin-ajax.php' ),
			'app_url'	=> get_template_directory_uri() . '/themify/',
			'theme_url'	=> get_template_directory_uri() . '/',
			'blog_url'	=> site_url() . '/'
		)
	);

	// Inject variable for Plupload
	$global_plupload_init = array(
	    'runtimes'				=> 'html5,flash,silverlight,html4',
	    'browse_button'			=> 'plupload-browse-button', // adjusted by uploader
	    'container' 			=> 'plupload-upload-ui', // adjusted by uploader
	    'drop_element' 			=> 'drag-drop-area', // adjusted by uploader
	    'file_data_name' 		=> 'async-upload', // adjusted by uploader
	    'multiple_queues' 		=> true,
	    'max_file_size' 		=> wp_max_upload_size() . 'b',
	    'url' 					=> admin_url('admin-ajax.php'),
	    'flash_swf_url' 		=> includes_url('js/plupload/plupload.flash.swf'),
	    'silverlight_xap_url' 	=> includes_url('js/plupload/plupload.silverlight.xap'),
	    'filters' 				=> array( array(
	    	'title' => __('Allowed Files', 'themify'), 'extensions' => 'jpg,jpeg,gif,png,ico,zip,txt,svg') ),
	    'multipart' 			=> true,
	    'urlstream_upload' 		=> true,
	    'multi_selection' 		=> false, // added by uploader
	     // additional post data to send to our ajax hook
	    'multipart_params' 		=> array(
	        '_ajax_nonce' 		=> '', // added by uploader
	        'action' 			=> 'themify_plupload', // the ajax action name
	        'imgid' 			=> 0 // added by uploader
	    )
	);
	wp_localize_script('themify-scripts', 'global_plupload_init', $global_plupload_init);

	wp_localize_script('themify-scripts', 'themify_lang', array(
			'confirm_reset_styling'	=> __('Are you sure you want to reset your theme style?', 'themify'),
			'confirm_reset_settings' => __('Are you sure you want to reset your theme settings?', 'themify'),
			'confirm_refresh_webfonts'	=> __('Are you sure you want to refresh the Google Fonts list? This will also save the current settings.', 'themify'),
			'check_backup' => __('Make sure to backup before upgrading. Files and settings may get lost or changed.', 'themify'),
			'confirm_delete_image' => __('Do you want to delete this image permanently?', 'themify'),
			'invalid_login' => __('Invalid username or password.<br/>Contact <a href="http://themify.me/contact">Themify</a> for login issues.', 'themify'),
			'unsuscribed' => __('Your membership might be expired. Login to <a href="http://themify.me/member">Themify</a> to check.', 'themify'),
			'enable_zip_upload' => sprintf(
				__('Go to your <a href="%s">Network Settings</a> to enable <strong>zip</strong>, <strong>txt</strong> and <strong>svg</strong> extensions in <strong>Upload file types</strong> field.', 'themify'),
				esc_url( network_admin_url('settings.php').'#upload_filetypes' )
			),
			'filesize_error' => __('The file you are trying to upload exceeds the maximum file size allowed.', 'themify'),
			'filesize_error_fix' => sprintf(
				__('Go to your <a href="%s">Network Settings</a> and increase the value of the <strong>Max upload file size</strong>.', 'themify'),
				esc_url( network_admin_url('settings.php').'#fileupload_maxk' )
			),
			'confirm_demo' => __( 'This will import demo and override current Themify panel settings.', 'themify' ),
			'confirm_clear_builder_cache' => esc_html__( 'This will clear all builder caches. click ok to continue.', 'themify' )
		)
	);
}

/**
 * Checks if the selected skin is in /skins/ directory in theme root folder.
 *
 * @since 2.1.6
 *
 * @return bool
 */
function themify_is_theme_skin() {
	static $theme_skin;

	if ( ! isset( $theme_skin ) ) {
		$current_skin = themify_get( 'skin' );
		$parsed_skin = parse_url( $current_skin, PHP_URL_PATH );
		$basedir_skin = basename( dirname( $parsed_skin ) );
		if ( is_file( THEME_DIR . '/skins/' . $basedir_skin . '/' . basename( $parsed_skin ) ) ) {
			$theme_skin = $current_skin;
		} else {
			$theme_skin = '';
		}
	}

	return $theme_skin;
}

/**
 * Enqueues the chosen skin, if there was one selected and custom_style.css if it exists
 * @since 1.7.4
 */
function themify_enqueue_framework_assets() {
	// Skin stylesheet
	if ( $skin = themify_is_theme_skin() ) {
		wp_enqueue_style( 'themify-skin', themify_https_esc( $skin ), array( 'theme-style' ), THEMIFY_VERSION );
	}

	// User stylesheet
	if ( is_file( get_template_directory() . '/custom_style.css' ) ) {
		wp_enqueue_style( 'custom-style', THEME_URI . '/custom_style.css', array( 'theme-style' ), THEMIFY_VERSION );
	}

	// Enqueue font icon stylesheet
	wp_enqueue_style( 'themify-icon-font', THEMIFY_URI . '/fontawesome/css/font-awesome.min.css', array(), THEMIFY_VERSION );

	// MediaElement
	wp_deregister_style( 'mediaelement' );
	wp_register_style( 'mediaelement', THEMIFY_URI . '/css/themify-mediaelement.min.css' );

	wp_deregister_style( 'wp-mediaelement' );
	wp_register_style( 'wp-mediaelement', THEMIFY_URI . '/css/themify-wp-mediaelement.min.css', array( 'mediaelement' ) );

	wp_deregister_script( 'mediaelement' );
	wp_register_script( 'mediaelement', THEMIFY_URI . '/js/themify-mediaelement-and-player.min.js', array( 'jquery' ), false, true );

	wp_deregister_script( 'wp-mediaelement' );
	wp_register_script( 'wp-mediaelement', THEMIFY_URI . '/js/themify-wp-mediaelement.min.js', array( 'mediaelement' ), false, true );
}


/**
 * Outputs the module styling and then the Custom CSS module content.
 * @since 1.7.4
 */
function themify_output_framework_styling() {
	// Module Styling
	themify_get_css();

	// Custom CSS
	if ( $custom_css = themify_get( 'setting-custom_css' ) ) {
		echo "\n\n<!-- custom css -->\n\n<style type='text/css'>$custom_css</style>";
	}
	add_filter( 'style_loader_tag', 'themify_add_style_property', 15, 4 );
}
/**
 * Add property stylesheet attribute for footer styles
 */ 
function themify_add_style_property($html,$handle,$href,$media){
	global $wp_styles;
	$wp_styles->add_data( $handle, 'property', 'stylesheet' );
	return $html;
}


/**
 * XML 2 Array Function
 * @param $string
 */
function themify_xml2array( &$string ) {
	$parser = xml_parser_create();
	xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
	xml_parse_into_struct($parser, $string, $vals, $index);
	xml_parser_free($parser);
	$mnary=array();
	$ary=&$mnary;
	foreach ($vals as $r) {
		$t=$r['tag'];
		if ($r['type']=='open') {
			if (isset($ary[$t])) {
				if (isset($ary[$t][0])) $ary[$t][]=array(); else $ary[$t]=array($ary[$t], array());
				$cv=&$ary[$t][count($ary[$t])-1];
			} else $cv=&$ary[$t];
			if (isset($r['attributes'])) {foreach ($r['attributes'] as $k=>$v) $cv['_a'][$k]=$v;}
			$cv['_c']=array();
			$cv['_c']['_p']=&$ary;
			$ary=&$cv['_c'];
		} elseif ($r['type']=='complete') {
			if (isset($ary[$t])) { // same as open
				if (isset($ary[$t][0])) $ary[$t][]=array(); else $ary[$t]=array($ary[$t], array());
				$cv=&$ary[$t][count($ary[$t])-1];
			} else $cv=&$ary[$t];
			if (isset($r['attributes'])) {foreach ($r['attributes'] as $k=>$v) $cv['_a'][$k]=$v;}
			$cv['_v']=(isset($r['value']) ? $r['value'] : '');

		} elseif ($r['type']=='close') {
			$ary=&$ary['_p'];
		}
	}
	_themify_del_p($mnary);
	return $mnary;
}

///////////////////////////////////////////
// _Internal: Remove recursion in result array
///////////////////////////////////////////
function _themify_del_p(&$ary) {
	foreach ($ary as $k=>$v) {
		if ($k==='_p') unset($ary[$k]);
		elseif (is_array($ary[$k])) _themify_del_p($ary[$k]);
	}
}

///////////////////////////////////////////
// Create ZIP Package
///////////////////////////////////////////
if(class_exists('ZipArchive')){
	function themify_create_zip($files = array(),$destination = "",$overwrite = false) {
		if(file_exists($destination) && !$overwrite) { return false; }
			$valid_files = array();
			if(is_array($files)) {
				foreach($files as $file) {
					if(file_exists($file)) {
						$valid_files[] = $file;
					}
				}
			}
		if(count($valid_files)) {
			$zip = new ZipArchive();
			$zip_opened = $overwrite ? $zip->open( $destination, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE ) : $zip->open( $destination, ZIPARCHIVE::CREATE );
			if( $zip_opened !== true ) {
				return false;
			}
			foreach($valid_files as $file) {
				$zip->addFile($file,pathinfo($file,PATHINFO_BASENAME));
			}
			$zip->close();
			return file_exists($destination);
		} else {
			return false;
		}
	}
}

///////////////////////////////////////////
// Build Custom Write Panels
///////////////////////////////////////////
function themify_build_write_panels($args){
	global $themify_write_panels;
	if(is_array($args)){
		$themify_write_panels = $args;
		add_action('admin_menu', 'themify_create_meta_boxes');
		add_action('save_post', 'themify_save_postdata');
		add_action('pre_post_update', 'themify_save_postdata');
	}
}

///////////////////////////////////////////
// Call Custom Write Panel
///////////////////////////////////////////
function themify_create_meta_boxes() {
	global $themify_write_panels;
	$themify_write_panels = apply_filters('themify_do_metaboxes', $themify_write_panels);
	if(function_exists('add_meta_box') && is_array($themify_write_panels)){
		foreach($themify_write_panels as $args){
			if($args['pages'] != ''){
				$themify_meta_page = $args['pages'];
			} else {
				$themify_meta_page = 'post';
			}
			$pages = explode(",", $themify_meta_page);
			foreach($pages as $page){
				add_meta_box( 'themify-meta-boxes', __('Themify Custom Panel', 'themify'), 'themify_meta_boxes', trim($page), 'normal', 'high' );
			}
		}
	}
}

/*
 * Protect $themify_write_panels fields
 * This will hide these fields from Custom Fields panel
 *
 * @since 1.8.2
 */
function themify_protected_meta( $protected, $meta_key, $meta_type ) {
	global $themify_protected_meta;

	if( is_array( $themify_protected_meta ) && in_array( $meta_key, $themify_protected_meta ) ) {
		$protected = true;
	}

	return $protected;
}

/**
 * Compiles a list of fields managed by the Themify Custom Panels
 * and store the result in global $themify_protected_meta variable.
 * This will prevent the options from appearing in Custom Fields metabox.
 *
 * @since 1.8.2
 */
function themify_compile_protected_meta_list() {
	global $themify_protected_meta, $themify_write_panels;

	$list = array();
	if( ! empty( $themify_write_panels ) ) : foreach( $themify_write_panels as $metabox ) :
		if( ! empty( $metabox['options'] ) ) { foreach( $metabox['options'] as $key => $field ) {
			if( $field['type'] == 'multi' ) {
				$list = array_merge( $list, wp_list_pluck( $field['meta']['fields'], 'name' ) );
			} else {
				$list[] = $field['name'];
			}
		} }
	endforeach; endif;

	$themify_protected_meta = array_unique( $list );
}

///////////////////////////////////////////
// Build Custom Write Panel
///////////////////////////////////////////
function themify_meta_boxes() {

	global $post, $themify_write_panels, $typenow;

echo '<div id="themify-meta-box-tabs">';
		echo '<ul class="ilc-htabs themify-tabs-heading">';
		foreach( $themify_write_panels as $write_panel ) {
			if( trim( $write_panel['pages'] ) == $typenow ) {
				$panel_id = isset( $write_panel['id'] )? $write_panel['id']: sanitize_title( $write_panel['name'] );
				echo '<li><span><a id="' . esc_attr( $panel_id . 't' ) . '" href="' . esc_attr( '#' . $panel_id ) . '">' . esc_html( $write_panel['name'] ) . '</a></span></li>';
			}
		}
		echo '</ul>';
		echo '<div class="ilc-btabs themify-tabs-body">';
		foreach( $themify_write_panels as $write_panel ) {

			$pages = explode(",", $write_panel['pages']);
			$check = false;

			foreach( $pages as $page ) {
				if( get_post_type($post) ) {
					if(get_post_type($post) == $page){
						$check = true;
					}
				} else {
					if( (trim($page) == 'post' && $_GET['post_type'] == '') || $_GET['post_type'] == trim($page) ) {
						$check = true;
					}
				}
			}

			if($check){
				$panel_id = isset( $write_panel['id'] )? $write_panel['id']: sanitize_title( $write_panel['name'] );
			?>
			<div id="<?php echo esc_attr( $panel_id ); ?>" class="ilc-tab themify_write_panel">

			<div class="inside">

				<input type="hidden" name="themify_proper_save" value="true" />

				<?php $themify_custom_panel_nonce = wp_create_nonce("themify-custom-panel"); ?>

				<!-- alerts -->
				<div class="alert"></div>
				<!-- /alerts -->

				<?php
				foreach($write_panel['options'] as $meta_box):
					$meta_value = isset($meta_box['name']) ? get_post_meta($post->ID, $meta_box['name'], true) : '';
	                $toggle_class = '';
	                $ext_attr = '';
					if( isset($meta_box['toggle']) ){
	                	$toggle_class .= 'themify-toggle ';
	                	$toggle_class .= (is_array($meta_box['toggle'])) ? implode(' ', $meta_box['toggle']) : $meta_box['toggle'];
	                    if ( is_array( $meta_box['toggle'] ) && in_array( '0-toggle', $meta_box['toggle'] ) ) {
		                    $toggle_class .= ' default-toggle';
	                    }
	                }
					if ( isset( $meta_box['class'] ) ) {
						$toggle_class .= ' ';
						$toggle_class .= is_array( $meta_box['class'] ) ? implode( ' ', $meta_box['class'] ) : $meta_box['class'];
					}
					$data_hide = '';
					if ( isset( $meta_box['hide'] ) ) {
						$data_hide = is_array( $meta_box['hide'] ) ? implode( ' ', $meta_box['hide'] ) : $meta_box['hide'];
					}
	                if( isset($meta_box['default_toggle']) && $meta_box['default_toggle'] == 'hidden' ){
	                	$ext_attr = 'style="display:none;"';
	                }
	                if( isset($meta_box['enable_toggle']) && $meta_box['enable_toggle'] == true ) {
	                	$toggle_class .= ' enable_toggle';
	                }

					///////////////////////////////////////////
					// Image Template
					///////////////////////////////////////////
					if($meta_box['type'] == 'image'){ ?>

						<input type="hidden" name="<?php echo esc_attr( $meta_box['name'] . '_noncename' ); ?>" id="<?php echo esc_attr( $meta_box['name'] . '_noncename' ); ?>" value="<?php echo wp_create_nonce( plugin_basename(__FILE__) ); ?>" />
						<div class="themify_field_row clearfix featimgcontrol <?php echo esc_attr( $toggle_class ); ?>" <?php echo esc_attr( $ext_attr ); ?> <?php if ( ! empty( $data_hide ) ) : echo 'data-hide="' . esc_attr( $data_hide ) . '"'; endif; ?>>

							<div class="themify_field_title"><?php echo esc_html( $meta_box['title'] ); ?></div>

							<div class="themify_field">

								<?php
								/** Parameters for the uploader @var Array */
								$featimg_uploader_args = array(
									'tomedia' => true,
									'topost' => $post->ID,
									'medialib' => true,
									'fields' => $meta_box['name']
								);

								$themify_featimg_field = themify_is_thumbnail_field($meta_box['name']);
								if( $themify_featimg_field ) {
									$featimg_uploader_args['featured'] = $meta_box['name'];
								}
								$this_attachment_id = '';
								if( has_post_thumbnail() && $themify_featimg_field ) {
									$this_attachment_id = get_post_thumbnail_id($post->ID);
									$thumb = wp_get_attachment_image_src( $this_attachment_id );
									$thumb_src = $thumb[0];
								} elseif( !$themify_featimg_field && ($this_attachment_id = get_post_meta($post->ID, '_'.$meta_box['name'].'_attach_id', true)) ){
									$thumb = wp_get_attachment_image_src( $this_attachment_id );
									$thumb_src = $thumb[0];
								} else {
									$thumb_src = $meta_value;
								}
								?>

								<div id="<?php echo esc_attr( 'remove-' . $meta_box['name'] ); ?>" class="themify_featimg_remove <?php if( $thumb_src == '' ) echo 'hide' ?>">
									<a data-attachid="<?php echo esc_attr( get_post_meta( $post->ID, '_' . $meta_box['name'] . '_attach_id', true ) ); ?>" href="#"><?php _e( 'Remove image', 'themify' ); ?></a>
								</div>

								<?php
								if( $thumb_src ) {
									$thumb = wp_get_attachment_image_src( $this_attachment_id, 'full');
									$full_src = ( false !== $thumb ) ? $thumb[0] : $thumb_src;
									echo '<div class="themify_upload_preview" style="display:block;"><a href="' . esc_url( $full_src ) . '" target="_blank"><img src="' . esc_url( $thumb_src ) . '" width="40" alt="' . esc_attr__( 'Post Image', 'themify' ) . '" /></a></div>';
								} else {
									echo '<div class="themify_upload_preview"></div>';
								}
								?>

								<!-- Field storing URL -->
								<input type="hidden" id="<?php echo esc_attr( $meta_box['name'] ); ?>" name="<?php echo esc_attr( $meta_box['name'] ); ?>" value="<?php echo esc_attr( $meta_value ); ?>" size="55" class="themify_input_field themify_upload_field" />

								<div class="themify_upload_buttons">
									<?php themify_uploader($meta_box['name'], $featimg_uploader_args) ?>
								</div>

								<?php if ( isset( $meta_box['description'] ) ) : ?>
									<span class="themify_field_description"><?php echo wp_kses_post( $meta_box['description'] ); ?></span>
								<?php endif; // meta_box description ?>
							</div>

							<script type="text/javascript">
								jQuery(function($){
									var $remove = $('#remove-<?php echo esc_js( $meta_box['name'] ); ?>');
									$remove.find('a').on('click', function(e){
										e.preventDefault();
										var $this = $(this);
										$.post(
											ajaxurl, {
												'action': 'themify_remove_post_image',
												'postid': <?php echo esc_js( $post->ID ); ?>,
												<?php if( !$themify_featimg_field )
														echo '\'attach_id\': $this.data(\'attachid\'),'; ?>
												'customfield' : '<?php echo esc_js( $meta_box['name'] ); ?>',
												'nonce' : '<?php echo esc_js( $themify_custom_panel_nonce ); ?>'
											},
											function() {
												$this.parent().parent().find('.themify_upload_field').val('');
												$this.parent().parent().find('.themify_upload_preview').fadeOut();
												$remove.addClass('hide');
											}
										);
									});
								});
							</script>
						</div><!--/themify_field_row -->

					<!-- Themify Image END -->
					<?php
					///////////////////////////////////////////
					// Audio Template
					///////////////////////////////////////////
					} elseif ( 'audio' == $meta_box['type'] ) { ?>

						<input type="hidden" name="<?php echo esc_attr( $meta_box['name'] . '_noncename' ); ?>" id="<?php echo esc_attr( $meta_box['name'] . '_noncename' ); ?>" value="<?php echo wp_create_nonce( plugin_basename(__FILE__) ); ?>" />
						<div class="themify_field_row clearfix <?php echo esc_attr( $toggle_class ); ?>" <?php echo esc_attr( $ext_attr ); ?> <?php if ( ! empty( $data_hide ) ) : echo 'data-hide="' . esc_attr( $data_hide ) . '"'; endif; ?>>

							<div class="themify_field_title"><?php echo esc_html( $meta_box['title'] ); ?></div>

								<div class="themify_field">

								<?php
								/** Parameters for the uploader @var Array */
								$featimg_uploader_args = array(
									'tomedia'  => true,
									'topost'   => $post->ID,
									'medialib' => true,
									'fields'   => $meta_box['name'],
									'formats'  => 'mp3,m4a,ogg,wav,wma',
									'type'     => 'audio',
								);

								$themify_featimg_field = themify_is_thumbnail_field($meta_box['name']);
								if( $themify_featimg_field ) {
									$featimg_uploader_args['featured'] = $meta_box['name'];
								}
								?>

								<div id="<?php echo esc_attr( 'remove-' . $meta_box['name'] ); ?>" class="themify_featimg_remove themify_video_remove <?php if( $meta_value == '' ) echo 'hide' ?>">
									<a href="#"><?php _e('Remove Audio', 'themify'); ?></a>
								</div>

								<!-- Field storing URL -->
								<input type="text" id="<?php echo esc_attr( $meta_box['name'] ); ?>" name="<?php echo esc_attr( $meta_box['name'] ); ?>" value="<?php echo esc_attr( $meta_value ); ?>" size="55" class="themify_input_field themify_upload_field" />

								<div class="themify_upload_buttons">
									<?php themify_uploader($meta_box['name'], $featimg_uploader_args) ?>
								</div>

								<?php if ( isset( $meta_box['description'] ) ) : ?>
									<span class="themify_field_description"><?php echo wp_kses_post( $meta_box['description'] ); ?></span>
								<?php endif; // meta_box description ?>
							</div>
						</div><!--/themify_field_row -->

						<script type="text/javascript">
						jQuery(function($){
							$('#remove-<?php echo esc_js( $meta_box['name'] ); ?> a').on('click', function(e){
		                    	e.preventDefault();
								var $self = $(this).parent();
								$self.parent().find('.themify_upload_field').val('');
								$self.addClass('hide');

								$.post(
									ajaxurl, {
										'action': 'themify_remove_audio',
										'postid': <?php echo esc_js( $post->ID ); ?>,
										'customfield' : '<?php echo esc_js( $meta_box['name'] ); ?>',
										'nonce' : '<?php echo esc_js( $themify_custom_panel_nonce ); ?>'
									},
									function() {
										$self.parent().find('.themify_upload_field').val('');
										$self.addClass('hide');
									}
								);
		                  	});
						});
						</script>


					<?php
					///////////////////////////////////////////
					// Image Size Dropdown Template
					///////////////////////////////////////////
					} else if($meta_box['type'] == 'featimgdropdown'){
	                    /** Define WP Featured Image sizes + blank + Themify's image script
		 				 * @var array */
						$themify_fi_sizes = themify_get_image_sizes_list();
						?>
						<div <?php if(!themify_check('setting-img_settings_use') || ( isset( $meta_box['class'] ) && 'hidden' == $meta_box['class'] )) echo 'style="display:none"'; ?> class="<?php echo esc_attr( $meta_box['type'] ); ?> clear">
							<input type="hidden" name="<?php echo esc_attr( $meta_box['name'] . '_noncename' ); ?>" id="<?php echo esc_attr( $meta_box['name'] . '_noncename' ); ?>" value="<?php echo wp_create_nonce( plugin_basename(__FILE__) ); ?>" />
							<div class="themify_field_row clearfix <?php echo esc_attr( $toggle_class ); ?>" <?php echo esc_attr( $ext_attr ); ?> <?php if ( ! empty( $data_hide ) ) : echo 'data-hide="' . esc_attr( $data_hide ) . '"'; endif; ?>>

								<div class="themify_field_title"><?php echo esc_html( $meta_box['title'] ); ?></div>

								<div class="themify_field">
									<select name="<?php echo esc_attr( $meta_box['name'] ); ?>">
										<?php foreach($themify_fi_sizes as $option): ?>
											<option value="<?php echo esc_attr( $option['value'] ); ?>" <?php selected( $option['value'], $meta_value ); ?>><?php echo esc_html( $option['name'] ); ?></option>
										<?php endforeach; ?>
									</select>
									<?php if ( isset( $meta_box['description'] ) ) : ?>
										<span class="themify_field_description"><?php echo wp_kses_post( $meta_box['description'] ); ?></span>
									<?php endif; // meta_box description ?>
								</div>
							</div><!--/themify_field_row -->
						</div>
					<?php
					///////////////////////////////////////////
					// Post Meta Checkboxes Template
					///////////////////////////////////////////
					} else if($meta_box['type'] == 'postmeta'){ ?>

						<input type="hidden" name="<?php echo esc_attr( $meta_box['name'] . '_noncename' ); ?>" id="<?php echo esc_attr( $meta_box['name'] . '_noncename' ); ?>" value="<?php echo wp_create_nonce( plugin_basename(__FILE__) ); ?>" />
						<div class="custom-post-meta-group themify_field_row clearfix <?php echo esc_attr( $toggle_class ); ?>" <?php echo esc_attr( $ext_attr ); ?> <?php if ( ! empty( $data_hide ) ) : echo 'data-hide="' . esc_attr( $data_hide ) . '"'; endif; ?>>

							<div class="themify_field_title"><?php echo esc_html( $meta_box['title'] ); ?></div>

							<div class="themify_field">
								<?php
								foreach($meta_box['meta'] as $meta => $name){
									$metakey = $meta_box['name'].'_'.$meta;
									$meta_class = 'all' != $meta? 'meta-sub meta-'.$meta : 'meta-all';
									echo '
									<label for="' . esc_attr( $metakey ) . '">
										<input type="checkbox" value="no" class="' . esc_attr( $meta_class ) . '" id="' . esc_attr( $metakey ) . '" name="' . esc_attr( $metakey ) . '" /> ' . esc_html( $name ) . '
									</label>';
								}
								?>
								<br/>
								<input type="hidden" class="widefat" value="<?php echo esc_attr( $meta_value ); ?>" id="<?php echo esc_attr( $meta_box['name'] ); ?>" name="<?php echo esc_attr( $meta_box['name'] ); ?>" />

								<?php if ( isset( $meta_box['description'] ) ) : ?>
									<span class="themify_field_description"><?php echo wp_kses_post( $meta_box['description'] ); ?></span>
								<?php endif; // meta_box description ?>
							</div>
						</div><!--/themify_field_row -->

					<?php
					///////////////////////////////////////////
					// Info Template
					///////////////////////////////////////////
					} else if($meta_box['type'] == 'post_id_info'){ ?>

						<div class="themify_field_row clearfix <?php echo esc_attr( $toggle_class ); ?>" <?php echo esc_attr( $ext_attr ); ?> <?php if ( ! empty( $data_hide ) ) : echo 'data-hide="' . esc_attr( $data_hide ) . '"'; endif; ?>>

							<div class="themify_field_title"><?php echo esc_html( $meta_box['title'] ); ?></div>

							<div class="themify_field">
								<?php global $post_ID; ?>
								<span class="themify_field_description themify_field_info"><?php echo sprintf( $meta_box['description'], $post_ID ); ?></span>
							</div>

						</div><!--/themify_field_row -->
					<?php
					///////////////////////////////////////////
					// Multi Template
					///////////////////////////////////////////
					} else if($meta_box['type'] == 'multi'){
						echo themify_before_meta_field(array(
							'meta_box' => $meta_box,
							'toggle_class' => $toggle_class,
							'ext_attr' => $ext_attr,
						));
						foreach ($meta_box['meta']['fields'] as $field) {
							if ( is_callable( 'themify_meta_field_'.$field['type'] ) ) {
								$call_args = array(
									'meta_box' => $field,
									'meta_value' => get_post_meta( $post->ID, $field['name'], true ),
									'call_before_after' => false,
									'post_id' => $post->ID,
									'themify_custom_panel_nonce' => $themify_custom_panel_nonce,
								);

								// Do nested toggle for multi fields
								if ( isset( $field['enable_toggle'] ) ) {
									echo '<div class="enable_toggle ' . $field['enable_toggle'] . '">';
								} elseif ( isset( $field['toggle'] ) ) {
									$field_toggle = is_array( $field['toggle'] ) ? implode( ' ', $field['toggle'] ) : $field['toggle'];
									echo '<div class="themify-toggle ' . $field_toggle . '">';
								}

								// Render the field
								call_user_func('themify_meta_field_'.$field['type'], $call_args);

								// End nested toggle for multi fields
								if ( isset( $field['enable_toggle'] ) ) {
									echo '</div>';
								} elseif ( isset( $field['toggle'] ) ) {
									echo '</div>';
								}
								if ( ! ( $field === end( $meta_box['meta']['fields'] ) ) ) {
									echo isset( $meta_box['meta']['separator'] ) ? $meta_box['meta']['separator'] : '';
								}
							}
						}
						if ( isset( $meta_box['meta']['description'] ) && '' != $meta_box['meta']['description'] ) {
							echo '<span class="themify_field_description">' . $meta_box['meta']['description'] . '</span>';
						}
						if ( isset( $meta_box['meta']['after'] ) ) {
							echo themify_after_meta_field( $meta_box['meta']['after'] );
						}

					///////////////////////////////////////////
					// Video Template
					///////////////////////////////////////////
					} elseif ( 'video' == $meta_box['type'] ) {
						themify_meta_field_video( array(
							'meta_box' => $meta_box,
							'meta_value' => $meta_value,
							'toggle_class' => $toggle_class,
							'data_hide' => $data_hide,
							'ext_attr' => $ext_attr,
							'post_id' => $post->ID,
						    'themify_custom_panel_nonce' => $themify_custom_panel_nonce,
						));

					///////////////////////////////////////////
					// Date Picker Template
					///////////////////////////////////////////
					} else if ( 'date' == $meta_box['type'] ) {
						themify_meta_field_date( array(
							'meta_box' => $meta_box,
							'meta_value' => $meta_value,
							'toggle_class' => $toggle_class,
							'data_hide' => $data_hide,
							'ext_attr' => $ext_attr,
						));

					///////////////////////////////////////////
					// Color Picker Template
					///////////////////////////////////////////
					} else if($meta_box['type'] == 'color'){
						themify_meta_field_color(array(
							'meta_box' => $meta_box,
							'meta_value' => $meta_value,
							'toggle_class' => $toggle_class,
							'data_hide' => $data_hide,
							'ext_attr' => $ext_attr,
						));

					///////////////////////////////////////////
					// Dropdown Template
					///////////////////////////////////////////
					} else if($meta_box['type'] == 'dropdown'){
						themify_meta_field_dropdown(array(
							'meta_box' => $meta_box,
							'meta_value' => $meta_value,
							'toggle_class' => $toggle_class,
							'data_hide' => $data_hide,
							'ext_attr' => $ext_attr,
						));

					///////////////////////////////////////////
					// Dropdown Button Template
					///////////////////////////////////////////
					} else if($meta_box['type'] == 'dropdownbutton'){
						themify_meta_field_dropdownbutton(array(
							'meta_box' => $meta_box,
							'meta_value' => $meta_value,
							'toggle_class' => $toggle_class,
							'data_hide' => $data_hide,
							'ext_attr' => $ext_attr,
						));

					///////////////////////////////////////////
					// Textbox Template
					///////////////////////////////////////////
					} else if($meta_box['type'] == 'textbox'){
						themify_meta_field_textbox(array(
							'meta_box' => $meta_box,
							'meta_value' => $meta_value,
							'toggle_class' => $toggle_class,
							'data_hide' => $data_hide,
							'ext_attr' => $ext_attr,
						));

					///////////////////////////////////////////
					// FontAwesome field template
					///////////////////////////////////////////
					} else if($meta_box['type'] == 'fontawesome'){
						themify_meta_field_fontawesome(array(
							'meta_box' => $meta_box,
							'meta_value' => $meta_value,
							'toggle_class' => $toggle_class,
							'data_hide' => $data_hide,
							'ext_attr' => $ext_attr,
						));

					///////////////////////////////////////////
					// Textarea Template
					///////////////////////////////////////////
					} else if($meta_box['type'] == 'textarea'){
						themify_meta_field_textarea(array(
							'meta_box' => $meta_box,
							'meta_value' => $meta_value,
							'toggle_class' => $toggle_class,
							'data_hide' => $data_hide,
							'ext_attr' => $ext_attr,
						));

					///////////////////////////////////////////
					// Checkbox Template
					///////////////////////////////////////////
					} else if($meta_box['type'] == 'checkbox'){

						themify_meta_field_checkbox(array(
							'meta_box' => $meta_box,
							'meta_value' => $meta_value,
							'toggle_class' => $toggle_class,
							'data_hide' => $data_hide,
							'ext_attr' => $ext_attr,
						));

					///////////////////////////////////////////
					// Separator Template
					///////////////////////////////////////////
					} else if($meta_box['type'] == 'separator'){

						themify_meta_field_separator(array(
							'meta_box' => $meta_box,
							'meta_value' => $meta_value,
							'toggle_class' => $toggle_class,
							'data_hide' => $data_hide,
							'ext_attr' => $ext_attr,
						));

					///////////////////////////////////////////
					// Layout Template
					///////////////////////////////////////////
					} else if($meta_box['type'] == 'layout'){

						themify_meta_field_layout(array(
							'meta_box' => $meta_box,
							'meta_value' => $meta_value,
							'toggle_class' => $toggle_class,
							'data_hide' => $data_hide,
							'ext_attr' => $ext_attr,
						));

					///////////////////////////////////////////
					// Radio Template
					///////////////////////////////////////////
					} else if($meta_box['type'] == 'radio') {
						themify_meta_field_radio(array(
							'meta_box' => $meta_box,
							'meta_value' => $meta_value,
							'toggle_class' => $toggle_class,
							'data_hide' => $data_hide,
							'ext_attr' => $ext_attr,
						));

					///////////////////////////////////////////
					// Gallery Shortcode Template
					///////////////////////////////////////////
					} else if($meta_box['type'] == 'gallery_shortcode'){
						wp_enqueue_script('gallery-shortcode');
						?>

						<input type="hidden" name="<?php echo esc_attr( $meta_box['name'] . '_noncename' ); ?>" id="<?php echo esc_attr( $meta_box['name'] . '_noncename' ); ?>" value="<?php echo wp_create_nonce( plugin_basename(__FILE__) ); ?>" />

						<div class="themify_field_row clearfix <?php echo esc_attr( $toggle_class ); ?>" <?php echo esc_attr( $ext_attr ); ?> <?php if ( ! empty( $data_hide ) ) : echo 'data-hide="' . esc_attr( $data_hide ) . '"'; endif; ?>>

							<div class="themify_field_title"><?php echo esc_html( $meta_box['title'] ); ?></div>

							<div class="themify_field">
								<?php
								if( isset($meta_box['meta']) && '' != $meta_box['meta']['size'] && 'small' == $meta_box['meta']['size'] ) {
									$class = 'small';
								} else {
									$class = '';
								}
								?>
								<textarea name="<?php echo esc_attr( $meta_box['name'] ); ?>" size="55" rows="4" class="themify_input_field themify-gallery-shortcode-input <?php echo esc_attr( $class ); ?>"><?php echo esc_textarea( $meta_value ); ?></textarea>

								<div class="themify-gallery-shortcode-btn">
									<a href="#" class="themify-gallery-shortcode-btn"><?php _e('Insert Gallery', 'themify') ?></a>
								</div>

								<?php if ( isset( $meta_box['description'] ) ) : ?>
									<span class="themify_field_description"><?php echo wp_kses_post( $meta_box['description'] ); ?></span>
								<?php endif; // meta_box description ?>
							</div>

						</div><!--/themify_field_row -->
					<?php
					///////////////////////////////////////////
					// Query Posts Template
					///////////////////////////////////////////
					} else if($meta_box['type'] == 'query_category'){ ?>

						<input type="hidden" name="<?php echo esc_attr( $meta_box['name'] . '_noncename' ); ?>" id="<?php echo esc_attr( $meta_box['name'] . '_noncename' ); ?>" value="<?php echo wp_create_nonce( plugin_basename(__FILE__) ); ?>" />

						<div class="themify_field_row clearfix <?php echo esc_attr( $toggle_class ); ?>" <?php echo esc_attr( $ext_attr ); ?> <?php if ( ! empty( $data_hide ) ) : echo 'data-hide="' . esc_attr( $data_hide ) . '"'; endif; ?>>
							<div class="themify_field_title"><?php echo esc_html( $meta_box['title'] ); ?></div>
							<div class="themify_field">
								<?php
								$terms_tax = isset($meta_box['meta']['taxonomy'])? $meta_box['meta']['taxonomy']: 'category';

								$terms_options = '';
								$terms_by_tax = get_terms($terms_tax);
															if(!empty($terms_by_tax) && !is_wp_error($terms_by_tax)){
								$terms_list = array();
								$terms_list['0'] = array(
									'title' => __('All Categories', 'themify'),
									'slug'	=> '0'
								);
								foreach ($terms_by_tax as $term) {
									$terms_list[$term->term_id] = array(
										'title' => $term->name,
										'slug'	=> $term->slug
									);
								}
								foreach ($terms_list as $term_id => $term) {
									$term_selected = '';
									if(!is_numeric($meta_value)) {
										if($meta_value == $term['slug']) $term_selected = 'selected="selected"';
									} else {
										if($meta_value == $term_id) $term_selected = 'selected="selected"';
									}
									$terms_options .= sprintf(
										'<option value="%s" data-termid="%s" %s>%s</option>',
										$term['slug'],
										$term_id,
										$term_selected,
										$term['title']
									);
								}
										?>
										<select id="<?php echo esc_attr( $meta_box['name'] ); ?>" class="query_category_single">
																				<option></option>
																				<?php echo !empty( $terms_options ) ? $terms_options : ''; ?>
										</select>
										<?php _e('or', 'themify'); ?>
										<?php }?> 
										<input type="text" class="query_category" value="<?php echo esc_attr( $meta_value ); ?>" />
								
								<input type="hidden" value="<?php echo esc_attr( $meta_value ); ?>" name="<?php echo esc_attr( $meta_box['name'] ); ?>" class="val" />
								<?php if ( isset( $meta_box['description'] ) ) : ?>
									<span class="themify_field_description"><?php echo wp_kses_post( $meta_box['description'] ); ?></span>
								<?php endif; // meta_box description ?>
							</div>
						</div>

					<?php
					///////////////////////////////////////////
					// Sidebar Visibility Template
					///////////////////////////////////////////
					} else if($meta_box['type'] == 'sidebar_visibility'){ ?>

						<input type="hidden" name="<?php echo esc_attr( $meta_box['name'] . '_noncename' ); ?>" id="<?php echo esc_attr( $meta_box['name'] . '_noncename' ); ?>" value="<?php echo wp_create_nonce( plugin_basename(__FILE__) ); ?>" />

						<div class="themify_field_row clearfix <?php echo esc_attr( $toggle_class ); ?>" <?php echo esc_attr( $ext_attr ); ?> <?php if ( ! empty( $data_hide ) ) : echo 'data-hide="' . esc_attr( $data_hide ) . '"'; endif; ?>>
							<div class="themify_field_title"><?php echo esc_html( $meta_box['title'] ); ?></div>
							<div class="themify_field">
								<?php
								$sidebars = get_option('sidebars_widgets');
								global $wp_registered_sidebars;
								foreach($sidebars as $sidebar => $val){
									if($sidebar != 'wp_inactive_widgets' && $sidebar != 'array_version' && strpos(strtolower($wp_registered_sidebars[$sidebar]['name']),'sidebar') !== false){
										$checked = "";
										if(get_post_meta($post->ID, $meta_box['name'], true) == "" || !get_post_meta($post->ID, $meta_box['name'], true)){
											$checked = "checked='checked'";
										} else {
											foreach($meta_value as $key => $val){
												if(str_replace("'","",$key) == $wp_registered_sidebars[$sidebar]['name']){
													$checked = "checked='checked'";
												}
											}
										}
										?>
										<input type="checkbox" name="<?php echo esc_attr( $meta_box['name'] ); ?>[<?php echo esc_attr( $wp_registered_sidebars[$sidebar]['name'] ); ?>]" <?php echo $checked; ?> /> <?php echo esc_html( $wp_registered_sidebars[$sidebar]['name'] ); ?><br />
									<?php
									}
								}
								?>
								<?php if ( isset( $meta_box['description'] ) ) : ?>
									<span class="themify_field_description"><?php echo wp_kses_post( $meta_box['description'] ); ?></span>
								<?php endif; // meta_box description ?>
							</div>
						</div>

					<?php
					///////////////////////////////////////////
					// Page builder template
					///////////////////////////////////////////
					} else if($meta_box['type'] == 'page_builder') {
						do_action('themify_builder_metabox');
					} ?>

				<?php endforeach; ?>
			</div>
			</div>
			<?php
			}
		}
	echo '</div>';//end .ilc-btabs
echo '</div>';//end #themify-meta-box-tabs

}

if(!function_exists('themify_framework_query_posts_page_args')){
	/**
	 * Allows to query by category slug or id
	 * @param array|string $qpargs Query parameters
	 * @return array
	 * @since 1.3.8
	 */
	function themify_framework_query_posts_page_args($qpargs) {
		global $themify;
		$cats = explode(',', str_replace(' ', '', $themify->query_category));
		if(is_array($qpargs)) {
			if(is_array($cats) && is_numeric($cats[0])) {
				return $qpargs;
			} else {
				$slugs = array();
				foreach ($cats as $cat) {
					$term = get_term_by('slug', $cat, $themify->query_taxonomy);
					$slugs[] = $term->term_id;
				}
				$qpargs['tax_query']['0']['terms'] = $slugs;
				return $qpargs;
			}
		} else {
			if(is_array($cats) && is_numeric($cats[0])) {
				return $qpargs;
			} else {
				$slugs = array();
				$taxo = isset($themify->query_taxonomy)? $themify->query_taxonomy: 'category';
				foreach ($cats as $cat) {
					$term = get_term_by('slug', $cat, $taxo);
					$slugs[] = $term->term_id;
				}
				parse_str($qpargs, $args);
				$qpargs = '';
				unset($args['cat']);
				$args['cat'] = implode(',', $slugs);
				foreach ($args as $key => $value) {
					$qpargs .= $key.'='.$value.'&';
				}
				$qpargs = substr($qpargs, 0, -1);
				return $qpargs;
			}
		}
	};
}

function themify_meta_field_fontawesome( $args, $call_before_after = true, $echo = true ) {
	$meta_box =  $args['meta_box'];
	$meta_value = $args['meta_value'];
	if ( isset( $meta_box['meta'] ) && isset( $meta_box['meta']['size'] ) && '' != $meta_box['meta']['size'] && 'small' == $meta_box['meta']['size'] ) {
		$class = 'small';
	} else {
		$class = '';
	}

	$html = '<div class="icon-preview font-icon-preview">
				<i class="fa ' . esc_attr( $meta_value ) . '"></i>
			</div>
			<!-- /icon-preview -->';
	$html .= sprintf( '<input type="text" id="%s" name="%s" value="%s" size="55" class="themify_input_field themify_fa %s" /> <a class="button button-secondary hide-if-no-js themify_fa_toggle" href="#" data-target="#%s">%s</a>',
		esc_attr( $meta_box['name'] ),
		esc_attr( $meta_box['name'] ),
		esc_attr( $meta_value ),
		$class,
		esc_attr( $meta_box['name'] ),
		__( 'Insert Icon', 'themify' ) );

	if ( isset( $meta_box['label'] ) && '' != $meta_box['label'] ) {
		$html = sprintf( '<label for="%s">%s %s</label>',
			esc_attr( $meta_box['name'] ),
			$html,
			esc_html( $meta_box['label'] )
		);
	}

	if ( isset( $meta_box['description'] ) ) {
		$html .= themify_meta_field_get_description( $meta_box['description'] );
	}

	if ( isset( $meta_box['before'] ) && $meta_box['before'] ) {
		$html = $meta_box['before'] . $html;
	}
	if ( isset( $meta_box['after'] ) && $meta_box['after'] ) {
		$html .= $meta_box['after'];
	}

	if ( $call_before_after ) {
		$html = themify_before_meta_field( $args ) . $html . themify_after_meta_field();
	}

	if ( $echo ) echo $html;
	return $html;
}

function themify_font_icons_admin_assets() {
	wp_enqueue_style( 'themify-font-icons-css' );
	wp_enqueue_script( 'themify-font-icons-js' );
	wp_enqueue_style( 'themify-icons' );
	wp_enqueue_style( 'google-fonts-admin' );
	add_action( 'admin_footer', 'themify_font_icons_dialog' );
}

function themify_font_icons_dialog() { ?>
	<div id="themify_lightbox_fa" class="themify-admin-lightbox clearfix" style="display: none;">
		<input type="text" id="themify-search-icon-input" placeholder="<?php _e('Search','themify')?>" />
		<h3 class="themify_lightbox_title"><?php _e( 'Choose icon', 'themify' ) ?></h3>
		<a href="#" class="close_lightbox"><i class="ti-close"></i></a>
		<div class="lightbox_container"></div>
	</div>
	<div id="themify_lightbox_overlay"></div>
<?php }

/**
 * Setup menu icon functionality
 *
 * @since 1.6.8
 */
function themify_setup_menu_icons() {
	if( is_admin() ) {
		add_filter( 'wp_edit_nav_menu_walker', 'themify_custom_edit_nav_menu_walker' );
		add_action( 'wp_nav_menu_item_custom_fields', 'themify_add_menu_icon_option', 12, 4 );
		add_action( 'wp_update_nav_menu_item', 'themify_update_menu_icon_option', 10, 3 );
		add_action( 'delete_post', 'themify_remove_menu_icon_meta', 1, 3 );
	} else {
		add_filter( 'wp_nav_menu_args', 'themify_add_menu_item_title_filter' );
		add_filter( 'wp_nav_menu', 'themify_remove_menu_item_title_filter' );
	}
}

/**
 * Start looking for menu icons
 */
function themify_add_menu_item_title_filter( $args ) {
	add_filter( 'the_title', 'themify_add_menu_icon', 10, 2 );
	return $args;
}

/**
 * The menu is rendered, we longer need to look for menu icons
 */
function themify_remove_menu_item_title_filter( $nav_menu ) {
	remove_filter( 'the_title', 'themify_add_menu_icon', 10, 2 );
	return $nav_menu;
}

/**
 * Setup custom walker for Nav_Menu_Edit
 *
 * @since 1.6.8
 */
function themify_custom_edit_nav_menu_walker( $walker ) {
	if( ! class_exists( 'Themify_Walker_Nav_Menu_Edit' ) ) {
		include_once THEMIFY_DIR . '/class-themify-walker-nav-menu-edit.php';
	}

	return 'Themify_Walker_Nav_Menu_Edit';
}

/**
 * Save the icon meta for a menu item. Also removes the meta entirely if the field is cleared.
 *
 * @since 1.6.8
 */
function themify_update_menu_icon_option( $menu_id, $menu_item_db_id, $args ) {
	if( isset( $_POST['menu-item-icon'] ) && isset( $_POST['menu-item-icon'][$menu_item_db_id] ) ) {
		$meta_key = '_menu_item_icon';
		$meta_value = themify_get_menu_icon( $menu_item_db_id );
		$menu_item_icon =  $_POST['menu-item-icon'][$menu_item_db_id];
		$new_meta_value = stripcslashes( $menu_item_icon );

		if ( $new_meta_value && '' == $meta_value )
			add_post_meta( $menu_item_db_id, $meta_key, $new_meta_value, true );
		elseif ( $new_meta_value && $new_meta_value != $meta_value )
			update_post_meta( $menu_item_db_id, $meta_key, $new_meta_value );
		elseif ( '' == $new_meta_value && $meta_value )
			delete_post_meta( $menu_item_db_id, $meta_key, $meta_value );
	}
}

/**
 * Clean up the icon meta field when a menu item is deleted
 *
 * @param int $post_id
 *
 * @since 1.6.8
 */
function themify_remove_menu_icon_meta( $post_id ) {
	if( is_nav_menu_item( $post_id ) ) {
		delete_post_meta( $post_id, '_menu_item_icon' );
	}
}

/**
 * Display the icon picker for menu items in the backend
 *
 * @since 1.6.8
 */
function themify_add_menu_icon_option( $item_id, $item, $depth, $args ) {
	$saved_meta = themify_get_menu_icon( $item_id );
?>
	<p class="field-icon description description-thin">
		<label for="edit-menu-item-icon-<?php echo esc_attr( $item_id ); ?>">
			<?php _e( 'Icon', 'themify' ) ?><br/>
			<input type="text" name="menu-item-icon[<?php echo esc_attr( $item_id ); ?>]" id="edit-menu-item-icon-<?php echo esc_attr( $item_id ) ?>" size="8" class="edit-menu-item-icon themify_field_icon" value="<?php echo esc_attr( $saved_meta ); ?>">
			<a class="button button-secondary hide-if-no-js themify_fa_toggle" href="#" data-target="#edit-menu-item-icon-<?php echo esc_attr( $item_id ) ?>"><?php _e( 'Insert Icon', 'themify' ); ?></a>
		</label>
	</p>
<?php }

/**
 * Returns the icon name chosen for a given menu item
 *
 * @return string|null
 * @since 1.6.8
 */
function themify_get_menu_icon( $item_id ) {
	return get_post_meta( $item_id, '_menu_item_icon', true );
}

/**
 * Append icon to a menu item
 *
 * @since 1.6.8
 *
 * @param string $title
 * @param string $id
 *
 * @return string
 */
function themify_add_menu_icon( $title, $id = '' ) {
	if ( '' != $id ) {
		if ( $icon = themify_get_menu_icon( $id ) ) {
			$title = '<i class="fa ' . esc_attr( themify_get_fa_icon_classname( $icon ) ) . '"></i> ' . $title;
		}
	}
	return $title;
}

/**
 * Generates date picker field for Themify Custom Panel.
 *
 * @param array $args Field settings.
 * @param bool  $call_before_after Output common wrapping markup before and after the field.
 * @param bool  $echo Just return the field or echo it too.
 *
 * @since 1.7.1
 * @return string
 */
function themify_meta_field_date( $args, $call_before_after = true, $echo = true ) {
	wp_enqueue_style( 'themify-datetimepicker-css', THEMIFY_URI . '/css/jquery-ui-timepicker.css', array(), THEMIFY_VERSION );
	wp_enqueue_script( 'themify-datetimepicker-js', THEMIFY_URI . '/js/jquery-ui-timepicker.js', array( 'jquery', 'jquery-ui-datepicker'/*, 'jquery-ui-slider'*/ ), false, true );

	$meta_box = $args['meta_box'];
	$meta_value = $args['meta_value'];
	extract($args, EXTR_OVERWRITE);

	if ( isset( $meta_box['meta']['default'] ) && $meta_box['meta']['default'] != '' ) {
		$default = $meta_box['meta']['default'];
	} else {
		$default = '';
	}

	$required = ( isset( $meta_box['meta']['required'] ) && true == $meta_box['meta']['required'] ) ? 'required' : '';

	$pick  = isset( $meta_box['meta']['pick'] ) && '' != $meta_box['meta']['pick'] ? $meta_box['meta']['pick']  : __( 'Pick Date', 'themify' );
	$close = isset( $meta_box['meta']['close'] ) && '' != $meta_box['meta']['close'] ? $meta_box['meta']['close'] : __( 'Done', 'themify' );
	$clear = isset( $meta_box['meta']['clear'] ) && '' != $meta_box['meta']['clear'] ? $meta_box['meta']['clear'] : __( 'Clear', 'themify' );
	$date_format = isset( $meta_box['meta']['date_format'] ) && '' != $meta_box['meta']['date_format'] ? $meta_box['meta']['date_format'] : 'yy-mm-dd';
	$time_format = isset( $meta_box['meta']['time_format'] ) && '' != $meta_box['meta']['time_format'] ? $meta_box['meta']['time_format'] : 'hh:mm tt';
	$timeseparator = isset( $meta_box['meta']['timeseparator'] ) && '' != $meta_box['meta']['timeseparator'] ? $meta_box['meta']['timeseparator'] : ' @ ';

	$html = sprintf( '
		<div class="disableDateField"></div>
		<input %s type="text" id="%s" name="%s" value="%s" data-clear="%s" data-label="%s"
		 data-close="%s"
		 data-dateformat="%s" data-timeformat="%s" data-timeseparator="%s" class="themify_input_field medium themifyDatePicker" data-first-day="%s" />
		<input type="button" id="%s" data-picker="%s" value="%s" class="button themifyClearDate themifyOpacityTransition %s" >',
	$required, esc_attr( $meta_box['name'] ), esc_attr( $meta_box['name'] ), esc_attr( $meta_value? $meta_value : $default ), 'clear-'.esc_attr( $meta_box['name'] ), esc_attr( $pick ), esc_attr( $close ), esc_attr( $date_format ), esc_attr( $time_format ), esc_attr( $timeseparator ), get_option( 'start_of_week', '0' ),
	'clear-'.esc_attr( $meta_box['name'] ), esc_attr( $meta_box['name'] ), esc_attr( $clear ), $meta_value? 'themifyFadeIn' : '' );

	if(isset($meta_box['label']) && '' != $meta_box['label'])
		$html = sprintf('<label for="%s">%s %s</label>', esc_attr( $meta_box['name'] ), $html, esc_attr( $meta_box['label'] ));

	$html .= isset( $meta_box['description'] )? themify_meta_field_get_description($meta_box['description']) : '';

	if ( isset( $meta_box['before'] ) ) $html = $meta_box['before'] . $html;
	if ( isset( $meta_box['after'] ) ) $html .= $meta_box['after'];

	if ( $call_before_after ) $html = themify_before_meta_field($args) . $html . themify_after_meta_field();

	if ( $echo ) echo $html;
	return $html;
}

/**
 * Generates color picker
 *
 * @param array $args Field settings
 * @param bool  $call_before_after Whether to output common wrapping markup before and after the field
 * @param bool  $echo Whether to echo or return the field
 *
 * @since 1.3.2
 * @return string
 */
function themify_meta_field_color($args, $call_before_after = true, $echo = true){
	$meta_box = $args['meta_box'];
	$meta_value = $args['meta_value'];
	extract($args, EXTR_OVERWRITE);

	$html = sprintf( '<span class="colorSelect"></span>
	<input type="text" id="%s" name="%s" value="%s" class="themify_input_field colorSelectInput" />
	<input type="button" class="button clearColor" value="' . __('&times;', 'themify') . '">',
		esc_attr( $meta_box['name'] ), esc_attr( $meta_box['name'] ), esc_attr( $meta_value? $meta_value : $meta_box['meta']['default'] ) );

	if(isset($meta_box['label']) && '' != $meta_box['label'])
		$html = sprintf('<label for="%s">%s %s</label>', esc_attr( $meta_box['name'] ), $html, esc_attr( $meta_box['label'] ));

	$html .= isset( $meta_box['description'] )? themify_meta_field_get_description($meta_box['description']) : '';

	if ( isset( $meta_box['before'] ) ) $html = $meta_box['before'] . $html;
	if ( isset( $meta_box['after'] ) ) $html .= $meta_box['after'];

	if($call_before_after)
		$html = themify_before_meta_field($args) . $html . themify_after_meta_field();

	if ( $echo ) echo $html;
	return $html;
}

/**
 * Generates layout field
 *
 * @param array $args Field settings
 * @param bool  $call_before_after Whether to output common wrapping markup before and after the field
 * @param bool  $echo Whether to echo or return the field
 *
 * @since 1.3.2
 * @return string
 */
function themify_meta_field_layout( $args, $call_before_after = true, $echo = true ) {
	$meta_box = $args['meta_box'];
	$meta_value = $args['meta_value'];
	extract($args, EXTR_OVERWRITE);
	$ops_html = '';

	foreach ( $meta_box['meta'] as $options ) {
		if ( ( '' == $meta_value || !$meta_value || !isset($meta_value)) && ( isset( $options['selected'] ) && $options['selected'] ) ) {
			$meta_value = $options['value'];
		}
		if ( $meta_value == $options['value'] ) {
			$class = 'selected';
		} else {
			$class = '';
		}

		if(isset($meta_box['show_title'])){
			$title = isset($options['title'])? $options['title']: ucwords(str_replace('-', ' ', $options['value']));
		} else {
			$title = '';
		}

		// Check image src whether absolute url or relative url
		$img_src = ( '' != parse_url( $options['img'], PHP_URL_SCHEME) ) ? $options['img'] : get_template_directory_uri() . '/' . $options['img'];

		$ops_html .= sprintf('<a href="#" class="preview-icon %s"><img src="%s" title="%s" alt="%s" %s /></a>',
			$class, esc_url( $img_src ), esc_attr( $title ), esc_attr( $options['value'] ),
			isset($meta_box['size'])? 'width="'.esc_attr( $meta_box['size'][0] ).'" height="'.esc_attr( $meta_box['size'][1] ).'"': ''
		);
	}

	$html = sprintf('%s<input type="hidden" name="%s" value="%s" class="val" />',
		$ops_html, esc_attr( $meta_box['name'] ), esc_attr( $meta_value ));

	if(isset($meta_box['label']) && '' != $meta_box['label'])
		$html = sprintf('<label for="%s">%s %s</label>', esc_attr( $meta_box['name'] ), $html, esc_attr( $meta_box['label'] ));

	$html .= isset( $meta_box['description'] )? themify_meta_field_get_description($meta_box['description']) : '';

	if( isset( $meta_box['before'] ) ) $html = $meta_box['before'] . $html;
	if( isset( $meta_box['after'] ) )  $html .= $meta_box['after'];

	if($call_before_after)
		$html = themify_before_meta_field($args) . $html . themify_after_meta_field();

	if ( $echo ) echo $html;
	return $html;
}

/**
 * Generates select field as a button
 *
 * @since 1.3.2
 *
 * @param array $args Field settings
 * @param bool $call_before_after Whether to output common wrapping markup before and after the field
 * @param bool $echo Echo or return the field
 *
 * @return string
 */
function themify_meta_field_dropdownbutton( $args, $call_before_after = true, $echo = true ) {
	$meta_box = $args['meta_box'];
	$meta_value = $args['meta_value'];
	$name = '';
	extract($args, EXTR_OVERWRITE);

	if(isset($meta_box['main']) && $meta_box['main']) {
		$metakey = $meta_box['name'];
		$meta_class = 'ddbtn-all';
	} else {
		$metakey = $meta_box['name'];
		$meta_class = 'ddbtn-sub';
	}

	$additional_classes = isset( $meta_box['class'] ) ? $meta_box['class'] : '';

	$toggle_class = '';
	$ext_attr = '';
	$toggle_enable = false;
	if( isset($meta_box['toggle']) ){
		$toggle_class .= 'themify-toggle ';
		$toggle_class .= (is_array($meta_box['toggle'])) ? implode(' ', $meta_box['toggle']) : $meta_box['toggle'];
	}
	if( isset($meta_box['default_toggle']) && $meta_box['default_toggle'] == 'hidden' ){
		$ext_attr = 'style="display:none;"';
	}
	if( isset($meta_box['enable_toggle']) && $meta_box['enable_toggle'] == true ) {
		$toggle_class .= ' enable_toggle';
		$toggle_enable = true;
	}

	$first = '';
	$others = '';
	$default_icon = '';

	foreach($meta_box['states'] as $state) {
		if($state['value'] == $meta_value) {
			$first = '
			<div class="first-ddbtn">
				<a href="#" data-val="'.esc_attr( $state['value'] ).'" data-name="'.esc_attr( $state['name'] ).'" title="'.esc_attr( $state['title'] ).'">
					<img src="'.esc_attr( $state['icon'] ).'" title="'.esc_attr( $state['title'] ).'" />
					<span class="ddbtn-name">'.esc_attr( $meta_box['title'] ).'</span>
				</a>
			</div>';
			$selected = 'selected';
		} else {
			$selected = '';
		}
		$others .= '
			<div class="ddbtn">
				<a href="#" data-sel="'.$selected.'" data-val="'.esc_attr( $state['value'] ).'" data-name="'.esc_attr( $state['name'] ).'" title="'.esc_attr( $state['title'] ).'">
					<img src="'.esc_attr( $state['icon'] ).'" title="'.esc_attr( $state['title'] ).'" />
					<span class="ddbtn-label">'.esc_attr( $state['name'] ).'</span>
				</a>
			</div>';
		if(isset($state['default']) && $state['default']){
			$default_icon = $state['icon'];
		}
	}

	$html = sprintf('
		<div class="%s %s %s"><div class="dropdownbutton-group multi-ddbtn">
			<div id="%s" class="dropdownbutton-list multi-%s" data-name="%s" data-def-icon="%s">
			%s<div class="dropdownbutton">%s</div>
			</div>
			<input type="hidden" value="%s" class="widefat %s" id="%s" name="%s" />
		</div></div>',
		$additional_classes, esc_attr( $toggle_class ), esc_attr( $ext_attr ),
		esc_attr( $metakey ), esc_attr( $meta_class ), esc_attr( $name ), esc_attr( $default_icon ), // group
		$first, $others, // dropdown
		esc_attr( $meta_value ), esc_attr( $meta_class ), esc_attr( $metakey ), esc_attr( $metakey ) // hidden field
	);

	$html = themify_meta_field_get_label($html, $meta_box);

	$html .= isset( $meta_box['description'] )? themify_meta_field_get_description($meta_box['description']) : '';

	if( isset( $meta_box['before'] ) && $meta_box['before'] ) $html = $meta_box['before'] . $html;
	if( isset( $meta_box['after'] ) && $meta_box['after'] )  $html .= $meta_box['after'];

	if($call_before_after)
		$html = themify_before_meta_field($args) . $html . themify_after_meta_field();

	if ( $echo ) echo $html;
	return $html;
}

/**
 * Generates select field
 *
 * @param array $args Field settings
 * @param bool  $call_before_after Whether to output common wrapping markup before and after the field
 * @param bool  $echo Whether to echo or return the field
 *
 * @since 1.3.2
 * @return string
 */
function themify_meta_field_dropdown($args, $call_before_after = true, $echo = true){
	$meta_box = $args['meta_box'];
	$meta_value = $args['meta_value'];
	extract($args, EXTR_OVERWRITE);

	$ops_html = '';

	/* dynamic data source, call a function to populate the field */
	if( is_callable( $meta_box['meta'] ) ) {
		$meta_box['meta'] = call_user_func( $meta_box['meta'] );
	}

	foreach($meta_box['meta'] as $option){
		$ops_html .= sprintf('<option value="%s" %s>%s</option>',
			esc_attr( $option['value'] ),
			isset( $meta_value ) && '' != $meta_value? selected( $meta_value, esc_attr( $option['value'] ), false )
				: selected( isset( $option['selected'] )? $option['selected'] : '', true, false ),
			esc_html( $option['name'] )
		);
	}

	$html = sprintf('<select id="%s" name="%s">%s</select>',
		esc_attr( $meta_box['name'] ), esc_attr( $meta_box['name'] ), $ops_html);

	$html = themify_meta_field_get_label($html, $meta_box);

	$html .= isset( $meta_box['description'] )? themify_meta_field_get_description($meta_box['description']) : '';

	if( isset( $meta_box['before'] ) && $meta_box['before'] ) $html = $meta_box['before'] . $html;
	if( isset( $meta_box['after'] ) && $meta_box['after'] )  $html .= $meta_box['after'];

	if($call_before_after)
		$html = themify_before_meta_field($args) . $html . themify_after_meta_field();

	if ( $echo ) echo $html;
	return $html;
}

/**
 * Generates radio buttons.
 *
 * @param array $args
 * @param bool  $call_before_after
 * @param bool  $echo
 *
 * @return string
 */
function themify_meta_field_radio($args, $call_before_after = true, $echo = true){
	$meta_box = $args['meta_box'];
	$meta_value = $args['meta_value'];
	extract($args, EXTR_OVERWRITE);

	$html = '';
	foreach ( $meta_box['meta'] as $k => $option ) {
		$radio_selected = ( isset( $option['selected'] ) && $option['selected'] && '' == $meta_value ) ? 'checked="checked"' : checked( $meta_value, esc_attr( $option['value'] ), false );
		$rid = $meta_box['name'] . '-' . esc_attr( $option['value'] );
		$html .= sprintf( '<input type="radio" name="%s" id="%s" value="%s" %s /><label for="%s" class="selectit">%s</label>',
			// radio
			esc_attr( $meta_box['name'] ),
			esc_attr( $rid ),
			esc_attr( $option['value'] ),
			$radio_selected,
			// label
			esc_attr( $rid ),
			esc_html( $option['name'] )
		);
	}
	$html .= isset( $meta_box['description'] )? themify_meta_field_get_description($meta_box['description']) : '';

	if( isset( $meta_box['before'] ) ) $html = $meta_box['before'] . $html;
	if( isset( $meta_box['after'] ) )  $html .= $meta_box['after'];
	if($call_before_after) $html = themify_before_meta_field($args) . $html . themify_after_meta_field();

	if ( $echo ) echo $html;
	return $html;
}

/**
 * Generates separator
 *
 * @param array $args Field settings
 * @param bool  $call_before_after Whether to output common wrapping markup before and after the field
 * @param bool  $echo Whether to echo or return the field
 *
 * @since 1.3.2
 * @return string
 */
function themify_meta_field_separator($args, $call_before_after = true, $echo = true){
	$meta_box = $args['meta_box'];
	extract($args, EXTR_OVERWRITE);
	$toggle_class = isset( $args['toggle_class'] ) ? $args['toggle_class'] : '';
	$ext_attr = isset( $args['ext_attr'] ) ? $args['ext_attr'] : '';

	$html = isset($meta_box['meta']['html']) && '' != $meta_box['meta']['html']? $meta_box['meta']['html'] : '<hr class="meta_fields_separator" />';

	$html .= isset( $meta_box['description'] )? themify_meta_field_get_description($meta_box['description']) : '';

	$out = '<div class="themify_field_row clearfix ' . esc_attr( $toggle_class ) . '" ' . esc_attr( $ext_attr );
	if ( isset( $args['data_hide'] ) && ! empty( $args['data_hide'] ) ) {
		$out .= ' data-hide="' . esc_attr( $args['data_hide'] ) . '"';
	}
	$out .= '>' . $html . '</div>';

	if ( $echo ) echo $out;
	return $out;
}

/**
 * Generates checkbox field
 *
 * @param array $args Field settings
 * @param bool  $call_before_after Whether to output common wrapping markup before and after the field
 * @param bool  $echo Whether to echo or return the field
 *
 * @since 1.3.2
 * @return string
 */
function themify_meta_field_checkbox($args, $call_before_after = true, $echo = true){
	$meta_box = $args['meta_box'];
	$meta_value = $args['meta_value'];
	extract($args, EXTR_OVERWRITE);

	$checked = $meta_value ? 'checked="checked"' : $checked = '';

	$html = sprintf('<input type="checkbox" id="%s" name="%s" %s class="%s" data-val="%s" />',
		esc_attr( $meta_box['name'] ), esc_attr( $meta_box['name'] ), $checked, esc_attr( $meta_box['name'] ).'-toggle-control', esc_attr( $meta_box['name'] ));

	if ( isset( $meta_box['label'] ) && '' != $meta_box['label'] ) {
		$html = sprintf( '<label for="%s">%s %s</label>', esc_attr( $meta_box['name'] ), $html, esc_attr( $meta_box['label'] ) );
	}

	if ( isset( $meta_box['description'] ) ) {
		$html .= themify_meta_field_get_description( $meta_box['description'] );
	}

	if( isset( $meta_box['before'] ) && $meta_box['before'] ) $html = $meta_box['before'] . $html;
	if( isset( $meta_box['after'] ) && $meta_box['after'] )  $html .= $meta_box['after'];

	if($call_before_after)
		$html = themify_before_meta_field($args) . $html . themify_after_meta_field();

	if ( $echo ) echo $html;
	return $html;
}

/**
 * Generates text field
 *
 * @param array $args Field settings
 * @param bool  $call_before_after Whether to output common wrapping markup before and after the field
 * @param bool  $echo Whether to echo or return the field
 *
 * @since 1.3.2
 * @return string
 */
function themify_meta_field_textbox($args, $call_before_after = true, $echo = true){
	$meta_box = $args['meta_box'];
	$meta_value = $args['meta_value'];
	extract($args, EXTR_OVERWRITE);

	if ( isset( $meta_box['meta'] ) && isset( $meta_box['meta']['size'] ) && '' != $meta_box['meta']['size'] && 'small' == $meta_box['meta']['size'] ) {
		$class = 'small';
	} else {
		$class = '';
	}

	$html = sprintf('<input type="text" id="%s" name="%s" value="%s" size="55" class="themify_input_field %s" />',
		esc_attr( $meta_box['name'] ), esc_attr( $meta_box['name'] ), esc_attr( $meta_value ), $class);

	if ( isset( $meta_box['label'] ) && '' != $meta_box['label'] ) {
		$html = themify_meta_field_get_label($html, $meta_box);
	}

	if ( isset( $meta_box['description'] ) ) {
		$html .= themify_meta_field_get_description( $meta_box['description'] );
	}

	if( isset( $meta_box['before'] ) && $meta_box['before'] ) $html = $meta_box['before'] . $html;
	if( isset( $meta_box['after'] ) && $meta_box['after'] )  $html .= $meta_box['after'];

	if($call_before_after)
		$html = themify_before_meta_field($args) . $html . themify_after_meta_field();

	if ( $echo ) echo $html;
	return $html;
}

/**
 * Generates textarea field
 *
 * @param array $args Field settings
 * @param bool  $call_before_after Whether to output common wrapping markup before and after the field
 * @param bool  $echo Whether to echo or return the field
 *
 * @since 1.3.2
 * @return string
 */
function themify_meta_field_textarea($args, $call_before_after = true, $echo = true){
	$meta_box = $args['meta_box'];
	$meta_value = $args['meta_value'];
	extract($args, EXTR_OVERWRITE);

	if( isset( $meta_box['meta'] ) && isset( $meta_box['meta']['size'] ) && $meta_box['meta']['size'] != '' && $meta_box['meta']['size'] == 'small'){
		$class = 'small';
	} else {
		$class = '';
	}

	$html = sprintf( '<textarea id="%s" name="%s" size="55" rows="4" class="themify_input_field %s">%s</textarea>',
		esc_attr( $meta_box['name'] ), esc_attr( $meta_box['name'] ), $class, esc_textarea( $meta_value ) );

	$html = themify_meta_field_get_label($html, $meta_box);

	if ( isset( $meta_box['description'] ) ) {
		$html .= themify_meta_field_get_description( $meta_box['description'] );
	}

	if( isset( $meta_box['before'] ) && $meta_box['before'] ) $html = $meta_box['before'] . $html;
	if( isset( $meta_box['after'] ) && $meta_box['after'] )  $html .= $meta_box['after'];

	if($call_before_after)
		$html = themify_before_meta_field($args) . $html . themify_after_meta_field();

	if ( $echo ) echo $html;
	return $html;
}

function themify_meta_field_video($args, $call_before_after = true, $echo = true){
	$meta_box = $args['meta_box'];
	$meta_value = $args['meta_value'];
	extract($args, EXTR_OVERWRITE);

	ob_start();

	/** Parameters for the uploader @var Array */
	$featimg_uploader_args = array(
		'tomedia'  => true,
		'topost'   => $post_id,
		'medialib' => true,
		'fields'   => $meta_box['name'],
		'formats'  => 'mp4,m4v,webm,ogv,wmv,flv',
		'type'     => 'video',
	);
	?>

	<div id="<?php echo esc_attr( 'remove-' . $meta_box['name'] ); ?>" class="themify_featimg_remove themify_video_remove <?php if( $meta_value == '' ) echo 'hide' ?>">
		<a href="#"><?php _e('Remove Video', 'themify'); ?></a>
	</div>

	<!-- Field storing URL -->
	<input type="text" id="<?php echo esc_attr( $meta_box['name'] ); ?>" name="<?php echo
	$meta_box['name']; ?>" value="<?php echo esc_attr( $meta_value ); ?>" size="55" class="themify_input_field themify_upload_field" />

	<div class="themify_upload_buttons">
		<?php themify_uploader($meta_box['name'], $featimg_uploader_args) ?>
	</div>

	<script type="text/javascript">
		jQuery(function($){
			$('#remove-<?php echo esc_js( $meta_box['name'] ); ?>').find('a').on('click', function(e){
				e.preventDefault();
				var $self = $(this).parent();
				$self.parent().find('.themify_upload_field').val('');
				$self.addClass('hide');

				$.post(
					ajaxurl, {
						'action': 'themify_remove_video',
						'postid': <?php echo esc_js( $post_id ); ?>,
						'customfield' : '<?php echo esc_js( $meta_box['name'] ); ?>',
						'nonce' : '<?php echo esc_js( $args['themify_custom_panel_nonce'] ); ?>'
					},
					function() {
						$self.parent().find('.themify_upload_field').val('');
						$self.addClass('hide');
					}
				);
			});
		});
	</script>
	<?php

	$html = ob_get_contents();
	ob_end_clean();

	$html .= isset( $meta_box['description'] )? themify_meta_field_get_description($meta_box['description']) : '';

	if( isset( $meta_box['before'] ) && $meta_box['before'] ) $html = $meta_box['before'] . $html;
	if( isset( $meta_box['after'] ) && $meta_box['after'] )  $html .= $meta_box['after'];

	if($call_before_after)
		$html = themify_before_meta_field($args) . $html . themify_after_meta_field();

	$html = $html . '<!-- Themify Video END -->';
	if ( $echo ) echo $html;
	return $html;
}

/**
 * Returns label before or after field
 * @param string $html field markup
 * @param array $meta_box field definition in key => value format
 * @param bool $echo Whether to echo or return the field
 * @return string field markup with label
 * @since 1.3.2
 */
function themify_meta_field_get_label($html, $meta_box, $echo = false){
	$label_for = ( isset( $meta_box['name'] ) && '' != $meta_box['name'] ) ? esc_attr( $meta_box['name'] ) : '';
	if ( isset( $meta_box['label'] ) && '' != $meta_box['label'] ) {
		if ( isset( $meta_box['label_before'] ) && $meta_box['label_before'] ) {
			$html = sprintf( '<label for="%s">%s %s</label>', $label_for, wp_kses_post( $meta_box['label'] ), $html );
		} else {
			$html = sprintf( '<label for="%s">%s %s</label>', $label_for, $html, wp_kses_post( $meta_box['label'] ) );
		}
	}
	if ( $echo ) echo $html;
	return $html;
}

/**
 * Renders description for meta fields.
 *
 * @uses wp_kses_post()
 *
 * @param string $desc
 *
 * @return string
 */
function themify_meta_field_get_description( $desc = '' ) {
	return ( isset( $desc ) && '' != $desc ) ? '<span class="themify_field_description">' . wp_kses_post( $desc ) . '</span>' : '';
}

/**
 * Markup added before a field in multi field.
 *
 * @param array $args
 *
 * @return string
 */
function themify_before_meta_field( $args = array() ) {
	$meta_box = $args['meta_box'];
	$meta_box_name = isset( $meta_box['name'] ) ? $meta_box['name'] : '';
	$toggle_class = isset( $args['toggle_class'] ) ? $args['toggle_class'] : '';
	$ext_attr = isset( $args['ext_attr'] ) ? $args['ext_attr'] : '';
	$html = '
	<input type="hidden" name="' . esc_attr( $meta_box_name ) . '_noncename" id="' . esc_attr( $meta_box_name ) . '_noncename" value="' . wp_create_nonce( plugin_basename(__FILE__) ) . '" />
	<div class="themify_field_row clearfix ' . esc_attr( $toggle_class ) . '" ' . esc_attr( $ext_attr );
	if ( isset( $args['data_hide'] ) && ! empty( $args['data_hide'] ) ) {
		$html .= ' data-hide="' . esc_attr( $args['data_hide'] ) . '"';
	}
	$html .= '>';
	if ( isset( $meta_box['title'] ) ) {
		$html .= '<div class="themify_field_title">' . esc_html( $meta_box['title'] ) . '</div>';
	}
	$html .= '<div class="themify_field themify_field-' . esc_attr( $meta_box['type'] ) . '">';

	$html .= isset( $meta_box['meta']['before'] ) ? $meta_box['meta']['before'] : '';
	return $html;
}

/**
 * Markup added after a field in multi field.
 *
 * @param null $after
 *
 * @return null|string
 */
function themify_after_meta_field( $after = null ) {
	$html = isset($after)? $after : '';
	$html .= '
		</div>
	</div><!--/themify_field_row -->';
	return $html;
}

/**
 * Save Custom Write Panel Data
 * @param number
 * @return mixed
 */
function themify_save_postdata( $post_id ) {
	global $post, $themify_write_panels;
	if(isset($_POST['themify_proper_save']) && $_POST['themify_proper_save'] != '') {
		foreach($themify_write_panels as $write_panel){

			foreach($write_panel['options'] as $meta_box) {
				if ( 'page' == $_POST['post_type'] ) {
					if ( !current_user_can( 'edit_page', $post_id ))
						return $post_id;
				} else {
					if ( !current_user_can( 'edit_post', $post_id ))
						return $post_id;
				}
				if('multi' == $meta_box['type']){
					// Grouped fields
					foreach ($meta_box['meta']['fields'] as $field) {
						$data = isset( $field['name'] ) && isset( $_POST[$field['name']] ) ? $_POST[$field['name']] : '';
						if('' == get_post_meta($post_id, $field['name']))
							add_post_meta($post_id, $field['name'], $data, true);
						elseif($data != get_post_meta($post_id, $field['name'], true))
							update_post_meta($post_id, $field['name'], $data);
					}
				} else {
					// Single field
					$data = isset( $_POST[$meta_box['name']] ) ? $_POST[$meta_box['name']] : '';
					if( isset( $meta_box['force_save'] ) ) { // check if the post meta MUST be saved, regardless of it's value
						update_post_meta( $post_id, $meta_box['name'], $data );
					} else if('' == get_post_meta($post_id, $meta_box['name']))
						add_post_meta($post_id, $meta_box['name'], $data, true);
					elseif($data != get_post_meta($post_id, $meta_box['name'], true))
						update_post_meta($post_id, $meta_box['name'], $data);
				}
			}
		}
	} else {
		if ( isset( $post ) && isset( $post->ID ) ) {
			return $post->ID;
		}
	}
	return false;
}

/**
 * Image Helper - Echoes themify_get_image
 * @param string $args Format string.
 */
function themify_image( $args ) {
	echo themify_get_image( $args );
}

/**
 * Returns the post image, either from Themify Custom Panel fields or from WordPress Featured Image.
 * @param string $args Format string.
 * @return string String with <img> tag and optional content prepended and/or appended
 */
function themify_get_image( $args ) {
	global $themify;

	/**
	 * List of parameters
	 * @var array
	 */
	$args = wp_parse_args( $args, array(
		'id' 		 => '',
		'src'		 => '',
		'class' 	 => '',
		'ignore' 	 => '',
		'w'			 => '', // width
		'h'			 => '', // height
		'before' 	 => '',
		'after' 	 => '',
		'alt'		 => '',
		'title'		 => '',
		'crop'		 => true,
		'setting' 	 => '',
		'field_name' => 'post_image,image,wp_thumb,feature_image',
		'urlonly' 	 => false,
		'image_size' => '',
		'image_meta' => false,
				'f_image'=>      false
	) );

	/**
	 * Post ID for single, query or archive views.
	 * Page ID is stored separately in $themify->page_id.
	 * @var string
	 */
	$post_id = get_the_ID();

	/**
	 * URL of the image to use
	 * @var string
	 */
	$img_url = '';

	/**
	 * Image width
	 * @var string
	 */
	$width = '';

	/**
	 * Image height
	 * @var string
	 */
	$height = '';

	/**
	 * Alt text of the attachment
	 * @var string
	 */
	$img_alt = '';

	/**
	 * Title text of the attachment
	 * @var string
	 */
	$img_title = '';

	$attachment_id = 0;
		
	$is_disabled = themify_is_image_script_disabled();
		
	// If ignore is set, just use width and height passed
	if ( ( ! empty( $args['ignore'] ) && !$is_disabled ) || ( isset( $themify->is_shortcode ) && $themify->is_shortcode ) ) {
		if ( ! empty( $args['w'] ) ) {
			$width = $args['w'];
		}
		if ( ! empty( $args['h'] ) ) {
			$height = $args['h'];
		}
	} elseif ( in_the_loop() ) { // Main query area

		if ( is_single() ) { // Single Entry

			if (($width = get_post_meta( $post_id, 'image_width', true ) )==='' && ($width = themify_get( 'setting-default_' . get_post_type() . '_single_image_post_width' ))==='') {
				$width = themify_get( "setting-{$args['setting']}_width" );
			}
			if ( ($height = get_post_meta( $post_id, 'image_height', true ))===''  && ($height = themify_get( 'setting-default_' . get_post_type() . '_single_image_post_height' ))==='' ) {
				$height = themify_get( "setting-{$args['setting']}_height" );
			}
		} elseif ( themify_is_query_page() ) { // Query pages like Query Posts or Query Portfolios
			$query_post_type = ( isset( $themify->query_post_type ) && 'post' != $themify->query_post_type ) ? $themify->query_post_type . '_' : '';
			if (($width = get_post_meta( $themify->page_id, $query_post_type . 'image_width', true ))==='' && ($width = themify_get( 'setting-default_' . get_post_type() . '_index_image_post_width' ))==='' ) {
				$width = themify_get( 'setting-image_post_width' );
			}
		
			if ( ($height = get_post_meta( $themify->page_id, $query_post_type . 'image_height', true ))==='' && ($height = themify_get( 'setting-default_' . get_post_type() . '_index_image_post_height' ))==='' ) {
				$height = themify_get( 'setting-image_post_height' );
			}
		} elseif ( is_archive() || is_tax() || is_search() || is_home() ) { // Category, Tag, Author, Date || Custom Taxonomy || Search
			if (($width = themify_get( 'setting-default_' . get_post_type() . '_index_image_post_width' ) )==='') {
				$width = themify_get( 'setting-image_post_width' );
			}
			if (($height = themify_get( 'setting-default_' . get_post_type() . '_index_image_post_height' ) )==='') {
				$height = themify_get( 'setting-image_post_height' );
			}
		}
	
		// Catch height before width so we can check if user entered something for width.
		if ( ( '' === $height || is_null( $height ) ) && ( '' === $width || is_null( $width ) ) ) {
			$height = $themify->height;
		}
		if ( '' === $width || is_null( $width ) ){
			$width = $themify->width;
		}
	} else {
		if ( !empty( $args['h'] ) && ($width = get_post_meta( $post_id, 'image_width', true ))==='' ) {
			$height = $args['h'];
		}
		if (!empty( $args['w'] ) && ($height = get_post_meta( $post_id, 'image_height', true ))==='') {
			$width = $args['w'];
		}
	}


	if ($is_disabled ) { // Use WP standard image sizes

		if ( ! empty( $args['image_size'] ) ) { // If image_size parameter is set
			$feature_size = $args['image_size'];
		} elseif ( isset( $themify->image_size ) && ! empty( $themify->image_size ) ) { // or if Themify::image_size is set
			$feature_size = $themify->image_size;
		} else {
			if ( in_the_loop() && ( ! isset( $themify->is_shortcode ) || ! $themify->is_shortcode ) ) { // Main query area
				if ( is_single() ) {
					$feature_size = get_post_meta( $post_id, 'feature_size', true );
					if ( empty( $feature_size ) || 'blank' == $feature_size ) {
						$feature_size = themify_get( 'setting-image_post_single_feature_size' );
					}
				} elseif ( themify_is_query_page() ) {
					$feature_size = get_post_meta( $themify->page_id, $query_post_type . 'feature_size_page', true );
					if ( empty( $feature_size ) || 'blank' == $feature_size ) {
						$feature_size = themify_get( 'setting-image_post_feature_size' );
					}
				} elseif ( is_archive() || is_tax() || is_search() || is_home() ) {
					$feature_size = themify_get( 'setting-image_post_feature_size' );
				}
			}
		}
		if ( ! isset( $feature_size ) || 'blank' == $feature_size ) {
			$feature_size = themify_get( 'setting-global_feature_size' );
			if ( empty( $feature_size ) || 'blank' == $feature_size ) {
				$feature_size = apply_filters( 'themify_global_feature_size', 'large' );
			}
		}

		// Set URL to use for final output.
		$img_url = empty( $args['src'] )?themify_image_url( false, $feature_size ):$args['src'];

	} else { // Use Image Script

		if ( empty( $args['src'] ) ) {
			if ( has_post_thumbnail() ) {
				$img_url = (int) get_post_thumbnail_id(); /* Image script works with thumbnail IDs as well as URLs, use ID which is faster */
			} else {
				foreach( explode( ',', $args['field_name'] ) as $field ) {
					if ( $img_url = get_post_meta( $post_id, trim( $field ), true ) ) {
						break;
					}
				}
			}
		} else {
			$img_url = $args['src'];
		}

		if ( 0 === $height ) {
			$args['crop'] = false;
		}
	
		// Set URL to use for final output.
		$temp = themify_do_img( $img_url, $width, $height, (bool) $args['crop'] );
		$img_url = $temp['url'];
		
		// Get title/alt text by attachment id if it was returned.
		if ( isset( $temp['attachment_id'] ) ) {
			$attachment_id = $temp['attachment_id'];
			$img_title = get_the_title( $attachment_id );
			$img_alt = get_post_meta( $temp['attachment_id'], '_wp_attachment_image_alt', true );
		}
	}

	// No image was defined, parse content to find the first image.
	if ( empty( $img_url ) && ($args['f_image'] || themify_check( 'setting-auto_featured_image' ) )) {

		$content = get_the_content();
				$upload_dir = wp_upload_dir();
		foreach ( array( 'img', 'embed', 'iframe' ) as $tag ) {
			$count = substr_count( $content, '<' . $tag );
			if ( $count >= 1 ) {
				$start = strpos( $content, '<' . $tag, 0 );
				$pos = substr( $content, $start );
				$end = strpos( $pos, '>' );
				$temp = themify_prep_image( substr( $pos, 0, $end + 1 ) );
				$ext = explode( '.', $temp['src'] );
				$ext = strtolower( $ext[ count( $ext ) - 1 ] );
				if ( strpos( $temp['src'], '.' ) && ( $ext == 'jpg' || $ext == 'jpeg' || $ext == 'gif' || $ext == 'png' ) ) {
					$auto_image_url = isset( $temp['src'] )? $temp['src'] : '';
					$args['class'] .= isset( $temp['class'] )? ' ' . $temp['class'] : '';
					$args['alt'] = $temp['alt'];
					if ( $is_disabled ) {
						$img_url = themify_image_url( false, $feature_size, themify_get_attachment_id_from_url( $auto_image_url, $upload_dir['baseurl'] ) );
						if ( empty( $img_url ) ) {
							$img_url = esc_url( $auto_image_url );
						}
					} elseif ( $temp = themify_do_img( $auto_image_url, $width, $height, (bool) $args['crop'] ) ) {
						$img_url = $temp['url'];
					}
					break;
				}
			}
		}
	}

	if ( ! empty( $img_url ) ) {
		if ( $args['urlonly'] ) {
			$out = $img_url;
		} else {
			// Build final image
			$out = '';
			if( $args['image_meta'] == true ) {
				$out .= "<meta itemprop=\"width\" content=\"{$width}\">";
				$out .= "<meta itemprop=\"height\" content=\"{$height}\">";
				$out .= "<meta itemprop=\"url\" content=\"{$img_url}\">";
			}
			$out .= "<img src=\"{$img_url}\"";
			if ( $width ) {
				$out .= " width=\"{$width}\"";
			}
			if ( $height ) {
				$out .= " height=\"{$height}\"";
			}
			if ( $attachment_id != 0 ) {
				$args['class'] .= ' wp-image-' . $attachment_id; /* add attachment_id class to img tag */
			}
			if ( ! empty( $args['class'] ) ) {
				$out .= " class=\"{$args['class']}\"";
			}
			// If title was passed as parameter, use it. Otherwise use attachment title.
			if ( ! empty( $args['title'] ) ) {
				$out_title = $args['title'];
			} elseif ( ! empty( $img_title ) ) {
				$out_title = $img_title;
			} else {
				$out_title = '';
			}
			if ( ! empty( $out_title ) ) {
				$out .= ' title="' . esc_attr( $out_title ) . '"';
			}
			// If alt was passed as parameter, use it. Otherwise use alt text by attachment id if it was fetched or post title.
			if ( ! empty( $args['alt'] ) ) {
				$out_alt = $args['alt'];
			} elseif ( ! empty( $img_alt ) ) {
				$out_alt = $img_alt;
			} else {
				$out_alt = the_title_attribute( 'echo=0' );
			}
			$out .= ' alt="' . esc_attr( $out_alt ) . '" />';
		}
		$out = $args['before'] . $out . $args['after'];
	} else {
		$out = '';
	}

	return $out;
}
/**
 * Sets the WP Featured Image size selected for Query Category pages
 * @since 1.1.5
 */
function themify_feature_size_page() {
	global $feature_size_page, $feature_size_cpt, $feature_size_query_page, $post;
	$feature_size_query_page = $post;
	/** Get size for WP Featured Image @var String $feature_size_page*/
	$feature_size_page = themify_get( 'feature_size_page' );
	$types = themify_specific_post_types();
	foreach ( $types as $type ) {
		$fs_cpt = themify_get( 'feature_size_' .$type );
		if ( isset( $fs_cpt ) ) {
			$feature_size_cpt = $fs_cpt;
		}
	}
}

if ( ! function_exists( 'themify_image_url' ) ) {
	/**
	 * Returns the featured image url
	 * @param bool $echo Specify to echo or return the url
	 * @param string $size The image size to return
	 * @param null|int $attachment_id ID of image to load.
	 * @return void|string
	 */
	function themify_image_url( $echo = false, $size = 'full', $attachment_id = null ) {
		$url = '';
		if ( has_post_thumbnail() ) {
			$image = wp_get_attachment_image_src( get_post_thumbnail_id(), $size );
			$url = $image[0];
		} elseif ( ! is_null( $attachment_id ) ) {
			$image = wp_get_attachment_image_src( $attachment_id, $size );
			$url = $image[0];
		}
		$url = apply_filters( 'themify_image_url', $url );
		if ( $echo ) {
			echo esc_url( $url );
			return '';
		} else {
			return $url;
		}
	}
}

/**
 * Image Helper - Prep Image
 * @param $tag
 * @return array
 */
function themify_prep_image( $tag ) {
	preg_match_all('/(alt|title|src|class)=("[^"]*")/i', $tag, $image);
	foreach($image[0] as $attr){
		parse_str($attr, $tempAttr);
		foreach($tempAttr as $key => $val){
			$tempArray[$key] = str_replace(array('"',"'"),array('',''),$val);
		}
	}
	$image = isset( $tempArray )? $tempArray : array( 'src' => '', 'alt' => '', 'title' => '' );
	if ( strpos( $image['src'], 'youtube.com' ) || strpos( $image['src'], 'vimeo.com' ) ) {
		$image['src'] = themify_video_image( $image['src'] );
	}
	return array(
		'src' => trim( $image['src'], "\\" ),
		'alt' => $image['alt'],
		'title' => isset( $image['title'] )? $image['title'] : ''
	);
}

/**
 * Vimeo / Youtube Thumbnail grab
 *
 * @param $url
 *
 * @return string
 */
function themify_video_image($url){
	$image_url = parse_url($url);
	$return_url = '';
	if($image_url['host'] == 'www.youtube.com' || $image_url['host'] == 'youtube.com'){
		parse_str($image_url['query'], $query);
		if(isset($query['v']) && $query['v'] != ""){
			$id = $query['v'];
		} else {
			$path = explode("/",$image_url['path']);
			$id = $path[count($path)-1];
		}
		$return_url = themify_https_esc('http://img.youtube.com/vi/').$id."/hqdefault.jpg";
	} else if($image_url['host'] == 'www.vimeo.com' || $image_url['host'] == 'vimeo.com' || $image_url['host'] == 'player.vimeo.com'){
		parse_str($image_url['query'], $query);
		if(isset($query['clip_id']) && $query['clip_id'] != ""){
			$id = $query['clip_id'];
		} else {
			$path = explode("/",$image_url['path']);
			$id = $path[(count($path)-1)];
		}
		if ( ! function_exists( 'WP_Filesystem' ) ) {
			require_once ABSPATH . 'wp-admin/includes/file.php';
		}
		WP_Filesystem();
		global $wp_filesystem;
		$hash = unserialize( $wp_filesystem->get_contents( themify_https_esc( 'http://vimeo.com/api/v2/video/' ) . $id . ".php" ) );
		if ( isset( $hash[0] ) && $hash[0] != '' ) {
			$return_url = $hash[0]["thumbnail_large"];
		}
	}
	return $return_url;
}

/**
 * Checks if a value referenced by $var exists in theme settings or post meta data.
 *
 * @param $var
 *
 * @return bool
 */
function themify_check( $var ) {
	global $post;
	$data = themify_get_data();
	if ( isset( $data[$var] ) && $data[$var] != '' ) {
		return true;
	} elseif ( is_object( $post ) && get_post_meta( $post->ID, $var, true ) != '' && get_post_meta( $post->ID, $var, true ) ) {
		return true;
	} else {
		return false;
	}
}

/**
 * Returns a value referenced by $var checking in theme settings or post meta data.
 *
 * @param $var
 *
 * @return mixed
 */
function themify_get( $var, $default = null ) {
	global $post;
	$data = themify_get_data();
	if ( isset( $data[$var] ) && $data[$var] != '' ) {
		return $data[$var];
	} else if ( is_object( $post ) && get_post_meta( $post->ID, $var, true ) != '' ) {
		return get_post_meta( $post->ID, $var, true );
	} else {
		return $default;
	}
}

/**
 * Returns a PLUPLOAD instance. If it's a multisite, checks user quota and shows message if it's not enough to continue upload files.
 *
 * @param string $id
 * @param array $params $label = '', $thumbs = false, $filelist = false, $multiple = false, $message = '', $fallback = ''
 *
 * @return string
 */
function themify_get_uploader( $id = '', $args = array() ){

	$defaults = array(
		'label'		=> __('Upload', 'themify'),
		'preset'	=> false,
		'preview'   => false,
		'tomedia'	=> false,
		'topost'	=> '',
		'fields'	=> '',
		'featured'	=> '',
		'message'	=> '',
		'fallback'	=> '',
		'dragfiles' => false,
		'confirm'	=> '',
		'medialib'	=> false,
		'formats'	=> 'jpg,jpeg,gif,png,ico,zip,txt,svg',
		'type'		=> 'image'
	);
	// Extract $label, $preset, $thumbs, $filelist, $multiple, $message, $fallback, $confirm
	$args = wp_parse_args($args, $defaults);

	$upload_visible = false;

	if ( is_multisite() && !is_upload_space_available() ) {
		if( '' != $args['message'] ){
			$html = $args['message'];
		} else {
			$html = '<small>' . sprintf( __( 'Sorry, you have filled your %s MB storage quota so uploading has been disabled.', 'themify' ), get_space_allowed() ) . '</small>';
		}
	} else {
		if( '' != $args['fallback'] )
			$html = $args['fallback'];
		else {
			ob_start();
			// $id is the name of form field. File urls will be submitted in $_POST using this key.
			// If $id == "file" then $_POST["file"] will have all the file urls
			?>
			<!--<input type="hidden" name="<?php echo esc_attr( $id ); ?>" id="<?php echo esc_attr( $id ); ?>" value="" />-->
			<?php if( $args['dragfiles'] ){ ?>
				<div id="<?php echo esc_attr( $id . 'drag-drop-area' ); ?>" class="plupload-drag-drop-area">
			<?php } ?>
				<?php
				$classes = '';
				if($args['preset']) $classes .= 'add-preset ';
				if($args['preview']) $classes .= 'add-preview ';
				if($args['tomedia']) $classes .= 'add-to-media ';

				$datas = array();
				if('' != $args['topost']) $datas[] = 'data-postid="' . esc_attr( $args['topost'] ) . '"';
				if('' != $args['fields']) $datas[] = 'data-fields="' . esc_attr( $args['fields'] ) . '"';
				if('' != $args['confirm']) $datas[] = 'data-confirm="' . esc_attr( $args['confirm'] ) . '"';
				if('' != $args['featured']) $datas[] = 'data-featured="' . esc_attr( $args['featured'] ) . '"';
				if('' != $args['formats']) $datas[] = 'data-formats="' . esc_attr( $args['formats'] ) . '"';
				?>
				<div class="plupload-upload-uic hide-if-no-js <?php echo esc_attr( $classes ); ?>" <?php echo implode( ' ', $datas ); ?> id="<?php echo esc_attr( $id ); ?>plupload-upload-ui">

					<input id="<?php echo esc_attr( $id ); ?>plupload-browse-button" type="button" value="<?php echo esc_attr( $args['label'] ); ?>" class="button plupload-button <?php echo esc_attr( 'plupload-' . $id ); ?>" />

					<span class="ajaxnonceplu" id="ajaxnonceplu<?php echo wp_create_nonce($id . 'themify-plupload'); ?>"></span>

				</div>

			<?php if( $args['dragfiles'] ){ ?>
					<small><?php _e(' or drag files here.', 'themify'); ?></small>
				</div>
			<?php } ?>
			<?php

			$html = ob_get_contents();
			ob_end_clean();
		}
		$upload_visible = true;
	}

	if( $args['medialib'] ) {
		ob_start();
		?>
		<?php
			if ( 'audio' == $args['type'] ) {
				$data_uploader_title = __( 'Browse Audio', 'themify' );
				$medialib_btn_text = __('Insert Audio', 'themify');
			} elseif ( 'video' == $args['type'] ) {
				$data_uploader_title = __( 'Browse Video', 'themify' );
				$medialib_btn_text = __('Insert Video', 'themify');
			} else {
				$data_uploader_title = __( 'Browse Image', 'themify' );
				$medialib_btn_text = __('Insert Image', 'themify');
			}
			$medialib_datas = array(
				'action' => 'themify_media_lib_browse',
				'media_lib_nonce' => wp_create_nonce( 'media_lib_nonce' ),
				'featured' => ($args['featured'] != '') ? 1 : 0,
				'field_name' => $args['fields'],
				'post_id' => $args['topost']
			);
		?>
		<div class="themify_medialib_wrapper">
			<?php if($upload_visible): echo '&nbsp;<em>' . __( 'or', 'themify' ) . '</em>'; endif; ?>&nbsp;
			<a href="#" class="themify-media-lib-browse" data-submit='<?php echo json_encode( $medialib_datas ); ?>' data-uploader-title="<?php echo esc_attr( $data_uploader_title ) ?>" data-uploader-button-text="<?php echo esc_attr( $medialib_btn_text ); ?>" data-fields="<?php echo esc_attr( $args['fields'] ); ?>" data-type="<?php echo esc_attr( $args['type'] ); ?>"><?php _e( 'Browse Library', 'themify' ) ?></a>
		</div>
		<?php
		$html .= ob_get_contents();
		ob_end_clean();
	}

	return $html;
}

/**
 * Echoes a PLUPLOAD uploader
 *
 * @uses themify_get_uploader
 *
 * @param string $id
 * @param array $args
 *
 */
function themify_uploader($id = '', $args = array()){
	echo themify_get_uploader( $id, $args );
}

/**
 * Check if user has available space in multisite installations
 * @param String $allowed Content to show if there is space available
 * @param Boolean $echo Flag establishing if content must be echoed or returned
 * @return String
 * @since 1.1.5
 */
function themify_has_quota($allowed, $echo = false, $custom = ''){
	if ( is_multisite() && !is_upload_space_available() ) {
		if( '' != $custom ){
			$message = $custom;
		} else {
			$message = '<small>' . sprintf( __( 'Sorry, you have filled your %s MB storage quota so uploading has been disabled.', 'themify' ), get_space_allowed() ) . '</small>';
		}
	} else {
		$message = $allowed;
	}
	if($echo){
		echo wp_kses_post( $message );
	}
	return $message;
}

if ( ! function_exists( 'themify_get_image_sizes_list' ) ) {
	/**
	 * Return list of image sizes with labels for translation.
	 * @param bool $nested
	 * @return mixed|void
	 * @since 1.6.8
	 */
	function themify_get_image_sizes_list( $nested = true ) {
		$size_names = apply_filters( 'image_size_names_choose',
			array(
				'thumbnail' => __( 'Thumbnail', 'themify' ),
				'medium' 	=> __( 'Medium', 'themify' ),
				'large' 	=> __( 'Large', 'themify' ),
				'full' 		=> __( 'Original Image', 'themify' )
			)
		);
		$out = array(
			array( 'value' => 'blank', 'name' => '' ),
		);
		foreach( $size_names as $size => $label ) {
			$out[] = array( 'value' => $size, 'name' => $label );
		}
		return apply_filters( 'themify_get_image_sizes_list', $nested ? $out : $size_names, $nested );
	}
}

/**
 * Check if the site is using an HTTPS scheme and returns the proper url
 * @param String $url requested url
 * @return String
 * @since 1.1.5
 */
function themify_https_esc( $url = '' ) {
	if ( is_ssl() ) {
		$url = preg_replace( '/^(http:)/i', 'https:', $url, 1 );
	}
	return $url;
}

/**
 * Returns an array with the post types managed by Themify,
 * where the Themify Custom Panel is initialized.
 * Filterable using themify_post_types
 * @param Array $types additional post types
 * @return Array
 * @since 1.1.5
 */
function themify_post_types($types = array()){
	$defaults = array_merge(
		array('post', 'page'),
		themify_specific_post_types(),
		$types
	);
	return array_unique(apply_filters('themify_post_types', $defaults));
}

/**
 * Returns an array with the post types that are specific to Themify,
 * where the Themify Custom Panel is initialized.
 * Filterable using themify_post_types
 * @return array
 * @since 1.1.5
 */
function themify_specific_post_types(){
	return array_unique(
		apply_filters('themify_specific_post_types', array(
			'menu',
			'slider',
			'highlight',
			'portfolio',
			'testimonial',
			'section'
		))
	);
}

/**
 * Get list of themes from Themify's versions.xml
 * @return Array List of themes
 * @since 1.1.8
 */
function themify_get_theme_names(){

	if ( false === ( $themes_list = get_transient( 'themify_themes_list' ) ) ) {

		$response = wp_remote_get( 'http://themify.me/versions/versions.xml' );
		if( is_wp_error( $response ) ) {
			echo '<h4>' . __('Can\'t load versions file.', 'themify') . '</h4><p>' . $response->get_error_code(). '</p>';
			return false;
		}
		$versionsxml = simplexml_load_string($response['body']);
		foreach($versionsxml->version as $version) {
			$themes_list[] = (string) $version->attributes()->name;
		}

	set_transient( 'themify_themes_list', $themes_list, 60*60 ); }

	return $themes_list;
}

/**
 * Outputs html to display alert messages in post edit/new screens. Excludes pages.
 * @since 1.2.2
 */
function themify_prompt_message() {
	global $pagenow, $typenow;
	if( ('post.php' == $pagenow || 'post-new.php' == $pagenow) && 'page' != $typenow )
		echo '<div class="prompt-box"><div class="show-error"></div></div><div class="overlay">&nbsp;</div>';
}

/**
 * Add different CSS classes to body tag.
 * Outputs:
 * 		skin name
 * 		layout
 * @param Array
 * @return Array
 * @since 1.2.2
 */
function themify_body_classes( $classes ) {
	global $themify;

	$template = get_template();
	$classes[] = 'template-' . $template;
	$classes[] = 'template-' . $template . '-' . str_replace( '.', '-', wp_get_theme( $template )->version );

	// Add skin name
	if( $skin = themify_is_theme_skin() ) {
		$skin_dir = explode( '/', $skin );
		$classes[] = 'skin-' . $skin_dir[sizeof( $skin_dir ) - 2];
	} else {
		$classes[] = 'skin-default';
	}

	// Browser classes
	global $is_gecko, $is_opera, $is_iphone, $is_IE, $is_winIE, $is_macIE;

	$is_android = $is_webkit = $is_ie10 = $is_ie9 = $is_ie8 = $is_ie7 = false;

	if ( isset( $_SERVER['HTTP_USER_AGENT'] ) ) {
		if ( stripos( $_SERVER['HTTP_USER_AGENT'], 'android' ) ) {
			$is_android = true;
		}
		if ( stripos( $_SERVER['HTTP_USER_AGENT'], 'webkit' ) ) {
			$is_webkit = true;
		}
		if ( stripos( $_SERVER['HTTP_USER_AGENT'], 'MSIE 10' ) ) {
			$is_ie10 = true;
		}
		if ( stripos( $_SERVER['HTTP_USER_AGENT'], 'MSIE 9' ) ) {
			$is_ie9 = true;
		}
		if ( stripos( $_SERVER['HTTP_USER_AGENT'], 'MSIE 8' ) ) {
			$is_ie8 = true;
		}
		if ( stripos( $_SERVER['HTTP_USER_AGENT'], 'MSIE 7' ) ) {
			$is_ie7 = true;
		}
	}

	$browsers = array(
		'gecko'   => $is_gecko,
		'opera'   => $is_opera,
		'iphone'  => $is_iphone,
		'android' => $is_android,
		'webkit'  => $is_webkit,
		'ie' 	  => $is_IE,
		'iewin'   => $is_winIE,
		'iemac'   => $is_macIE,
		'ie10' 	  => $is_ie10,
		'ie9' 	  => $is_ie9,
		'ie8' 	  => $is_ie8,
		'ie7' 	  => $is_ie7
	);

	$is_not_ie = true;

	foreach( $browsers as $browser => $state ) {
		if ( $state ) {
			$classes[] = $browser;
			if ( stripos( $browser, 'ie' ) !== false ) {
				$is_not_ie = false;
			}
		}
	}
	if ( $is_not_ie ) {
		$classes[] = 'not-ie';
	}

	// Add default layout and post layout
	$layout = themify_get('setting-default_layout');
	$post_layout = themify_get('setting-default_post_layout');

	// Set content width
	if ( is_search() ) {
		$classes[] = 'default_width';
	} elseif ( is_singular() ) {
		$classes[] = themify_check( 'content_width' ) ? themify_get( 'content_width' ) : 'default_width';
	}

	// It's a page
	if( is_page() ){
		// It's a page
		$layout = (themify_get('page_layout') != 'default' && themify_check('page_layout')) ? themify_get('page_layout') : themify_get('setting-default_page_layout');
	}

	if( themify_is_query_page() ) {
		$classes[] = 'query-page';
		$classes[] = isset($themify->query_post_type) ? 'query-'.$themify->query_post_type: 'query-post';
	}

	// It's a post
	if( is_single() ){
		$layout = (themify_get('layout') != 'default' && themify_check('layout')) ? themify_get('layout') : themify_get('setting-default_page_post_layout');
	}

	// It's a singular view (post, page, portfolio, any custom post type)
	if ( is_singular() ) {
		// Post requires password
		if ( post_password_required( get_the_ID() ) ) {
			$classes[] = 'entry-password-required';
		}
	}

	// If still empty, set default
	if( apply_filters('themify_default_layout_condition', '' == $layout) ){
		$layout = apply_filters('themify_default_layout', 'sidebar1');
	}
	$classes[] = $layout;

	// non-homepage pages
	if( ! ( is_home() || is_front_page() ) ) {
		$classes[] = 'no-home';
	}

	// if the page is being displayed in lightbox
	if( isset( $_GET['iframe'] ) && $_GET['iframe'] == 'true' ) {
		$classes[] = 'lightboxed';
	}

	// Set post layout for blog, archive or a query category page
	$post_query_category = isset($themify->query_category)? $themify->query_category : themify_get('query_category');
	if( is_home() || is_archive() || '' != $post_query_category || is_search() ){
		$post_layout = $themify->post_layout;
		if(apply_filters('themify_default_post_layout_condition', '' == $post_layout)){
			$post_layout = apply_filters('themify_default_post_layout', 'list-post');
		}
		$classes[] = $post_layout;
	}

	$classes[] = themify_is_touch() ? 'touch' : 'no-touch';
		
		if(themify_get('setting-lightbox_content_images')){
			$classes[] = 'themify_lightboxed_images';
		}
		
	return apply_filters('themify_body_classes', $classes);
}

/**
 * Adds classes to .post based on elements enabled for the currenty entry.
 *
 * @since 2.0.4
 *
 * @param $classes
 *
 * @return array
 */
function themify_post_class( $classes ) {
	global $themify;

	$classes[] = ( ! isset($themify->hide_title) || ( isset( $themify->hide_title ) && $themify->hide_title != 'yes' ) ) ? 'has-post-title' : 'no-post-title';
	$classes[] = ( ! isset( $themify->hide_date ) || ( isset( $themify->hide_date ) && $themify->hide_date != 'yes' ) ) ? 'has-post-date' : 'no-post-date';
	$classes[] = ( ! isset( $themify->hide_meta_category ) || ( isset( $themify->hide_meta_category ) && $themify->hide_meta_category != 'yes' ) ) ? 'has-post-category' : 'no-post-category';
	$classes[] = ( ! isset( $themify->hide_meta_tag ) || ( isset( $themify->hide_meta_tag ) && $themify->hide_meta_tag != 'yes' ) ) ? 'has-post-tag' : 'no-post-tag';
	$classes[] = ( ! isset( $themify->hide_meta_comment ) || ( isset( $themify->hide_meta_comment ) && $themify->hide_meta_comment != 'yes' ) ) ? 'has-post-comment' : 'no-post-comment';
	$classes[] = ( ! isset( $themify->hide_meta_author ) || ( isset( $themify->hide_meta_author ) && $themify->hide_meta_author != 'yes' ) ) ? 'has-post-author' : 'no-post-author';

	return apply_filters( 'themify_post_classes', $classes );
}

/**
 * Checks if the image field is the thumbnail or not.
 * @return Bool
 * @since 1.2.2
 */
function themify_is_thumbnail_field($field){
	return apply_filters('themify_is_thumbnail_field', 'post_image' == $field || 'feature_image' == $field);
}

/**
 * Search array by key and value
 *
 * @param      $array
 * @param      $key
 * @param      $value
 * @param bool $duplicate
 * @param null $uniq_key
 * @param null $uniq_val
 *
 * @return array
 */
function themify_search_arr( $array, $key, $value, $duplicate = false, $uniq_key = null, $uniq_val = null ) {
	$results = array();
	themify_search_r( $array, $key, $value, $results, $duplicate, $uniq_key, $uniq_val );
	return $results;
}

/**
 * Function search array by key and value
 *
 * @param      $array
 * @param      $key
 * @param      $value
 * @param      $results
 * @param bool $duplicate
 * @param null $uniq_key
 * @param null $uniq_val
 */
function themify_search_r( $array, $key, $value, &$results, $duplicate = false, $uniq_key = null, $uniq_val = null ) {
	if ( ! is_array( $array ) )
		return;

	if ( $duplicate ) {
		if ( isset( $array[$key] ) && $array[$key] == $value )
			$results[] = $array;
	} else {
		if ( isset( $array[ $key ] ) && stripos( $array[ $uniq_key ], $uniq_val ) !== false )
			$results[] = $array;
	}

	foreach ( $array as $subarray )
		themify_search_r( $subarray, $key, $value, $results, $duplicate, $uniq_key, $uniq_val );
}

/**
 * Get styling selector by id or selector
 *
 * @param      $key
 * @param      $value
 * @param      $context
 * @param bool $duplicate
 * @param null $uniq_key
 * @param null $uniq_val
 *
 * @return string
 */
function themify_get_styling_selector( $key, $value, $context, $duplicate = false, $uniq_key = null, $uniq_val = null ) {
	global $ThemifyConfig;
	$config = $ThemifyConfig->get_config();
	$result = '';
	$arr = themify_search_arr( $config['panel']['styling']['tab'][ $context ]['element'], $key, $value, $duplicate, $uniq_key, $uniq_val );

	if ( isset( $arr[0]['selector'] ) )
		$result = $arr[0]['selector'];

	return $result;
}

/**
 * Return specific array
 * @param string $key
 * @param string $context
 * @return array
 */
function themify_get_theme_arr( $key, $context = 'settings' ) {
	global $ThemifyConfig;
	$config = $ThemifyConfig->get_config();
	$return = array();

	if ( isset( $config['panel'][ $context ]['tab'][ $key ] ) )
		$return = $config['panel'][ $context ]['tab'][ $key ];

	return $return;
}

/**
 * Check whether array is associative or indexed
 * @param array $array
 * @return boolean
 */
function themify_is_associative_array( $array ) {
	return ( is_array( $array ) && ! is_numeric( implode( "", array_keys( $array ) ) ) );
}

/**
 * Get google font lists
 * @return array
 */
function themify_get_google_font_lists() {
	if( !defined('THEMIFY_GOOGLE_FONTS') ) {
		define('THEMIFY_GOOGLE_FONTS', true);
	}
	if( !THEMIFY_GOOGLE_FONTS ) {
		return array();
	}
	return themify_grab_remote_google_fonts();
}

/**
 * Return file to use depending if user selected Recommended or Full list in theme settings.
 *
 * @since 2.1.7
 *
 * @return string
 */
function themify_get_google_fonts_file() {
	if ( 'full' == themify_get( 'setting-webfonts_list' ) ) {
		$fonts = THEMIFY_DIR . '/google-fonts.php';
	} else {
		$fonts = THEMIFY_DIR . '/google-fonts-recommended.php';
	}

	/**
	 * Filters the file loaded.
	 * Useful for recovery in case user loaded Full List and their server can't manage it.
	 * @param string $fonts
	 */
	return apply_filters( 'themify_google_fonts_file', $fonts );
}

/**
 * Grab google fonts lists from api
 * @return array
 */
function themify_grab_remote_google_fonts() {
	$fonts_file_path = themify_get_google_fonts_file();
	$setting_webfonts_subsets = sanitize_text_field( themify_get( 'setting-webfonts_subsets' ) );
	if ( themify_check( 'setting-webfonts_subsets' ) && '' != $setting_webfonts_subsets ) {
		$user_subsets = explode( ',', str_replace( ' ', '', $setting_webfonts_subsets ) );
	} else {
		$user_subsets = array();
	}
	$subsets = apply_filters( 'themify_google_fonts_subsets', array_merge( array('latin'), $user_subsets ) );
	$subsets_count = count($subsets);

	$fonts = array();
	$results = include( $fonts_file_path );
	if( $results !== false ) {
		foreach ( $results as $font ) {
			// If user specified additional subsets
			if( $subsets_count > 1) {
				$font_subsets = $font['subsets'];
				$subsets_match = true;
				// Check that all specified subsets are available in this font
				foreach ($subsets as $subset) {
					if(!in_array($subset, $font_subsets)) {
						$subsets_match = false;
					}
				}
				// Ok, this font supports all subsets requested by user, add it to the list
				if($subsets_match) {
					$fonts[] = array(
						'family' => $font['label'],
						'variant' => $font['variants'][0]
					);
				}
			} else {
				$fonts[] = array(
					'family' => $font['label'],
					'variant' => $font['variants'][0]
				);
			}
		}
	}
	return $fonts;
}

/**
 * Check if given value is google fonts or web safe fonts
 * @param string $value
 * @return boolean
 */
function themify_is_google_fonts( $value ) {
	global $themify_gfonts;
	$found = false;
	if ( sizeof( $themify_gfonts ) > 0 ) {
		foreach ( $themify_gfonts as $font ) {
			if ( $found ) break;
			if ( $font['family'] == $value ) $found = true;
		}
	}
	return $found;
}

/**
 * Get selected custom css google fonts
 * @return array
 */
function themify_get_custom_css_gfonts() {
	$data = themify_get_data();
	$fonts = array();
	if ( is_array( $data ) ) {
		$new_arr = array();
		foreach ( $data as $name => $value ) {
			$array = explode( '-', $name );
			$path = '';
			foreach( $array as $part ) {
				$path .= "[$part]";
			}
			$new_arr[ $path ] = $value;
		}
		$config = themify_convert_brackets_string_to_arrays( $new_arr );
		if ( isset( $config['styling'] ) && is_array( $config['styling'] ) ) {
			foreach ( $config['styling'] as $ks => $styling ) {
				foreach ( $styling as $element => $val ) {
					foreach ( $val as $attribute => $v ) {
						switch ( $attribute ) {
							case 'font_family':
								if ( ! empty( $v['value']['value'] ) && themify_is_google_fonts( $v['value']['value'] ) )
									array_push( $fonts, $v['value']['value'] );
								break;
						}
					}
				}
			}
		}
	}
	return $fonts;
}

/**
 * Load google fonts library
 * @param array $fonts
 */
function themify_enqueue_gfonts() {
	$fonts = themify_get_custom_css_gfonts();
	$families = array();
	if ( themify_check( 'setting-webfonts_subsets' ) && '' != themify_get( 'setting-webfonts_subsets' ) ) {
		$user_subsets = explode( ',', str_replace( ' ', '', themify_get( 'setting-webfonts_subsets' ) ) );
	} else {
		$user_subsets = array();
	}
	$subsets = apply_filters( 'themify_google_fonts_subsets', array_merge( array( 'latin' ), $user_subsets ) );
	$query = null;
	$fonts = array_unique( $fonts );
	foreach ( $fonts as $font ) {
		$words = explode( '-', $font );
		$variant = themify_get_gfont_variant( $font );
		foreach ( $words as $key => $word ) {
			$words[$key] = ucwords( $word );
		}
		array_push( $families, implode( '+', $words ) . ':' . $variant );
	}
	if ( ! empty( $families ) ) {
		$query .= '?family=' . implode( '|', $families );
		$query .= '&subset=' . implode( ',', $subsets );

		// check to see if site is uses https
		$http = ( is_ssl() ) ? 'https' : 'http';
		$url = $http.'://fonts.googleapis.com/css';
		$url .= $query;

		wp_enqueue_style( 'themify-google-fonts', $url );
	}
}

if ( ! function_exists( 'themify_get_gfont_variant' ) ) {
	/**
	 * Get font default variant
	 * @param $family
	 * @return string
	 */
	function themify_get_gfont_variant( $family ) {
		global $themify_gfonts;
		$variant = 400;
		if ( isset( $themify_gfonts ) && is_array( $themify_gfonts ) ) {
			foreach ($themify_gfonts as $v) {
				if ( $v['family'] == $family ) {
					$variant = $v['variant'];
					break;
				}
			}
		}
		return $variant;
	}
}

if(!function_exists('themify_options_module')){
	/**
	 * Returns list of <option>
	 * @param array $options List of options
	 * @param string $key
	 * @param bool $associative
	 * @param string $default
	 * @return string
	 * @since 1.3.5
	 */
	function themify_options_module($options = array(), $key = '', $associative = true, $default = ''){
		$data = themify_get_data();
		$output = '';
		if(true == $associative) {
			foreach($options as $option){
				$output .= '<option '.selected($option['value'], isset($data[$key])? $data[$key] : $default, false).' value="' . esc_attr( $option['value'] ) . '">' . esc_html( $option['name'] ) . '</option>';
			}
		} elseif(false == $associative) {
			foreach($options as $option){
				if($option == $data[$key]){
					$output .= '<option value="' . esc_attr( $option ) . '" selected="selected">' . esc_html( $option ) . '</option>';
				} else {
					$output .= '<option value="' . esc_attr( $option ) . '">' . esc_html( $option ) . '</option>';
				}
			}
		}
		return $output;
	}
}

if(!function_exists('themify_lightbox_vars_init')){
	/**
	 * Post Gallery lightbox/fullscreen and single lightbox definition
	 * @return array Lightbox/Fullscreen galleries initialization parameters
	 */
	function themify_lightbox_vars_init(){
		$lightbox_content_images = themify_get('setting-lightbox_content_images');
		$gallery_lightbox = themify_get('setting-gallery_lightbox');
		$lightboxSelector = '.themify_lightbox';
		$file_extensions = array('jpg', 'gif', 'png', 'JPG', 'GIF', 'PNG', 'jpeg', 'JPEG');
		$content_images = '';
		$gallery_selector = '';
		foreach ($file_extensions as $ext) {
			$content_images .= '.post-content a[href$='.$ext.'],.page-content a[href$='.$ext.'],';
			$gallery_selector .= '.gallery-icon > a[href$='.$ext.'],';
		}
		$content_images = substr($content_images, 0, -1);
		$gallery_selector = substr($gallery_selector, 0, -1);

		// Lightbox default settings
		$overlay_args = array(
			'lightboxSelector' 	=> $lightboxSelector,
			'lightboxOn'		=> true,
			'lightboxContentImages' => '' == $lightbox_content_images? false : true,
			'lightboxContentImagesSelector' => $content_images,
			'theme' 			=> apply_filters('themify_overlay_gallery_theme', 'pp_default'),
			'social_tools' 		=> false,
			'allow_resize' 		=> true,
			'show_title' 		=> false,
			'overlay_gallery' 	=> false,
			'screenWidthNoLightbox' => 600,
			'deeplinking' 		=> false,
			'contentImagesAreas' => '.post, .type-page, .type-highlight, .type-slider'
		);

		// If user selected lightbox or is a new install/reset
		if('lightbox' == $gallery_lightbox || 'prettyphoto' == $gallery_lightbox || null == $gallery_lightbox){
			$overlay_args['gallerySelector'] = $gallery_selector;
			$overlay_args['lightboxGalleryOn'] = true;

		// else if user selected fullscreen gallery
		} elseif('photoswipe' == $gallery_lightbox){
			// Include fullscreen gallery style and script
			wp_enqueue_style(  'photoswipe', THEMIFY_URI . '/css/photoswipe.css', array(), THEMIFY_VERSION );
			wp_enqueue_script( 'photoswipe', THEMIFY_URI . '/js/photoswipe.js', array('jquery'), THEMIFY_VERSION, true );

			// Parameter to handle fullscreen gallery
			$overlay_args = array_merge($overlay_args, array(
				'fullscreenSelector' => $gallery_selector,
				'fullscreenOn' 	 => true,
				'imageScaleMethod'	=> (themify_get('setting-lightbox_swipe_upscale')) ? 'fit' : 'fitNoUpscale'
			));
		}

		return apply_filters('themify_gallery_plugins_args', $overlay_args);
	}
}

if ( ! function_exists( 'themify_lightbox_link_field' ) ) {
	/**
	 * Returns Lightbox Link field definition for themify custom panel
	 * @return array
	 */
	function themify_lightbox_link_field( $args = array() ) {

		$defaults = array(
			'name' 	=> 'multi_lightbox_link',
			'title' => __('Lightbox Link', 'themify'),
			'description' => '',
			'type' 	=> 'multi',
			'meta'	=> array(
				'fields' => array(
			  		// Lightbox link field
			  		array(
						'name' 	=> 'lightbox_link',
						'label' => '',
						'description' => __('Link Featured Image and Post Title to lightbox image, video or iframe URL <br/>(<a href="http://themify.me/docs/lightbox">learn more</a>)', 'themify'),
						'type' 	=> 'textbox',
						'meta'	=> array(),
						'before' => '',
						'after' => '',
					),
					array(
						'name' 		=> 'iframe_url',
						'label' 		=> __('iFrame URL', 'themify'),
						'description' => '',
						'type' 		=> 'checkbox',
						'before' => '',
						'after' => '',
					),
					array(
						'name' 		=> 'lightbox_icon',
						'label' 		=> __('Add zoom icon on lightbox link', 'themify'),
						'description' => '',
						'type' 		=> 'checkbox',
						'before' => '',
						'after' => '',
					)
				),
				'description' => '',
				'before' => '',
				'after' => '',
				'separator' => ''
			)
		);

		$field = wp_parse_args( $args, $defaults );

		return apply_filters( 'themify_lightbox_link_field', $field );
	}
}

if( ! function_exists( 'themify_image_dimensions_field' ) ) {
	/**
	 * Multi field: Image dimensions fields to enter width and height.
	 * @param array $args
	 * @param string $prefix
	 * @return mixed|void
	 * @since 1.5.2
	 */
	function themify_image_dimensions_field( $args = array(), $prefix = 'image' ) {
		if(!themify_is_image_script_disabled()){
			$defaults = array(
				'type' => 'multi',
				'name' => $prefix . '_dimensions',
				'title' => __('Image Dimension', 'themify'),
				'meta' => array(
					'fields' => array(
						// Image Width
						array(
							'name' => $prefix . '_width',
							'label' => __('width', 'themify'),
							'description' => '',
							'type' => 'textbox',
							'meta' => array('size' => 'small')
						),
						// Image Height
						array(
							'name' => $prefix . '_height',
							'label' => __('height', 'themify'),
							'type' => 'textbox',
							'meta' => array( 'size' => 'small')
						),
					),
					'description' => __('Enter height = 0 to disable vertical cropping with image script enabled', 'themify'),
					'before' => '',
					'after' => '',
					'separator' => ''
				)
			);
		} else {
			$defaults = array( 'name'=>'','type'=>'' );
		}
		$field = wp_parse_args( $args, $defaults );

		return apply_filters( 'themify_image_dimensions_field', $field );
	}
}

if( ! function_exists( 'themify_multi_meta_field' ) ) {
	/**
	 * Definition for tri-state hide meta buttons
	 *
	 * @param array  $args
	 * @param string $prefix
	 *
	 * @return mixed|void
	 * @since 1.5.2
	 */
	function themify_multi_meta_field( $args = array(), $prefix = 'hide_meta' ) {

		$states = themify_ternary_states( array( 'label_no' => __('Do not hide', 'themify') ) );

		$defaults = array(
			'name' 		=> $prefix . '_multi',
			'title' 	=> __('Hide Post Meta', 'themify'),
			'description' => '',
			'type' 		=> 'multi',
			'meta'		=>  array (
				'fields' => array(
					array(
						'name' => $prefix . '_all',
						'title' => __('Hide All', 'themify'),
						'description' => '',
						'type' => 'dropdownbutton',
						'states' => $states,
						'main' => true,
						'disable_value' => 'yes'
					),
					array(
						'name' => $prefix . '_author',
						'title' => __('Author', 'themify'),
						'description' => '',
						'type' => 'dropdownbutton',
						'states' => $states,
						'sub' => true
					),
					array(
						'name' => $prefix . '_category',
						'title' => __('Category', 'themify'),
						'description' => '',
						'type' => 'dropdownbutton',
						'states' => $states,
						'sub' => true
					),
					array(
						'name' => $prefix . '_comment',
						'title' => __('Comment', 'themify'),
						'description' => '',
						'type' => 'dropdownbutton',
						'states' => $states,
						'sub' => true
					),
					array(
						'name' => $prefix . '_tag',
						'title' => __('Tag', 'themify'),
						'description' => '',
						'type' => 'dropdownbutton',
						'states' => $states,
						'sub' => true
					),
				),
				'description' => '',
				'before' => '',
				'after' => '',
				'separator' => ''
			)
		);

		$field = wp_parse_args( $args, $defaults );

		return apply_filters( 'themify_multi_meta_field', $field );
	}
}

if ( ! function_exists( 'themify_get_shortcode_template' ) ) {
	/**
	 * Returns markup
	 * @param $posts
	 * @param string $slug
	 * @param string $name
	 * @param bool $echo
	 * @return mixed|void
	 * @since 1.3.8
	 */
	function themify_get_shortcode_template($posts, $slug = 'includes/loop', $name = 'index', $echo = false) {
		global $post, $themify, $ThemifyBuilder;
		if ( is_object( $post ) )
			$saved_post = clone $post;

		$themify->is_shortcode_template = true;

		// Add flag that template loop is in builder loop
		if ( is_object( $ThemifyBuilder ) ) {
			$ThemifyBuilder->in_the_loop = true;
		}
		ob_start();

		// get_template_part, defined in wp-includes/general-template.php
		$templates = array();
		$name = (string) $name;
		if ( '' !== $name )
			$templates[] = "{$slug}-{$name}.php";
		$templates[] = "{$slug}.php";
		$template_file = apply_filters( 'themify_get_shortcode_template_file', locate_template( $templates, false, false ), $slug, $name );

		foreach ( $posts as $post ) {
			setup_postdata( $post );

			// get_template_part, defined in wp-includes/general-template.php
			do_action( "get_template_part_{$slug}", $slug, $name );
			if( ! empty( $template_file ) ) {
				include $template_file;
			}
		}
		$html = ob_get_contents();
		ob_end_clean();

		if ( isset( $saved_post ) && is_object( $saved_post ) )
			$post = $saved_post;

		// Add flag that template loop is in builder loop
		if ( is_object( $ThemifyBuilder ) ) {
			$ThemifyBuilder->in_the_loop = false;
		}

		return apply_filters('themify_get_shortcode_template', $html);
	}
}

if(!function_exists('themify_get_current_post_type')){
	function themify_get_current_post_type() {
		global $post, $typenow, $current_screen;
		if ( $post && $post->post_type )
			return $post->post_type;
		elseif( $typenow )
			return $typenow;
		elseif( $current_screen && $current_screen->post_type )
			return $current_screen->post_type;
		elseif( isset( $_REQUEST['post_type'] ) )
			return sanitize_key( $_REQUEST['post_type'] );
		elseif( isset( $_GET ) && isset( $_GET['post'] ) )
			return get_post_type( $_GET['post'] );
		return null;
	}
}

if ( ! function_exists( 'themify_get_all_terms_ids' ) ) {
	/**
	 * Returns all IDs from the given taxonomy
	 * @param string $tax Taxonomy to retrieve terms from.
	 * @return array $term_ids Array of all taxonomy terms
	 * @since 1.5.6
	 */
	function themify_get_all_terms_ids($tax = 'category') {
		if ( ! $term_ids = wp_cache_get( 'all_'.$tax.'_ids', $tax ) ) {
			$term_ids = get_terms( $tax, array('fields' => 'ids', 'get' => 'all') );
			wp_cache_add( 'all_'.$tax.'_ids', $term_ids, $tax );
		}
		return $term_ids;
	}
}

if ( ! function_exists('themify_get_google_web_fonts_list') ) {
	/**
	 * Returns a list of Google Web Fonts
	 * @return array
	 * @since 1.5.6
	 */
	function themify_get_google_web_fonts_list() {
		static $google_fonts_list;
                if(!$google_fonts_list){
                    $google_fonts_list = array(
                            array('value' => '', 'name' => ''),
                            array(
                                    'value' => '',
                                    'name' => '--- '.__('Google Fonts', 'themify').' ---'
                            )
                    );
                    foreach( wp_list_pluck( themify_get_google_font_lists(), 'family' ) as $font ) {
                            $google_fonts_list[] = array(
                                    'value' => $font,
                                    'name' => $font
                            );
                    }
                    $google_fonts_list = apply_filters('themify_get_google_web_fonts_list', $google_fonts_list);
                }
                return $google_fonts_list;
	}
}

if ( ! function_exists('themify_get_web_safe_font_list') ) {
	/**
	 * Returns a list of web safe fonts
	 * @param bool $only_names Whether to return only the array keys or the values as well
	 * @return mixed|void
	 * @since 1.0.0
	 */
	function themify_get_web_safe_font_list($only_names = false) {
		$web_safe_font_names = array(
			'Arial, Helvetica, sans-serif',
			'Verdana, Geneva, sans-serif',
			'Georgia, \'Times New Roman\', Times, serif',
			'\'Times New Roman\', Times, serif',
			'Tahoma, Geneva, sans-serif',
			'\'Trebuchet MS\', Arial, Helvetica, sans-serif',
			'Palatino, \'Palatino Linotype\', \'Book Antiqua\', serif',
			'\'Lucida Sans Unicode\', \'Lucida Grande\', sans-serif'
		);

		if( ! $only_names ) {
			$web_safe_fonts = array(
				array('value' => 'default', 'name' => '', 'selected' => true),
				array('value' => '', 'name' => '--- '.__('Web Safe Fonts', 'themify').' ---')
			);
			foreach( $web_safe_font_names as $font ) {
				$web_safe_fonts[] = array(
					'value' => $font,
					'name' => str_replace( '\'', '"', $font )
				);
			}
		} else {
			$web_safe_fonts = $web_safe_font_names;
		}

		return apply_filters( 'themify_get_web_safe_font_list', $web_safe_fonts );
	}
}

if ( ! function_exists( 'themify_is_touch' ) ) {
	/**
	 * According to what $check parameter specifies to check, returns true if it's a phone, tablet, or both.
	 * @param string $check
	 * @return mixed
	 * @since 1.6.8
	 */
	function themify_is_touch( $check = 'all' ) {
		static $themify_mobile_detect;

		if ( ! isset( $themify_mobile_detect ) ) {
			if ( ! class_exists( 'Themify_Mobile_Detect' ) ) {
				require_once 'class-themify-mobile-detect.php';
			}
			$detect = new Themify_Mobile_Detect;
			$is_tablet = $detect->isTablet();
			$is_mobile = $detect->isMobile();
			$themify_mobile_detect = array(
				'phone' => $is_mobile && ! $is_tablet,
				'tablet' =>  $is_tablet,
				'all' => $is_mobile,
			);
		}

		return $themify_mobile_detect[$check];
	}
}

/**
 * Checks that status of the image script.
 * @return bool
 * @since 1.7.4
 */
function themify_is_image_script_disabled() {
	if ( themify_check( 'setting-img_settings_use' ) ) {
		return true;
	}
	return false;
}

/**
 * Checks if current user is allowed to view the update interface.
 *
 * @since 2.0.0
 *
 * @return bool
 */
function themify_allow_update() {
	static $allow;
	if ( ! isset( $allow ) ) {
		$allow = current_user_can( 'update_themes' );
	}
	return $allow;
}

/**
 * Checks if there is styling data or custom CSS.
 *
 * 1.9.1 Removed cached option because it might be misleading on certain situations.
 *		 Refactored to exit as soon as possible and minimize execution time and memory usage.
 *
 * @since 1.8.2
 *
 * @return bool
 */
function themify_has_styling_data() {

	/* Allow to restore the Styling panel by filtering and returning true */
	if ( apply_filters( 'themify_show_styling_panel', false ) ) {
		return true;
	}

	/**
	 * @var array $themify_data Themify theme settings and styling.
	 */
	$themify_data = themify_get_data();

	// Check Custom CSS
	$custom_css = isset( $themify_data['setting-custom_css'] ) && ! empty( $themify_data['setting-custom_css'] );
	if ( $custom_css ) {
		return true;
	}

	// Check styling data
	foreach ( $themify_data as $key => $val ) {
		if ( false !== stripos( $key, 'styling-' ) ) {
			$val = trim($val);
			if ( ! empty( $val ) ) {
				return true;
			}
		}
	}

	return false;
}

/**
 * Adds lightbox parameters to a given URI
 *
 * @since 1.8.2
 * @return string
 */
function themify_get_lightbox_iframe_link( $uri ) {
	if( preg_match( '/\.(jpe?g|gif|png)$/i', $uri ) )
		return $uri;
	$uri_segments = parse_url( $uri );
	$query_args = isset( $uri_segments['query'] ) ? $uri_segments['query'] : '';
	wp_parse_str( $query_args, $uri_args );
	$percent =  '100%';
	$args = wp_parse_args( $uri_args, array( 'iframe' => 'true', 'width' => $percent, 'height' => $percent ) );

	return add_query_arg( $args, $uri );
}

/**
 * Get demo cache dir
 * @return array
 */
function themify_get_cache_dir() {
	$upload_dir = wp_upload_dir();

	$dir_info = array(
		'path'   => $upload_dir['basedir'] . '/themify/',
		'url'    => $upload_dir['baseurl'] . '/themify/'
	);

	if( ! file_exists( $dir_info['path'] ) ) {
		wp_mkdir_p( $dir_info['path'] );
	}

	return $dir_info;
}

/**
 * Uncompress GZip file
 * @param string $srcName
 * @param string $dstName
 */
function themify_uncompress_gzip( $srcName, $dstName ) {
	$sfp = gzopen( $srcName, "rb" );
	if ( ! function_exists( 'WP_Filesystem' ) ) {
		require_once( ABSPATH . 'wp-admin/includes/file.php' );
	}

	WP_Filesystem();
	global $wp_filesystem;

	$string = '';
	while ( ! gzeof( $sfp ) ) {
		$string .= gzgets( $sfp, 8192 );
	}
	$wp_filesystem->put_contents( $dstName, $string, FS_CHMOD_FILE );
	gzclose($sfp);
}

if ( ! function_exists( 'themify_get_available_menus' ) ) {
	/**
	 * Returns available navigation menus.
	 *
	 * @since 1.9.5
	 *
	 * @return array
	 */
	function themify_get_available_menus() {
		$out = array( array( 'name' => '', 'value' => '', 'selected' => true ) );
		$menus = get_terms( 'nav_menu' );
		if ( ! empty( $menus ) && ! is_wp_error( $menus ) ) {
			foreach ( $menus as $menu ) {
				$out[] = array( 'name' => $menu->name, 'value' => $menu->slug );
			}
		}
		return apply_filters( 'themify_get_available_menus', $out );
	}
}

/**
 * Add "js" classname to html element when JavaScript is enabled
 *
 * @since 1.9.9
 */
function themify_html_js_class() {
	echo "<script>(function(html){ html.className = html.className.replace(/\bno-js\b/,'js'); if (html.classList) { html.classList.add( 'js' ); } else { html.className += ' js'; } })(document.documentElement);</script>";
}

/**
 * Checks if a given number is negative or not.
 *
 * @since 2.0.7
 *
 * @param $number
 *
 * @return bool
 */
function themify_is_negative_number( $number ) {
	return $number < 0;
}
/**
 * Checks if a given number is positive or not.
 *
 * @since 2.0.7
 *
 * @param $number
 *
 * @return bool
 */
function themify_is_positive_number( $number ) {
	return $number >= 0;
}
/**
 * Converts a given number to absolute value.
 *
 * @since 2.0.7
 *
 * @param $number
 *
 * @return bool
 */
function themify_make_absolute_number( $number ) {
	return abs( $number );
}

/**
 * Checks if the string begins with - like "-excluded"
 *
 * @since 2.1.6
 *
 * @param string $string String to check
 *
 * @return bool True if string begins with -, false otherwise.
 */
function themify_is_negative_string( $string ) {
	return '-' === $string[0];
}

/**
 * Checks if the string does not being with - like "included"
 *
 * @since 2.1.6
 *
 * @param string $string String to check
 *
 * @return bool True if string does not begin with -, false otherwise.
 */
function themify_is_positive_string( $string ) {
	return '-' !== $string[0];
}

/**
 * If installation is in debug mode, returns '' to load non-minified scripts and stylesheets.
 *
 * @since 2.1.3
 */
function themify_minified() {
	return ( defined( 'WP_DEBUG' ) && WP_DEBUG ) ? '' : '.min';
}

/**
 * Returns a collection of options: yes, no and default which means the theme settings will be used.
 *
 * @since 2.1.3
 *
 * @param string $yes
 * @param string $no
 * @param string $default
 * @param array $args
 *
 * @return array
 */
function themify_ternary_options( $yes = '', $no = '', $default = '', $args = array() ) {
	return wp_parse_args( $args, array(
		array(
			'value' => 'default',
			'name'  => !empty( $default ) ? $default : __( 'Default', 'themify' ),
			'selected' => true
		),
		array(
			'value'    => 'yes',
			'name'     => !empty( $yes ) ? $yes : __( 'Yes', 'themify' ),
		),
		array(
			'value' => 'no',
			'name'  => !empty( $no ) ? $no : __( 'No', 'themify' ),
		),
	));
}

/**
 * Returns a collection of states: yes, no and default which means the theme settings will be used.
 *
 * @since 2.1.3
 *
 * @param string $yes
 * @param string $no
 * @param string $default
 * @param array $args
 *
 * @return array
 */
function themify_ternary_states( $args = array(), $all = array() ) {
	$args = wp_parse_args( $args, array(
		'label_yes' => '',
		'label_no' => '',
		'icon_yes' => THEMIFY_URI . '/img/ddbtn-check.png',
		'icon_no' => THEMIFY_URI . '/img/ddbtn-cross.png',
		'value_default' => '',
	) );
	return wp_parse_args( $all, array(
		array(
			'name' => empty( $args['label_yes'] ) ? __('Hide', 'themify') : $args['label_yes'],
			'value' => 'yes',
			'icon' => $args['icon_yes'],
			'title' => __('Hide this', 'themify')
		),
		array(
			'name' => empty( $args['label_no'] ) ? __('Show', 'themify') : $args['label_no'],
			'value' => 'no',
			'icon' => $args['icon_no'],
			'title' => __('Show this', 'themify')
		),
		array(
			'name' => empty( $default ) ? __('Theme default', 'themify') : $default,
			'value' => $args['value_default'],
			'icon' => THEMIFY_URI . '/img/ddbtn-blank.png',
			'title' => __('Use theme settings', 'themify'),
			'default' => true
		)
	));
}

if ( ! function_exists( 'themify_disable_responsive_design' ) ) {
	/**
	 * Disables the responsive design by removing media-queries.css file and changing viewport tag
	 *
	 * @since 2.1.5
	 */
	function themify_disable_responsive_design() {
		// Remove media-queries.css
		add_action( 'wp_enqueue_scripts', create_function( '', "wp_deregister_style( 'themify-media-queries' );" ), 20 );

		// Remove JS for IE
		remove_action( 'wp_head', 'themify_ie_enhancements' );

		// Remove meta viewport tag
		remove_action( 'wp_head', 'themify_viewport_tag' );
	}
}

if ( ! function_exists( 'themify_enable_mobile_zoom' ) ) {
	/**
	 * Enable pinch to zoom on mobile by changing viewport tag
	 *
	 * @since 2.1.5
	 */
		function themify_enable_mobile_zoom() {
		  // remove theme viewport tag first
		remove_action('wp_head', 'themify_viewport_tag');

		// add custom viewport tag
		function themify_mobile_zoom_viewport_tag() {
			echo '<meta name="viewport" content="width=device-width, initial-scale=1">';
		};
		add_action( 'wp_head', 'themify_mobile_zoom_viewport_tag' );
	}
}

/**
 * Returns allowed tags for widget params before_widget and after_widget
 *
 * @since 2.1.8
 *
 * @return mixed|void
 */
function themify_before_after_widget_allowed_tags() {
	/**
	 * Filters allowed tags.
	 *
	 * @since 2.1.8
	 *
	 * @param array
	 */
	return apply_filters( 'themify_before_after_widget_allowed_tags', array(
		'div'     => array(
			'id'    => true,
			'class' => true,
		),
		'section' => array(
			'id'    => true,
			'class' => true,
		),
	));
}

/**
 * Returns allowed tags for widget params before_title and after_title
 *
 * @since 2.1.8
 *
 * @return mixed|void
 */
function themify_before_after_widget_title_allowed_tags() {
	/**
	 * Filters allowed tags.
	 *
	 * @since 2.1.8
	 *
	 * @param array
	 */
	return apply_filters( 'themify_before_after_widget_title_allowed_tags', array(
		'h3'     => array(
			'class' => true,
		),
		'h4' => array(
			'class' => true,
		),
		'strong' => array(
			'class' => true,
		),
	));
}

/**
 * Returns allowed tags for updater notice markup
 *
 * @since 2.1.8
 *
 * @return mixed|void
 */
function themify_updater_notice_allowed_tags() {
	/**
	 * Filters allowed tags.
	 *
	 * @since 2.1.8
	 *
	 * @param array
	 */
	return apply_filters( 'themify_updater_notice_allowed_tags', array(
		'div' => array(
			'id'    => true,
			'class' => true,
		),
		'p'   => array( 'class' => true, ),
		'a'   => array(
			'href'           => true,
			'title'          => true,
			'class'          => true,
			'target'         => true,
			'data-changelog' => true,
		),
		'select' => array( 'id' => true, ),
		'option' => array(
			'selected' => true,
			'value'    => true,
		),
	) );
}

/**
 * Safely add "fa-" prefix to the icon name
 *
 * @since 2.2.0
 */
function themify_get_fa_icon_classname( $icon ) {
	if( ! ( substr( $icon, 0, 3 ) == 'fa-' ) ) {
		$icon = 'fa-' . $icon;
	}

	return $icon;
}

/**
 * Returns true if the active theme is using Themify framework
 *
 * @since 2.2.5
 * @return bool
 */
function themify_is_themify_theme() {
	if( file_exists( get_template_directory() . '/themify/themify-utils.php' ) ) {
		return true;
	}

	return false;
}

if( ! function_exists( 'themify_is_woocommerce_active' ) ) {
	/**
	 * Checks if Woocommerce plugin is active and returns the proper value
	 * @return bool
	 * @since 1.4.6
	 */
	function themify_is_woocommerce_active() {
		$plugin = 'woocommerce/woocommerce.php';
		$network_active = false;
		if ( is_multisite() ) {
			$plugins = get_site_option( 'active_sitewide_plugins' );
			if ( isset( $plugins[$plugin] ) )
				$network_active = true;
		}
		$active_plugins = apply_filters( 'active_plugins', get_option( 'active_plugins' ) );
		return in_array( $plugin, (array) $active_plugins ) || $network_active;
	}
}

/**
 * Run shortcode with same functionality as WP prior to 4.2.3 update and
 * this ticket: https://core.trac.wordpress.org/ticket/15694
 * Similar to do_shortcode, however will not encode html entities
 *
 * @return string
 */
function themify_do_shortcode_wp_422( $content ) {
	global $shortcode_tags;

	if ( false === strpos( $content, '[' ) ) {
		return $content;
	}

	if (empty($shortcode_tags) || !is_array($shortcode_tags))
		return $content;

	// Find all registered tag names in $content.
	preg_match_all( '@\[([^<>&/\[\]\x00-\x20=]++)@', $content, $matches );
	$tagnames = array_intersect( array_keys( $shortcode_tags ), $matches[1] );

	if ( empty( $tagnames ) ) {
		return $content;
	}

	$pattern = get_shortcode_regex( $tagnames );
	$content = preg_replace_callback( "/$pattern/", 'do_shortcode_tag', $content );

	// Always restore square braces so we don't break things like <!--[if IE ]>
	$content = unescape_invalid_shortcodes( $content );

	return $content;
}

/**
 * Modified version of wp_parse_args which adds filters to modify the args
 *
 * @return array
 * @since 2.7.7
 */
function themify_parse_args( $args, $defaults = '', $filter_key = '' ) {
	// Setup a temporary array from $args
	if ( is_object( $args ) )
		$r = get_object_vars( $args );
	elseif ( is_array( $args ) )
		$r = & $args;
	else
		wp_parse_str( $args, $r );

	// Passively filter the args before the parse
	if ( ! empty( $filter_key ) )
		$r = apply_filters( 'themify_before_' . $filter_key . '_parse_args', $r );

	// Parse
	if ( is_array( $defaults ) )
		$r = array_merge( $defaults, $r );

	// Aggressively filter the args after the parse
	if ( ! empty( $filter_key ) )
		$r = apply_filters( 'themify_after_' . $filter_key . '_parse_args', $r );

	// Return the parsed results
	return $r;
}

/**
 * Handle Builder's JavaScript fullwidth rows, forces fullwidth rows if sidebar is disabled
 *
 * @return bool
 */
function themify_theme_fullwidth_layout_support( $support ) {
	global $themify;

	/* if Content Width option is set to Fullwidth, do not use JavaScript */
	if( themify_get( 'content_width' ) == 'full_width' ) {
		return true;
	}

	/* using sidebar-none layout, force fullwidth rows using JavaScript */
	if( $themify->layout == 'sidebar-none' ) {
		return false;
	}

	return true;
}