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

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

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

/**
 * Build custom write panels
 * This function is required to provide backward compatibility
 */
function themify_build_write_panels( $args = null ) {
	global $themify_write_panels;

	if( is_array( $args ) ) {
		$themify_write_panels = $args;
	}
}

/**
 * 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]) && is_array( $ref )) {
				$ref[$part] = array();
			}

			if ( is_array( $ref ) ) {
				$ref = &$ref[$part];
			}
		}

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

///////////////////////////////////////////
// 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_style( 'themify-ui',  themify_enque(THEMIFY_URI . '/css/themify-ui.css'), array(), THEMIFY_VERSION );
	wp_register_style( 'themify-ui-rtl',  themify_enque(THEMIFY_URI . '/css/themify-ui-rtl.css'), array(), THEMIFY_VERSION );
	wp_register_style( 'themify-colorpicker', themify_enque(THEMIFY_METABOX_URI . 'css/jquery.minicolors.css'), array(), THEMIFY_VERSION );
	wp_register_script( 'validate', THEMIFY_URI . '/js/jquery.validate.pack.min.js', array('jquery'), THEMIFY_VERSION );
	wp_register_script( 'markjs', THEMIFY_URI . '/js/jquery.mark.min.js', array('jquery'), THEMIFY_VERSION );
	wp_register_script( 'themify-colorpicker', THEMIFY_METABOX_URI . 'js/jquery.minicolors.min.js', array('jquery'), THEMIFY_VERSION );
	wp_register_script( 'themify-scripts', themify_enque(THEMIFY_URI . '/js/scripts.js'), array('jquery', 'jquery-ui-tabs'), THEMIFY_VERSION );
	wp_register_script( 'themify-plupload', themify_enque(THEMIFY_METABOX_URI . 'js/plupload.js'), array('jquery', 'themify-scripts'), THEMIFY_VERSION);
	wp_register_style ( 'magnific', themify_enque(THEMIFY_URI . '/css/lightbox.css'), array(), THEMIFY_VERSION );
	wp_register_script( 'magnific', THEMIFY_URI . '/js/lightbox.min.js', array('jquery'), THEMIFY_VERSION, true );
        if(themify_is_themify_theme()){
            wp_register_style ( 'themify-admin-widgets-css', themify_enque(THEMIFY_URI . '/css/themify-admin-widgets.css'), array(), THEMIFY_VERSION );
            wp_register_script( 'themify-admin-widgets-js', themify_enque(THEMIFY_URI . '/js/themify-admin-widgets.js'), array('jquery'), THEMIFY_VERSION, true );
			wp_localize_script( 'themify-admin-widgets-js', 'themifyAdminWidget', array(
				'labels' => array(
					'errorUpdate' => esc_html__( 'Try again', 'themify' ),
					'successUpdate' => esc_html__( 'Updated', 'themify' )
				),
				'nonce' => wp_create_nonce( 'ajax-admin-widget-nonce' )
			)
		);
        }
	// Custom Write Panel
	if( ($page === 'post.php' || $page === 'post-new.php') && in_array($typenow, $types,true) ){
		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_style( 'themify-icons', themify_enque(THEMIFY_URI . '/themify-icons/themify-icons.css'), array(), THEMIFY_VERSION );

	// Settings Panel
	if( $page === 'toplevel_page_themify' ){
		wp_enqueue_script( 'jquery-ui-sortable' );
	}
	if( in_array( $page, $pages,true ) ) {
		//Enqueue styles
		wp_enqueue_style( 'themify-ui' );
		wp_enqueue_style( 'themify-metabox' );
		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' );
                if( 'themify' === $pagenow){
                        wp_enqueue_script( 'jquery-ui-autocomplete' );
                }
		wp_enqueue_script( 'json2' );
		wp_enqueue_script( 'plupload-all' );
		wp_enqueue_script( 'validate' );
		wp_enqueue_script( 'markjs' );
		wp_enqueue_script( 'themify-colorpicker' );
		if( in_array($typenow, $types,true) || in_array( $pagenow, $pagenows,true ) ){
			//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' );
			Themify_Metabox::get_instance()->enqueue();
		}
		// 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() . '/',
                        'theme'=>  get_template(),
			'blog_url'	=> site_url() . '/',
			'page_not_found' => esc_html__( 'Page not found', 'themify' )
		)
	);

	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="https://themify.me/contact">Themify</a> for login issues.', 'themify'),
			'unsuscribed' => __('Your membership might be expired. Login to <a href="https://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' )
		)
	);

	// Enqueu admin widgets stuff
	if( $page === 'index.php' && themify_is_themify_theme()) {
		wp_enqueue_style( 'themify-admin-widgets-css' );
		wp_enqueue_script( 'themify-admin-widgets-js' );
	}
}

/**
 * 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=null;

	if ( $theme_skin===NULL ) {
		$current_skin = themify_get( 'skin' );
		$parsed_skin = parse_url( $current_skin, PHP_URL_PATH );
		$basedir_skin = basename( dirname( $parsed_skin ) );
		if ( 'default' !== $basedir_skin && 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() ) {
		$parsed_skin = parse_url( themify_get( 'skin' ), PHP_URL_PATH );
		$basedir_skin = basename( dirname( $parsed_skin ) );
		wp_enqueue_style( 'themify-skin', themify_enque(themify_https_esc( $skin )), array( 'theme-style' ), THEMIFY_VERSION );
		if ( is_rtl() && file_exists( trailingslashit( get_template_directory() ) . 'skins/' . $basedir_skin . '/rtl.css' ) ) {
			wp_enqueue_style( 'themify-skin-rtl', themify_enque( themify_https_esc( trailingslashit( get_template_directory_uri() ) . 'skins/' . $basedir_skin . '/rtl.css' ) ), array( 'theme-style', 'themify-skin' ), THEMIFY_VERSION );
		}
	}

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

/**
 * 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(!empty($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;
		}
	}
}

///////////////////////////////////////////
// Display Sticky posts in the loops
///////////////////////////////////////////
if( ! function_exists( 'themify_sticky_post_helper' ) ) {
	function themify_sticky_post_helper( $posts ) {
		$stickies = array();
		foreach( $posts as $i => $post ) {
			if( is_sticky( $post->ID ) ) {
				$stickies[] = $post;
				unset( $posts[$i] );
			}
		}
		return array_merge( $stickies, $posts );
	}
}

function themify_font_icons_admin_assets() {
	wp_enqueue_style( 'themify-font-icons-css' );
	wp_enqueue_style( 'themify-icons' );
	Themify_Icon_Picker::get_instance()->enqueue();
}

/**
 * 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, $wp_version;

	/**
	 * List of parameters
	 * @var array
	 */
	$args = themify_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
	), 'get_image' );

	/**
	 * 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 = '';

	$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 ) || !empty( $themify->is_shortcode )) {
		if ( ! empty( $args['w'] ) ) {
			$width = $args['w'];
		}
		if ( ! empty( $args['h'] ) ) {
			$height = $args['h'];
		}
	} elseif ( in_the_loop() ) { // Main query area
		$post_type = get_post_type();
		if ( is_single() ) { // Single Entry

			if (($width = get_post_meta( $post_id, 'image_width', true ) )==='' && ($width = themify_get( 'setting-default_' . $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_' . $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_' . $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_' . $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_' . $post_type . '_index_image_post_width' ) )==='') {
				$width = themify_get( 'setting-image_post_width' );
			}
			if (($height = themify_get( 'setting-default_' .$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 (! empty( $themify->image_size ) ) { // or if Themify::image_size is set
			$feature_size = $themify->image_size;
		} else {
			if ( in_the_loop() && empty( $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 = apply_filters( 'themify_global_feature_size', themify_get( 'setting-global_feature_size','large' ));
		}

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

		// Fix for showing feature_image when Themify Image Script is disabled
		if( '' == trim( $img_url) ) {
			foreach( explode( ',', $args['field_name'] ) as $field ) {
				if ( $img_url = get_post_meta( $post_id, trim( $field ), true ) ) break;
			}
		}

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

		/** filter $img_url before it goes off to themify_do_img for processing **/
		$img_url = apply_filters( 'themify_get_image_before_do_img', $img_url, $width, $height, $args );

		// 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_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 ) );
				$src = $temp['src'];
				$parse = parse_url($src);
				if(!empty($parse['query'])){
					$src = str_replace('?'.$parse['query'], '', $src);
				}
				$ext = strtolower(pathinfo($src,PATHINFO_EXTENSION));
				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-post-image wp-image-' . $attachment_id; /* add attachment_id class to img tag */
			}
			if ( ! empty( $args['class'] ) ) {
				$out .= " class=\"{$args['class']}\"";
			}

			// Add title attribute only if explicitly set in $args
			if ( ! empty( $args['title'] ) ) {
				$out .= ' title="' . esc_attr( $args['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'] === 'false' ? '' : $args['alt'];
			} elseif ( ! empty( $img_alt ) ) {
				$out_alt = $img_alt;
			} else {
				if(!empty( $args['title'] )){
					$out_alt = $args['title'];
				}
				elseif($attachment_id){
					$p = get_post($attachment_id);
					$out_alt = $p->post_title;
				}
				else{
					$out_alt = the_title_attribute( 'echo=0' );
				}
			}
			$out .= ' alt="' . esc_attr( $out_alt ) . '" />';
		}
		$out = $args['before'] . $out . $args['after'];
	} else {
		$out = '';
	}

	if( version_compare( $wp_version, '4.4', '>=' ) ) {
		$out = wp_make_content_images_responsive( $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 ) {
	$image = array('src' => '', 'alt' => '', 'title' => '');
	preg_match_all( '/(alt|title|src)=(("|\')[^("|\')]*("|\'))/i', $tag, $image_reg );

	foreach( $image_reg[0] as $attr ){
		parse_str( $attr, $tempAttr );
		foreach( $tempAttr as $key => $val ) {
			if( isset( $image[$key] ) ) {
				$image[$key] = str_replace( array('"',"'"), array('',''), $val );
			}
		}
	}

	if ( strpos( $image['src'], 'youtube.com' )!==false || strpos( $image['src'], 'vimeo.com' )!==false ) {
		$image['src'] = themify_video_image( $image['src'] );
	}

	$image['src'] = preg_replace('/(-\d+x\d+)(?=\.\w{3,4})/', '', $image['src'] );

	return $image;
}

/**
 * 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(!empty($query['v'])){
			$id = $query['v'];
		} else {
			$path = explode('/',$image_url['path']);
			$id = $path[count($path)-1];
		}
		$return_url = themify_https_esc('https://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(!empty($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( 'https://vimeo.com/api/v2/video/' ) . $id . '.php') );
		if ( !empty( $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 themify_is_shop() && get_post_meta( get_option( 'woocommerce_shop_page_id' ), $var, true ) != '' && get_post_meta( get_option( 'woocommerce_shop_page_id' ), $var, true );
	}
}

/**
 * Returns a value referenced by $var checking in theme settings or post meta data.
 *
 * @param $var
 *
 * @return mixed
 */
function themify_get( $var, $default = null, $data_only = false ) {
	$data = themify_get_data();

	if ( isset( $data[ $var ] ) && $data[ $var ] !== '' ) {
		return $data[ $var ];
	} else if ( ! $data_only ) {
		global $post;
		if( ! is_object( $post ) ) {
			return $default;
		} else if ( ($post_meta = get_post_meta( $post->ID, $var, true ))!= '' ) {
			return $post_meta;
		} else if ( themify_is_shop() ) {
			return get_post_meta( get_option( 'woocommerce_shop_page_id' ), $var, true );
		}
	}
	return $default;
}

/**
 * Get a color value, uses themify_get and sanitizes the value
 *
 * @return string
 */
function themify_get_color( $var, $default = null ) {
	return themify_sanitize_hex_color( themify_get( $var, $default ) );
}

/**
 * Sanitize a string to ensure it's valid hex color code
 *
 * @since 3.1.2
 */
function themify_sanitize_hex_color( $value ) {
	$value = ltrim( $value, '#' );
	/* match 3 to 6 hex digits */
	if ( preg_match('|^([A-Fa-f0-9]{3}){1,2}$|', $value ) ) {
		$value = '#' . $value;
	}

	return $value;
}

/**
 * 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 ) {
                static $result = array();
                $key = $nested?1:0;
                if(!isset($result[$key])){
                    $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 );
                    }
                    $result[$key] = apply_filters( 'themify_get_image_sizes_list', $nested ? $out : $size_names, $nested );
                }
		return $result[$key];
	}
}

/**
 * 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( 'https://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, 3600 ); }

	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('page' !== $typenow && ('post.php' === $pagenow || 'post-new.php' === $pagenow || 'admin.php' === $pagenow) ){
		echo '<div class="prompt-box"><div class="show-error"></div></div><div class="overlay">&nbsp;</div>';
        }
}

/**
 * @deprecated
 * @since 4.5.1
 */
function themify_is_thumbnail_field( $field ) {
	return false;
}

/**
 * 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(isset( $array[$key] )){
            if ( $duplicate ) {
                    if ( $array[$key] == $value ){
                        $results[] = $array;
                    }
            } 
            elseif (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 );
}

/**
 * Load themify_config
 */
function themify_load_config() {
	$themify_theme_config = array();
	$config_file = locate_template( array( 'custom-config.php', 'theme-config.php' ) );
	include $config_file;

	return apply_filters( 'themify_theme_config_setup', $themify_theme_config );
}

/**
 * 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 ) {
	$config = themify_load_config();
	$arr = themify_search_arr( $config['panel']['styling']['tab'][ $context ]['element'], $key, $value, $duplicate, $uniq_key, $uniq_val );
	return isset( $arr[0]['selector'] )?$arr[0]['selector']:'';
}

/**
 * Return specific array
 * @param string $key
 * @param string $context
 * @return array
 */
function themify_get_theme_arr( $key, $context = 'settings' ) {
	$config = themify_load_config();
	return isset( $config['panel'][ $context ]['tab'][ $key ] )?$config['panel'][ $context ]['tab'][ $key ]:array();
}

/**
 * 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 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 ) {
                                                if($attribute==='font_family' && ! empty( $v['value']['value'] )){
                                                    $fonts[] = $v['value']['value'];
                                                }
					}
				}
			}
		}
	}
	return $fonts;
}

/**
 * Enqueue Google fonts enabled through Styling panel
 * @param array $fonts
 */
function themify_enqueue_gfonts( $google_fonts ) {
	$fonts = themify_get_custom_css_gfonts();
	if( ! empty( $fonts ) ) {
		foreach( $fonts as $font ) {
			$key = sanitize_title( $font );
			$google_fonts[ $key ] = $font;
	}
		}

	return $fonts;
	}

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){
                            $option = esc_attr( $option );
				if($option == $data[$key]){
					$output .= '<option value="' . $option . '" selected="selected">' . esc_html( $option ) . '</option>';
				} else {
					$output .= '<option value="' . $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';
		$content_images = '';
		$file_extensions = array('jpg', 'gif', 'png', 'JPG', 'GIF', 'PNG', 'jpeg', 'JPEG');
		foreach ($file_extensions as $ext) {
			if($lightbox_content_images){
				$content_images .= '.post-content a[href$='.$ext.'],.page-content a[href$='.$ext.'],';
			}
		}
		if($lightbox_content_images){
			$content_images = substr($content_images, 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' => $lightbox_content_images?'.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-icon > a';
			$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_enque(THEMIFY_URI . '/css/photoswipe.css'),null, THEMIFY_VERSION );
			wp_enqueue_script( 'photoswipe', themify_enque(THEMIFY_URI . '/js/photoswipe.js'), array('jquery'), THEMIFY_VERSION, true );

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

		$overlay_args = apply_filters('themify_gallery_plugins_args', $overlay_args);
		// sanitize contentImagesAreas, ensure it's a valid CSS selector
		$overlay_args['contentImagesAreas'] = trim( $overlay_args['contentImagesAreas'], ',' );
		return $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="https://themify.me/docs/lightbox" target="_blank">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' => __('Featured Image Size', '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
 * @return mixed|void
 */
function themify_get_shortcode_template( $posts, $slug = 'includes/loop', $name = 'index', $args = array() ) {
	global $post, $themify, $ThemifyBuilder;

	$args = wp_parse_args( $args, array(
		'before_post' => '',
		'after_post' => '',
		/**
		 * Type of returned data. Can be STRING / ARRAY_N
		 */
		'output' => ''
	) );

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

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

	$output = array();
	foreach ( $posts as $post ) {
		ob_start();
		setup_postdata( $post );

		echo $args['before_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;
		}

		echo $args['after_post'];
		$output[] = ob_get_clean();
	}

	if ( isset( $saved_post ) && is_object( $saved_post ) ) {
		$post = $saved_post;
		/**
		 * WooCommerce plugin resets the global $product on the_post hook,
		 * call setup_postdata on the original $post object to prevent fatal error from WC
		 */
		setup_postdata( $saved_post );
	}

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

	if( $args['output'] == ARRAY_N ) {
		return $output;
	} else {
		return apply_filters( 'themify_get_shortcode_template', join( '', $output ) );
	}
}
endif;

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['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_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=array();

		if ( ! isset( $themify_mobile_detect[$check] ) ) {
			if ( ! class_exists( 'Themify_Mobile_Detect' ) ) {
				require_once 'class-themify-mobile-detect.php';
			}
			$detect = new Themify_Mobile_Detect;
			$is_tablet = isset($themify_mobile_detect['tablet'])?$themify_mobile_detect['tablet']:$detect->isTablet();
			$is_mobile = isset($themify_mobile_detect['phone'])?$themify_mobile_detect['phone']:$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() {
		static $is_enabled = null;
		if($is_enabled===null){
			$is_enabled =  themify_check( 'setting-img_settings_use' );
		}
	return $is_enabled;
}

/**
 * Checks if current user is allowed to view the update interface.
 *
 * @since 2.0.0
 *
 * @return bool
 */
function themify_allow_update() {
	static $allow=null;
	if ($allow===null ) {
		$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() {
	/* bypass the styling check */
	$has_styling = apply_filters( 'themify_show_styling_panel', null );
	if ($has_styling!==null) {
		return $has_styling;
	}

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

	// Check Custom CSS
	if ( ! empty( $themify_data['setting-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;
}

/**
 * @deprecated since 3.1.2
 */
function themify_get_lightbox_iframe_link( $uri ) {
		return $uri;
}

/**
 * Get demo cache dir
 * @return array
 */
function themify_get_cache_dir() {
		static $dir_info = null;
		if($dir_info===null){
			$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 );
	}
}


/**
 * 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 !themify_is_negative_string($string);
}

/**
 * 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.svg',
		'icon_no' => THEMIFY_URI . '/img/ddbtn-cross.svg',
		'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
		)
	));
}

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

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

	return $is_themify_theme;
}

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() {
		static $is_active = null;
		if ( $is_active===null ) {
			$plugin = 'woocommerce/woocommerce.php';
			include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
			return is_plugin_active( $plugin )
				// validate if $plugin actually exists, the plugin might be active however not installed.
				&& file_exists( trailingslashit( WP_PLUGIN_DIR ) . $plugin );
		}
		return $is_active;
	}
}

/**
 * Calls is_shop() in a safe manner
 *
 * @note: this function should not be called before template_redirect,
 * and also the value must not be cached.
 *
 * @since 2.9.0
 * @return bool
 */
function themify_is_shop() {
	$is_shop = themify_is_woocommerce_active() && function_exists( 'is_shop' ) && is_shop();
	return $is_shop;
}

/**
 * Check if multiple plugins are active, returns true only if all of them are
 *
 * @return bool
 * @since 2.8.6
 */
function themify_are_plugins_active( $plugins ) {
	$result = true;
	foreach( $plugins as $plugin ) {
		if( ! is_plugin_active( $plugin ) ) {
			$result = false;
			break;
		}
	}

	return $result;
}

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

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

	$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 (  !empty( $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 ( !empty( $meta_box['before'] )) {
		$html = $meta_box['before'] . $html;
	}
	if ( !empty( $meta_box['after'] )) {
		$html .= $meta_box['after'];
	}

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

/**
 * Display the Builder's backend editor in Themify Custom Panel
 *
 * @return null
 * @since 2.8.8
 */
function themify_meta_field_page_builder() {
	do_action( 'themify_builder_metabox' );
}

/**
 * featimgdropdown field type, creates an option to select image sizes
 *
 * @since 2.8.8
 */
function themify_meta_field_featimgdropdown( $args ) {
	extract( $args, EXTR_OVERWRITE );
	/** Define WP Featured Image sizes + blank + Themify's image script
	 * @var array */
	$themify_fi_sizes = themify_get_image_sizes_list();
	?>
	<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
}

/**
 * Get an array of key => value pairs and outputs them as HTML attributes
 *
 * @since 2.9.1
 * @return string
 */
function themify_get_element_attributes( $props ) {
	$out = '';
	foreach( $props as $atts => $val ) { 
		$out .= ' ' . $atts . '="' . esc_attr( $val ) . '"';
	}

	return $out;
}

/**
 * Adds aria-hidden attribute if $condition is set
 *
 * @return string|null
 */
function themify_aria_hidden( $condition, $echo = true ) {
	if( $condition ) {
		if( $echo ) {
			echo ' aria-hidden="true"';
		}
		return ' aria-hidden="true"';
	}
}

/**
 * Load common.css file, required for pre-load CSS codes
 */
function themify_enqueue_common_css() {
	wp_enqueue_style( 'themify-common', themify_enque(THEMIFY_URI . '/css/themify.common.css'),null,THEMIFY_VERSION );
}


/**
 * Get contents of a file
 * wp_filesystem sometimes fails, using include seems safer
 *
 * return string|bool
 */
function themify_get_file_contents( $path ) {
	if( file_exists( $path ) ) {
		ob_start();
		include $path;
		return ob_get_clean();
	}

	return false;
}

if( ! function_exists('themify_parse_video_embed_vars') ) :
/**
 * Add wmode transparent and post-video container for responsive purpose
 * Remove webkitallowfullscreen and mozallowfullscreen for HTML validation purpose
 * @param string $html The embed markup.
 * @param string $url The URL embedded.
 * @return string The modified embed markup.
 */
function themify_parse_video_embed_vars($html, $url) {
	$services = array(
		'youtube.com',
		'youtu.be',
		'blip.tv',
		'vimeo.com',
		'dailymotion.com',
		'hulu.com',
		'viddler.com',
		'qik.com',
		'revision3.com',
		'wordpress.tv',
		'wordpress.com',
		'funnyordie.com'
	);
	$video_embed = false;
	foreach( $services as $service ) {
		if( stripos($html, $service) ) {
			$video_embed = true;
			break;
		}
	}
	if( $video_embed ) {
		if ( strpos( $html, '<iframe ' ) !== false ) {
			$html = str_replace( array( ' webkitallowfullscreen', ' mozallowfullscreen' ), '', $html );
		}
		$html = '<div class="post-video">' . $html . '</div>';
		if( strpos( $html, '<embed src=' ) !== false ) {
			$html = str_replace('</param><embed', '</param><param name="wmode" value="transparent"></param><embed wmode="transparent" ', $html);
		}
		elseif( strpos( $html, 'wmode=transparent' ) === false ) {
			if( stripos($url, 'youtube') || stripos($url, 'youtu.be') ) {

				if( stripos($url, 'youtu.be') ) {
					$parsed = parse_url($url);
					$ytq = isset( $parsed['query'] )? $parsed['query']: '';
					$url = 'https://www.youtube.com/embed' . $parsed['path'] . '?wmode=transparent&fs=1' . $ytq;
				} else {
					$parsed = parse_url($url);
					parse_str($parsed['query'], $query);

					$parsed['scheme'] .= '://';

					if ( !empty( $query['v'] ) ) {
						$parsed['path'] = '/embed/' . $query['v'];
						unset( $query['v'] );
					} else {
						$parsed['path'] = '/embed/';
					}

					$query['wmode'] = 'transparent';
					$query['fs'] = '1';

					$parsed['query'] = '?';
					foreach ( $query as $param => $value ) {
						$parsed['query'] .= $param . '=' . $value . '&';
					}
					$parsed['query'] = substr($parsed['query'], 0, -1);

					$url = implode('', $parsed);
				}
				$url = str_replace('038;','&',$url);

				$html = preg_replace('/src="(.*)" (frameborder)/i', 'src="' . esc_url( themify_https_esc( $url ) ) . '" $2', $html);
			} else {
				if ( false !== stripos( $html, 'http:'  && is_ssl()) ) {
					$html = str_replace( 'http:', 'https:', $html );
				}
				$html = str_replace(array('?fs=1', '?fs=0'), array('?fs=1&wmode=transparent', '?fs=0&wmode=transparent'), $html);
				
			}
		} 
	}
	else {
		$html = '<div class="post-embed">' . $html . '</div>';
	}
	
	return str_replace('frameborder="0"','',$html);
}
endif;

/**
 * Get breakpoints settings
 * if it's framework return customizer breakpoints,else if it's builder plugin builder breakpoints
 * @since 3.0.0
 * @return array
 */
function themify_get_breakpoints( $select = 'all',$max_min=false ) {
			$breakpoints = array(
					'tablet_landscape' => array(769,1280),
					'tablet' => array(681,768),  
					'mobile' => 680
			);
			if($max_min){
				return $breakpoints;
			}
			static $return = array();
			if(($select==='all' && empty($return)) || (empty($return[$select]))){
				foreach( $breakpoints as $bp => $value ) {
						$v = themify_builder_get('setting-customizer_responsive_design_' . $bp,'builder_responsive_design_' . $bp );
						if ( '' != $v ) {
								if(is_array($value)){
									$return[ $bp ] = array();
									$return[ $bp ][0] = $value[0];
									$return[ $bp ][1] = $v;
									$return[ $bp ] = $return[ $bp ];
								}
								else{
									$return[ $bp ] = '';
									$return[ $bp ] = $v;
								}
						} else {
								$return[ $bp ] = $value;
						}
				}
			}
	return 'all' === $select?$return:$return[ $select ];
}
if( ! function_exists( 'themify_index_query_posts' ) ):
/**
 * Deprecated, since 3.1.2
 */
function themify_index_query_posts() {}
endif;

/**
 * Unserialize data if it is serialized
 *
 * If PHP supports it disables unserializing PHP objects in order to prevent object injection.
 *
 * @param string $original Maybe unserialized original, if is needed.
 * @return mixed Unserialized data can be any type.
 */
function themify_maybe_unserialize( $original ) {
	if ( is_serialized( $original ) ) { // don't attempt to unserialize data that wasn't serialized going in
		if( version_compare( PHP_VERSION, '7.0.0' ) >= 0 ) {
			return @unserialize( $original, array( 'allowed_classes' => false ) );
		} else {
			return @unserialize( $original );
		}
	}

	return $original;
}

/**
 * Get a flag
 *
 * @return bool
 */
function themify_get_flag( $name, $default = false ) {
	$flags = get_option( 'themify_flags', array() );

	$value = $default;
	if ( isset( $flags[ $name ] ) ) {
		$value = $flags[ $name ];
	}

	return apply_filters( "themify_flag_{$name}", $value );
}

/**
 * Set a flag
 *
 * @return null
 */
function themify_set_flag( $name, $value = 1 ) {
	$flags = get_option( 'themify_flags', array() );
	$flags[ $name ] = $value;
	update_option( 'themify_flags', $flags );
}

/**
 * Remove a flag
 *
 * @return null
 */
function themify_unset_flag( $name ) {
	$flags = get_option( 'themify_flags', array() );
	unset( $flags[ $name ] );
	update_option( 'themify_flags', $flags );
}

if ( ! function_exists( 'themify_enque' ) ) :
/**
 * Load/Check minified file is exist
 *
 * @return string/bool
 */
function themify_enque( $url, $check = false ) {
	static $is_disabled = null;

	if ( $is_disabled === null ) {
		/**
		 * Check if using minified script files in disabled by wp-config.
		 * @ref: https://codex.wordpress.org/Debugging_in_WordPress#SCRIPT_DEBUG
		 */
		$is_disabled = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) || defined( 'THEMIFY_DISABLE_MIN' );
		if( ! $is_disabled ) {
		   $is_disabled =  themify_builder_get( 'setting-script_minification-min','builder_minified' )===null?false:true; 
		}
	}
	
	if( $is_disabled ) return $check ? false : $url;

	$f = pathinfo( $url );
	$return = 0;

	if ( strpos( $f['filename'], '.min.', 2 ) === false ) {
		$absolute = str_replace( WP_CONTENT_URL, '', $f['dirname'] );
		$name = $f['filename'] . '.min.' . $f['extension'];
		
		if ( is_file( trailingslashit( WP_CONTENT_DIR ) . trailingslashit( $absolute ) . $name ) ) {
			if( $check ) {
				$return = 1;
			} else {
				$url = trailingslashit( $f['dirname'] ) . $name;
			}
		}
	}

	return $check ? $return : $url;
}
endif;

if( ! function_exists( 'themify_get_query_categories' ) ) {
	function themify_get_query_categories() {
		global $themify;

		return $themify->query_category == '0'
			? themify_get_all_terms_ids( $themify->query_taxonomy ) 
			: explode( ',', str_replace( ' ', '', $themify->query_category ) );
	}
}

if( ! function_exists( 'themify_post_types_by_tax' ) ) {
	function themify_post_types_by_tax() {
		global $wp_taxonomies, $themify;
	
		if( ! empty( $wp_taxonomies[ $themify->query_taxonomy ] ) && ! empty( $themify->query_all_post_types ) ) {
			return $wp_taxonomies[ $themify->query_taxonomy ]->object_type;
		}
	
		return $themify->query_post_type;
	}
}

if( ! function_exists( 'themify_custom_query_posts' ) ) {
	function themify_custom_query_posts( $args ) {
		global $themify;

		$qpargs = array(
			'post_type' => !empty($themify->query_post_type)?$themify->query_post_type:'post',
			'posts_per_page' => ! empty( $themify->posts_per_page ) ? $themify->posts_per_page : get_option( 'posts_per_page' ),
			'paged' => $themify->paged,
			'order' => $themify->order,
			'orderby' => $themify->orderby
		);

		if( ! empty( $themify->order_meta_key ) ) {
			$qpargs['meta_key'] = $themify->order_meta_key;
		}

		if ( $themify->query_category !== '0' ) {
			$taxonomy = isset( $themify->query_taxonomy ) ? $themify->query_taxonomy : 'category';
			$category = array_map( 'trim', explode( ',', $themify->query_category ) );
			$ids_in = $ids_not_in = $slugs_in = $slugs_not_in = array();
			foreach($category as $c){
				if(!empty($c)){
                                    if('-' !== $c[0]){
                                        if(is_numeric( $c ) ){
                                            $ids_in[] = $c;
                                        }
                                        else{
                                            $slugs_in[] = $c;
                                        }
                                    }
                                    elseif(is_numeric( $c )){
                                        $ids_not_in[] = $c;
                                    }
                                    else{
                                        $slugs_not_in[] = substr( $c, 1 );// remove the minus sign (first character)
                                    }
				}
			}
			unset($category);
			$qpargs['tax_query'] = array(
				'relation' => 'AND',
			);
			if ( ! empty( $ids_in ) ) {
				$qpargs['tax_query'][] = array(
					'taxonomy' => $taxonomy,
					'field' => 'id',
					'terms' => $ids_in
				);
			}
			if ( ! empty( $ids_not_in ) ) {
				$qpargs['tax_query'][] = array(
					'taxonomy' => $taxonomy,
					'field' => 'id',
					'terms' => array_map( 'abs', $ids_not_in ),
					'operator' => 'NOT IN'
				);
			}
			if ( ! empty( $slugs_in ) ) {
				$qpargs['tax_query'][] = array(
					'taxonomy' => $taxonomy,
					'field' => 'slug',
					'terms' => $slugs_in
				);
			}
			if ( ! empty( $slugs_not_in ) ) {
				$qpargs['tax_query'][] = array(
					'taxonomy' => $taxonomy,
					'field' => 'slug',
					'terms' => $slugs_not_in, 
					'operator' => 'NOT IN'
				);
			}
		}

		if( ! empty( $args ) ) {
			$qpargs = wp_parse_args( $args, $qpargs );
		}

		query_posts( apply_filters( 'themify_query_posts_page_args', $qpargs ) );
	}
}

/**
 * Load assets required by Themify framework
 *
 * @since 1.1.2
 */
function themify_load_main_script() {
	global $themify_twitter_instance;
	$themify_twitter_instance = 0;

	//Enqueue main js that will load others needed js
	if ( ! wp_script_is( 'themify-main-script' ) ) {
		wp_register_script( 'themify-main-script', themify_enque(THEMIFY_URI.'/js/main.js'), array('jquery'), THEMIFY_VERSION, true );
                $localiztion = array(
			'version' => THEMIFY_VERSION,
			'url' => THEMIFY_URI,
			'map_key' => themify_builder_get('setting-google_map_key', 'builder_settings_google_map_key'),
			'bing_map_key' => themify_builder_get('setting-bing_map_key', 'builder_settings_bing_map_key'),
            'includesURL' => includes_url(),
            'isCached' => themify_builder_get('setting-page_builder_cache','builder_enable_cache'),
            'minify'=>array(
                'css'=>array(
                    'themify-icons'=>themify_enque(THEMIFY_URI.'/themify-icons/themify-icons.css',true),
                    'themify.framework'=>themify_enque(THEMIFY_URI.'/css/themify.framework.css',true),
                    'lightbox'=>themify_enque(THEMIFY_URI.'/css/lightbox.css',true),
                ),
                'js'=>array(
                    'backstretch.themify-version'=>themify_enque(THEMIFY_URI.'/js/backstretch.themify-version.js',true),
                    'bigvideo'=>themify_enque(THEMIFY_URI.'/js/bigvideo.js',true),
                    'themify.dropdown'=>themify_enque(THEMIFY_URI.'/js/themify.dropdown.js',true),
                )
            )
		);
		wp_localize_script( 'themify-main-script', 'themify_vars',apply_filters('themify_main_script_vars',$localiztion) );
		wp_enqueue_script( 'themify-main-script' );
	}
}

/**
 * Enqueues JS, CSS and writes inline scripts
 */
add_action( 'wp_enqueue_scripts', 'themify_load_main_script', 8 );

/**
 * Outputs inline CSS that must be present before page renders
 *
 * @since 4.1.7
 */
function themify_above_the_fold_css() {
	echo '<style>
	.themify_builder .wow { visibility: hidden; }
	div:not(.caroufredsel_wrapper) > .themify_builder_slider > li:not(:first-child), .mfp-hide { display: none; }
a.themify_lightbox, .module-gallery a, .gallery-icon, .themify_lightboxed_images .post a[href$="jpg"], .themify_lightboxed_images .post a[href$="gif"], .themify_lightboxed_images .post a[href$="png"], .themify_lightboxed_images .post a[href$="JPG"], .themify_lightboxed_images .post a[href$="GIF"], .themify_lightboxed_images .post a[href$="PNG"], .themify_lightboxed_images .post a[href$="jpeg"], .themify_lightboxed_images .post a[href$="JPEG"] { cursor:not-allowed; }
	.themify_lightbox_loaded a.themify_lightbox, .themify_lightbox_loaded .module-gallery a, .themify_lightbox_loaded .gallery-icon { cursor:pointer; }
	</style>';
}

/**
 * Convert URLs to absolute system path
 *
 * @since 4.5.1
 * @return string|bool false if conversion fails, string system path otherwise
 */
function themify_get_absolute_path( $url ) {
	$upload_dir = wp_upload_dir();
	$path = str_replace( $upload_dir['baseurl'], $upload_dir['basedir'], $url );
	if ( is_file( $path ) ) {
		return $path;
	}

	// alternative: try getting an attachment ID by just using the filename
	global $wpdb;
	$pathinfo = pathinfo( $url );
	$basename = $pathinfo['basename'];
	$attachment = $wpdb->get_col("SELECT ID FROM $wpdb->posts WHERE guid LIKE '%{$basename}%';"); 
	if ( $attachment ) {
		return get_attached_file( end( $attachment ) );
	}

	return false;
}