<?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';
}
	
///////////////////////////////////////////
// Create Nav Options
///////////////////////////////////////////
function themify_admin_nav() {
	$theme = wp_get_theme();
	$do = 'menu_page';
	/**
	 * Add Themify menu entry
	 * @since 2.0.2
	 */
	call_user_func( 'add' . "_$do" , 'themify', $theme->display('Name'), 'manage_options', 'themify', 'themify_page', get_template_directory_uri().'/themify/img/favicon.png', '49.3' );
	/**
	 * Add Themify settings page
	 * @since 2.0.2
	 */
	call_user_func( 'add_sub' . $do, 'themify', $theme->display('Name'), __('Themify Settings', 'themify'), 'manage_options', 'themify', 'themify_page' );
	if ( Themify_Builder_Model::builder_check() ) {
		/**
		 * Add Themify Builder Layouts page
		 * @since 2.0.2
		 */
		call_user_func( 'add_sub' . $do, 'themify', __( 'Builder Layouts', 'themify' ), __( 'Builder Layouts', 'themify' ), 'edit_posts', 'edit.php?post_type=tbuilder_layout' );
		/**
		 * Add Themify Builder Layout Parts page
		 * @since 2.0.2
		 */
		call_user_func( 'add_sub' . $do, 'themify', __( 'Builder Layout Parts', 'themify' ), __( 'Builder Layout Parts', 'themify' ), 'edit_posts', 'edit.php?post_type=tbuilder_layout_part' );
	}
	/**
	 * Add Themify Customize submenu entry
	 * @since 2.0.2
	 */
	call_user_func( 'add_sub' . $do, 'themify', 'themify_customize', __( 'Customize', 'themify' ), 'manage_options', 'customize.php' );
	/**
	 * Add submenu entry that redirects to Themify documentation site
	 * @since 2.0.2
	 */
	call_user_func( 'add_sub' . $do, 'themify', $theme->display('Name'), __('Documentation', 'themify'), 'manage_options', 'themify_docs', 'themify_docs' );
}

/*  Pages
/***************************************************************************/	

///////////////////////////////////////////
// Themify Documentation
///////////////////////////////////////////
function themify_docs() {
	$theme = wp_get_theme();
	$doc_path = str_replace( 'themify-', '', $theme->get_template() );
	?>
	<script type="text/javascript">window.location = "http://themify.me/docs/<?php echo $doc_path; ?>-documentation";</script>
	<?php
}

///////////////////////////////////////////
// Themify Page
///////////////////////////////////////////
function themify_page() {

	if ( ! current_user_can( 'manage_options' ) )
		wp_die( __( 'You do not have sufficient permissions to update this site.', 'themify' ) );

	if (isset($_GET['action'])) {
		$action = 'upgrade';
		themify_updater();
	}

	global $themify_config;

	// check theme information
	$theme = wp_get_theme();
	$check_theme_name = ( is_child_theme() ) ? $theme->parent()->Name : $theme->display('Name');
	$check_theme_version = ( is_child_theme() ) ? $theme->parent()->Version : $theme->display('Version');

	$themify_has_styling_data = themify_has_styling_data();

	/**
     * Markup for Themify skins. It's empty if there are no skins
     * @since 2.1.8
     * @var string
     */
    $themify_skins = themify_get_skins();
	?>
    <!-- alerts -->
    <div class="alert"></div>
    <!-- /alerts -->

    <!-- prompts -->
    <div class="prompt-box">
        <div class="show-login">
            <form id="themify_update_form" method="post" action="admin.php?page=themify&action=upgrade&type=theme&login=true">
            <p class="prompt-msg"><?php _e('Enter your Themify login info to upgrade', 'themify'); ?></p>
            <p><label><?php _e('Username', 'themify'); ?></label> <input type="text" name="username" class="username" value=""/></p>
            <p><label><?php _e('Password', 'themify'); ?></label> <input type="password" name="password" class="password" value=""/></p>
            <input type="hidden" value="theme" name="type" />
            <input type="hidden" value="true" name="login" />
            <p class="pushlabel"><input name="login" type="submit" value="Login" class="button upgrade-login" /></p>
            </form>
        </div>
        <div class="show-error">
            <p class="error-msg"><?php _e('There were some errors updating the theme', 'themify'); ?></p>
        </div>
    </div>
    <div class="overlay">&nbsp;</div>
    <!-- /prompts -->

    <!-- html -->
    <form id="themify" method="post" action="" enctype="multipart/form-data">
    <p id="theme-title"><?php echo esc_html( $check_theme_name ); ?> <em><?php echo esc_html( $check_theme_version ); ?> (<a href="http://themify.me/logs/<?php echo '' != $theme->display('Template')? $theme->display('Template') : strtolower($check_theme_name); ?>-changelogs" class="themify_changelogs" target="_blank" data-changelog="<?php echo themify_https_esc( 'http://themify.me/changelogs/' ); ?><?php echo get_template(); ?>.txt"><?php _e('changelogs', 'themify'); ?></a>)</em></p>
    <p class="top-save-btn">
        <a href="#" class="save-button"><?php _e('Save', 'themify'); ?></a>
    </p>
	<div id="content">

        <!-- nav -->
        <ul id="maintabnav">
            <li class="setting"><a href="#setting"><?php _e( 'Settings', 'themify' ); ?></a></li>
			<?php if ( $themify_has_styling_data ) : ?>
                <li class="styling"><a href="#styling"><?php _e( 'Styling', 'themify' ); ?></a></li>
			<?php endif; // $themify_has_styling_data ?>
			<?php if ( ! empty( $themify_skins ) ) : ?>
				<li class="skins"><a href="#skins"><?php _e( 'Skins', 'themify' ); ?></a></li>
			<?php endif; ?>
            <li class="transfer"><a href="#transfer"><?php _e( 'Transfer', 'themify' ); ?></a></li>
			<li class="demo-import"><a href="#demo-import"><?php _e( 'Demo Import', 'themify' ); ?></a></li>
			<?php if ( themify_allow_update() ) : ?>
				<li class="update-check"><a href="#update-check"><?php _e( 'Update', 'themify' ); ?></a></li>
			<?php endif; ?>
        </ul>
        <!-- /nav -->

        <!------------------------------------------------------------------------------------>

        <!--setting tab -->
        <div id="setting" class="maintab">

            <ul class="subtabnav">
                <?php
                $x = 1;
                foreach($themify_config['panel']['settings']['tab'] as $tab){
                    if($x){
                        echo '<li class="selected"><a href="' . esc_attr( '#setting-' . themify_scrub_func( $tab['id'] ) ) . '">' . $tab['title'] . '</a></li>';
                        $x = 0;
                    } else {
                        if ( isset( $tab['id'] ) ) {
	                        echo '<li><a href="' . esc_attr( '#setting-' . themify_scrub_func( $tab['id'] ) ) . '">' . $tab['title'] . '</a></li>';
                        }
                    }
                }
                ?>
            </ul>

            <?php $themify_settings_notice = false; ?>
             <?php foreach($themify_config['panel']['settings']['tab'] as $tab){ ?>
                <!-- subtab: setting-<?php echo themify_scrub_func($tab['id']); ?> -->
                <div id="<?php echo esc_attr( 'setting-' . themify_scrub_func( $tab['id'] ) ); ?>" class="subtab">
                    <?php
					if ( ! $themify_settings_notice ) :
                        ?>
                        <div class="themify-info-link"><?php printf( __( 'For more info about the options below, refer to the <a href="%s">General Settings</a> documentation.', 'themify' ), 'http://themify.me/docs/general-settings' ); ?></div>
                        <?php
                        $themify_settings_notice = true;
					endif; // themify settings notice
					?>
					<?php
					if(is_array($tab['custom-module'])){
						if(isset($tab['custom-module']['title']) && isset($tab['custom-module']['function'])){
							echo themify_fieldset($tab['custom-module']['title'], themify_scrub_func($tab['custom-module']['function']), $tab['custom-module']);
						} else {
							foreach($tab['custom-module'] as $module){
								echo themify_fieldset($module['title'], themify_scrub_func($module['function']),$module);
							}
						}
					}
                    ?>
                </div>
                <!-- /subtab: setting-<?php echo themify_scrub_func($tab['id']); ?> -->
            <?php } ?>

        </div>
        <!--/setting tab -->

        <!------------------------------------------------------------------------------------>

		<?php if ( $themify_has_styling_data ) : ?>
        <!--styling tab -->
        <div id="styling" class="maintab">

			<?php if ( get_option( 'themify_customize_notice', 1 ) ) : ?>
				<div class="themify-big-notice black js-customize-notice">
					<h3><?php _e( 'New Customize Panel', 'themify' ); ?></h3>
					<p><strong><?php _e( 'We have a new Customize panel which allows you to customize the theme
					with live preview on the frontend. This Themify Styling panel still works as is,
					but we recommend you to start using the new Customize panel.', 'themify' ); ?></strong></p>
					<p><?php _e( 'Because the Customize panel stores data differently,
					the data in the Themify Styling is not migrated to the Customize panel. You can either start
					fresh by resetting the Themify Styling or use both as you like.',
							'themify' ); ?></p>
					<a href="#" class="button notice-dismiss" data-notice="customize"><?php _e( 'Start Customize', 'themify' ); ?></a>
					<a href="#" class="close notice-dismiss" data-notice="customize">
						<i class="ti-close"></i>
					</a>
				</div>
			<?php endif; ?>

            <ul class="subtabnav">
                <?php
                $x = 1;
				if(isset($themify_config['panel']['styling']['tab']['title'])){
					echo '<li class="selected"><a href="' . esc_attr( '#styling-' . themify_scrub_func( $themify_config['panel']['styling']['tab']['title'] ) ) . '">' . $themify_config['panel']['styling']['tab']['title'] . '</a></li>';
				} else {
					foreach($themify_config['panel']['styling']['tab'] as $tab){
						if($x){
							echo '<li class="selected"><a href="' . esc_attr( '#styling-' . themify_scrub_func( $tab['id'] ) ) . '">' . $tab['title'] . '</a></li>';
							$x = 0;
						} else {
							echo '<li><a href="' . esc_attr( '#styling-' . themify_scrub_func( $tab['id'] ) ) . '">' . $tab['title'] . '</a></li>';
						}
					}
				}
				?>
            </ul>

            <?php
			if(isset($themify_config['panel']['styling']['tab']['title'])){
			?>
				<!-- subtab: styling-<?php echo themify_scrub_func($themify_config['panel']['styling']['tab']['_a']['title']); ?> -->
				<div id="<?php echo esc_attr( 'styling-' . themify_scrub_func( $themify_config['panel']['styling']['tab']['title'] ) ); ?>" class="subtab">
						<?php
						if(is_array($themify_config['panel']['styling']['tab']['element'])){
							if(isset($themify_config['panel']['styling']['tab']['element']['title']) && isset($themify_config['panel']['styling']['tab']['element']['selector'])){
								echo themify_container(themify_scrub_func($tab['id']), $themify_config['panel']['styling']['tab']['element']);
							} else {
								foreach($themify_config['panel']['styling']['tab']['element'] as $element){
									echo themify_container(themify_scrub_func($themify_config['panel']['styling']['tab']['title']), $element);
								}
							}
						}
						?>
					</div>
					<!-- /subtab: styling-<?php echo themify_scrub_func($tab['_a']['title']); ?> -->
			<?php
			} else {
				foreach($themify_config['panel']['styling']['tab'] as $tab){ ?>
					<!-- subtab: styling-<?php echo themify_scrub_func($tab['id']); ?> -->
					<div id="<?php echo esc_attr( 'styling-' . themify_scrub_func( $tab['id'] ) ); ?>" class="subtab">
						<?php
						if(is_array($tab['element'])){
							if(isset($tab['element']['title']) && isset($tab['element']['selector'])){
								echo themify_container(themify_scrub_func($tab['id']), $tab['element']);
							} else {
								foreach($tab['element'] as $element){
									echo themify_container(themify_scrub_func($tab['id']), $element);
								}
							}
						}
						?>
					</div>
					<!-- /subtab: styling-<?php echo themify_scrub_func($tab['id']); ?> -->
				<?php }
			}
			?>

        </div>
        <!--/styling tab -->
		<?php endif; // $themify_has_styling_data ?>

        <!------------------------------------------------------------------------------------>

        <!--skins tab -->
        <?php
        if ( ! empty( $themify_skins ) ) : ?>
			<div id="skins" class="maintab">
				<ul class="subtabnav">
					<li class="selected"><a href="#setting-general"><?php _e('Skins', 'themify'); ?></a></li>
				</ul>

				<div id="load-load" class="subtab">
					<?php echo themify_get_skins(); ?>
				</div>
			</div>
			<!--/skins tab -->
		<?php endif; ?>

        <!------------------------------------------------------------------------------------>

        <!--transfer tab -->
        <div id="transfer" class="maintab">
            <ul class="subtabnav">
                <li><a href="#transfer-import"><?php _e( 'Theme Settings', 'themify' ); ?></a></li>
            </ul>

            <div id="transfer-import" class="subtab">
				<div class="themify-info-link"><?php _e( 'Click "Export" to export the Themify panel data which you can use to import in the future by clicking the "Import" button. Note: this will only export/import the data within the Themify panel (the WordPress settings, widgets, content, comments, page/post settings, etc. are not included).', 'themify' ) ?></div>

                <div class="biggest-transfer-btn">
                <input type="hidden" id="import" />
                 <?php themify_uploader( 'import', array(
                            'label' => __('Import', 'themify'),
                            'confirm' => __('Import will overwrite all settings and configurations. Press OK to continue, Cancel to stop.', 'themify') )
						); ?>

                <em><?php _e('or', 'themify'); ?></em>
                <?php
                /**
				 * URL of Themify Settings Page properly nonced.
				 * @var String
				 */
                $baseurl = wp_nonce_url(admin_url('admin.php?page=themify'), 'themify_export_nonce');
                $baseurl = add_query_arg( 'export', 'themify', $baseurl );
                ?>
                <a href="<?php echo esc_url( $baseurl ) ?>" class="export" id="download-export"><?php _e('Export', 'themify'); ?></a>
                </div>
            </div>

        </div>
        <!--/transfer tab -->

		<!--demo import tab -->
        <div id="demo-import" class="maintab">
            <ul class="subtabnav">
                <li><a href="#demo-import"><?php _e( 'Demo Import', 'themify' ); ?></a></li>
            </ul>

            <div id="demo-import" class="subtab demo-import-main">
				<p>
				<a href="#" class="button import-sample-content" data-default="<?php _e( 'Import Demo', 'themify' ); ?>" data-success="<?php _e( 'Done', 'themify' ); ?>" data-importing="<?php _e( 'Importing', 'themify' ) ?>"> <i class="ti-arrow-down"></i> <span><?php _e( 'Import Demo', 'themify' ); ?></span> </a>
				</p>
				<p><?php _e( 'Import Demo will import the content (posts/pages), Themify panel settings, menus and widgets as our demo. Due to copyright reasons, demo images will be replaced with a placeholder image.', 'themify' ); ?></p>
                <p><small><?php printf( __( 'Demo Import might not work for some servers with restrict settings. Sample content can also be imported manually with
WordPress <a href="%s">Tools &gt; Import</a>.', 'themify' ), 'http://themify.me/docs/importing#import-tool' ); ?></small></p>
				<p>
				<a href="#" class="button erase-sample-content" data-default="<?php _e( 'Erase Demo', 'themify' ); ?>" data-erasing="<?php _e( 'Erasing', 'themify' ); ?>" data-success="<?php _e( 'Done', 'themify' ); ?>"> <i class="ti-close"></i> <span><?php _e( 'Erase Demo', 'themify' ); ?></span> </a>
				</p>
				<p><?php _e( 'Erase demo will delete the imported posts/pages. Existing and modified imported post/page will not be deleted. Themify panel settings and widgets will not be removed. You may import the content again later.', 'themify' ); ?></p>
			</div>

        </div>
        <!--/demo import tab -->

        <?php if ( themify_allow_update() ) : ?>
		<!--update theme/framework tab -->
        <div id="update-check" class="maintab">
            <ul class="subtabnav">
                <li><a href="#update-main"><?php _e( 'Update', 'themify' ); ?></a></li>
            </ul>

            <div id="update-main" class="subtab update-main">
				<?php
				ob_start();
				themify_check_version( 'tab' );
				$update_message = ob_get_contents();
				ob_end_clean();
				$button_label = __( 'Check for Updates', 'themify' );
				$update_available = __( 'Check for theme and framework updates.', 'themify' );
				if ( isset( $_GET['update'] ) && 'check' == $_GET['update'] ) {
					$button_label = __( 'Check Again', 'themify' );
					$update_available = __( 'No updates available.', 'themify' );
				}

				if ( $update_message ) : ?>
					<?php if ( false !== strpos( $update_message, 'reinstalltheme' ) && false === strpos( $update_message, 'updateready' ) ) : ?>
						<p><a href="<?php echo esc_url( add_query_arg( 'update', 'check', admin_url('admin.php?page=themify') ) ); ?>" class="button big-button update"><span><?php echo esc_html( $button_label ); ?></span></a>
						</p>
						<p><?php echo esc_html( $update_available ); ?></p>
					<?php endif; ?>
					<?php echo !empty( $update_message ) ? $update_message : ''; ?>
				<?php else : ?>
					<p><a href="<?php echo esc_url( add_query_arg( 'update', 'check', admin_url('admin.php?page=themify') ) ); ?>" class="button big-button update"><span><?php echo esc_html( $button_label ); ?></span></a>
					</p>
					<p><?php echo esc_html( $update_available ); ?></p>
				<?php endif; ?>
			</div>
        </div>
        <!--/update theme/framework tab -->
        <?php endif; // user can update_themes ?>

        <!------------------------------------------------------------------------------------>

    </div>
    <!--/content -->

	<?php if( get_option( get_template() . '_themify_import_notice', 1 ) ) : ?>
		<div id="demo-import-notice">
			<h3><?php _e( 'Import Demo', 'themify' ); ?></h3>
			<p><?php _e( 'Would you like to import the demo content to have the exact look as our demo?', 'themify' ); ?></p>
			<p><?php _e( 'You may import or erase demo content later at the Import tab of the Themify panel.', 'themify' ); ?></p>
			<a href="#" class="button import-sample-content" data-default="<?php _e( 'Import Demo', 'themify' ); ?>" data-success="<?php _e( 'Done', 'themify' ); ?>" data-importing="<?php _e( 'Importing', 'themify' ) ?>"> <i class="ti-arrow-down"></i> <span><?php _e( 'Yes, import', 'themify' ); ?></span> </a>
			<a href="#" class="thanks-button dismiss-import-notice"> <?php _e( 'No, thanks', 'themify' ); ?> </a>
			<a href="#" class="close dismiss-import-notice"><i class="ti-close"></i></a>
		</div>
		<?php
			// disable the demo import modal after first visit
			update_option( get_template() . '_themify_import_notice', 0 ); ?>
	<?php endif; ?>

    <!-- footer -->
    <div id="bottomtab">
       <p id="logo"><a href="http://themify.me/logs/framework-changelogs/" data-changelog="http://themify.me/changelogs/themify.txt" target="_blank" class="themify_changelogs">v<?php echo THEMIFY_VERSION; ?></a></p>
        <div class="reset">
			<strong><?php _e( 'Reset', 'themify' ); ?></strong>
			<ul>
                <li><a href="#" id="reset-setting" class="reset-button"><?php _e('Settings', 'themify'); ?></a></li>
				<li><?php if ( $themify_has_styling_data ) : ?>
					<a href="#" id="reset-styling" class="reset-button"><?php _e('Styling', 'themify'); ?></a>
				<?php endif; ?></li>
			</ul>
        </div>
        <p class="btm-save-btn">
            <a href="#" class="save-button"><?php _e('Save', 'themify'); ?></a>
        </p>
    </div>
    <!--/footer -->

    </form>
    <div class="clearBoth"></div>
    <!-- /html -->

	<?php
	do_action('themify_settings_panel_end');
}


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

///////////////////////////////////////////
// Get Skins
///////////////////////////////////////////
function themify_get_skins(){
	$data = themify_get_data();
	$output = '';

	// Open Styles Folder
	$dir = dirname(__FILE__).'/../skins';

	if ( is_dir( $dir ) ) {
		// If skin exists in /skins/ directory in theme root, select it, otherwise set to No Skin
		$current_skin = themify_get( 'skin' );
		$parsed_skin = parse_url( $current_skin, PHP_URL_PATH );
		$basedir_skin = basename( dirname( $parsed_skin ) );
		$is_theme_skin = is_file( THEME_DIR . '/skins/' . $basedir_skin . '/' . basename( $parsed_skin ) );
		if ( ! $is_theme_skin ) {
			$current_skin = get_template_directory_uri() . '/themify/img/non-skin.gif';
		}
		$output = '<input type="hidden" name="skin" value="' . esc_url( $current_skin ) . '">';
		if( ! isset( $data['skin'] ) || '' == $data['skin'] || ! $is_theme_skin ) {
			$output .= '<div class="skin-preview"><a href="#"><img src="' . esc_url( get_template_directory_uri() . '/themify/img/non-skin.gif' ) . '" alt="' . esc_attr__( 'Skin', 'themify' ) . '" class="selected" /></a><br />' . __( 'No Skin', 'themify' ) . '</div>';
		} else {
			$output .= '<div class="skin-preview"><a href="#"><img src="' . esc_url( get_template_directory_uri() . '/themify/img/non-skin.gif' ) . '" alt="' . esc_attr__( 'Skin', 'themify' ) . '" /></a><br />' . __( 'No Skin', 'themify' ) . '</div>';
		}

		if($handle = opendir($dir)){
			// Grab Folders
			while (false !== ($dirTwo = readdir($handle))){
				if($dirTwo != '.' && $dirTwo != '..'){
					// Check For Folder
					if(is_dir(str_replace('//','/',dirname(__FILE__).'/').'../skins/'.$dirTwo)){
						// Open Folders
						if($handleTwo = opendir(str_replace('//','/',dirname(__FILE__).'/').'../skins/'.$dirTwo)){
							// Grab Files
							while(false !== ($file = readdir($handleTwo))){
								$ext = substr(strrchr($file, '.'), 1); // File Extension

								if($file == 'style.css'){
									$info = themify_get_skin_info(str_replace('//','/',dirname(__FILE__).'/').'../skins/'.$dirTwo.'/'.$file);
									$fullpath = get_template_directory_uri().'/skins/'.$dirTwo.'/'.$file;
									if(is_file(str_replace('//','/',dirname(__FILE__).'/').'../skins/'.$dirTwo.'/screenshot.png')){
										$image = get_template_directory_uri().'/skins/'.$dirTwo.'/screenshot.png';
									} else {
										$image = get_template_directory_uri().'/themify/img/screenshot-na.png';
									}
									if ( $fullpath == themify_get( 'skin' ) ) {
										$output .= '<div class="skin-preview"><a href="#"><img src="' . esc_url( $image ) . '" alt="' . esc_attr__( 'Skin', 'themify' ) . '" class="selected" id="' . esc_attr( get_template_directory_uri() . '/skins/' . $dirTwo . '/style.css' ) . '" /></a><br />' . $info['Skin Name'] . '</div>';
									} else {
										$output .= '<div class="skin-preview"><a href="#"><img src="' . esc_url( $image ) . '" alt="' . esc_attr__( 'Skin', 'themify' ) . '" id="' . esc_attr( get_template_directory_uri() . '/skins/' . $dirTwo . '/style.css' ) . '" /></a><br />' . $info['Skin Name'] . '</div>';
									}
								}
							}
							closedir($handleTwo);
						}
					}
				}
			}
			closedir($handle);
		}
	}
	return $output;
}

/**
 * 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($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($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($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($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($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($v['value']['top'] != '' || $v['value']['right'] != '' || $v['value']['bottom'] != '' || $v['value']['left'] != ''){
											if($v['value']['top'] != ''){
												$temp .= "padding-top: ".$v['value']['top']."px;\n";
											}
											if($v['value']['right'] != ''){
												$temp .= "padding-right: ".$v['value']['right']."px;\n";
											}
											if($v['value']['bottom'] != ''){
												$temp .= "padding-bottom: ".$v['value']['bottom']."px;\n";
											}
											if($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($v['value']['top'] != '' || $v['value']['right'] != '' || $v['value']['bottom'] != '' || $v['value']['left'] != ''){
											if($v['value']['top'] != ''){
												$temp .= "margin-top: ".$v['value']['top']."px;\n";
											}
											if($v['value']['right'] != ''){
												$temp .= "margin-right: ".$v['value']['right']."px;\n";
											}
											if($v['value']['bottom'] != ''){
												$temp .= "margin-bottom: ".$v['value']['bottom']."px;\n";
											}
											if($v['value']['left'] != ''){
												$temp .= "margin-left: ".$v['value']['left']."px;\n";
											}
										}
									}
								break;
								case "color":
									if($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";
									} else {
										if($v['value']['value'] != '' && $v['value']['value'] != ' '){
											$temp .= $attribute.": ";
											$temp .= "#".$v['value']['value'].";\n";
										}
									}
								break;
								case "background-image":
									if($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($v['value']['value'] != '' && $v['value']['value'] != ' '){
										$temp .= $attribute.": ";
										$temp .= $v['value']['value'].";\n";
									}
								break;
								case "font-family":
									if($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($v['value']['value'] != '' && $v['value']['value'] != ' '){
										$temp .= $attribute.": ";
										$temp .= $v['value']['value'].$v['value']['unit'].";\n";
									}
								break;
								case "position":
									if($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($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;
}

///////////////////////////////////////////
// Get Skin Info
///////////////////////////////////////////
function themify_get_skin_info($file){
	if ( ! function_exists( 'WP_Filesystem' ) ) {
		require_once ABSPATH . 'wp-admin/includes/file.php';
	}
	WP_Filesystem();
	global $wp_filesystem;
	$data = $wp_filesystem->get_contents( $file );
	$tempArray = explode("\n",themify_strip("/*", "*/", $data, 0));
	$array = array();
	foreach($tempArray as $line){
		$tempLine = explode(":", $line);
		if ( isset( $tempLine[1] ) )
			$array[$tempLine[0]] = $tempLine[1];
	}
	return $array;
}

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

/**
 * Create Settings Fieldset
 *
 * @param string $title
 * @param string $module
 * @param string $attr
 *
 * @return string
 */
function themify_fieldset( $title = '', $module = '', $attr = '' ) {
	$data = themify_get_data();
	$module = trim( $module );
	$data_param = isset( $data['setting'] ) && isset( $data['setting'][$title] )? $data['setting'][$title] : '';
	$function = '';
	if ( function_exists( 'themify_' . $module ) ) {
		$function = 'themify_' . $module;
	} else if ( function_exists( $module ) ) {
		$function = $module;
	}
	if ( '' == $function ) {
		return '';
	}
	$output = '<fieldset><legend>' . esc_html( $title ) . '</legend>';
	$output .= call_user_func( $function, array(
		'data' => $data_param,
		'attr' => $attr )
	);
	$output .= '</fieldset>';
	return $output;
}

///////////////////////////////////////////
// Create Styles Container
///////////////////////////////////////////
function themify_container( $category = '', $element = array() ) {
	$data = themify_get_data();
	$temp = 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;
		}
		$temp = themify_convert_brackets_string_to_arrays( $new_arr );
	}
	if($element){
		$base_id = $element['id'];
		$output = '	<fieldset><legend>' . esc_html( $element['title'] ) . '</legend>';
		if(is_array($element['module'])){
			foreach($element['module'] as $module){
				if( themify_is_associative_array($module) ) {
					$module_name = $module['name'];
				} else {
					$module_name = $module;
				}

				$title = $element['id'];
				$attr = $module;
				$module = trim(str_replace(array(' ','-','|'),array('','_','hr'),$module_name));
				$value = isset( $temp['styling'][$category][$title][$module] )? $temp['styling'][$category][$title][$module] : '';
				if(function_exists("themify_".$module)){
					$output .=	call_user_func("themify_".$module, array('category' => $category, 'title' => $title, 'value' => $value, 'attr' => $attr, 'id' => $base_id));
				} else {
					if(function_exists($module)){
						$output .=	call_user_func($module, array('category' => $category, 'title' => $title, 'value' => $value, 'attr' => $attr, 'id' => $base_id));
					}
				}
			}
		}
		$output .= '</fieldset>';
		return $output;
	}
}

/**
 * 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' ) );
	
	// Custom Write Panel
	if( ($page == 'post.php' || $page == 'post-new.php') && in_array($typenow, $types) ){
		wp_enqueue_script( 'meta-box-tabs', THEMIFY_URI . '/js/meta-box-tabs.js', array('jquery'), '1.0', true );
		wp_enqueue_script( 'media-library-browse', THEMIFY_URI . '/js/media-lib-browse.js', array('jquery'), '1.0', true );
	}

	// 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_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',  THEMIFY_URI . '/css/themify-ui.css', array(), THEMIFY_VERSION );
		if ( is_rtl() ) {
			wp_enqueue_style( 'themify-ui-rtl',  THEMIFY_URI . '/css/themify-ui-rtl.css', array(), THEMIFY_VERSION );
		}
		wp_enqueue_style( 'colorpicker', THEMIFY_URI . '/css/jquery.minicolors.css', array(), THEMIFY_VERSION );
		
		//Enqueue scripts
		wp_enqueue_script( 'jquery' );
		wp_enqueue_script( 'jquery-ui-core' );
		wp_enqueue_script( 'jquery-ui-tabs' );
		wp_enqueue_script( 'json2' );
		wp_enqueue_script( 'plupload-all' );
		wp_enqueue_script( 'validate', THEMIFY_URI . '/js/jquery.validate.pack.js', array('jquery'), THEMIFY_VERSION );
		wp_enqueue_script( 'colorpicker-js', THEMIFY_URI . '/js/jquery.minicolors.js', array('jquery'), THEMIFY_VERSION );
		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', THEMIFY_URI . '/js/scripts.js', array('jquery'), THEMIFY_VERSION );
			wp_enqueue_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 );
		}
		// Enqueue font icon assets.
		themify_font_icons_admin_assets();
		wp_enqueue_style ( 'magnific', THEMIFY_URI . '/css/lightbox.css', array(), THEMIFY_VERSION );
		wp_enqueue_script( 'magnific', THEMIFY_URI . '/js/lightbox.js', array('jquery'), THEMIFY_VERSION, true );
	}
	//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' ),
		)
	);
}

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

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

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

		wp_deregister_script( 'wp-mediaelement' );
		wp_register_script( 'wp-mediaelement', THEMIFY_URI . '/js/themify-mediaelement.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>";
		}
	}

	
	/**
	 * 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();
					if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== 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( 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 ) :
		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);
								$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']
									);
								}//*/
                                /*$terms_dropdown = wp_dropdown_categories(
								array(
                                	'taxonomy' => $terms_tax, 
                                	'class' => 'query_category_single',
                                    'show_option_all' => __('All Categories', 'themify'),
                                    'hide_empty' => 0,
                                    'echo' => 0,
                                    'name' => $meta_box['name'],
                                    'selected' => $meta_value
								));
                                echo preg_replace('/>/', '><option></option>', $terms_dropdown, 1);//*/
                                ?>
                                <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'); ?> 
                                <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;">
		<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">
			<?php include( THEMIFY_DIR . '/fontawesome/list.html' ); ?>
		</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 ) {
	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 ) {
	$meta_key = '_menu_item_icon';
	$meta_value = themify_get_menu_icon( $menu_item_db_id );
	$menu_item_icon = isset( $_POST['menu-item-icon'] ) && isset( $_POST['menu-item-icon'][$menu_item_db_id] ) ? $_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;
}

/**
 * Lightbox support for menu items
 */
function themify_lightbox_menu_item( $atts, $item, $args ) {
	if( in_array( 'lightbox', $item->classes ) ) {
		$atts['class'] = isset( $atts['class'] ) ? $atts['class'] . ' lightbox' : 'lightbox';
		if( substr( $atts['href'], 0, 1 ) != '#' ) { // for inline modals do not add the query parameters
			$atts['href'] = themify_get_lightbox_iframe_link( $atts['href'] );
		}
	}

	return $atts;
}

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

	$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 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" />
		<input type="button" id="%s" data-picker="%s" value="%s" class="button themifyClearDate themifyOpacityTransition %s" >',
	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 ),
	'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';
	}
	
	$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"><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>',
		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( $meta_box['name'] ) && isset( $_POST[$meta_box['name']] ) ? $_POST[$meta_box['name']] : '';
					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'		 => '',
		'crop'		 => 'false',
		'setting' 	 => '',
		'field_name' => 'post_image,image,wp_thumb,feature_image',
		'urlonly' 	 => false,
		'image_size' => '',
	) );

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

	// If ignore is set, just use width and height passed
	if ( ( ! empty( $args['ignore'] ) && ! themify_is_image_script_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 ) ) {
				if ( ! $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 ) ) {
				if ( ! $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 ) ) {
				if ( ! $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 ) ) {
				if ( ! $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() ) { // 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' );
			}
		}

		if ( '' == $width ) {
			$width = $themify->width;
		}
		if ( '' == $height) {
			$height = $themify->height;
		}
	} else {
		if ( ! $width = get_post_meta( $post_id, 'image_width', true ) ) {
			if ( ! empty( $args['h'] ) ) {
				$height = $args['h'];
			}
		}
		if ( ! $height = get_post_meta( $post_id, 'image_height', true ) ) {
			if ( ! empty( $args['w'] ) ) {
				$width = $args['w'];
			}
		}
	}

	if ( ! themify_is_image_script_disabled() ) { // Use Image Script

		if ( empty( $args['src'] ) ) {
			foreach( explode( ',', $args['field_name'] ) as $field ) {
				if ( $img_url = get_post_meta( $post_id, trim( $field ), true ) ) {
					break;
				}
			}
			if ( '' === $img_url && themify_check( 'setting-auto_featured_image' ) ) {
				// No image was defined, parse content to find an image.
				$content = get_the_content();
				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' ) ) {
							$img_url = isset( $temp['src'] )? $temp['src'] : '';
							$args['class'] .= isset( $temp['class'] )? ' ' . $temp['class'] : '';
							if ( empty( $args['alt'] ) ) {
								$alt = $temp['alt'];
							}
							break;
						}
					}
				}
			}
		} else {
			$img_url = $args['src'];
		}

		// Set URL to use for final output.
		$temp = themify_do_img( $img_url, $width, $height, $args['crop'] );
		$img_url = $temp['url'];

	} else { // Use WP standard 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() ) {
					$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.
		$temp = wp_get_attachment_image_src( get_post_thumbnail_id( $post_id ), $feature_size );
		$img_url = $temp[0];
	}

	if ( ! empty( $img_url ) ) {
		if ( $args['urlonly'] ) {
			$out = $img_url;
		} else {
			// Build final image
			$out = "<img src=\"{$img_url}\"";
			if ( $width ) {
				$out .= " width=\"{$width}\"";
			}
			if ( $height ) {
				$out .= " height=\"{$height}\"";
			}
			if ( ! empty( $args['class'] ) ) {
				$out .= " class=\"{$args['class']}\"";
			}
			$out .= ' alt="' . the_title_attribute( 'echo=0' ) . '" />';
		}
		$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
	 * @return void|string
	 */
	function themify_image_url( $echo = false, $size = 'full' ) {
		$url = '';
		if ( has_post_thumbnail() ) {
			$image = wp_get_attachment_image_src( get_post_thumbnail_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 ) {
	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 );
	}
}
	
/**
 * Return post content with the proper filters applied
 * @param string $more_link_text Text to use for (more...)
 * @param int $stripteaser Optional. Strip teaser content before the more text
 * @param string $more_file
 * @return string Post content
 */
function themify_get_content($more_link_text = '(more...)', $stripteaser = 0, $more_file = '') {
	$content = get_the_content($more_link_text, $stripteaser, $more_file);
	$content = apply_filters('the_content', $content);
	$content = str_replace(']]>', ']]&gt;', $content);
	return $content;
}

/**
 * Themify Excerpt
 *
 * @param $limit
 *
 * @return array|mixed|string
 */
function themify_excerpt($limit) {
	$excerpt = explode(' ', get_the_excerpt(), $limit);
	if (count($excerpt)>=$limit) {
		array_pop($excerpt);
		$excerpt = implode(" ",$excerpt).'...';
	} else {
		$excerpt = implode(" ",$excerpt);
	}
		$excerpt = preg_replace('`[[^]]*]`','',$excerpt);
	return $excerpt;
}

///////////////////////////////////////
// Load theme languages
///////////////////////////////////////
load_theme_textdomain( 'themify', THEME_DIR.'/languages' );

/**
 * Echoes page navigation
 *
 * @param string $before
 * @param string $after
 * @param bool   $query
 */
function themify_pagenav($before = '', $after = '', $query = false) {
	echo themify_get_pagenav($before, $after, $query);
}

/**
 * Returns page navigation
 * @param string $before Markup to show before pagination links
 * @param string $after Markup to show after pagination links
 * @param object $query WordPress query object to use
 * @return string
 * @since 1.2.4
 */
function themify_get_pagenav($before = '', $after = '', $query = false) {
	global $wp_query;

	if( false == $query ){
		$query = $wp_query;
	}
	$request = $query->request;
	$posts_per_page = intval(get_query_var('posts_per_page'));
	$paged = intval(get_query_var('paged'));
	$numposts = $query->found_posts;
	$max_page = $query->max_num_pages;

	if(empty($paged) || $paged == 0) {
		$paged = 1;
	}
	$pages_to_show = apply_filters('themify_filter_pages_to_show', 5);
	$pages_to_show_minus_1 = $pages_to_show-1;
	$half_page_start = floor($pages_to_show_minus_1/2);
	$half_page_end = ceil($pages_to_show_minus_1/2);
	$start_page = $paged - $half_page_start;
	if($start_page <= 0) {
		$start_page = 1;
	}
	$end_page = $paged + $half_page_end;
	if(($end_page - $start_page) != $pages_to_show_minus_1) {
		$end_page = $start_page + $pages_to_show_minus_1;
	}
	if($end_page > $max_page) {
		$start_page = $max_page - $pages_to_show_minus_1;
		$end_page = $max_page;
	}
	if($start_page <= 0) {
		$start_page = 1;
	}
	$out = '';
	if ($max_page > 1) {
		$out .=  $before.'<div class="pagenav clearfix">';
		if ($start_page >= 2 && $pages_to_show < $max_page) {
			$first_page_text = '&laquo;';
			$out .=  '<a href="'.get_pagenum_link().'" title="'.$first_page_text.'" class="number">'.$first_page_text.'</a>';
		}
		if($pages_to_show < $max_page)
			$out .= get_previous_posts_link('&lt;');
		for($i = $start_page; $i  <= $end_page; $i++) {
			if($i == $paged) {
				$out .=  ' <span class="number current">'.$i.'</span> ';
			} else {
				$out .=  ' <a href="'.get_pagenum_link($i).'" class="number">'.$i.'</a> ';
			}
		}
		if($pages_to_show < $max_page)
			$out .= get_next_posts_link('&gt;');
		if ($end_page < $max_page) {
			$last_page_text = '&raquo;';
			$out .=  '<a href="'.get_pagenum_link($max_page).'" title="'.$last_page_text.'" class="number">'.$last_page_text.'</a>';
		}
		$out .=  '</div>'.$after;
	}
	return $out;
}

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

/**
 * Display select element with featured image sizes + blank slot
 * @param String $key setting name
 * @return String
 * @since 1.1.5
 */
function themify_feature_image_sizes_select($key = ''){
	/** Define WP Featured Image sizes + blank + Themify's image script
	 * @var array */
	$themify_layout_feature_sizes = themify_get_image_sizes_list();
	
	$output = '<p class="show_if_disabled_img_php">
				<span class="label">' . __('Featured Image Size', 'themify') . '</span>
				<select name="' . esc_attr( 'setting-' . $key ) . '">';
	foreach($themify_layout_feature_sizes as $option){
		if($option['value'] == themify_get('setting-'.$key.'')){
			$output .= '<option value="' . esc_attr( $option['value'] ) . '" selected="selected">';
				$output .= esc_html( $option['name'] );
			$output .= '</option>';
		} else {
			$output .= '<option value="' . esc_attr( $option['value'] ) . '">' . esc_html( $option['name'] ) . '</option>';
		}
	}
	$output .= '</select></p>';
	
	return $output;
}

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() ){
		$parsed_url = parse_url($url);
		$url = 'https://' . $parsed_url['host'] . $parsed_url['path'];
	}
	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'
		))
	);
}

/**
 * Hijacks themes passed for upgrade checking and remove those from Themify
 * @param Bool
 * @param Array $r List of themes
 * @param String $url URL of upgrade check
 * @return Array
 * @since 1.1.8
 */
function themify_hide_themes( $r, $url ){
	if ( false !== stripos( $url, 'api.wordpress.org/themes/update-check' ) ) {
		$themes = json_decode( $r['body']['themes'] );
		$themes_list = themify_get_theme_names();
		if ( is_array( $themes_list ) ) {
		foreach( $themes_list as $theme_name ){
			unset( $themes->themes->{$theme_name} );
		}
		$r['body']['themes'] = json_encode( $themes );
	}
	}
	return $r;
}

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

/**
 * Display an additional column in categories list
 * @since 1.1.8
 */
function themify_custom_category_header($cat_columns){
    $cat_columns['cat_id'] = 'ID';
    return $cat_columns;
}
/**
 * Display ID in additional column in categories list
 * @since 1.1.8
 */
function themify_custom_category($null, $column, $termid){
	return $termid;
}

/**
 * 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 RSS link tag in header
 */
function themify_head_rss_link(){
	$rss_link = themify_check('setting-custom_feed_url') ? themify_get('setting-custom_feed_url') : get_bloginfo('rss2_url');
	echo "\n".'<!-- RSS Feed -->'."\n".'<link rel="alternate" type="application/rss+xml" title="' . get_bloginfo('name') . ' RSS Feed" href="' . esc_url( $rss_link ) . '" />'."\n";
}

if ( ! function_exists( 'themify_get_html_schema' ) ) {
	/**
	 * Generates microdata information for the html tag.
	 * @return string
	 * @since 1.7.4
	 */
	function themify_get_html_schema() {
		$schema = 'http://schema.org/';
		if ( is_single() ) {
			$type = 'Article';
		} elseif( is_author() ) {
			$type = 'ProfilePage';
		} elseif( is_search() ) {
			$type = 'SearchResultsPage';
		} else {
			$type = 'WebPage';
		}
		return 'itemscope="itemscope" itemtype="' . $schema . $type . '"';
	}
}

if ( ! function_exists( 'themify_get_author_link' ) ) {
	/**
	 * Builds the markup for the entry author with microdata information.
	 * @return string
	 * @since 1.7.4
	 */
	function themify_get_author_link() {
		$output = '<span class="author vcard" itemprop="author" itemscope itemtype="http://schema.org/Person"><a class="url fn n" href="' . esc_url( get_author_posts_url( get_the_author_meta( 'ID' ) ) ) . '" rel="author" itemprop="url"><span itemprop="name">' . get_the_author() . '</span></a></span>';
		return $output;
	}
}

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

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

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

/**
 * Returns logo image.
 * Available filters:
 * 'themify_'.$location.'_logo_tag': filter the HTML tag used to wrap the text or image.
 * 'themify_logo_home_url': filter the home URL linked.
 * 'themify_'.$location.'_logo_html': filter the final HTML output to page.
 * @param string $location Logo location used as key to get theme setting values
 * @param string $cssid ID attribute for the logo tag.
 * @return string logo markup
 */
function themify_logo_image( $location = 'site_logo', $cssid = 'site-logo' ) {
	global $themify_customizer;

	$logo_tag = apply_filters( 'themify_' . $location . '_logo_tag', 'div' );
	$logo_mod = get_theme_mod( $cssid . '_image' );
	$logo_is_image = themify_get( 'setting-' . $location ) == 'image' && themify_check( 'setting-' . $location . '_image_value' );

	$html = '<' . $logo_tag . ' id="' . esc_attr( $cssid ) . '">';

	if ( $logo_is_image && empty( $logo_mod ) ) {
		$html .= '<a href="' . esc_url( apply_filters( 'themify_logo_home_url', home_url() ) ) . '" title="' . esc_attr( get_bloginfo( 'name' ) ) . '">';
		$type = $logo_is_image ? 'image' : 'text';
		$site_name = get_bloginfo( 'name' );
		if ( 'image' == $type ) {
			$html .= themify_get_image( 'ignore=true&src=' . themify_get( 'setting-' . $location . '_image_value' ) . '&w=' . themify_get( 'setting-' . $location . '_width' ) . '&h=' . themify_get( 'setting-' . $location . '_height' ) . '&alt=' . urlencode( get_bloginfo( 'name' ) ) );
			$html .= isset( $themify_customizer ) ? '<span style="display: none;">' . esc_html( $site_name ) . '</span>' : '';
		} else {
			$html .= isset( $themify_customizer ) ? '<span>' . esc_html( $site_name ) . '</span>' : esc_html( $site_name );
		}
		$html .= '</a>';
	} else {
		$type = 'customizer';
		$html .= $themify_customizer->site_logo( $cssid );
	}

	$html .= '</' . $logo_tag . '>';

	return apply_filters( 'themify_' . $location . '_logo_html', $html, $location, $logo_tag, $type );
}

/**
 * Returns site description markup.
 *
 * @since 1.3.2
 *
 * @return string
 */
function themify_site_description() {

	if ( $description = get_bloginfo( 'description' ) ) {
		global $themify_customizer;
		$html = '<div id="site-description" class="site-description">';
			$html .= $themify_customizer->site_description( $description );
		$html .=  '</div>';
	} else {
		$html = '';
	}

	/**
	 * Filters description markup before it's returned.
	 *
	 * @param string $html
	 */
	return apply_filters( 'themify_site_description', $html );
}

/**
 * Registers footer sidebars.
 *
 * @param array  $columns Sets of sidebars that can be created.
 * @param array  $widget_attr General markup for widgets.
 * @param string $widgets_key
 * @param string $default_set
 */
function themify_register_grouped_widgets($columns = array(), $widget_attr = array(), $widgets_key = 'setting-footer_widgets', $default_set = 'footerwidget-3col'){
	$data = themify_get_data();
	if(empty($columns)){
		$columns = array(
			'footerwidget-4col' => 4,
			'footerwidget-3col'	=> 3,
			'footerwidget-2col' => 2,
			'footerwidget-1col' => 1,
			'none'			 	=> 0
		);
	}
	$option = (!isset($data[$widgets_key]) || '' == $data[$widgets_key])? $default_set: $data[$widgets_key];
	if(empty($widget_attr)){
		$widget_attr = array(
			'sidebar_name' => __('Footer Widget', 'themify'),
			'sidebar_id' => 'footer-widget',
			'before_widget' => '<div id="%1$s" class="widget %2$s">',
			'after_widget' => '</div>',
			'before_title' => '<h4 class="widgettitle">',
			'after_title' => '</h4>',
		);
	}
	if ( ! isset( $columns[$option] ) ) {
		$columns[$option] = 0;
	}
	for($x = 1; $x <= $columns[$option]; $x++){
		register_sidebar(array(
			'name' => $widget_attr['sidebar_name'] . ' ' .$x,
			'id' => $widget_attr['sidebar_id'].'-'.$x,
			'before_widget' => $widget_attr['before_widget'],
			'after_widget' => $widget_attr['after_widget'],
			'before_title' => $widget_attr['before_title'],
			'after_title' => $widget_attr['after_title'],
		));
	}
}

/**
 * Adds itemprop='image' microdata to avatar called by author box
 * @param string $avatar The original markup for avatar
 * @return string Modified markup with microdata
 */
function themify_authorbox_microdata($avatar){
	return str_replace("class='avatar", "itemprop='image' class='avatar", $avatar);
}

/**
 * Outputs footer text
 *
 * @param string $area Footer text area
 * @param bool   $wrap Class to add to block
 * @param string $block The block of text this is
 * @param string $date_fmt Date format for year shown
 * @param bool   $echo Whether to echo or return the markup
 *
 * @return mixed|string|void
 * @internal param string $key The footer text to show. Default: left
 */
function themify_the_footer_text($area = 'left', $wrap = true, $block = '', $date_fmt = 'Y', $echo = true) {
	// Prepare variables
	if('' == $block){
		if('left' == $area){
			$block = 'one';
		} elseif('right' == $area){
			$block = 'two';
		}
	}
	$text_block = '';
	if('one' == $block) {
		$text_block = '&copy; <a href="' . esc_url( home_url() ) . '">' . esc_html( get_bloginfo( 'name' ) ) . '</a> ' . date( $date_fmt );
	} elseif('two' == $block) {
		$text_block = __( 'Powered by <a href="http://wordpress.org">WordPress</a> &bull; <a href="http://themify.me">Themify WordPress Themes</a>', 'themify' );
	}
	$key = 'setting-footer_text_'.$area;
	
	// Get definitive text to display, parse through WPML if available
	if ( '' != themify_get($key) ) {
		$data = themify_get_data();
		if ( function_exists( 'icl_t' ) ) {
			$text = icl_t('Themify', $key, $data[$key]);
		} else {
			$text = $data[$key];
		}
	} else {
		$text = $text_block;
	}
	// Start markup
	$html = apply_filters('themify_footer_text'.$block, $text);
	if ( true === is_bool( $wrap ) && true == $wrap ) {
		$html = '<div class="' . esc_attr( $block ) . '">' . $html . '</div>';
	} elseif( ! is_bool( $wrap ) ) {
		$html = '<div class="' . esc_attr( $wrap ) . '">' . $html . '</div>';
	}
	$html = apply_filters('themify_the_footer_text_'.$area, $html);
	if ( $echo ) echo $html;
	return $html;
}

/**
 * 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 . '/js/google-fonts.json';
	} else {
		$fonts = THEMIFY_DIR . '/js/google-fonts-recommended.json';
	}

	/**
	 * Filters the file loaded.
	 * Useful for recovery in case user loaded Full List and their server can't manage it.
	 * Can be used as:
	 *
	 * function custom_themify_load_recommended_fonts( $fonts ) {
	 *      return THEMIFY_DIR . '/js/google-fonts-recommended.json';
	 * }
	 * add_filter( 'themify_google_fonts_file', 'custom_themify_load_recommended_fonts' );
	 *
	 * @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();
	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));
	$subsets_count = count($subsets);
	if ( isset( $GLOBALS['google_fonts_json_file_cache'] ) && '' != $GLOBALS['google_fonts_json_file_cache'] ) {
		$response = $GLOBALS['google_fonts_json_file_cache'];
	} else {
		if ( ! function_exists( 'WP_Filesystem' ) ) {
			require_once ABSPATH . 'wp-admin/includes/file.php';
		}
		WP_Filesystem();
		global $wp_filesystem;
		$response = $wp_filesystem->get_contents( $fonts_file_path );
		if ( false === $response ) {
			$response = call_user_func( 'file_get' . '_contents', $fonts_file_path );
			if ( false === $response ) {
				ob_start();
				include_once $fonts_file_path;
				$response = ob_get_contents();
				ob_end_clean();
			}
		}
		$GLOBALS['google_fonts_json_file_cache'] = $response;
	}
	$fonts = array();
	if( $response !== false ) {
		if ( isset( $GLOBALS['google_fonts_json_decode_cache'] ) && '' != $GLOBALS['google_fonts_json_decode_cache'] ) {
			$results = $GLOBALS['google_fonts_json_decode_cache'];
		} else {
			$results = json_decode( $response );
			$GLOBALS['google_fonts_json_decode_cache'] = $results;
		}
		foreach ( $results->items 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->family,
						'variant' => $font->variants[0]
					);
				}
			} else {
				$fonts[] = array(
					'family' => $font->family,
					'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;
	}
}

function themify_editor_gfonts_config_view() {
	return $GLOBALS['themify_editor_gfonts']->config_view();
}

if(!function_exists('themify_is_query_page')){
	/**
	 * Checks if current page is a query category page
	 * @return bool
	 * @since 1.3.8
	 */
	function themify_is_query_page(){
		global $themify;
		if(isset($themify->query_category) && '' != $themify->query_category){
			return true;
		} else {
			return false;
		}
	}
}

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 = '.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);
		
		// Include Magnific style and script
		wp_enqueue_style ( 'magnific', THEMIFY_URI . '/css/lightbox.css', array(), THEMIFY_VERSION );
		wp_enqueue_script( 'magnific', THEMIFY_URI . '/js/lightbox.js', array('jquery'), THEMIFY_VERSION, true );
		
		// 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_get_featured_image_link')){
	/**
	 * Returns escaped URL for featured image link
	 * @return string
	 * @since 1.3.5
	 */
	function themify_get_featured_image_link($args = array()) {
		$defaults = array (
			'no_permalink' => false // if there is no lightbox link, don't return a link
		);
		$args = wp_parse_args( $args, $defaults );
		extract( $args, EXTR_SKIP );

		if ( themify_get('external_link') != '') {
			$link = esc_url(themify_get('external_link'));
		} elseif ( themify_get('lightbox_link') != '') {
			$link = esc_url(themify_get('lightbox_link'));
			if(themify_check('iframe_url')) {
				$link = themify_get_lightbox_iframe_link( $link );
			}
			$link = $link . '" class="lightbox';
		} elseif(themify_check('link_url')) {
			$link = themify_get('link_url');
		} elseif($args['no_permalink']) {
			$link = '';
		} else {
			$link = get_permalink();
			if(current_theme_supports('themify-post-in-lightbox')){
				if( !is_single() && '' != themify_get('setting-open_inline') ){
					$link = add_query_arg( array( 'post_in_lightbox' => 1 ), get_permalink() ) . '" class="themify-lightbox';
				}
				if( themify_is_query_page() ){
					if( 'no' == themify_get('post_in_lightbox') ){
						$link = get_permalink();
					} else {
						$link = add_query_arg( array( 'post_in_lightbox' => 1 ), get_permalink() ) . '" class="themify-lightbox';
					}
				}
			}
		}
		return apply_filters('themify_get_featured_image_link', $link);
	}
}

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' ) {

		$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'),
						'before' => '',
						'after' => '',
					),
					// Image Height
					array(
						'name' => $prefix . '_height',
						'label' => __('height', 'themify'),
						'type' => 'textbox',
						'meta' => array( 'size' => 'small'),
						'before' => '',
						'after' => '',
					),
				),
				'description' => __('Enter height = 0 to disable vertical cropping with image script enabled',
					'themify'),
				'before' => '',
				'after' => '',
				'separator' => ''
			)
		);

		$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_zoom_icon' ) ) {
	/**
	 * Returns zoom icon markup for lightboxed featured image
	 *
	 * @param bool $echo
	 *
	 * @return mixed|void
	 */
	function themify_zoom_icon( $echo = true ) {
		if ( $echo ) {
			echo apply_filters( 'themify_zoom_icon', themify_check( 'lightbox_icon' ) ? '<span class="zoom"></span>' : '' );
		}
		return apply_filters( 'themify_zoom_icon', themify_check( 'lightbox_icon' ) ? '<span class="zoom"></span>' : '' );
	}
}

if ( ! function_exists('themify_theme_feed_link') ) {
	/**
	 * Returns the feed link, usually RSS
	 * @param string $setting
	 * @param bool $echo
	 * @return mixed|void
	 * @since 1.5.2
	 */
	function themify_theme_feed_link( $setting = 'setting-custom_feed_url', $echo = true ){
		$out = '';
		if(themify_get( $setting ) != ''){
			$out .= themify_get( $setting );
		} else {
			$out .= get_bloginfo('rss2_url');
		}
		$out = apply_filters('themify_theme_feed_link', $out);
		if( $echo ) {
			echo esc_url( $out );
		}
		return esc_url( $out );
	}
}

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;
		$themify->is_shortcode_template = true;
		ob_start();
		foreach ( $posts as $post ) {
			setup_postdata( $post );
			get_template_part( $slug, $name );
		}
		$html = ob_get_contents();
		ob_end_clean();
		wp_reset_postdata();
		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_upload_mime_types')) {
	/**
	 * Adds .svg and .svgz to list of mime file types supported by WordPress
	 * @param array $existing_mime_types WordPress supported mime types
	 * @return array Array extended with svg/svgz support
	 * @since 1.3.9
	 */
	function themify_upload_mime_types( $existing_mime_types = array() ) {
		$existing_mime_types['svg'] = 'image/svg+xml';
		$existing_mime_types['svgz'] = 'image/svg+xml';
		return $existing_mime_types;
	}
}

if( ! function_exists('themify_parse_video_embed_vars') ) {
	/**
	 * Add wmode transparent and post-video container for responsive 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 ) {
			$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);
				return $html;
			} else {
				if( 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 = 'http://www.youtube.com/embed' . $parsed['path'] . '?wmode=transparent&fs=1' . $ytq;
						} else {
							$parsed = parse_url($url);
							parse_str($parsed['query'], $query);

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

							if ( isset( $query['v'] ) && '' != $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);
						}

						return preg_replace('/src="(.*)" (frameborder)/i', 'src="'.esc_url( $url ).'" $2', $html);
					} else {
						$search = array('?fs=1', '?fs=0');
						$replace = array('?fs=1&wmode=transparent', '?fs=0&wmode=transparent');
						$html = str_replace($search, $replace, $html);
						return $html;
					}
				} else {
					return $html;
				}
			}
		} else {
			return '<div class="post-embed">' . $html . '</div>';
		}
	}
}

if ( ! function_exists( 'themify_wp_video_shortcode' ) ) {
	/**
	 * Removes height in video to replicate this fix https://github.com/markjaquith/WordPress/commit/3d8e31fb82cc1485176c89d27b736bcd9d2444ba#diff-297bf46a572d5f80513d3fed476cd2a2R1862
	 *
	 * @param $out
	 * @param $atts
	 *
	 * @return mixed
	 */
	function themify_wp_video_shortcode( $out, $atts ) {
		$width_rule = '';
		if ( ! empty( $atts['width'] ) ) {
			$width_rule = sprintf( 'width: %dpx; ', $atts['width'] );
		}
		return preg_replace( '/<div style="(.*?)" class="wp-video">/i', '<div style="' . esc_attr( $width_rule ) . '" class="wp-video">', $out );
	}
}

/////////////////////// Woocommerce Routines //////////////////////////

if(!function_exists('themify_before_shop_content')) {
	/**
	 * Add initial portion of wrapper
	 * @since 1.4.6
	 */
	function themify_before_shop_content() { ?>
		<!-- layout -->
		<div id="layout" class="pagewidth clearfix">

			<?php themify_content_before(); // Hook ?>

			<!-- content -->
			<div id="content" class="<?php echo (is_product() || is_shop()) ? 'list-post':''; ?>">

				<?php
				if(!themify_check('setting-hide_shop_breadcrumbs')) {
					themify_breadcrumb_before();
					woocommerce_breadcrumb();
					themify_breadcrumb_after();
				}
				themify_content_start(); // Hook
	}
}

if(!function_exists('themify_after_shop_content')) {
	/**
	 * Add end portion of wrapper
	 * @since 1.4.6
	 */
	function themify_after_shop_content() {
				if (is_search() && is_post_type_archive() ) {
					add_filter( 'woo_pagination_args', 'woocommerceframework_add_search_fragment', 10 );
				}
				themify_content_end(); // Hook ?>

			</div>
			<!-- /#content -->

			<?php themify_content_after() // Hook ?>

		</div><!-- /#layout -->
	<?php
	}
}

if(!function_exists('themify_wc_compatibility_sidebar')) {
	/**
	 * Add sidebar if it's enabled in theme settings
	 * @since 1.4.6
	 */
	function themify_wc_compatibility_sidebar(){

		// Check if WC is active and this is a WC-managed page
		if( !themify_is_woocommerce_active() || !function_exists('is_woocommerce') || !is_woocommerce() ) return;

		$sidebar_layout = 'sidebar1';

		if( is_product() ) {
			if( themify_check('setting-single_product_layout') ) {
				$sidebar_layout = themify_get('setting-single_product_layout');
			} elseif( themify_check('setting-default_page_post_layout') ) {
				$sidebar_layout = themify_get('setting-default_page_post_layout');
			}
		} else {
			global $wp_query;
			if ( isset( $wp_query->queried_object ) && isset( $wp_query->queried_object->ID ) ) {
				$sidebar_layout = get_post_meta( $wp_query->queried_object->ID, 'page_layout', true );
			} elseif( themify_check('setting-shop_layout') ) {
				$sidebar_layout = themify_get('setting-shop_layout');
			} elseif( themify_check('setting-default_layout') ) {
				$sidebar_layout = themify_get('setting-default_layout');
			}
		}

		themify_ecommerce_sidebar_before(); // Hook

		if ( $sidebar_layout != 'sidebar-none' ) {
			get_sidebar();
		}

		themify_ecommerce_sidebar_after(); // Hook
	}
}

if ( ! function_exists( 'themify_wc_body_class' ) ) {
	/**
	 * Set correct layout class in body for Shop page
	 *
	 * @since 1.9.4
	 *
	 * @param array $classes
	 * @return array
	 */
	function themify_wc_body_class( $classes = array() ) {
		// Check if WC is active and this is a WC-managed page
		if( !themify_is_woocommerce_active() || !function_exists('is_woocommerce') || !is_woocommerce() ) return $classes;
		$sidebar_layout = '';
		if( is_product() ) {
			if( themify_check('setting-single_product_layout') ) {
				$sidebar_layout = themify_get('setting-single_product_layout');
			} elseif( themify_check('setting-default_page_post_layout') ) {
				$sidebar_layout = themify_get('setting-default_page_post_layout');
			}
		} else {
			global $wp_query;
			if ( isset( $wp_query->queried_object ) && isset( $wp_query->queried_object->ID ) ) {
				$sidebar_layout = get_post_meta( $wp_query->queried_object->ID, 'page_layout', true );
			} elseif( themify_check('setting-shop_layout') ) {
				$sidebar_layout = themify_get('setting-shop_layout');
			} elseif( themify_check('setting-default_layout') ) {
				$sidebar_layout = themify_get('setting-default_layout');
			}
		}
		if ( '' != $sidebar_layout ) {
			$key = 0;
			foreach ( $classes as $class ) {
				if ( false !== stripos( $class, 'sidebar' ) ) {
					unset( $classes[$key] );
				}
				$key++;
			}
			$classes[] = $sidebar_layout;
		}

		return $classes;
	}
}

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;
		}
		return in_array( $plugin, apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) || $network_active;
	}
}

/////////////////////// End Woocommerce Routines //////////////////////////

if ( ! function_exists( 'themify_get_term_description' ) ) {
	/**
	 * Returns term description
	 * @param string $taxonomy The taxonomy for the term that will be described.
	 * @return string
	 * @since 1.5.6
	 */
	function themify_get_term_description( $taxonomy = 'category' ) {
		$term_description = term_description( 0, $taxonomy );
		if ( ! empty( $term_description ) ) {
			$output = '<div class="category-description">' . $term_description . '</div>';
		} else {
			$output = '';
		}
		return apply_filters( 'themify_get_term_description', $output );
	}
}

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() {
		$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
			);
		}
		return apply_filters('themify_get_google_web_fonts_list', $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_generic_slider_controls' ) ) {
	/**
	 * Creates a general module to setup slider parameters
	 * @param $prefix
	 * @return string
	 */
	function themify_generic_slider_controls( $prefix ) {
		/**
		 * Associative array containing theme settings
		 * @var array
		 */
		$data = themify_get_data();

		$auto_options = apply_filters( 'themify_generic_slider_auto',
			array(
				__('4 Secs (default)', 'themify') => 4000,
				__('Off', 'themify') => 'off',
				__('1 Sec', 'themify') => 1000,
				__('2 Secs', 'themify') => 2000,
				__('3 Secs', 'themify') => 3000,
				__('4 Secs', 'themify') => 4000,
				__('5 Secs', 'themify') => 5000,
				__('6 Secs', 'themify') => 6000,
				__('7 Secs', 'themify') => 7000,
				__('8 Secs', 'themify') => 8000,
				__('9 Secs', 'themify') => 9000,
				__('10 Secs', 'themify')=> 10000
			)
		);
		$speed_options = apply_filters( 'themify_generic_slider_speed',
			array(
				__('Fast', 'themify') => 500,
				__('Normal', 'themify') => 1000,
				__('Slow', 'themify') => 1500
			)
		);
		$effect_options = array(
			array('name' => __('Slide', 'themify'), 'value' => 'slide'),
			array('name' => __('Fade', 'themify'), 'value' =>'fade')
		);

		/**
		 * Auto Play
		 */
		$output = '<p>
						<span class="label">' . __('Auto Play', 'themify') . '</span>
						<select name="' . esc_attr( $prefix ) . 'autoplay">';
						foreach ( $auto_options as $name => $val ) {
							$output .= '<option value="' . esc_attr( $val ) . '" ' . selected( themify_get( $prefix . 'autoplay' ), themify_check( $prefix . 'autoplay' ) ? $val : 4000, false ) . '>' . esc_html( $name ) . '</option>';
						}
		$output .= '	</select>
					</p>';

		/**
		 * Effect
		 */
		$output .= '<p>
						<span class="label">' . __( 'Effect', 'themify' ) . '</span>
						<select name="' . esc_attr( $prefix ) . 'effect">' .
						themify_options_module( $effect_options, $prefix . 'effect' ) . '
						</select>
					</p>';

		/**
		 * Transition Speed
		 */
		$output .= '<p>
						<span class="label">' . __( 'Transition Speed', 'themify' ) . '</span>
						<select name="' . esc_attr( $prefix ) . 'transition_speed">';
						foreach ( $speed_options as $name => $val ) {
							$output .= '<option value="' . esc_attr( $val ) . '" ' . selected( themify_get( $prefix . 'transition_speed' ), themify_check( $prefix . 'transition_speed' ) ? $val : 500, false ) . '>' . esc_html( $name ) . '</option>';
						}
		$output .= '	</select>
					</p>';

		return apply_filters( 'themify_generic_slider_controls', $output );
	}
}

if ( function_exists( 'icl_register_string' ) ) {
	/**
	 * Make dynamic strings in Themify theme available for translation with WPML String Translation
	 * @param $context
	 * @param $name
	 * @param $value
	 * @since 1.5.3
	 */
	function themify_register_wpml_strings( $context, $name, $value ) {
	    $value = maybe_unserialize( $value );
	    if ( is_array( $value ) ) {
	        foreach ( $value as $k => $v ) {
				themify_register_wpml_strings( $context, $k, $v );
			}
	    } else {
			$translatable = array(
				'setting-footer_text_left',
				'setting-footer_text_right',
				'setting-homepage_welcome',
				'setting-action_text',
			);
			foreach ( array('one','two','three','four','five','six','seven','eight','nine','ten') as $option ) {
				$translatable[] = 'setting-slider_images_' . $option . '_title';
				$translatable[] = 'setting-header_slider_images_' . $option . '_title';
				$translatable[] = 'setting-footer_slider_images_' . $option . '_title';
			}
			if ( stripos( $name, 'title_themify-link' ) || in_array( $name, $translatable ) ) {
				icl_register_string( $context, $name, $value );
			}
	    }
	}
	themify_register_wpml_strings( 'Themify', 'Themify Option', themify_get_data() );
}

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

if ( ! function_exists( 'themify_js_window_resize' ) ) {
	/**
	 * Trigger window resize event on JS
	 * @since 1.6.8
	 */
	function themify_js_window_resize() {
		echo "\n<script>\n\tjQuery(window).load(function(){ jQuery(window).resize(); });\n</script>\n";
	}
}

/**
 * Display the Hook Content admin screen
 *
 * @since 1.6.9
 */
function themify_hooks_config_view() {
	return $GLOBALS['themify_hooks']->config_view();
}

if ( ! function_exists( 'themify_wpml_pagination_setup' ) && class_exists( 'SitePress' ) ) {
	/**
	 * Checks if WPML is active and if so, sets the correct page number.
	 * @param $wp_query
	 * @since 1.7.3
	 */
	function themify_wpml_pagination_setup( $wp_query ) {
		$paged = 1;
		if ( get_query_var( 'paged' ) ) {
			$paged = get_query_var( 'paged' );
		} elseif( get_query_var( 'page' ) ) {
			$paged = get_query_var( 'page' );
		}
		set_query_var( 'paged', $paged );
	}
}

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

/**
 * Load demo importer classname and it's dependencies.
 *
 * @since 1.7.6
 */
function themify_import_sample_content_setup() {

	define( 'WP_LOAD_IMPORTERS', true );

	require_once ABSPATH . 'wp-admin/includes/taxonomy.php';
	require_once ABSPATH . 'wp-admin/includes/post.php';
	require_once ABSPATH . 'wp-admin/includes/image.php';
	include THEMIFY_DIR . '/demo-import/demo-importer.php';

	class Themify_Import extends WP_Import {

		var $placeholder_image = null;

		/**
		 * Replace attachments with the placeholder image provided by the theme.
		 *
		 * @return int $post_id
		 * @since 1.7.6
		 */
		public function process_attachment( $post, $url ) {
			if ( ! $this->fetch_attachments )
			return new WP_Error( 'attachment_processing_error',
				__( 'Fetching attachments is not enabled', 'themify' ) );

			if( $this->placeholder_image == null ) {
				if ( ! function_exists( 'WP_Filesystem' ) ) {
					require_once ABSPATH . 'wp-admin/includes/file.php';
				}
				WP_Filesystem();
				global $wp_filesystem;
				$upload = wp_upload_bits( $post['post_name'] . '.jpg', null, $wp_filesystem->get_contents( get_template_directory() . '/sample/image-placeholder.jpg' ) );

				if ( $info = wp_check_filetype( $upload['file'] ) )
					$post['post_mime_type'] = $info['type'];
				else
					return new WP_Error( 'attachment_processing_error', __( 'Invalid file type', 'themify' ) );

				$post['guid'] = $upload['url'];
				$post_id = wp_insert_attachment( $post, $upload['file'] );
				wp_update_attachment_metadata( $post_id, wp_generate_attachment_metadata( $post_id, $upload['file'] ) );

				$this->placeholder_image = $post_id;
			}

			return $this->placeholder_image;
		}

		function process_menu_item( $item ) {
			// skip draft, orphaned menu items
			if ( 'draft' == $item['status'] )
				return;

			$menu_slug = false;
			if ( isset($item['terms']) ) {
				// loop through terms, assume first nav_menu term is correct menu
				foreach ( $item['terms'] as $term ) {
					if ( 'nav_menu' == $term['domain'] ) {
						$menu_slug = $term['slug'];
						break;
					}
				}
			}

			// no nav_menu term associated with this menu item
			if ( ! $menu_slug ) {
				_e( 'Menu item skipped due to missing menu slug', 'themify' );
				echo '<br />';
				return;
			}

			$menu_id = term_exists( $menu_slug, 'nav_menu' );
			if ( ! $menu_id ) {
				printf( __( 'Menu item skipped due to invalid menu slug: %s', 'themify' ), esc_html( $menu_slug ) );
				echo '<br />';
				return;
			} else {
				$menu_id = is_array( $menu_id ) ? $menu_id['term_id'] : $menu_id;
			}

			foreach ( $item['postmeta'] as $meta )
				$$meta['key'] = $meta['value'];

			if ( 'taxonomy' == $_menu_item_type && isset( $this->processed_terms[intval($_menu_item_object_id)] ) ) {
				$_menu_item_object_id = $this->processed_terms[intval($_menu_item_object_id)];
			} else if ( 'post_type' == $_menu_item_type && isset( $this->processed_posts[intval($_menu_item_object_id)] ) ) {
				$_menu_item_object_id = $this->processed_posts[intval($_menu_item_object_id)];
			} else if ( 'custom' != $_menu_item_type ) {
				// associated object is missing or not imported yet, we'll retry later
				$this->missing_menu_items[] = $item;
				return;
			}

			if ( isset( $this->processed_menu_items[intval($_menu_item_menu_item_parent)] ) ) {
				$_menu_item_menu_item_parent = $this->processed_menu_items[intval($_menu_item_menu_item_parent)];
			} else if ( $_menu_item_menu_item_parent ) {
				$this->menu_item_orphans[intval($item['post_id'])] = (int) $_menu_item_menu_item_parent;
				$_menu_item_menu_item_parent = 0;
			}

			// wp_update_nav_menu_item expects CSS classes as a space separated string
			$_menu_item_classes = maybe_unserialize( $_menu_item_classes );
			if ( is_array( $_menu_item_classes ) )
				$_menu_item_classes = implode( ' ', $_menu_item_classes );

			$args = array(
				'menu-item-object-id' => $_menu_item_object_id,
				'menu-item-object' => $_menu_item_object,
				'menu-item-parent-id' => $_menu_item_menu_item_parent,
				'menu-item-position' => intval( $item['menu_order'] ),
				'menu-item-type' => $_menu_item_type,
				'menu-item-title' => $item['post_title'],
				'menu-item-url' => $_menu_item_url,
				'menu-item-description' => $item['post_content'],
				'menu-item-attr-title' => $item['post_excerpt'],
				'menu-item-target' => $_menu_item_target,
				'menu-item-classes' => $_menu_item_classes,
				'menu-item-xfn' => $_menu_item_xfn,
				'menu-item-status' => $item['status']
			);

			$id = wp_update_nav_menu_item( $menu_id, 0, $args );
			if ( $id && ! is_wp_error( $id ) )
				$this->processed_menu_items[intval($item['post_id'])] = (int) $id;

			/** add menu icon */
			if( isset( $_menu_item_icon ) ) {
				update_post_meta( $id, '_menu_item_icon', $_menu_item_icon );
			}
		}

		/**
		 * Replace the original post author with "themify" user.
		 *
		 * @since 1.7.6
		 */
		public function __get_author_mapping() {
			$user_id = wp_create_user( 'themify', wp_generate_password() );
			foreach ( $this->authors as $i => $old_login ) {
				$santized_old_login = sanitize_user( $old_login, true );
				$old_id = isset( $this->authors[$old_login]['author_id'] ) ? intval($this->authors[$old_login]['author_id']) : false;
				$this->processed_authors[$old_id] = $user_id;
				$this->author_mapping[$santized_old_login] = $user_id;
			}
		}
	}
}

/**
 * Performs importing the sample contents to replicate the theme's demo site
 *
 * @since 1.7.6
 */
function themify_do_import_sample_contents() {
	do_action( 'themify_before_demo_import' );

	themify_import_sample_content_setup();
	$resource_file = get_template_directory().'/sample/sample-content.gz';
	$cache_dir = themify_get_cache_dir();
	$extract_file = $cache_dir['path'] . 'sample-content.xml';

	themify_uncompress_gzip( $resource_file, $extract_file );
	$parse_file = file_exists( $extract_file ) ? $extract_file : $resource_file;
	
	$import = new Themify_Import();
	$import->fetch_attachments = true;
	$import->import( $parse_file );

	// remove extract file
	if ( file_exists( $extract_file ) ) {
		unlink( $extract_file );
	}
	
	if( file_exists( THEME_DIR . '/sample/demo-settings.php' ) ) {
		require_once( THEME_DIR . '/sample/demo-settings.php' );
	}

	do_action( 'themify_after_demo_import' );
}

/**
 * Undo demo setup and reverts back to state before importing the sample contents.
 * Does not remove post/pages that have been modified by the user.
 *
 * @since 1.7.6
 */
function themify_undo_import_sample_content() {
	do_action( 'themify_before_demo_erase' );
	
	themify_import_sample_content_setup();
	$import = new Themify_Import();
	$data = $import->parse( get_template_directory().'/sample/sample-content.gz' );
	//$data = $import->parse( $parse_file );

	foreach( $data['categories'] as $cat ) {
		$term_id = term_exists( $cat['category_nicename'], 'category' );
		if( $term_id ) {
			if ( is_array($term_id) ) $term_id = $term_id['term_id'];
			if ( isset($cat['term_id']) ) {
				wp_delete_category( $term_id );
			}
		}
	}

	foreach( $data['tags'] as $tag ) {
		$term_id = term_exists( $tag['tag_slug'], 'post_tag' );
		if( $term_id ) {
			if ( is_array($term_id) ) $term_id = $term_id['term_id'];
			if ( isset($tag['term_id']) ) {
				wp_delete_term( $term_id, 'post_tag' );
			}
		}
	}

	foreach( $data['terms'] as $term ) {
		$term_id = term_exists( $term['slug'], $term['term_taxonomy'] );
		if ( $term_id ) {
			if ( is_array($term_id) ) $term_id = $term_id['term_id'];
			if ( isset($term['term_id']) ) {
				wp_delete_term( $term_id, $term['term_taxonomy'] );
			}
		}
	}

	foreach( $data['posts'] as $post ) {
		$post_exists = post_exists( $post['post_title'], '', $post['post_date'] );
		if( $post_exists && get_post_type( $post_exists ) == $post['post_type'] ) {
			/* check if the post has not been modified since it was created */
			if( $post['post_date'] == get_post_field( 'post_modified', $post_exists ) ) {
				wp_delete_post( $post_exists, true ); // true: bypass trash
			}
		}
	}

	do_action( 'themify_after_demo_erase' );
}

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

/**
 * Set a default title for the front page
 *
 * @return string
 * @since 1.7.6
 */
function themify_filter_wp_title( $title, $sep ) {
	global $aioseop_options;

	if( empty( $title ) && ( is_home() || is_front_page() ) ) {
		if( class_exists( 'All_in_One_SEO_Pack' ) && '' != $aioseop_options['aiosp_home_title'] ) {
			return $aioseop_options['aiosp_home_title'];
		}
		return get_bloginfo( 'name' );
	}

	return str_replace( $sep , '', $title );
}

/**
 * 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 ) {
	$uri_segments = parse_url( $uri );
	$query_args = isset( $uri_segments['query'] ) ? $uri_segments['query'] : '';
	wp_parse_str( $query_args, $uri_args );
	$args = wp_parse_args( $uri_args, array( 'iframe' => 'true', 'width' => '100%', 'height' => '100%' ) );

	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'] ) ) {
		mkdir( $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_enqueue_dropdown_script' ) ) {
	/**
	 * Load Touch Dropdown script for touch devices
	 *
	 * @since 1.9.1
	 */
	function themify_enqueue_dropdown_script() {
		if( themify_is_touch() ) {
			wp_enqueue_script( 'themify-dropdown', THEMIFY_URI . '/js/themify.dropdown.js', array( 'jquery' ), THEMIFY_VERSION, true );
		}
	}
}

if ( ! function_exists( 'themify_custom_menu_nav' ) ) {
	/**
	 * Sets custom menu selected in page custom panel as navigation, otherwise sets the default.
	 *
	 * @since 1.9.5
	 *
	 * @param array $args Settings to configure navigation menu
	 */
	function themify_custom_menu_nav( $args = array() ) {
		// Get page ID reliably
		$queried_object = get_queried_object();
		$page_id = isset( $queried_object->ID ) ? $queried_object->ID : 0;

		// Compile menu arguments
		$args = wp_parse_args( $args, array(
			'theme_location' => 'main-nav',
			'fallback_cb' => 'themify_default_main_nav',
			'container'   => '',
			'menu_id'     => 'main-nav',
			'menu_class'  => 'main-nav'
		));

		// See if the page has a menu assigned
		$custom_menu = get_post_meta( $page_id, 'custom_menu', true );
		if ( ! empty( $custom_menu ) ) {
			$args['menu'] = $custom_menu;
		}

		// Render the menu
		wp_nav_menu( $args );
	}
}

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>document.documentElement.className += " js";</script>';
}

/**
 * Filters the title. Removes the default separator.
 *
 * @since 2.0.2
 *
 * @param string $title Page title to be output.
 * @param string $sep Separator to search and replace.
 *
 * @return mixed
 */
function themify_wp_title( $title, $sep ) {
	return str_replace( $sep, '', $title );
}

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

/**
 * Checks the area design setting and returns 'none' or a design option.
 *
 * @since 2.1.3
 *
 * @param string $key Main prefix for setting and field.
 * @param array $args
 *
 * @return mixed
 */
function themify_area_design( $key = 'header', $args = array() ) {
	$args = wp_parse_args( $args, array(
		'setting' => 'setting-' . $key . '_design',
		'field'   => $key . '_design',
		'default' => $key . '-horizontal',
		'values'  => array( 'header-horizontal', 'header-block', 'none' )
	) );
	
	if ( is_singular() ) {
		$single = themify_get( $args['field'] );
		if ( in_array( $single, $args['values'] ) ) {
			$design = $single;
		}
	}

	if ( empty( $design ) || 'default' == $design ) {
		$design = themify_check( $args['setting'] ) ? themify_get( $args['setting'] ) : $args['default'];
	}

	return $design;
}

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

		// Include html5.js for IE
		add_action( 'wp_head', 'themify_custom_ie_html5' );
	}
}

if ( ! function_exists( 'themify_custom_ie_html5' ) ) {
	/**
	 * Load html5.js file from Google CDN
	 *
	 * @since 2.1.5
	 */
	function themify_custom_ie_html5() {
		echo '<!-- html5.js -->
		<!--[if lt IE 9]>
		<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
		<![endif]-->';
	}
}

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

/**
 * Add extra protocols like skype: to list of allowed protocols.
 * 
 * @since 2.1.8
 *
 * @param array $protocols List of protocols allowed by default by WordPress.
 *
 * @return array $protocols Updated list including extra protocols added.
 */
function themify_allow_extra_protocols( $protocols ){
	$protocols[] = 'skype';
	return $protocols;
}

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