<?php
/***************************************************************************
 *  					Theme Functions
 * 	----------------------------------------------------------------------
 * 						DO NOT EDIT THIS FILE
 *	----------------------------------------------------------------------
 *
 *  					Copyright (C) Themify
 * 						http://themify.me
 *
 *  To add custom PHP functions to the theme, create a child theme (https://themify.me/docs/child-theme) and add it to the child theme functions.php file.
 *  They will be added to the theme automatically.
 *
 ***************************************************************************/

/////// Actions ////////
// Init post, page and additional post types if they exist
add_action( 'after_setup_theme', 'themify_theme_init_types' );

if (!defined('DOING_AJAX')) {
    // Enqueue scripts and styles required by theme
    add_action( 'wp_enqueue_scripts', 'themify_theme_enqueue_scripts', 11 );
    add_filter('themify_main_script_vars','themify_add_minify_vars',10,1);
    add_filter( 'themify_google_fonts', 'themify_theme_google_fonts' );
}

// Browser compatibility
add_action( 'wp_head', 'themify_viewport_tag' );

// Register custom menu
add_action( 'init', 'themify_register_custom_nav');

// Register sidebars
add_action( 'widgets_init', 'themify_theme_register_sidebars' );

// Add additional sidebar
add_action( 'themify_content_after', 'themify_theme_add_sidebar_alt' );

/////// Filters ////////
add_filter( 'themify_parallax_header', 'themify_disable_parallax_header_on_mobile' );

// Set class on body tag according to layout width
add_filter( 'body_class', 'themify_theme_body_class', 99 );

// WooCommerce
remove_action( 'woocommerce_after_shop_loop', 'woocommerce_pagination', 10 );
add_action( 'woocommerce_after_shop_loop', 'themify_theme_shop_pagination', 10 );

/**
 * Enqueue Stylesheets and Scripts
 * @since 1.0.0
 */
function themify_theme_enqueue_scripts() {
	global $themify;

	// Get theme version for Themify theme scripts and styles
	$theme_version = wp_get_theme()->display( 'Version' );

	$is_fullpage_scroll = themify_theme_is_fullpage_scroll();

	$font = themify_area_design( 'font', array(
		'default' => '',
		'values'  => wp_list_pluck( themify_theme_font_design_options(), 'value' ),
	) );
	$color = themify_area_design( 'color', array(
		'default' => '',
		'values'  => wp_list_pluck( themify_theme_color_design_options(), 'value' ),
	) );
	$header = themify_theme_get_header_design();
	$design_preset_dependency = array( 'theme-style' );
	if( themify_is_theme_skin() ) {
		$design_preset_dependency[] = 'themify-skin';
	}

	///////////////////
	//Enqueue styles
	///////////////////

	// Themify base styling
	wp_enqueue_style( 'theme-style', themify_enque( THEME_URI . '/style.css' ), array(), $theme_version);

	// Themify Media Queries CSS
	wp_enqueue_style( 'themify-media-queries', themify_enque(THEME_URI . '/media-queries.css'), array(), $theme_version);

	if( themify_is_using_custom_setting( 'font_design' ) || themify_is_using_custom_setting( 'color_design' ) ) {
		if( $GLOBALS['themify_customizer']->test_stylesheet() ) {
			$design_preset_dependency[] = 'themify-customize';
		}
	}
	if( themify_is_woocommerce_active() ) {
		wp_enqueue_style( 'themify-woocommerce', themify_enque(THEME_URI . '/styles/woocommerce.css') );
		$design_preset_dependency[] = 'themify-woocommerce';
	}
	if( $color != '' && $color != 'default' ) {
		wp_enqueue_style( 'ultra-color', themify_enque(THEME_URI . '/styles/' . $color . '.css'), $design_preset_dependency );
	}

	if( $font != '' && $font != 'default' ) {
		wp_enqueue_style( 'ultra-font', themify_enque(THEME_URI . '/styles/' . $font . '.css'), $design_preset_dependency );
	}

	if( $header != '' && $header != 'default' && $header != 'header-none'  && $header != 'header-block'  ) {
		wp_enqueue_style( 'ultra-header', themify_enque(THEME_URI . '/styles/' . $header . '.css'), $design_preset_dependency );
	}

	// Themify child base styling
	if( is_child_theme() ) {
		wp_enqueue_style( 'theme-style-child', themify_enque( get_stylesheet_uri() ), array(), $theme_version );
	}

	///////////////////
	//Enqueue scripts
	///////////////////

	wp_enqueue_script( 'imagesloaded');

	if ( $themify->post_layout_type === 'slider' && is_single() ) {
		wp_enqueue_script( 'themify-carousel-js' );
	}
	if ( $is_fullpage_scroll && (class_exists('Themify_Builder_Model') && !Themify_Builder_Model::is_front_builder_activate())) {
		wp_enqueue_style( 'themify-section-scroll', themify_enque(THEME_URI . '/styles/section-scroll.css'), array(), $theme_version);
		wp_enqueue_style( 'themify-splitscroll', themify_enque(THEME_URI . '/styles/splitscroll.css'), array(), $theme_version);
		wp_enqueue_script( 'themify-slimscroll', THEME_URI . '/js/jquery.slimscroll.min.js', array(), $theme_version, true );
		wp_enqueue_script( 'themify-fullpage', THEME_URI . '/js/jquery.fullPage.min.js', array( 'jquery', 'jquery-effects-core' ), $theme_version, true );
	}

	// Slide mobile navigation menu
	wp_enqueue_script( 'slide-nav', themify_enque(THEMIFY_URI . '/js/themify.sidemenu.js'), array( 'jquery' ), $theme_version, true );

	if ( ( is_home() || is_archive() || themify_is_query_page() || is_search() ) && 'slider' !== $themify->post_layout ) {
		// Infinite scroll
		wp_enqueue_script( 'infinitescroll', THEME_URI . '/js/jquery.infinitescroll.min.js', array('jquery'), false, true );
	}

	// Carousel
	if ( 'slider' === $themify->post_layout ) {
		wp_enqueue_script('themify-carousel-js');
	}

	// Themify internal scripts
	wp_enqueue_script( 'theme-script',	themify_enque(THEME_URI . '/js/themify.script.js'), array('jquery'), $theme_version, true );

	global $wp_query;

	// Prepare JS variables
	$themify_script_vars = array(
		'themeURI' => THEME_URI,
		'lightbox' => themify_lightbox_vars_init(),
		'lightboxContext' => apply_filters('themify_lightbox_context', '#pagewrap'),
		'fixedHeader' => themify_theme_fixed_header(),
		'sticky_header'=>themify_theme_sticky_logo(),
		'ajax_nonce'  => wp_create_nonce('ajax_nonce'),
		'ajax_url'	  => admin_url( 'admin-ajax.php' ),
		// Screen size at which horizontal menu is moved into side panel
		'smallScreen' => '760',
		// Resize refresh rate
		'resizeRefresh' => '250',
		'parallaxHeader' => apply_filters( 'themify_parallax_header', true ),
		// Infinite Scroll
		'loadingImg'   	=> THEME_URI . '/images/loading.gif',
		'maxPages'	   	=> $wp_query->max_num_pages,
		'currentPage' => get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1,
		'autoInfinite' 	=> themify_check( 'setting-autoinfinite' ) ? 'no': 'auto',
		'infiniteURL' => themify_check( 'setting-infinite-url' ) ? 1 : 0,
		'scrollToNewOnLoad' => 'scroll',
		'resetFilterOnLoad' => 'reset',
		'fullPageScroll' => $is_fullpage_scroll,
			'shop_masonry'=>  themify_is_woocommerce_active() && themify_get('setting-product_disable_masonry')!=='no'?'yes':'no',
		'scrollHighlight' => array(
			'scroll' =>  $is_fullpage_scroll?'external':'internal', // performed by themes
		),
		// auto tiles
		'tiledata' => array(
			'grids' => array(
				"post" => themify_is_touch('phone')?false:themify_set_tiles_template(),
				"mobile" => array("AA", "..")
			),
			'default_grid' => 'post',
			'small_screen_grid' => 'mobile',
			'breakpoint' => 800,
			'padding' => 5,
			'full_width' => false,
			'animate_init' => false,
			'animate_resize' => true,
			'animate_template' => false
		)
	);

	// Pass variable values to JavaScript
	wp_localize_script( 'theme-script', 'themifyScript', apply_filters('themify_script_vars', $themify_script_vars ) );

	// Collect page variables or use defaults
	$page_id = get_queried_object_id();
	if($page_id != null) {
		$slider_play = get_post_meta( $page_id, 'background_auto', true ) ? get_post_meta( $page_id, 'background_auto', true ) : (themify_check('setting-footer_slider_auto') ? themify_get('setting-footer_slider_auto') : 'yes');
		$slider_autoplay = get_post_meta( $page_id, 'background_autotimeout', true ) ? get_post_meta( $page_id, 'background_autotimeout', true ) : (themify_check('setting-footer_slider_autotimeout') ? themify_get('setting-footer_slider_autotimeout') : 5);
		$slider_speed = get_post_meta( $page_id, 'background_speed', true ) ? get_post_meta( $page_id, 'background_speed', true ) : (themify_check('setting-footer_slider_speed') ? themify_get('setting-footer_slider_speed') : 500);
		$slider_wrap = get_post_meta( $page_id, 'background_wrap', true ) ? get_post_meta( $page_id, 'background_wrap', true ) : 'yes';
		$slider_background_mode = get_post_meta( $page_id, 'background_mode', true ) ? get_post_meta( $page_id, 'background_mode', true ) : 'cover';
		$slider_background_position = get_post_meta( $page_id, 'background_position', true ) ? get_post_meta( $page_id, 'background_position', true ) : 'center-center';
	} else {
		$slider_play = 'yes';
		$slider_autoplay = 5;
		$slider_speed = 500;
		$slider_wrap = 'yes';
		$slider_background_mode = 'cover';
		$slider_background_position = 'center-center';
	}

	// Header gallery
	wp_register_script( 'header-slider', themify_enque(THEME_URI . '/js/themify.header-slider.js'), array( 'jquery' ), false, true );

	//Inject variable values in gallery script
	wp_localize_script( 'header-slider', 'themifyVars', array(
			'play'					=> $slider_play,
			'autoplay'				=> $slider_autoplay,
			'speed'					=> $slider_speed,
			'wrap'					=> $slider_wrap,
			'backgroundMode'		=> $slider_background_mode,
			'backgroundPosition'	=> $slider_background_position
		)
	);

	// WordPress internal script to move the comment box to the right place when replying to a user
	if ( is_single() || is_page() ) wp_enqueue_script( 'comment-reply' );
}


function themify_add_minify_vars($vars){
    $vars['minify']['js']['themify-tiles'] = themify_enque(THEME_URI.'/js/themify-tiles.js',true);
    return $vars;
}
/**
 * Load Google fonts used by the theme
 *
 * @return array
 */
function themify_theme_google_fonts( $fonts ) {
	$font = themify_area_design( 'font', array(
		'default' => '',
		'values'  => wp_list_pluck( themify_theme_font_design_options(), 'value' ),
	) );

	/* translators: If there are characters in your language that are not supported by Open Sans, translate this to 'off'. Do not translate into your own language. */
	if ( 'off' !== _x( 'on', 'Open Sans font: on or off', 'themify' ) ) {
		$fonts['open-sans'] = 'Open+Sans:400italic,600italic,700italic,400,300,600,700';
	}
	if( $font == 'theme-font-slab' || $font == 'theme-font-slab-sans' ) {
		/* translators: If there are characters in your language that are not supported by Roboto Slab, translate this to 'off'. Do not translate into your own language. */
		if ( 'off' !== _x( 'on', 'Roboto Slab font: on or off', 'themify' ) ) {
			$fonts['roboto-slab'] = 'Roboto+Slab:300,700,400';
		}
	}
	if( $font == 'theme-font-serif' || $font == 'theme-font-slab-sans' ) {
		/* translators: If there are characters in your language that are not supported by Sorts Mill Goudy, translate this to 'off'. Do not translate into your own language. */
		if ( 'off' !== _x( 'on', 'Sorts Mill Goudy font: on or off', 'themify' ) ) {
			$fonts['sorts-mill-goudy'] = 'Sorts+Mill+Goudy:400,400italic';
		}
	}

	return apply_filters( 'themify_theme_google_fonts', $fonts );
}

function themify_is_using_custom_setting( $name ) {
	global $post;

	if( is_object( $post ) && ( is_singular() || is_single() || is_page() ) && get_post_meta( $post->ID, $name, true ) != '' ) {
		if( get_post_meta( $post->ID, $name, true ) != 'default' ) {
			return true;
		}
	}

	return false;
}
if (is_admin()) {
	add_action('admin_enqueue_scripts', 'themify_admin_script_style');

	function themify_admin_script_style() {
		wp_enqueue_script('themify-admin-script', themify_enque(THEME_URI . '/admin/js/admin-script.js'));
	}
}

//Remove class has-post-thumbnail when hide_image is yes 

add_filter('post_class','themify_hide_feature_image',10,1);

function themify_hide_feature_image($classes){
	global $themify;
	if($themify->hide_image==='yes' && ($index=array_search('has-post-thumbnail', $classes))!==false){
		unset($classes[$index]);
	}
	return $classes;
}

/**
 * Check whether fullpage scrolling is enabled
 *
 * @return bool
 * @since 1.5.4
 */
function themify_theme_is_fullpage_scroll() {
        static $is_fullpage_scroll = null;
        if($is_fullpage_scroll===null){
            $is_fullpage_scroll = ( themify_is_touch( 'phone' ) && 'on' !== themify_get( 'section_scrolling_mobile' ) ) || is_search() ? false :  'yes' === themify_get( 'section_full_scrolling' ); // disable fullpage scroll on mobile
            $is_fullpage_scroll = apply_filters( 'themify_theme_is_fullpage_scroll', $is_fullpage_scroll );
        }
	return $is_fullpage_scroll;
}
/**
 * Logic for fixed header. Checks, if it applies, custom fields first and then theme settings.
 *
 * @since 1.0.0
 *
 * @return string
 */
function themify_theme_fixed_header() {
        static $fixed = NULL;
        if(is_null($fixed)){
            $header = themify_area_design( 'header', array(
                    'values'  => wp_list_pluck( themify_theme_header_design_options(), 'value' ), ) );
            if ( in_array( $header, array( 'header-leftpane', 'header-minbar', 'boxed-content', 'none', 'header-rightpane' ) ) ) {
                    $fixed = '';
                    return $fixed;
            }
            if ( is_singular( array( 'post', 'page', 'portfolio' ) ) ) {
                    $fixed_header_field = themify_get( 'fixed_header' );
                    if ( 'yes' == $fixed_header_field ) {
                        $fixed = 'fixed-header';
                        return $fixed;
                    } elseif ( 'no' == $fixed_header_field ) {
                            $fixed = '';
                            return $fixed;
                    }
            }
            $fixed = themify_check( 'setting-fixed_header_disabled' ) ? '' : 'fixed-header';
        }
        return $fixed;
}

function themify_theme_shrinking_logo() {
	static $shrinking = NULL;
	if(is_null($shrinking)){ 
		if ( is_singular( array( 'post', 'page', 'portfolio' ) ) ) {
			$shrinking_field = themify_get( 'shrinking_logo' );
			if ( 'yes' == $shrinking_field ) {
				$shrinking = 'no-shrinking-logo';
				return $shrinking;
			} elseif ( 'no' == $shrinking_field ) {
				$shrinking = '';
				return $shrinking;
			}
		}
		$shrinking = themify_check( 'setting-shrinking_logo_disabled' ) ? '' : 'no-shrinking-logo';
	} 
	return $shrinking;
}

/**
 * Disable Parallax header on mobile devices
 * @param bool $bool
 * @return bool
 */
function themify_disable_parallax_header_on_mobile( $bool ) {
	if ( themify_is_touch() ) $bool = false;
	return $bool;
}

/**
 * Add viewport tag for responsive layouts
 * @since 1.0.0
 */
function themify_viewport_tag() {
	echo "\n".'<meta name="viewport" content="width=device-width, initial-scale=1">'."\n";
}

/* Custom Write Panels
/***************************************************************************/

///////////////////////////////////////
// Build Write Panels
///////////////////////////////////////

if ( ! function_exists( 'themify_theme_init_types' ) ) {
	/**
	 * Initialize custom panel with its definitions
	 * Custom panel definitions are located in admin/post-type-TYPE.php
	 * @since 1.0.0
	 */
	function themify_theme_init_types() {
		// Load required files for post, page and custom post types where it applies
		foreach ( array( 'post', 'page', 'portfolio' ) as $type ) {
			require_once( "admin/post-type-$type.php" );
		}
	}
}

function themify_theme_setup_metaboxes( $meta_boxes, $post_type ) {

	if( ! in_array( $post_type, array( 'post', 'page', 'portfolio', 'product' ) ) ) {
		return $meta_boxes;
	}

	/**
	 * Navigation menus used in page custom panel to specify a custom menu for the page.
	 * @since 1.0.0
	 * @var array
	 */
	$nav_menus = array(	array( 'name' => '', 'value' => '', 'selected' => true ) );
	foreach ( get_terms( 'nav_menu' ) as $menu ) {
		$nav_menus[] = array( 'name' => $menu->name, 'value' => $menu->slug );
	}

	/**
	 * Options for header design
	 * @since 1.0.0
	 * @var array
	 */
	$header_design_options = themify_theme_header_design_options();

	/**
	 * Options for footer design
	 * @since 1.0.0
	 * @var array
	 */
	$footer_design_options = themify_theme_footer_design_options();

	/**
	 * Options for font design
	 * @since 1.0.0
	 * @var array
	 */
	$font_design_options = themify_theme_font_design_options();

	/**
	 * Options for color design
	 * @since 1.0.0
	 * @var array
	 */
	$color_design_options = themify_theme_color_design_options();

	$entry_id = isset( $_GET['post'] ) ? $_GET['post'] : null;
	$background_slider = false;
	if ( $entry_id ) {
		$background_slider = ( get_post_meta( $entry_id, 'header_wrap', true ) == '' && get_post_meta( $entry_id, 'background_gallery', true ) != '' );
		$background_mode = get_post_meta( $entry_id,'background_mode', true );
	}
	if ( ! isset( $background_mode ) || ! $background_mode ) {
		$background_mode = 'fullcover';
	}

	if( $post_type == 'post' ) {
		$theme_metaboxes = array(
			array(
				'name'    => __( 'Post Options', 'themify' ),
				'id'      => 'post-options',
				'options' => themify_theme_post_meta_box( array(
					'nav_menus' => $nav_menus,
				) ),
				'pages'   => 'post'
			),
			array(
				'name'    => __( 'Page Appearance', 'themify' ),
				'id'      => 'post-theme-design',
				'options' => themify_theme_page_theme_design_meta_box( array(
					'header_design_options' => $header_design_options,
					'footer_design_options' => $footer_design_options,
					'font_design_options'   => $font_design_options,
					'color_design_options'  => $color_design_options,
					'background_slider'		=> $background_slider,
					'background_mode'		=> $background_mode,
				) ),
				'pages'   => 'post'
			),
		);
	} elseif( $post_type == 'page' ) {
		$theme_metaboxes = array(
			array(
				'name'    => __( 'Page Options', 'themify' ),
				'id'      => 'page-options',
				'options' => themify_theme_page_meta_box( array(
					'nav_menus' => $nav_menus,
					'header_design_options' => $header_design_options,
					'footer_design_options' => $footer_design_options,
					'font_design_options'   => $font_design_options,
					'color_design_options'  => $color_design_options,
				) ),
				'pages'   => 'page'
			),
			array(
				'name'    => __( 'Page Appearance', 'themify' ),
				'id'      => 'page-theme-design',
				'options' => themify_theme_page_theme_design_meta_box( array(
					'header_design_options' => $header_design_options,
					'footer_design_options' => $footer_design_options,
					'font_design_options'   => $font_design_options,
					'color_design_options'  => $color_design_options,
					'background_slider'		=> $background_slider,
					'background_mode'		=> $background_mode,
				) ),
				'pages'   => 'page'
			),
			array(
				'name'    => __( 'Query Posts', 'themify' ),
				'id'      => 'query-posts',
				'options' => themify_theme_query_post_meta_box(),
				'pages'   => 'page'
			),
		);
		if( post_type_exists( 'portfolio' ) ) {
			$theme_metaboxes[] = array(
				'name'    => __( 'Query Portfolios', 'themify' ),
				'id'      => 'query-portfolio',
				'options' => themify_theme_query_portfolio_meta_box(),
				'pages'   => 'page'
			);
		}
	} elseif( $post_type == 'portfolio' ) {
		$theme_metaboxes = array(
			array(
				'name'    => __( 'Portfolio Options', 'themify' ),
				'id'      => 'portfolio-options',
				'options' => themify_theme_portfolio_meta_box( array(
					'nav_menus' => $nav_menus,
					'header_design_options' => $header_design_options,
					'footer_design_options' => $footer_design_options,
					'font_design_options'   => $font_design_options,
					'color_design_options'  => $color_design_options,
				) ),
				'pages'   => 'portfolio'
			),
			array(
				'name'    => __( 'Page Appearance', 'themify' ),
				'id'      => 'portfolio-theme-design',
				'options' => themify_theme_page_theme_design_meta_box( array(
					'header_design_options' => $header_design_options,
					'footer_design_options' => $footer_design_options,
					'font_design_options'   => $font_design_options,
					'color_design_options'  => $color_design_options,
					'background_slider'		=> $background_slider,
					'background_mode'		=> $background_mode,
				) ),
				'pages'   => 'portfolio'
			),
		);
	} elseif( $post_type == 'product' ) {
		$theme_metaboxes = array(
			array(
				'name'    => __( 'Page Appearance', 'themify' ),
				'id'      => 'product-theme-design',
				'options' => themify_theme_page_theme_design_meta_box( array(
					'header_design_options' => $header_design_options,
					'footer_design_options' => $footer_design_options,
					'font_design_options'   => $font_design_options,
					'color_design_options'  => $color_design_options,
					'background_slider'		=> $background_slider,
					'background_mode'		=> $background_mode,
				) ),
				'pages'   => 'product'
			),
		);
	}

	return isset( $theme_metaboxes ) ? array_merge( $theme_metaboxes, $meta_boxes ) : $meta_boxes;
}
add_filter( 'themify_metabox/fields/themify-meta-boxes', 'themify_theme_setup_metaboxes', 10, 2 );

/* Custom Functions
/***************************************************************************/

///////////////////////////////////////
// Enable WordPress feature image
///////////////////////////////////////
add_theme_support( 'post-thumbnails' );

if ( ! function_exists( 'themify_register_custom_nav' ) ) {
	/**
	 * Register Custom Menu Function
	 * @since 1.0.0
	 */
	function themify_register_custom_nav() {
		register_nav_menus( array(
			'main-nav' => __( 'Main Navigation', 'themify' ),
			'footer-nav' => __( 'Footer Navigation', 'themify' ),
		));
	}
}

if ( ! function_exists( 'themify_default_main_nav' ) ) {
	/**
	 * Default Main Nav Function
	 * @since 1.0.0
	 */
	function themify_default_main_nav() {
		echo '<ul id="main-nav" class="main-nav clearfix">';
			wp_list_pages('title_li=');
		echo '</ul>';
	}
}

if ( ! function_exists( 'themify_theme_register_sidebars' ) ) {
	/**
	 * Register sidebars
	 * @since 1.0.0
	 */
	function themify_theme_register_sidebars() {
		$sidebars = array(
			array(
				'name' => __( 'Sidebar', 'themify' ),
				'id' => 'sidebar-main',
				'before_widget' => '<div id="%1$s" class="widget %2$s">',
				'after_widget' => '</div>',
				'before_title' => '<h4 class="widgettitle">',
				'after_title' => '</h4>',
			),
			array(
				'name' => __('Sidebar Narrow', 'themify'),
				'id' => 'sidebar-alt',
				'before_widget' => '<div id="%1$s" class="widget %2$s">',
				'after_widget' => '</div>',
				'before_title' => '<h4 class="widgettitle">',
				'after_title' => '</h4>',
			),
			array(
				'name' => __( 'Social Widget', 'themify' ),
				'id' => 'social-widget',
				'before_widget' => '<div id="%1$s" class="widget %2$s">',
				'after_widget' => '</div>',
				'before_title' => '<strong class="widgettitle">',
				'after_title' => '</strong>',
			),
			array(
				'name' => __( 'Footer Social Widget', 'themify' ),
				'id' => 'footer-social-widget',
				'before_widget' => '<div id="%1$s" class="widget %2$s">',
				'after_widget' => '</div>',
				'before_title' => '<strong class="widgettitle">',
				'after_title' => '</strong>',
			),
		);
		foreach ( $sidebars as $sidebar ) {
			register_sidebar( $sidebar );
		}

		// Header Sidebars
		themify_register_grouped_widgets( array(
			'headerwidget-4col' => 4,
			'headerwidget-3col'	=> 3,
			'headerwidget-2col' => 2,
			'headerwidget-1col' => 1,
			'none'			 	=> 0
		), array(
			'sidebar_name' => __( 'Header Widget', 'themify' ),
			'sidebar_id' => 'header-widget',
			'before_widget' => '<div id="%1$s" class="widget %2$s">',
			'after_widget' => '</div>',
			'before_title' => '<h4 class="widgettitle">',
			'after_title' => '</h4>',
		), 'setting-header_widgets', 'headerwidget-3col' );

		// Footer Sidebars
		themify_register_grouped_widgets();
	}
}

if( ! function_exists('themify_theme_add_sidebar_alt') ) {
	/**
	 * Includes second sidebar
	 * @since 1.0.0
	 */
	function themify_theme_add_sidebar_alt() {
		global $themify;
		if( 'sidebar2' == $themify->layout || 'sidebar2 content-left' == $themify->layout || 'sidebar2 content-right' == $themify->layout ): ?>
			<?php get_template_part( 'includes/sidebar-alt'); ?>
		<?php endif;
	}
}

if ( ! function_exists( 'themify_theme_comment' ) ) {
	/**
	 * Custom Theme Comment
	 *
	 * @since 1.0.0
	 *
	 * @param object $comment Current comment.
	 * @param array $args Parameters for comment reply link.
	 * @param int $depth Maximum comment nesting depth.
	 */
	function themify_theme_comment( $comment, $args, $depth ) {
	   $GLOBALS['comment'] = $comment; ?>

		<li id="comment-<?php comment_ID() ?>">
			<p class="comment-author">
				<?php echo get_avatar( $comment, $size = '48' ); ?>
				<cite <?php comment_class(); ?>><span <?php comment_class(); ?>><?php echo get_comment_author_link(); ?></span></cite>
				<br/>
				<small class="comment-time">
					<?php comment_date( apply_filters('themify_comment_date', '') ); ?>
					 @
					<?php comment_time( apply_filters('themify_comment_time', '') ); ?>
					<?php edit_comment_link( __('Edit', 'themify'),' [',']'); ?>
				</small>
			</p>
			<div class="commententry">
				<?php if ($comment->comment_approved == '0') : ?>
					<p><em><?php _e('Your comment is awaiting moderation.', 'themify') ?></em></p>
				<?php endif; ?>
				<?php comment_text(); ?>
			</div>
			<p class="reply">
				<?php comment_reply_link(array_merge( $args, array('add_below' => 'comment', 'depth' => $depth, 'reply_text' => __( 'Reply', 'themify' ), 'max_depth' => $args['max_depth']))) ?>
			</p>
		<?php
	}
}

if ( ! function_exists( 'themify_theme_has_submenu' ) ) {
	/**
	 * Sets custom class if menu item has a submenu.
	 *
	 * @since 1.0.0
	 *
	 * @param array $sorted_menu_items The menu items to filter.
	 *
	 * @return array The filtered menu items.
	 */
	function themify_theme_has_submenu( $sorted_menu_items ) {
		$last_top = 0;
		foreach ( $sorted_menu_items as $key => $obj ) {
			if ( 0 == $obj->menu_item_parent ) {
				$last_top = $key;
			} else {
				$sorted_menu_items[$last_top]->classes['has-sub-menu'] = 'has-sub-menu';
			}
		}
		return $sorted_menu_items;
	}
	add_filter( 'wp_nav_menu_objects', 'themify_theme_has_submenu', 10 );
}


if ( ! function_exists( 'themify_theme_custom_post_css' ) ) {
	/**
	 * Outputs custom post CSS at the end of a post
	 *
	 * @since 1.0.0
	 */
	function themify_theme_custom_post_css() {
		global $themify;

		if ( in_array( get_post_type(), array( 'post', 'page', 'portfolio', 'product' ) ) || themify_is_shop() ) {
			$post_id = get_the_ID();
			if ( is_page() ) {
				$entry_id = '.page-id-' . $post_id;
				$archive_entry_id = '.page-' . $post_id;
			} elseif ( themify_is_shop() ) {
				$entry_id = '.woocommerce-page';
				$archive_entry_id = '.post-' . $post_id;
			} else {
				$entry_id = '.postid-' . $post_id;
				$archive_entry_id = '.post-' . $post_id;
			}
			$headerwrap = $entry_id . ' #headerwrap';
			$site_logo = $entry_id . ' #site-logo';
			$site_description = $entry_id . ' #site-description';
			$main_nav = $entry_id . ' #main-nav';
			$header_widget = $entry_id . ' .header-widget';
			$social_widget = $entry_id . ' .social-widget';
			$header_search = $entry_id . ' #searchform-wrap';
			$css = array();
			$style = '';
			$rules = array();
			$header_type = themify_get( 'header_wrap' );

			if ( 'transparent' != $header_type ) {
				$rules = array(
					"$entry_id #site-logo span:after, $entry_id #headerwrap #searchform, $entry_id #main-nav .current_page_item a, $entry_id #main-nav .current-menu-item a" => array(
							array(
								'prop' => 'border-color',
								'key'  => 'headerwrap_text_color'
							),
					),
				);
				if ( 'solid' === $header_type || !$header_type || 'video' === $header_type ) {
					$rules[$headerwrap] = array(
						array(
							'prop' => 'background-color',
							'key'  => 'background_color'
						),
						array(
							'prop' => 'background-image',
							'key'  => 'background_image'
						),
						array(
							'prop' => 'background-repeat',
							'key'  => 'background_repeat',
							'dependson' => array(
								'prop' => 'background-image',
								'key'  => 'background_image'
							),
						),
					);
				}
			}
						
			$custom_color =  themify_theme_get( 'color_scheme_mode', 'color-presets' ) == 'color-custom';
			$custom_font =  themify_theme_get( 'typography_mode' ) == 'typography-custom';
			if ( ( is_singular() || themify_is_shop() ) && ($custom_color || $custom_font) ) {
				if($custom_font){
					$rules = array_merge( $rules, array(
						'.skin-styles' => array(
							array(
								'prop' => 'font-family',
								'key'  => 'body_font'
							),
							array(
								'prop' => 'color',
								'key'  => 'body_text_color'
							),
						),
						'.skin-styles .post-meta, .skin-styles #site-description, .skin-styles .post-date .year, .skin-styles .post-date .month, .skin-styles .post-date .day, .skin-styles .loops-wrapper .entry-content' => array(
							array(
								'prop' => 'font-family',
								'key'  => 'body_font'
							),
						),
					));
					// No space between .skin-styles and $main_nav because the latter has the body classes prepended.
					$rules[".skin-styles a, .skin-styles .post-nav .arrow"] = array(
						array(
							'prop' => 'color',
							'key'  => 'body_link_color'
						),
					);

					$rules['.skin-styles h1, .skin-styles h2, .skin-styles h3, .skin-styles h4, .skin-styles h5, .skin-styles h6'] = array(
						array(
							'prop' => 'color',
							'key'  => 'heading_color'
						),
						array(
							'prop' => 'font-family',
							'key'  => 'heading_font'
						),
					);
				}
				if($custom_color){
					// Accent Background Color
					$rules['.skin-styles #headerwrap,.skin-styles #footerwrap,.skin-styles input[type=reset],.skin-styles input[type=submit],.skin-styles button,.skin-styles #respond #cancel-comment-reply-link,.skin-styles .commentlist .comment-reply-link,.skin-styles.footer-horizontal-left .back-top .arrow-up a,.skin-styles.footer-horizontal-right .back-top .arrow-up a,.skin-styles.footer-left-col .back-top .arrow-up a,.skin-styles.footer-right-col .back-top .arrow-up a,.skin-styles.woocommerce #content input.button,.skin-styles.woocommerce #respond input#submit,.skin-styles.woocommerce a.button,.skin-styles.woocommerce button.button,.skin-styles.woocommerce input.button,.skin-styles.woocommerce-page #content input.button,.skin-styles.woocommerce-page #respond input#submit,.skin-styles.woocommerce-page a.button,.skin-styles.woocommerce-page button.button,.skin-styles.woocommerce-page input.button,.skin-styles.woocommerce #content input.button.alt,.skin-styles.woocommerce #respond input#submit.alt,.skin-styles.woocommerce a.button.alt,.skin-styles.woocommerce button.button.alt,.skin-styles.woocommerce input.button.alt,.skin-styles.woocommerce-page #content input.button.alt,.skin-styles.woocommerce-page #respond input#submit.alt,.skin-styles.woocommerce-page a.button.alt,.skin-styles.woocommerce-page button.button.alt,.skin-styles.woocommerce-page input.button.alt,.skin-styles.woocommerce ul.products li.product .add_to_cart_button,.skin-styles.woocommerce-page ul.products li.product .add_to_cart_button,.skin-styles.woocommerce ul.products li.product .button[data-product_id],.skin-styles.woocommerce-page ul.products li.product .button[data-product_id],.skin-styles.woocommerce span.onsale,.skin-styles.woocommerce-page span.onsale,.skin-styles.woocommerce ul.products li.product .onsale,.skin-styles.woocommerce-page ul.products li.product .onsale,.skin-styles.woocommerce-checkout #payment div.payment_box,.skin-styles.woocommerce #content nav.woocommerce-pagination ul li a:focus,.skin-styles.woocommerce #content nav.woocommerce-pagination ul li a:hover,.skin-styles.woocommerce #content nav.woocommerce-pagination ul li span.current,.skin-styles.woocommerce nav.woocommerce-pagination ul li a:focus,.skin-styles.woocommerce nav.woocommerce-pagination ul li a:hover,.skin-styles.woocommerce nav.woocommerce-pagination ul li span.current,.skin-styles.woocommerce-page #content nav.woocommerce-pagination ul li a:focus,.skin-styles.woocommerce-page #content nav.woocommerce-pagination ul li a:hover,.skin-styles.woocommerce-page #content nav.woocommerce-pagination ul li span.current,.skin-styles.woocommerce-page nav.woocommerce-pagination ul li a:focus,.skin-styles.woocommerce-page nav.woocommerce-pagination ul li a:hover,.skin-styles.woocommerce-page nav.woocommerce-pagination ul li span.current,.skin-styles.woocommerce #content table.cart a.remove:hover,.skin-styles.woocommerce table.cart a.remove:hover,.skin-styles.woocommerce-page #content table.cart a.remove:hover,.skin-styles.woocommerce-page table.cart a.remove:hover'] = array(
						array(
							'prop' => 'background-color',
							'key'  => 'scheme_background'
						),
					);

					// Accent Font Color
					$rules['.skin-styles #headerwrap,.skin-styles #footerwrap,.footer-widgets .widgettitle,.skin-styles #site-description,.skin-styles input[type=reset],.skin-styles input[type=submit],.skin-styles button,.skin-styles #respond #cancel-comment-reply-link,.skin-styles .commentlist .comment-reply-link,.skin-styles .post-title a,.skin-styles #main-nav > li > a,.skin-styles #main-nav > .current_page_item > a,.skin-styles #main-nav > .current-menu-item > a,.skin-styles #main-nav > li > a:hover,.skin-styles.footer-horizontal-left .back-top .arrow-up a,.skin-styles.footer-horizontal-right .back-top .arrow-up a,.skin-styles.footer-left-col .back-top .arrow-up a,.skin-styles.footer-right-col .back-top .arrow-up a,.skin-styles.woocommerce #content input.button,.skin-styles.woocommerce #respond input#submit,.skin-styles.woocommerce a.button,.skin-styles.woocommerce button.button,.skin-styles.woocommerce input.button,.skin-styles.woocommerce-page #content input.button,.skin-styles.woocommerce-page #respond input#submit,.skin-styles.woocommerce-page a.button,.skin-styles.woocommerce-page button.button,.skin-styles.woocommerce-page input.button,.skin-styles.woocommerce #content input.button.alt,.skin-styles.woocommerce #respond input#submit.alt,.skin-styles.woocommerce a.button.alt,.skin-styles.woocommerce button.button.alt,.skin-styles.woocommerce input.button.alt,.skin-styles.woocommerce-page #content input.button.alt,.skin-styles.woocommerce-page #respond input#submit.alt,.skin-styles.woocommerce-page a.button.alt,.skin-styles.woocommerce-page button.button.alt,.skin-styles.woocommerce-page input.button.alt,.skin-styles.woocommerce ul.products li.product .add_to_cart_button,.skin-styles.woocommerce-page ul.products li.product .add_to_cart_button,.skin-styles.woocommerce ul.products li.product .button[data-product_id],.skin-styles.woocommerce-page ul.products li.product .button[data-product_id],.skin-styles.woocommerce span.onsale,.skin-styles.woocommerce-page span.onsale,.skin-styles.woocommerce ul.products li.product .onsale,.skin-styles.woocommerce-page ul.products li.product .onsale,.skin-styles.woocommerce-checkout #payment div.payment_box,.skin-styles.woocommerce #content nav.woocommerce-pagination ul li a:focus,.skin-styles.woocommerce #content nav.woocommerce-pagination ul li a:hover,.skin-styles.woocommerce #content nav.woocommerce-pagination ul li span.current,.skin-styles.woocommerce nav.woocommerce-pagination ul li a:focus,.skin-styles.woocommerce nav.woocommerce-pagination ul li a:hover,.skin-styles.woocommerce nav.woocommerce-pagination ul li span.current,.skin-styles.woocommerce-page #content nav.woocommerce-pagination ul li a:focus,.skin-styles.woocommerce-page #content nav.woocommerce-pagination ul li a:hover,.skin-styles.woocommerce-page #content nav.woocommerce-pagination ul li span.current,.skin-styles.woocommerce-page nav.woocommerce-pagination ul li a:focus,.skin-styles.woocommerce-page nav.woocommerce-pagination ul li a:hover,.skin-styles.woocommerce-page nav.woocommerce-pagination ul li span.current,.skin-styles.woocommerce #content table.cart a.remove:hover,.skin-styles.woocommerce table.cart a.remove:hover,.skin-styles.woocommerce-page #content table.cart a.remove:hover,.skin-styles.woocommerce-page table.cart a.remove:hover'] = array(
						array(
							'prop' => 'color',
							'key'  => 'scheme_color'
						),
					);

					// Accent Link Color
					$rules['.skin-styles #headerwrap a, .skin-styles #footerwrap a, .skin-styles .sidemenu a, .skin-styles .post-nav .arrow, .skin-styles .widget .social-links a, .skin-styles .widget .social-links a:hover, .skin-styles .footer-nav li a'] = array(
						array(
							'prop' => 'color',
							'key'  => 'scheme_link'
						),
					);

					$rules['.skin-styles.woocommerce .woocommerce-error,.skin-styles.woocommerce .woocommerce-info,.skin-styles.woocommerce .woocommerce-message,.skin-styles.woocommerce-page .woocommerce-error,.skin-styles.woocommerce-page .woocommerce-info,.skin-styles.woocommerce-page .woocommerce-message'] = array(
						array(
							'prop' => 'border-top-color',
							'key'  => 'scheme_background'
						),
					);

					$rules['.skin-styles.woocommerce-checkout #payment div.payment_box:after'] = array(
						array(
							'prop' => 'border-bottom-color',
							'key'  => 'scheme_background'
						),
					);

					$rules['.skin-styles .post-title a:hover'] = array(
						array(
							'prop' => 'color',
							'key'  => 'scheme_background'
						),
					);
				}
			}

			// Body background color, image and image repeat is not influenced by presets.
			$body_bg_color_image = array(
				array(
					'prop' => 'background-color',
					'key'  => 'body_background_color'
				),
				array(
					'prop' => 'background-image',
					'key'  => 'body_background_image'
				),
				array(
					'prop' => 'background-repeat',
					'key'  => 'body_background_repeat',
					'dependson' => array(
						'prop' => 'background-image',
						'key'  => 'body_background_image'
					),
				),
			);
			if ( isset( $rules['.skin-styles'] ) ) {
				// If there is some preset styling, merge body background color and image
				$rules['.skin-styles'] = array_merge( $rules['.skin-styles'], $body_bg_color_image);
			} else {
				// Otherwise create the key and assign body background color and image
				$rules['.skin-styles'] = $body_bg_color_image;
			}

			$rules["$headerwrap, $site_logo, $site_description"] = array(
				array(
					'prop' => 'color',
					'key'  => 'headerwrap_text_color'
				),
			);

			$rules["$site_logo a, $site_description a, $header_widget a, $social_widget a, $social_widget .rss a, $main_nav > li > a, $headerwrap .header-icons a"] = array(
				array(
					'prop' => 'color',
					'key'  => 'headerwrap_link_color'
				),
			);

			foreach ( $rules as $selector => $property ) {
				foreach ( $property as $val ) {
					$prop = $val['prop'];
					$key = $val['key'];
					if ( is_array( $key ) ) {
						if ( $prop == 'font-size' && themify_check( $key[0] ) ) {
							$css[$selector][$prop] = $prop . ': ' . themify_get( $key[0] ) . themify_get( $key[1] );
						}
					} elseif ( themify_check( $key ) && 'default' != themify_get( $key ) ) {
						if ( $prop == 'color' || stripos( $prop, 'color' ) ) {
							if ( 'scheme_background' == $key ) {
								$header_bg_opacity = 'transparent' == themify_get( 'header_wrap' ) ? '0.9': '1';
								$css[$selector][$prop] = $prop . ':' . 'rgba(' . themify_theme_hex2rgb( themify_get( $key ) ) . ', ' . $header_bg_opacity . ')';
							} else {
								$css[$selector][$prop] = $prop . ': ' . themify_get_color( $key );
							}
						}
						elseif ( $prop == 'background-image' && 'default' != themify_get( $key ) ) {
							$css[$selector][$prop] = $prop .': url(' . themify_get( $key ) . ')';
						}
						elseif ( $prop == 'background-repeat' && 'fullcover' == themify_get( $key ) ) {
							if ( isset( $val['dependson'] ) ) {
								if ( $val['dependson']['prop'] == 'background-image' && ( themify_check( $val['dependson']['key'] ) && 'default' != themify_get( $val['dependson']['key'] ) ) ) {
									if( $selector === '.skin-styles' ) {
										$css['.iphone:before'] = $css[$selector];
										$css['.iphone:before']['background-size'] = 'background-size: cover; content: ""';
									}
									$css[$selector]['background-size'] = 'background-size: cover; background-attachment:fixed;';
								}
							} else {
								$css[$selector]['background-size'] = 'background-size: cover; background-attachment:fixed;';
							}
						}
						elseif ( $prop == 'font-family' ) {
							$font = themify_get( $key );
							$css[$selector][$prop] = $prop .': '. $font;
							if ( ! in_array( $font, themify_get_web_safe_font_list( true ) ) ) {
								$themify->google_fonts .= str_replace( ' ', '+', $font.'|' );
							}
						}
						else {
							$css[$selector][$prop] = $prop .': '. themify_get( $key );
						}
					}
				}
				if ( ! empty( $css[$selector] ) ) {
					global $is_iphone;
					if( !empty( $css['.iphone:before'] ) && $selector === '.skin-styles' && $is_iphone ) {
						$style .= ".iphone:before {\n\t" . implode( ";\n\t", $css[ '.iphone:before' ] ) . "\n}\n";
					} else {
						$style .= "$selector {\n\t" . implode( ";\n\t", $css[$selector] ) . "\n}\n";
					}
				}
			}

			if ( '' != $style ) {
				echo "\n<!-- Entry Style -->\n<style>\n$style</style>\n<!-- End Entry Style -->\n";
			}
		}
	}
	add_action( 'wp_head', 'themify_theme_custom_post_css', 77 );
}

if ( ! function_exists( 'themify_theme_enqueue_google_fonts' ) ) {
	/**
	 * Enqueue Google Fonts
	 * @since 1.0.0
	 */
	function themify_theme_enqueue_google_fonts() {
		global $themify;
		if ( ! isset( $themify->google_fonts ) || '' == $themify->google_fonts ) return;
		$themify->google_fonts = substr( $themify->google_fonts, 0, -1 );
		wp_enqueue_style( 'section-styling-google-fonts', themify_https_esc( 'http://fonts.googleapis.com/css' ). '?family='.$themify->google_fonts );
	}
	add_action( 'wp_footer', 'themify_theme_enqueue_google_fonts' );
}

if ( ! function_exists( 'themify_theme_animated_bg_default_colors' ) ) {
	/**
	 * Returns the default colors. Used if user enabled animated colors but didn't specified colors.
	 *
	 * @since 1.0.0
	 *
	 * @return array
	 */
	function themify_theme_animated_bg_default_colors() {
		return array( '#33baab', '#e33b9e', '#4961d7', '#2ea85c', '#2bb8ed', '#dd5135', );
	}
}

if ( ! function_exists( 'themify_theme_animated_bg_check' ) ) {
	/**
	 * Checks if there is the area passed has color animation enabled.
	 *
	 * @since 1.0.0
	 *
	 * @param string $area
	 *
	 * @return mixed|string
	 */
	function themify_theme_animated_bg_check( $area ) {
		if ( 'header' == $area ) {
			if ( is_singular() || themify_is_shop() ) {
				if ( 'colors' == themify_get( 'header_wrap' ) ) {
					return true;
				}
			} else {
				return themify_theme_get( 'header_wrap', '', 'setting-header_color_animation_enabled' );
			}
		} else {
			return themify_check( 'setting-' . $area . '_color_animation_enabled' );
		}
	}
}

/**
 * Checks if .animated-bg class must be output and sets the first animation color as initial background
 * Displays the data-bg and class attributes, including the background image and fullcover class
 *
 * @since 1.0.0
 *
 * @param string $area
 * @param string $classes Additional CSS classes to output for this element
 */
function themify_theme_header_background( $area = 'header', $classes = '' ) {
	$class = '';
	$style = '';
	$image = null;
	$repeat = '';
	$data_bg = '';
	$post_id = get_the_ID();
	$nobg = '';
	$area_wrap = themify_get( $area . '_wrap' );
	$image_meta = '';
	$background_gallery = '';
  
	if ( 'header' === $area && in_array( $area_wrap, array( 'video', 'slider' ) ) ) {
		$back_key = 'styling-background-header_wrap_background-background_image-value-value';
		$mode_key = 'styling-background-header_wrap_background-background_mode-value-value';
		$nobg_key = 'styling-background-header_wrap_background-background_image-value-none';
		$header_customizer = json_decode( get_theme_mod( 'headerwrap_background' ) );

		if ( isset( $header_customizer->src ) && '' != $header_customizer->src ) {
			$image = $header_customizer->src;
			$repeat = isset( $header_customizer->style ) ? $header_customizer->style : 'fullcover';
		} elseif ( themify_check( $back_key ) ) {
			$image = themify_get( $back_key );
			$repeat = themify_check( $mode_key )? themify_get( $mode_key ): 'fullcover';
		}
		$nobg = themify_get( $nobg_key ) || ( isset( $header_customizer->noimage ) && 'noimage' === $header_customizer->noimage );

		if ( is_page() || is_singular( 'post' ) || is_singular( 'portfolio' ) ) {
			global $themify;

			if ( is_page() ) {
				$post_id = $themify->page_id;
			} else {
				$post_id = get_the_ID();
			}

			$image_meta = get_post_meta($post_id, 'background_image', true);
			if ( $image_meta ) {
				$image = $image_meta;
				$repeat_meta = get_post_meta($post_id, 'background_repeat', true);
				if ( $repeat_meta ) {
					$repeat = $repeat_meta;
				}
			}
			
			if ( $area_wrap === 'slider' ) {
                            $background_color = get_post_meta( $post_id, 'background_color', true );
                            if($background_color != ''){
                                $data_bg .= "data-bgcolor='$background_color'";
                            }
			}
                        elseif ( 'video' === $area_wrap ) {
                            $video = get_post_meta( $post_id, 'video_file', true );
                            if($video!=''){
                                $data_bg .= " data-fullwidthvideo='$video'";
                            }
			}
			$background_gallery = get_post_meta( $post_id, 'background_gallery', true );
			if ( $gallery = ( ( $area_wrap === 'slider' ) || ( $area_wrap == '' && $background_gallery != '' ) ) ) {
				$repeat = 'fullcover header-gallery';
			} elseif ( $nobg ) {
				// Checks $image_meta because $image might have been set in customizer and we don't need to check that.
				if ( is_singular() && $image_meta ) {
					$data_bg .= " data-bg='$image'";
				}
			} elseif ( $image ) {
				$data_bg .= " data-bg='$image'";
			} else {
				$data_bg .= ' data-bg="http://themify.me/demo/themes/wp-content/uploads/2013/05/header.jpg"';
				$repeat = 'fullcover';
			}
		}
	}

	if ( $repeat || $classes ) {
		$class = "class='$repeat $classes'";
	}

	if ( !empty( $style ) ) {
		$style = 'style="' . $style . '"';
	}

	echo "$data_bg $class $style";
}

if ( ! function_exists( 'themify_theme_entry_title_tag' ) ) :
/**
 * Displays the entry title tag, outputting h1 for singular views and h2 otherwise.
 * @Deprecated
 *
 * @since 1.0.0
 *
 * @return string
 */
function themify_theme_entry_title_tag( $echo = true ) {
	global $themify;
	$tag = is_singular() && !$themify->is_shortcode ? 'h1' : 'h2';
	$tag = apply_filters( 'themify_entry_title_tag', $tag );
	if( ! $echo )
		return $tag;
	echo $tag;
}
endif;

/**
 * Returns options for header design. Used in custom panel and theme settings.
 *
 * @since 1.0.0
 *
 * @return array List of header design options.
 */
function themify_theme_header_design_options() {
	return apply_filters( 'themify_theme_header_design_options', array(
		array(
			'value' => 'default',
			'img'   => 'images/layout-icons/default.png',
			'title' => __( 'Default', 'themify' ),
			'selected' => true,
		),
		array(
			'value' => 'header-block',
			'img'   => 'images/layout-icons/header-block.png',
			'title' => __( 'Header Block', 'themify' ),
		),
		array(
			'value' => 'header-horizontal',
			'img'   => 'images/layout-icons/header-horizontal.png',
			'title' => __( 'Header Horizontal', 'themify' ),
		),
		array(
			'value' => 'header-top-widgets',
			'img'   => 'images/layout-icons/header-top-widget.png',
			'title' => __( 'Header Top Widget', 'themify' ),
		),
		array(
			'value' => 'boxed-content', // hides sticky header
			'img'   => 'images/layout-icons/boxed-content.png',
			'title' => __( 'Header Boxed Content', 'themify' ),
		),
		array(
			'value' => 'boxed-layout',
			'img'   => 'images/layout-icons/boxed-layout.png',
			'title' => __( 'Header Boxed Layout', 'themify' ),
		),
		array(
			'value' => 'header-leftpane', // hides sticky header
			'img'   => 'images/layout-icons/leftpanel.png',
			'title' => __( 'Header Left Pane', 'themify' ),
		),
		array(
			'value' => 'header-slide-out', // hides sticky header
			'img'   => 'images/layout-icons/slide-out.png',
			'title' => __( 'Header Slide Out', 'themify' ),
		),
		array(
			'value' => 'header-minbar', // hides sticky header
			'img'   => 'images/layout-icons/minbar.png',
			'title' => __( 'Header Min Bar', 'themify' ),
		),
		array(
			'value' => 'header-top-bar', // hides sticky header
			'img'   => 'images/layout-icons/header-top-bar.png',
			'title' => __( 'Header Top Bar', 'themify' ),
		),
		array(
			'value' => 'boxed-compact', // hides sticky header
			'img'   => 'images/layout-icons/boxed-compact.png',
			'title' => __( 'Boxed Compact', 'themify' ),
		),
		array(
			'value' => 'header-overlay', // hides sticky header
			'img'   => 'images/layout-icons/header-overlay.png',
			'title' => __( 'Header Overlay ', 'themify' ),
		),
		array(
			'value' => 'header-rightpane', // hides sticky header
			'img'   => 'images/layout-icons/rightpanel.png',
			'title' => __( 'Header Right Pane ', 'themify' ),
		),
		array(
			'value' => 'header-menu-split', // hides sticky header
			'img'   => 'images/layout-icons/menu-split.png',
			'title' => __( 'Menu Split', 'themify' ),
		),
		array(
			'value' => 'header-stripe',
			'img'   => 'images/layout-icons/header-stripe.png',
			'title' => __( 'Header Stripe', 'themify' ),
		),
		array(
			'value' => 'header-magazine',
			'img'   => 'images/layout-icons/header-magazine.png',
			'title' => __( 'Header Magazine', 'themify' ),
		),
		array(
			'value' => 'none', // hides sticky header
			'img'   => 'images/layout-icons/none.png',
			'title' => __( 'No Header ', 'themify' ),
		)
	));
}

/**
 * Returns options for font design. Used in custom panel and theme settings.
 *
 * @since 1.0.0
 *
 * @return array List of font design options.
 */
function themify_theme_font_design_options() {
	return apply_filters( 'themify_theme_font_design_options', array(
		array(
			'value' => 'default',
			'img'   => 'images/layout-icons/default.png',
			'title' => __( 'Theme Default', 'themify' ),
			'selected' => true,
		),
		array(
			'value' => 'theme-font-sans-serif',
			'img'   => 'images/layout-icons/font-sans-serif.png',
			'title' => __( 'Sans Serif', 'themify' ),
		),
		array(
			'value' => 'theme-font-serif',
			'img'   => 'images/layout-icons/font-serif.png',
			'title' => __( 'Serif', 'themify' ),
		),
		array(
			'value' => 'theme-font-slab-sans',
			'img'   => 'images/layout-icons/font-slab-sans.png',
			'title' => __( 'Slab Sans', 'themify' ),
		),
		array(
			'value' => 'theme-font-slab',
			'img'   => 'images/layout-icons/font-slab.png',
			'title' => __( 'Slab', 'themify' ),
		),
	));
}

/**
 * Returns options for color design. Used in custom panel and theme settings.
 *
 * @since 1.0.0
 *
 * @return array List of color design options.
 */
function themify_theme_color_design_options() {
	return apply_filters( 'themify_theme_color_design_options', array(
		array(
			'value' => 'default',
			'img'   => 'images/layout-icons/color-default.png',
			'title' => __( 'Theme Default', 'themify' ),
			'selected' => true,
		),
		array(
			'value' => 'theme-color-black',
			'img'   => 'images/layout-icons/color-black.png',
			'title' => __( 'Black', 'themify' ),
		),
		array(
			'value' => 'theme-color-blue',
			'img'   => 'images/layout-icons/color-blue.png',
			'title' => __( 'Blue', 'themify' ),
		),
		array(
			'value' => 'theme-color-brown',
			'img'   => 'images/layout-icons/color-brown.png',
			'title' => __( 'Brown', 'themify' ),
		),
		array(
			'value' => 'theme-color-burgundy',
			'img'   => 'images/layout-icons/color-burgundy.png',
			'title' => __( 'Burgundy', 'themify' ),
		),
		array(
			'value' => 'theme-color-green',
			'img'   => 'images/layout-icons/color-green.png',
			'title' => __( 'Green', 'themify' ),
		),
		array(
			'value' => 'theme-color-grey',
			'img'   => 'images/layout-icons/color-grey.png',
			'title' => __( 'Grey', 'themify' ),
		),
		array(
			'value' => 'theme-color-lime',
			'img'   => 'images/layout-icons/color-lime.png',
			'title' => __( 'Lime', 'themify' ),
		),
		array(
			'value' => 'theme-color-magenta',
			'img'   => 'images/layout-icons/color-magenta.png',
			'title' => __( 'Magenta', 'themify' ),
		),
		array(
			'value' => 'theme-color-orange',
			'img'   => 'images/layout-icons/color-orange.png',
			'title' => __( 'Orange', 'themify' ),
		),
		array(
			'value' => 'theme-color-pink',
			'img'   => 'images/layout-icons/color-pink.png',
			'title' => __( 'Pink', 'themify' ),
		),
		array(
			'value' => 'theme-color-purple',
			'img'   => 'images/layout-icons/color-purple.png',
			'title' => __( 'Purple', 'themify' ),
		),
		array(
			'value' => 'theme-color-red',
			'img'   => 'images/layout-icons/color-red.png',
			'title' => __( 'Red', 'themify' ),
		),
		array(
			'value' => 'theme-color-turquoise',
			'img'   => 'images/layout-icons/color-turquoise.png',
			'title' => __( 'Turquoise', 'themify' ),
		),
		array(
			'value' => 'theme-color-violet',
			'img'   => 'images/layout-icons/color-violet.png',
			'title' => __( 'Violet', 'themify' ),
		),
		array(
			'value' => 'theme-color-yellow',
			'img'   => 'images/layout-icons/color-yellow.png',
			'title' => __( 'Yellow', 'themify' ),
		),
	));
}

/**
 * Returns options for footer design. Used in custom panel and theme settings.
 *
 * @since 1.0.0
 *
 * @return array List of footer design options.
 */
function themify_theme_footer_design_options() {
	return apply_filters( 'themify_theme_footer_design_options', array(
		array(
			'value' => 'default',
			'img'   => 'images/layout-icons/default.png',
			'title' => __( 'Theme Default', 'themify' ),
			'selected' => true,
		),
		array(
			'value' => 'footer-block',
			'img'   => 'images/layout-icons/footer-block.png',
			'title' => __( 'Footer Block', 'themify' ),
		),
		array(
			'value' => 'footer-left-col',
			'img'   => 'images/layout-icons/footer-left-col.png',
			'title' => __( 'Footer Left Column', 'themify' ),
		),
		array(
			'value' => 'footer-right-col',
			'img'   => 'images/layout-icons/footer-right-col.png',
			'title' => __( 'Footer Right Column', 'themify' ),
		),
		array(
			'value' => 'footer-horizontal-left',
			'img'   => 'images/layout-icons/footer-horizontal-left.png',
			'title' => __( 'Footer Horizontal Left', 'themify' ),
		),
		array(
			'value' => 'footer-horizontal-right',
			'img'   => 'images/layout-icons/footer-horizontal-right.png',
			'title' => __( 'Footer Horizontal Right', 'themify' ),
		),
		array(
			'value' => 'none',
			'img'   => 'images/layout-icons/none.png',
			'title' => __( 'No Footer ', 'themify' ),
		)
	)); // default, footer-left-col, footer-right-col, footer-horizontal-left, footer-horizontal-right
}

function themify_theme_get_header_design() {
	$header = themify_area_design( 'header', array(
		'default' => '',
		'values'  => wp_list_pluck( themify_theme_header_design_options(), 'value' ),
	) );
	return 'none' === $header ? 'header-none' : $header;
}

if ( ! function_exists( 'themify_theme_body_class' ) ) {
	/**
	 * Adds body classes for special theme features.
	 *
	 * @since 1.0.0
	 *
	 * @param $classes
	 *
	 * @return array
	 */
	function themify_theme_body_class( $classes ) {
		
		$header = themify_theme_get_header_design();
		$classes[] = $header;
		$classes[] = themify_theme_fixed_header() ? 'fixed-header' : 'no-fixed-header'; 
		$classes[] = themify_theme_shrinking_logo() ? 'shrinking-logo' : 'no-shrinking-logo';

		if ( ! in_array( $header, array( 'header-leftpane', 'header-rightpane', 'header-minbar', 'header-none' ) ) ) {
			// Add transparent-header class to body if user selected it in custom panel
			if ( ( is_single() || is_page() || themify_is_shop() ) && 'transparent' == themify_get( 'header_wrap' ) ) {
				$classes[] = 'transparent-header';
			}
		}
		if ( 'header-block' == $header && 'yes' == themify_theme_get( 'full_height_header' ) ) {
			$classes[] = 'header-full-height';
		}

		// Footer Design
		$footer = themify_area_design( 'footer', array(
			'default' => '',
			'values'  => wp_list_pluck( themify_theme_footer_design_options(), 'value' ),
		) );
		$classes[] = 'none' == $footer ? 'footer-none' : $footer;

		// Theme Color
		$color = themify_area_design( 'color', array(
			'default' => '',
			'values'  => wp_list_pluck( themify_theme_color_design_options(), 'value' ),
		) );
		$classes[] = $color;

		// Typography
		$font = themify_area_design( 'font', array(
			'default' => '',
			'values'  => wp_list_pluck( themify_theme_font_design_options(), 'value' ),
		) );
		$classes[] = $font;

		// Exclusion classes
		if ( ! themify_theme_show_area( 'site_logo' ) ) {
			$classes[] = 'logo-off';
		}
		if ( ! themify_theme_show_area( 'site_tagline' ) ) {
			$classes[] = 'tagline-off';
		}
		if ( ! themify_theme_show_area( 'social_widget' ) ) {
			$classes[] = 'social-widget-off';
		}
		if ( ! themify_theme_show_area( 'rss' ) ) {
			$classes[] = 'rss-off';
		}
		if ( ! themify_theme_show_area( 'search_form' ) ) {
			$classes[] = 'search-off';
		}
		if ( ! themify_theme_show_area( 'menu_navigation' ) ) {
			$classes[] = 'menu-navigation-off';
		}
		if ( ! themify_theme_show_area( 'footer' ) ) {
			$classes[] = 'footer-off';
		}
		if ( ! themify_theme_show_area( 'header_widgets' ) ) {
			$classes[] = 'header-widgets-off';
		}
		if ( ! themify_theme_show_area( 'footer_widgets' ) ) {
			$classes[] = 'footer-widgets-off';
		}
		if ( ! themify_theme_show_area( 'footer_menu_navigation' ) ) {
			$classes[] = 'footer-menu-navigation-off';
		}
				
		// Image Filters
		$filter = '';
		$filter_hover = '';
		$apply_to = '';
		global $themify;
		if ( is_page() || themify_is_shop() ) {

			if ( $do_filter = themify_get( 'imagefilter_options' ) ) {
				if ( 'initial' !== $do_filter ) {
					$filter = 'filter-' . $do_filter;
				}
			}

			if ( $do_hover_filter = themify_get( 'imagefilter_options_hover' ) ) {
				if ( 'initial' !== $do_hover_filter ) {
					$filter_hover = 'filter-hover-' . $do_hover_filter;
				}
			}

			if ( $apply_here = themify_get( 'imagefilter_applyto' ) ) {
				if ( 'initial' !== $apply_here ) {
					$apply_to = 'filter-' . $apply_here;
				}
			}

		} elseif ( is_singular() ) {

			if ( $do_filter = themify_get( 'imagefilter_options' ) ) {
				if ( 'initial' !== $do_filter ) {
					$filter = 'filter-' . $do_filter;
				}
			}

			if ( $do_hover_filter = themify_get( 'imagefilter_options_hover' ) ) {
				if ( 'initial' !== $do_hover_filter ) {
					$filter_hover = 'filter-hover-' . $do_hover_filter;
				}
			}

			if ( $apply_here = themify_get('imagefilter_applyto') ) {
				if ( 'initial' !== $apply_here ) {
					$apply_to = 'filter-' . $apply_here;
				}
			}
			
			$layout = $themify->post_layout_type;
			if (!$layout) {
				$layout = 'default';
			} elseif ($layout === 'split') {
				foreach ($classes as $key => $class) {
					if (false !== stripos($class, 'sidebar')) {
						unset($classes[$key]);
					}
				}
				$classes[] = 'sidebar-none';
			}
			$classes[] = 'single-' . $layout . '-layout';
		}
                if ($themify->post_layout === 'auto_tiles' && ($k=array_search($themify->post_layout, $classes))!==false) {
                        unset($classes[$k]);
                }
		if ( '' == $filter ) {
			if ( $do_filter = themify_get( 'setting-imagefilter_options' ) ) {
				$filter = 'filter-' . $do_filter;
			}
		}

		if ( '' == $filter_hover ) {
			if ( $do_hover_filter = themify_get( 'setting-imagefilter_options_hover' ) ) {
				$filter_hover = 'filter-hover-' . $do_hover_filter;
			} else {
				$filter_hover = 'filter-hover-none';
			}
		}

		if ( '' == $apply_to ) {
			if ( '' != $filter || '' != $filter_hover ) {
				if ( 'allimages' == themify_get('setting-imagefilter_applyto') ) {
					$apply_to = 'filter-all';
				} else {
					$apply_to = 'filter-featured-only';
				}
			}
		}
                $classes[] = themify_is_touch('phone') ? 'is_phone' : 'tile_enable';
		$classes[] = $filter;
		$classes[] = $filter_hover;
		$classes[] = $apply_to;

		// Check if masonry is enabled
		$classes[] = $themify->post_layout_type === 'gallery' ? 'masonry-enabled' : themify_theme_is_masonry_enabled();
		if ( is_page() && themify_theme_is_fullpage_scroll() ) {
			$classes[] = 'query-section';
			$classes[] = 'full-section-scrolling';
			// Add loading animation
			add_action( 'themify_content_start', 'themify_theme_add_section_loader' );
		}
		// Skin Styles
		if ( '' != themify_get( 'body_background_color' ) || '' != themify_get( 'body_background_image' ) || '' != themify_get( 'body_font' ) || '' != themify_get( 'body_text_color' ) || '' != themify_get( 'body_link_color' ) || '' != themify_get( 'heading_font' ) || '' != themify_get( 'heading_color' ) || '' != themify_get( 'scheme_background' ) || '' != themify_get( 'scheme_color' ) ) {
			$classes[] = 'skin-styles';
		}
		return $classes;
	}
}

/**
 * Adds page loading animation
 *
 * @since 1.3.6
 */
function themify_theme_add_section_loader() {
	$color = themify_get_color('setting-page_loader_color');
	$icon = themify_get('setting-page_loader_icon');
	$cl = $bg = '';
	if($icon){
		if(strpos($icon,'fa-')===0){
			$cl = ' fa '.$icon;
		}
		else{
			$bg = 'background:url('.$icon.') center/cover no-repeat';
		}
	}
	?>
	<div class="section_loader"<?php echo $color?'style="background-color:'.$color.'"':''?>>
			<div <?php echo $bg?'style="'.$bg.'"':'';?> class="section_spinner<?php echo $cl?>"></div>
	</div>
	<?php
}

/**
 * Checks if masonry is enabled in this query page or in the default index layout settings.
 *
 * @since 1.0.0
 *
 * @return string
 */
function themify_theme_is_masonry_enabled() {
	$do_masonry = '';
	$post_type = '';
	if ( themify_is_query_page() ) {
		global $themify;
		if ( isset($themify->query_post_type) && !in_array( $themify->query_post_type, array( 'post', 'page' ) ) ) {
			$post_type = $themify->query_post_type . '_';
		}
		$enable_masonry = themify_get( $post_type . 'disable_masonry' );
		if ( 'yes' === $enable_masonry ) {
			$do_masonry = 'masonry-enabled';
		} elseif ( 'default' === $enable_masonry || '' == $enable_masonry ) {
			if ( 'no' !== themify_get( 'setting-' . $post_type . 'disable_masonry' ) ) {
				$do_masonry = 'masonry-enabled';
			}
		}
	} else {
		if ( ! is_search() ) {
			$post_type = in_array( get_post_type(), apply_filters( 'themify_post_type_uses_post_masonry_setting', array( 'post', 'product' ) ) ) ? '' : get_post_type() . '_';
		}
		if ( 'no' !== themify_get( 'setting-' . $post_type . 'disable_masonry' ) ) {
			$do_masonry = 'masonry-enabled';
		}
	}
	return $do_masonry;
}

if ( ! function_exists( 'themify_theme_show_area' ) ) {
	/**
	 * Checks whether to show a certain layout area or not.
	 *
	 * @param string $area
	 *
	 * @return bool
	 */
	function themify_theme_show_area( $area = '' ) {
		$show = true;
		switch ( $area ) {
			case 'header':
				$show = 'none' === themify_area_design( $area, array( 'values'  => wp_list_pluck( themify_theme_header_design_options(), 'value' ) ) ) ? false : true;
				break;
			case 'footer':
				$show = 'none' === themify_area_design( $area, array( 'values'  => wp_list_pluck( themify_theme_footer_design_options(), 'value' ) ) ) ? false : true;
				break;
			default:
				if ( ( is_singular() && ! is_attachment() ) || themify_is_shop() ) {
					$exclude = themify_get( 'exclude_' . $area );
					if ( 'yes' === $exclude ) {
						$show = false;
					} elseif ( 'no' === $exclude ) {
						$show = true;
					} else {
						$show = themify_check( 'setting-exclude_' . $area ) ? false : true;
					}
				} elseif ( themify_check( 'setting-exclude_' . $area ) ) {
					$show = false;
				}
				break;
		}

		return apply_filters( "themify_theme_show_{$area}", $show );
	}
}

if ( ! function_exists( 'themify_theme_do_not_exclude_all' ) ) {
	/**
	 * Checks if all the elements in a certain area have been excluded.
	 *
	 * @since 1.0.0
	 *
	 * @param string $area
	 *
	 * @return bool
	 */
	function themify_theme_do_not_exclude_all( $area = 'header' ) {
		if ( 'mobile-menu' === $area ) {
			return themify_theme_show_area( 'search_form' ) || themify_theme_show_area( 'social_widget' ) || themify_theme_show_area( 'header_widgets' ) || themify_theme_show_area( 'rss' ) || themify_theme_show_area( 'menu_navigation' );
		} elseif ( 'header' === $area ) {
			return themify_theme_show_area( 'site_logo' ) || themify_theme_show_area( 'site_tagline' ) || themify_theme_show_area( 'search_form' ) || themify_theme_show_area( 'social_widget' ) || themify_theme_show_area( 'header_widgets' ) || themify_theme_show_area( 'rss' ) || themify_theme_show_area( 'menu_navigation' );
		} elseif ( 'footer' === $area ) {
			return themify_theme_show_area( 'footer_site_logo' ) || themify_theme_show_area( 'footer_menu_navigation' ) || themify_theme_show_area( 'footer_texts' ) || themify_theme_show_area( 'footer_widgets' ) || themify_theme_show_area( 'footer_back' );
		}
		return false;
	}
}
if (!function_exists('themify_get_gallery_param_option')) {

	/**
	 * Get gallery shortcode options
	 * @param $shortcode
	 * @param $param
	 */
	function themify_get_gallery_param_option($shortcode, $param = 'link') {
		$pattern = '/\[gallery .*?(?=' . $param . ')' . $param . '=.([^\']+)./si';
		preg_match($pattern, $shortcode, $out);

		$out = isset($out[1]) ? explode('"', $out[1]) : array('');
		return $out[0];
	}

}

if (!function_exists('themify_get_images_from_gallery_shortcode')) {

	/**
	 * Get images from gallery shortcode
	 * @return object
	 */
	function themify_get_images_from_gallery_shortcode($shortcode) {
		preg_match('/\[gallery.*ids=.(.*).\]/', $shortcode, $ids);
		$image_ids = explode(",", $ids[1]);
		$orderby = themify_get_gallery_param_option($shortcode, 'orderby');
		$orderby = $orderby != '' ? $orderby : 'post__in';
		$order = themify_get_gallery_param_option($shortcode, 'order');
		$order = $order != '' ? $order : 'ASC';

		// Check if post has more than one image in gallery
		return get_posts(array(
			'post__in' => $image_ids,
			'post_type' => 'attachment',
			'post_mime_type' => 'image',
			'numberposts' => -1,
			'orderby' => $orderby,
			'order' => $order
		));
	}

}

/**
 * Set the fixed-header selector for the scroll highlight script
 *
 * @since 1.0.0
 */
function themify_theme_scroll_highlight_vars( $vars ) {
	$vars['fixedHeaderSelector'] = '#headerwrap.fixed-header';
	return $vars;
}
add_filter( 'themify_builder_scroll_highlight_vars', 'themify_theme_scroll_highlight_vars' );

/**
 * Custom Post Type Background Gallery
 */
class Themify_Background_Gallery{

	function __construct(){}

	function create_controller(){
		/** ID of default background gallery
		 * @var String|Number */
		$bggallery_id = $this->get_bggallery_id();
		$bggallery_order = $this->get_bggallery_order();

		$bggallery_enable = themify_get( 'header_wrap' ) === 'slider' && themify_get( 'background_gallery', '' ) != '';

		// If we still don't have a background gallery ID, do nothing.
		if( !$bggallery_id || 'default' == $bggallery_id || !$bggallery_enable ) {
			return;
		}

		$images = get_posts(array(
			'post__in' => $bggallery_id,
			'post_type' => 'attachment',
			'post_mime_type' => 'image',
			'numberposts' => -1,
			'orderby' => $bggallery_order,
			'order' => 'ASC'
		));

		if ( $images ) {
			wp_enqueue_script( 'header-slider' );
			$hide_controlls = get_post_meta( get_queried_object_id(), 'header_hide_controlls', true ) === 'on'
				? 'class="tf-hide"' : '';
				echo '
				<div id="gallery-controller" ' . $hide_controlls . '>
					<div class="slider">
						<ul class="slides clearfix">';
				foreach( $images as $image ){
					// Get large size for background
					$image_data = wp_get_attachment_image_src( $image->ID, apply_filters( 'themify_theme_background_gallery_image_size', 'large' ) );
					echo '<li data-bg="',$image_data[0],'"><span class="slider-dot"></span></li>';
				}
				echo '		</ul>
							<div class="carousel-nav-wrap">
								<a href="#" class="carousel-prev" style="display: block; ">&lsaquo;</a>
								<a href="#" class="carousel-next" style="display: block; ">&rsaquo;</a>
							</div>

					</div>
				</div>
				<!-- /gallery-controller -->';
		}
	}

	/**
	 * Return the background gallery ID if one of the following is found:
	 * - bg gallery defined in theme settings
	 * - bg gallery defined in Themify custom panel, either in post or page
	 * @return String|Mixed Background Gallery ID or 'default'
	 */
	function get_bggallery_id() {
		$gallery_raw = '';

		$gallery_raw = themify_get( 'background_gallery' );

		$sc_gallery = preg_replace( '#\[gallery(.*)ids="([0-9|,]*)"(.*)\]#i', '$2', $gallery_raw );

		$image_ids = explode( ',', str_replace( ' ', '', $sc_gallery ) );

		return $image_ids;
	}

	function get_bggallery_order() {
		$sc_order = false;

		$gallery_raw = themify_get( 'background_gallery' );

		if ( strpos( $gallery_raw, 'orderby' ) !== false ) {
			$sc_order = preg_replace('#\[gallery(.*)orderby="([a-zA-Z0-9]*)"(.*)\]#i', '$2', $gallery_raw);
		}

		return $sc_order ? $sc_order : 'post__in';
	}
}
// Start Background Gallery
$GLOBALS['themify_bg_gallery'] = new Themify_Background_Gallery();

/**
 * Outputs classes based on certain user-specified parameters.
 *
 * @since 1.0.0
 */
function themify_theme_query_classes() {
	global $themify;
	$class = array();

	$class[] = $themify->layout;
	$class[] = $themify->post_layout;

	$is_portfolio = is_post_type_archive( 'portfolio' ) || is_tax('portfolio-category');

	$is_masonry = themify_get( $is_portfolio ? 'portfolio_disable_masonry' : 'disable_masonry' );
	$is_masonry = ! empty( $is_masonry ) ? $is_masonry : themify_get( $is_portfolio ? 'setting-portfolio_disable_masonry' : 'setting-disable_masonry' );

	if ( isset( $themify->query_post_type ) && ! in_array( $themify->query_post_type, array( 'post', 'page' ) ) ) {
		$class[] = $themify->query_post_type;
	}
	
	if ( themify_is_query_page() || is_archive() || is_search() || is_tax() || is_home() ) {
		if ( $themify->post_layout_type ) {
			$class[] = $themify->post_layout_type;
		}
		if ( 'yes' === $is_masonry && ! in_array( $themify->post_layout, array( 'list-post','slider','auto_tiles' ) ) || ( isset( $themify->page_id ) && 'yes' === themify_get( 'disable_masonry' ) ) ) {
			$class[] = 'masonry';
		}
		if ( 'no-gutter' === themify_get( $is_portfolio ? 'setting-portfolio_gutter' : 'setting-post_gutter' ) ) {
			$class[] = 'no-gutter';
		}
		if ( $temp_class = themify_theme_get( 'more_posts', 'infinite' ) ) {
			if ( 'slider' !== $themify->post_layout ) {
				$class[] = $temp_class;
			}
		}
	}

	return implode( ' ', apply_filters( 'themify_theme_loops_wrapper_class', $class ) );
}

/**
 * Outputs datas for slider.
 *
 * @since 1.0.0
 */
function themify_theme_maybe_add_slider_datas() {
	global $themify;
	$datas = '';
	if ( 'slider' === $themify->post_layout ) {
		$datas .= 'data-id="loops-wrapper" data-autoplay="off" data-speed="1000" data-effect="scroll" data-visible="3"';
	}
	return $datas;
}

/**
 * Function that checks if meta data exists and retrieves it, otherwise checks theme setting and retrieves it instead.
 * If it still doesn't exist, uses the default provided.
 *
 * @since 1.0.0
 *
 * @param string $meta
 * @param string $default
 * @param string $theme_setting
 *
 * @return mixed
 */
function themify_theme_get( $meta, $default = '', $theme_setting = '' ) {
	global $themify;
	$post_type = '';

	// If it's a singular view or a query page, try to get the post meta data first
	if ( themify_is_query_page() ) {
		// Let's check now prefixing with post type since it's a query post type page
			// Check without checking for custom post type
			$value = get_post_meta( $themify->page_id, $meta, true );
		if ( '' != $themify->query_post_type && 'post' !== $themify->query_post_type ) {
			$post_type = $themify->query_post_type . '_';
			$cpt_meta = $post_type . $meta;
			$value = get_post_meta( $themify->page_id, $cpt_meta, true );
		} else {
		}
		if ( $value  && 'default' !== $value ) {
			return $value;
		}

	} elseif ( is_singular() ) {
		// Check first without checking for custom post type
		$value = get_post_meta( get_the_ID(), $meta, true );

		if ( $value  && 'default' !== $value ) {
			return $value;
		}
		// Let's check now prefixing with post type
		if ( ( 'post' !== get_post_type() && 'page' !==get_post_type() ) ) {
			$post_type = get_post_type() . '_';
		}
		$cpt_meta = $post_type . $meta;
		$value = get_post_meta( get_the_ID(), $cpt_meta, true );
		if ( $value && 'default' !== $value ) {
			return $value;
		}
	} elseif( themify_is_shop() ) {
		return themify_get( $meta, $default );
	}

	// If there is no post meta data or is '' (default), prepare to fetch theme setting
	if ( empty( $theme_setting ) ) {
		if ( themify_is_query_page() && '' != $themify->query_post_type && 'post' != $themify->query_post_type ) {
			$post_type = $themify->query_post_type . '_';
		} elseif ( is_singular() && ( 'post' != get_post_type() && 'page' != get_post_type() ) ) {
			$post_type = get_post_type() . '_';
		}
		$theme_setting = 'setting-' . $post_type . $meta;
	}

	// Check theme setting (if there's a special setting like for portfolios it will be checked)
	if ( themify_check( $theme_setting ) ) {
		return themify_get( $theme_setting );
	}

	// Prepare to check non special setting stripping out the post type from setting key
	if ( 'post' != $post_type ) {
		$theme_setting = str_replace( $post_type, '', $theme_setting );
	}
	// Check regular setting (like portfolios that rely in default layouts setting)
	if ( themify_check( $theme_setting ) ) {
		return themify_get( $theme_setting );
	}
	// No luck so return default
	return $default;
}

/**
 * Load pagination for shop. Hooked to 'woocommerce_after_shop_loop' at priority 10.
 *
 * @since 1.0.0
 */
function themify_theme_shop_pagination() {
	get_template_part( 'includes/pagination');
}

/**
 * Checks if the sidebars in a group have widgets or not.
 *
 * @since 1.0.0
 *
 * @param string $sidebar_prefix Prefix for sidebars.
 * @param array $areas Areas to check.
 *
 * @return bool
 */
function themify_theme_has_widgets( $sidebar_prefix, $areas ) {
	$x = 0;
	foreach ( $areas as $col ) {
		$x++;
		if ( is_active_sidebar( $sidebar_prefix . $x ) ) {
			return true;
		}
	}
	return false;
}

/**
 * Tweak offset so fixed header remains in place when scrolling to a section at the top of everything.
 *
 * @since 1.0.5
 *
 * @param array $vars JavaScript variables for scroll/highlight script.
 *
 * @return array
 */
function themify_theme_builder_scroll_highlight_vars( $vars ) {
	$vars['scrollOffset'] = -5;
	return $vars;
}
add_filter( 'themify_builder_scroll_highlight_vars', 'themify_theme_builder_scroll_highlight_vars' );

/** Compatibility with portfolio posts plugin */
define( 'THEMIFY_PORTFOLIO_POSTS_COMPAT_MODE', true );

/* load the TGMPA library */
if( is_admin() ) {
	require_once THEMIFY_DIR . '/class-tgm-plugin-activation.php';
}

/**
 * Register plugins required for the theme
 *
 * @since 1.0.0
 */
function themify_theme_register_required_plugins() {
	$plugins = array(

		// This is an example of how to include a plugin pre-packaged with a theme.
		array(
			'name'               => __( 'Themify Portfolio Posts', 'themify' ),
			'slug'               => 'themify-portfolio-post',
			'source'             => 'https://themify.me/files/themify-portfolio-post/themify-portfolio-post.zip',
			'required'           => true,
			'version'            => '1.0.0',
			'force_activation'   => false,
			'force_deactivation' => false,
		),

	);

	/**
	 * Array of configuration settings. Amend each line as needed.
	 * If you want the default strings to be available under your own theme domain,
	 * leave the strings uncommented.
	 * Some of the strings are added into a sprintf, so see the comments at the
	 * end of each line for what each argument will be.
	 */
	$config = array(
		'default_path' => '',                      // Default absolute path to pre-packaged plugins.
		'menu'         => 'themify-install-plugins', // Menu slug.
		'has_notices'  => true,                    // Show admin notices or not.
		'dismissable'  => true,                    // If false, a user cannot dismiss the nag message.
		'dismiss_msg'  => '',                      // If 'dismissable' is false, this message will be output at top of nag.
		'is_automatic' => false,                   // Automatically activate plugins after installation or not.
		'message'      => '',                      // Message to output right before the plugins table.
		'strings'      => array(
			'page_title'                      => __( 'Install Required Plugins', 'themify' ),
			'menu_title'                      => __( 'Install Plugins', 'themify' ),
			'installing'                      => __( 'Installing Plugin: %s', 'themify' ), // %s = plugin name.
			'oops'                            => __( 'Something went wrong with the plugin API.', 'themify' ),
			'notice_can_install_required'     => _n_noop( 'This theme requires the following plugin: %1$s.', 'This theme requires the following plugins: %1$s.', 'themify' ), // %1$s = plugin name(s).
			'notice_can_install_recommended'  => _n_noop( 'This theme recommends the following plugin: %1$s.', 'This theme recommends the following plugins: %1$s.', 'themify' ), // %1$s = plugin name(s).
			'notice_cannot_install'           => _n_noop( 'Sorry, but you do not have the correct permissions to install the %s plugin. Contact the administrator of this site for help on getting the plugin installed.', 'Sorry, but you do not have the correct permissions to install the %s plugins. Contact the administrator of this site for help on getting the plugins installed.', 'themify' ), // %1$s = plugin name(s).
			'notice_can_activate_required'    => _n_noop( 'The following required plugin is currently inactive: %1$s.', 'The following required plugins are currently inactive: %1$s.', 'themify' ), // %1$s = plugin name(s).
			'notice_can_activate_recommended' => _n_noop( 'The following recommended plugin is currently inactive: %1$s.', 'The following recommended plugins are currently inactive: %1$s.', 'themify' ), // %1$s = plugin name(s).
			'notice_cannot_activate'          => _n_noop( 'Sorry, but you do not have the correct permissions to activate the %s plugin. Contact the administrator of this site for help on getting the plugin activated.', 'Sorry, but you do not have the correct permissions to activate the %s plugins. Contact the administrator of this site for help on getting the plugins activated.', 'themify' ), // %1$s = plugin name(s).
			'notice_ask_to_update'            => _n_noop( 'The following plugin needs to be updated to its latest version to ensure maximum compatibility with this theme: %1$s.', 'The following plugins need to be updated to their latest version to ensure maximum compatibility with this theme: %1$s.', 'themify' ), // %1$s = plugin name(s).
			'notice_cannot_update'            => _n_noop( 'Sorry, but you do not have the correct permissions to update the %s plugin. Contact the administrator of this site for help on getting the plugin updated.', 'Sorry, but you do not have the correct permissions to update the %s plugins. Contact the administrator of this site for help on getting the plugins updated.', 'themify' ), // %1$s = plugin name(s).
			'install_link'                    => is_multisite() ? _n_noop( '', '', 'themify' ) : _n_noop( 'Begin installing plugin', 'Begin installing plugins', 'themify' ),
			'activate_link'                   => _n_noop( 'Begin activating plugin', 'Begin activating plugins', 'themify' ),
			'return'                          => __( 'Return to Required Plugins Installer', 'themify' ),
			'plugin_activated'                => __( 'Plugin activated successfully.', 'themify' ),
			'complete'                        => __( 'All plugins installed and activated successfully. %s', 'themify' ), // %s = dashboard link.
			'nag_type'                        => 'updated' // Determines admin notice type - can only be 'updated', 'update-nag' or 'error'.
		)
	);

	tgmpa( $plugins, $config );
	add_action( 'admin_menu', 'themify_theme_required_plugins_admin_menu', 11 );
}
add_action( 'tgmpa_register', 'themify_theme_register_required_plugins' );

/**
 * Relocate the tgmpa admin menu under Themify
 *
 * @since 1.0.0
 */
function themify_theme_required_plugins_admin_menu() {
	// Make sure privileges are correct to see the page
	if ( ! current_user_can( 'install_plugins' ) ) {
		return;
	}

	TGM_Plugin_Activation::get_instance()->populate_file_path();

	foreach ( TGM_Plugin_Activation::get_instance()->plugins as $plugin ) {
		if ( ! is_plugin_active( $plugin['file_path'] ) ) {
			add_submenu_page( 'themify', __( 'Install Plugins', 'themify' ), __( 'Install Plugins', 'themify' ), 'manage_options', 'themify-install-plugins', array( TGM_Plugin_Activation::get_instance(), 'install_plugins_page' ) );
			break;
		}
	}
}

/**
 * Fix issue with tgmpa and WP multisite
 *
 * @since 1.0.0
 */
function themify_theme_tgmpa_mu_fix( $links ) {
	if( is_multisite() ) {
		$links['install'] = __( 'Auto plugin installation is not support in WordPress multisite. To install this plugin: go to Network Admin > Plugins > Add New (the plugin zip is included in the theme folder > plugins > folder).', 'themify' );
	}

	return $links;
}
add_filter( 'tgmpa_notice_action_links', 'themify_theme_tgmpa_mu_fix' );

/**
 * Hide plugin activation link on WP Multisite
 */
function themify_theme_tgmpa_mu_hide_activate_link() {
	global $hook_suffix;

	if($hook_suffix === 'appearance_page_themify-install-plugins' && is_multisite()  ) {
		echo '<style>.plugins .row-actions { display: none !important; }</style>';
	}
}
add_filter( 'admin_head', 'themify_theme_tgmpa_mu_hide_activate_link' );

/**
 * Set portfolio post type slug
 *
 * @since 1.1.0
 * @return string
 */
function themify_theme_portfolio_post_rewrite( $id ) {
	$slug = themify_get( 'themify_portfolio_slug' );
	return empty( $slug ) ? apply_filters( 'themify_portfolio_rewrite', 'project' ) : $slug;
}
add_filter( 'themify_portfolio_post_rewrite', 'themify_theme_portfolio_post_rewrite' );


function themify_theme_announcement_bar_script_vars( $vars ) {
	$header_design = themify_theme_get_header_design();
	if( $header_design === 'header-minbar' ) {
		$vars['margin_top_to_bar_height'] = 'null';
	} elseif( $header_design === 'header-leftpane' ) {
		$vars['margin_top_to_bar_height'] = '#header'; // @todo: the scroll bar fails to calculate the height
	} elseif( $header_design === 'header-slide-out' ) {
		$vars['margin_top_to_bar_height'] = '#header';
	} elseif( $header_design === 'boxed-compact' ) {
		$vars['margin_top_to_bar_height'] = 'body';
	} else {
		$vars['margin_top_to_bar_height'] = 'body';
	}

	return $vars;
}
add_filter( 'announcement_bar_script_vars', 'themify_theme_announcement_bar_script_vars' );

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

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

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

	return true;
}
add_filter( 'themify_builder_fullwidth_layout_support', 'themify_theme_fullwidth_layout_condition', 20 );

/**
 * Disable both Widgets and Menus manager in Customizer screen, when using Advanced mode
 * to make the screen lighter
 *
 * @since 1.1.5
 */
function themify_customizer_disable_menus_and_widgets() {
	global $wp_customize, $themify_customizer;

	if( isset( $wp_customize ) && $themify_customizer->is_advanced_mode() ) {
		/**
		 * Disable widgets manager in Customizer
		 * original hooks located in wp-includes/class-wp-customize-widgets.php
		 */
		remove_filter( 'customize_dynamic_setting_args',          array( $wp_customize->widgets, 'filter_customize_dynamic_setting_args' ), 10, 2 );
		remove_action( 'after_setup_theme',                       array( $wp_customize->widgets, 'register_settings' ) );
		remove_action( 'wp_loaded',                               array( $wp_customize->widgets, 'override_sidebars_widgets_for_theme_switch' ) );
		remove_action( 'customize_controls_init',                 array( $wp_customize->widgets, 'customize_controls_init' ) );
		remove_action( 'customize_register',                      array( $wp_customize->widgets, 'schedule_customize_register' ), 1 );
		// Review this line
		//remove_action( 'customize_controls_enqueue_scripts',      array( $wp_customize->widgets, 'enqueue_scripts' ) );
		remove_action( 'customize_controls_print_styles',         array( $wp_customize->widgets, 'print_styles' ) );
		remove_action( 'customize_controls_print_scripts',        array( $wp_customize->widgets, 'print_scripts' ) );
		remove_action( 'customize_controls_print_footer_scripts', array( $wp_customize->widgets, 'print_footer_scripts' ) );
		remove_action( 'customize_controls_print_footer_scripts', array( $wp_customize->widgets, 'output_widget_control_templates' ) );
		remove_action( 'customize_preview_init',                  array( $wp_customize->widgets, 'customize_preview_init' ) );
		remove_filter( 'customize_refresh_nonces',                array( $wp_customize->widgets, 'refresh_nonces' ) );

		/**
		 * Disable Menus manager in Customizer
		 * original hooks located in wp-includes/class-wp-customize-nav-menus.php
		 */
		remove_action( 'customize_controls_enqueue_scripts', array( $wp_customize->nav_menus, 'enqueue_scripts' ) );
		remove_action( 'customize_register', array( $wp_customize->nav_menus, 'customize_register' ), 11 );
		remove_filter( 'customize_dynamic_setting_args', array( $wp_customize->nav_menus, 'filter_dynamic_setting_args' ), 10, 2 );
		remove_filter( 'customize_dynamic_setting_class', array( $wp_customize->nav_menus, 'filter_dynamic_setting_class' ), 10, 3 );
		remove_action( 'customize_controls_print_footer_scripts', array( $wp_customize->nav_menus, 'print_templates' ) );
		remove_action( 'customize_controls_print_footer_scripts', array( $wp_customize->nav_menus, 'available_items_template' ) );
		remove_action( 'customize_preview_init', array( $wp_customize->nav_menus, 'customize_preview_init' ) );
	}
}
add_action( 'init', 'themify_customizer_disable_menus_and_widgets' );

// Load Themify Mega Menu
add_theme_support( 'themify-mega-menu' );

if ( ! function_exists( 'themify_theme_hex2rgb' ) ) {
	/**
	 * Convert Hex color to RGB color.
	 *
	 * @since 1.2.8
	 * @param string $hex
	 * @return string
	 */
	function themify_theme_hex2rgb( $hex ) {
		$hex = str_replace("#", "", $hex);

		if (strlen($hex) == 3) {
			$r = hexdec(substr($hex, 0, 1) . substr($hex, 0, 1));
			$g = hexdec(substr($hex, 1, 1) . substr($hex, 1, 1));
			$b = hexdec(substr($hex, 2, 1) . substr($hex, 2, 1));
		} else {
			$r = hexdec(substr($hex, 0, 2));
			$g = hexdec(substr($hex, 2, 2));
			$b = hexdec(substr($hex, 4, 2));
		}
		return implode(',', array($r, $g, $b));
	}
}

/**
 * Color animation effect for rows and header
 *
 * @since 1.2.9
 */
function themify_theme_do_animated_bg() {
	// Set colors for color animation
	$color_key = 'setting-color_stop_';
	$colors = array();
	for ( $i = 1; $i <= 7; $i++ ) {
		if ( themify_check( $color_key . $i ) ) {
			$colors[] = themify_get_color( $color_key . $i );
		}
	}
	// If there are no colors set in theme settings, use default colors
	if ( empty( $colors ) ) {
		$colors = array(
			'#33baab',
			'#e33b9e',
			'#4961d7',
			'#2ea85c',
			'#2bb8ed',
			'#dd5135',
		);
	}

	$selector = array(
		'.themify_builder_row.animated-bg'
	);
	if( themify_check( 'setting-footer_color_animation_enabled' ) ) {
		$selector[] = '#footerwrap';
	}
	if( themify_check( 'setting-header_color_animation_enabled' ) || 'colors' === themify_get( 'header_wrap' ) ) {
		/* when using transparent header or Background option is set, do not use the animated bg */
		if( ! ( themify_check( 'background_color' ) || ( themify_check( 'header_wrap' ) && 'transparent' === themify_get( 'header_wrap' ) ) ) ) {
			$selector[] = '#headerwrap';
		}
	}

	$options = apply_filters( 'themify_animated_bg_params', array(
		'disabled' => themify_check( 'setting-color_animation_disabled' ),
		'selector' => $selector,
		'speed' => themify_check( 'setting-color_animation_speed' ) ? (int) themify_get( 'setting-color_animation_speed' ) * 1000 : '5000',
		'colors' => $colors
	) );

	if( $options['disabled'] )
		return;

	$css_steps = '';
	foreach( $options['colors'] as $key => $val ) {
		$css_steps .= ( $key == 0 ? '0' : 100 / $key ) . '% { background-color: ' . $val . '; }' . "\n";
	}
	$selector = implode( ',', $options['selector'] );
	$speed = $options['speed'] * count( $colors ); // @note: in CSS the speed for the entire duration of the animation, so so we need to multiply the number of slides

	echo"
	<style>
	@-webkit-keyframes themifyAnimatedBG {
		{$css_steps}
	}
	@keyframes themifyAnimatedBG {
		{$css_steps}
	}
	{$selector} {
		-webkit-animation: themifyAnimatedBG {$speed}ms infinite alternate;
		animation: themifyAnimatedBG {$speed}ms infinite alternate;
	}
	</style>
	";
}
add_action( 'wp_head', 'themify_theme_do_animated_bg' );

/**
 * Setup Split Menu layout
 *
 * @since 1.4.4
 */
function themify_theme_setup_split_menu_layout() {
	$header = themify_theme_get_header_design();
	if( 'header-menu-split' !== $header )
		return;

	add_filter( 'themify_theme_show_site_logo', '__return_false' );
	add_filter( 'wp_nav_menu_objects', 'themify_theme_split_menu_wp_nav_menu_objects', 10, 2 );
	add_filter( 'walker_nav_menu_start_el', 'themify_theme_split_menu_add_logo', 10, 4 );
}
add_action( 'template_redirect', 'themify_theme_setup_split_menu_layout' );

/**
 * Add a menu item in the middle of the menu that acts as the placeholder for logo
 *
 * @since 1.4.4
 */
function themify_theme_split_menu_wp_nav_menu_objects( $menu_items, $args ) {
	if( $args->theme_location !== 'main-nav' )
		return $menu_items;

	$copy = $menu_items;

	/* reduce the menu to only top-level menu items */
	foreach( $copy as $key => $item ) {
		if( $item->menu_item_parent != 0 ) {
			unset( $copy[$key] );
		}
	}
        if(!empty($copy)){
            /* get the middle item */
            $middle = floor( count( $copy ) / 2 );

            /* reset the keys */
            $copy = array_values( $copy );

            /* make a fake menu item */
            $new_menu_item = clone $copy[0];
            $new_id = 0;
            $new_menu_item->type = $new_menu_item->object = $new_menu_item->title = $new_menu_item->url = 'custom';
            $new_menu_item->ID = $new_menu_item->post_name = $new_menu_item->db_id = $new_id;
            $new_menu_item->classes = array( 'themify-logo-menu-item' );
            $new_menu_item->themify_logo = true;

            $original_position = $copy[$middle - 1]->menu_order;

            /* inject the new menu item in */
            $menu_items = array_slice( $menu_items, 0, $original_position, true )
                                    + array( $new_menu_item )
                                    + array_slice( $menu_items, $original_position, count( $menu_items ) - 1, true );
        }
	return $menu_items;
}

/**
 * Output logo in the menu when using Menu Split layout
 *
 * @since 1.4.4
 */
if( ! function_exists( 'themify_theme_split_menu_add_logo' ) ) :
function themify_theme_split_menu_add_logo( $item_output, $item, $depth, $args ) {
	if( isset( $item->themify_logo ) ) {
		return themify_logo_image();
	}

	return $item_output;
}
endif;

////////////////////////////////////
// Custom Skin
////////////////////////////////////
add_filter( 'themify_show_skins_and_demos_admin', '__return_true' ); 

/**
* Customize the skins list in the admin screen
*
* @since 1.4.8
*/
function themify_theme_skins_list( $skins ) {
	unset( $skins[0] ); // remove No Skin option

	// set Default as the first choice
	$default = $skins['default'];
	unset( $skins['default'] );
	$skins = array_merge( array( 'default' => $default ), $skins );

	return $skins;
}
add_filter( 'themify_theme_skins', 'themify_theme_skins_list' ); 

/**
 * Allow updating bonus addons for Ultra
 *
 * @since 1.4.8
 */
function themify_theme_bonus_addons_update( $match, $subs ) {
	$theme = wp_get_theme();
	$theme_name = ( is_child_theme() ) ? $theme->parent()->Name : $theme->display('Name');
	$theme_name = preg_replace( '/^Themify\s/', '', $theme_name );
	foreach ( $subs as $key => $value ) {
		if( stripos( $value['title'], $theme_name ) !== false && isset( $_POST['nicename_short'] ) && in_array( $_POST['nicename_short'], array( 'Slider Pro', 'Pricing Table', 'Maps Pro', 'Typewriter', 'Image Pro', 'Timeline', 'WooCommmerce', 'Contact', 'Counter', 'Progress Bar', 'Countdown', 'Audio' ) ) ) {
			$match = 'true';
			break;
		}
	}

	return $match;
}
add_filter( 'themify_builder_validate_login', 'themify_theme_bonus_addons_update', 10, 2 );

/**
 * Template tag to display the page title
 *
 * uses themify_parse_args to filter the $args
 */
function themify_theme_page_title( $args = array() ) {
	extract( themify_parse_args( $args, array(
		'tag' => themify_theme_entry_title_tag( false ),
		'class' => 'page-title',
		'before' => '',
		'after' => '',
		'before_title' => '',
		'after_title' => '',
		'echo' => true,
	), 'page_title' ) );

	the_title( "{$before} <{$tag} class=\"{$class}\">{$before_title}", "{$after_title} </{$tag}>{$after}", $echo );
}

// WooCommerce additional options

/**
 * Alters condition to filter layout class
 * @param bool
 * @return bool
 */
function themify_theme_default_layout_condition($condition){
	return $condition || themify_is_shop() || themify_is_function('is_product') || themify_is_function('is_product_category') || themify_is_function('is_product_tag');
}
/**
 * Returns default shop layout
 * @param String $class
 * @return @String
 */
function themify_theme_default_layout($class) {
	if( themify_is_shop() || themify_is_function('is_product_category') || themify_is_function('is_product_tag') ) {
		$class = themify_get('setting-shop_layout')? themify_get('setting-shop_layout') : 'sidebar1';
	} elseif( themify_is_function('is_product') ){
		$class = themify_get('setting-single_product_layout')? themify_get('setting-single_product_layout') : 'sidebar1';
	}
	return $class;
}
/**
 * Alters condition to filter post layout class
 * @param bool
 * @return bool
 */
function themify_theme_default_post_layout_condition($condition) {
	return $condition || themify_is_shop() || themify_is_function('is_product_category') || themify_is_function('is_product_tag');
};
/**
 * Returns default shop layout
 * @param String $class
 * @return @String
 */
function themify_theme_default_post_layout($class) {
	if( themify_is_shop() || themify_is_function('is_product_category') || themify_is_function('is_product_tag') ) {
		$class = '' != themify_get('setting-products_layout')? themify_get('setting-products_layout') : 'grid4';
	}
	return $class;
};

/**
 * Checks if it's the function name passed exists and in that case, it calls the function
 * @param string $context
 * @return bool|mixed
 * @since 1.3.1
 */
function themify_is_function( $context = '' ) {
	if( function_exists( $context ) )
		return call_user_func( $context );
	else
		return false;
}

// Filters to change body class applied in shop
add_filter('themify_default_layout_condition', 'themify_theme_default_layout_condition');
add_filter('themify_default_layout', 'themify_theme_default_layout');
add_filter('themify_default_post_layout_condition', 'themify_theme_default_post_layout_condition');
add_filter('themify_default_post_layout', 'themify_theme_default_post_layout');

///////////////////////////////////////
// Start Woocommerce functions
///////////////////////////////////////

// Declare Woocommerce support
if( themify_is_woocommerce_active() ) {
	add_theme_support( 'woocommerce' );
}

add_action( 'template_redirect', 'themify_redirect_product_ajax_content', 20 );

add_filter('woocommerce_params', 'themify_woocommerce_params');

if ( ! function_exists( 'themify_get_ecommerce_template' ) ) {
	/**
	 * Checks if Woocommerce is active and loads the requested template
	 * @param string $template
	 * @since 1.3.1
	 */
	function themify_get_ecommerce_template( $template = '' ) {
		if ( themify_is_woocommerce_active() )
			get_template_part( $template );
	}
}

/**
 * Add woocommerce_enable_ajax_add_to_cart option to JS
 * @param Array
 * @return Array
 */
function themify_woocommerce_params($params){
	return array_merge($params, array(
		'option_ajax_add_to_cart' => ( 'yes' == get_option('woocommerce_enable_ajax_add_to_cart') )? 'yes': 'no'
	) );
}

/**
 * Single product lightbox
 **/
function themify_redirect_product_ajax_content() {
	global $post, $wp_query;
	// locate template single page in lightbox
	if (is_single() && isset($_GET['ajax']) && $_GET['ajax']) {
		// remove admin bar inside iframe
		add_filter( 'show_admin_bar', '__return_false' );
		if (have_posts()) {
			woocommerce_single_product_content_ajax();
			die();
		} else {
			$wp_query->is_404 = true;
		}
	}
}

// Load required files
if ( themify_is_woocommerce_active() ) {
	require_once(TEMPLATEPATH . '/woocommerce/theme-woocommerce.php'); // WooCommerce overrides
	require_once(TEMPLATEPATH . '/woocommerce/woocommerce-hooks.php'); // WooCommerce hook overrides
	require_once(TEMPLATEPATH . '/woocommerce/woocommerce-template.php'); // WooCommerce template overrides
}

// Add specific CSS class by filter.
function themify_theme_slide_cart_body_class( $classes ) {
	if ( themify_is_woocommerce_active() ) {
		$classes[] = 'slide-cart';
	}

	return $classes;
}
add_filter( 'body_class', 'themify_theme_slide_cart_body_class' );


//date format
function themify_date_format(){
    static $date_format = array();
    if(empty($date_format)){
        $format = get_option( 'date_format' );
        $date_items = array('Y'=>'year',
                            'y'=>'year',
                            'm'=>'month',
                            'M'=>'month',
                            'n'=>'month',
                            'F'=>'month',
                            'd'=>'day',
                            'j'=>'day',
                            's'=>'day'
                            );
        foreach($date_items as $i=>$k){
            if(($pos=strpos($format,$i))!==false){
                $date_format[$pos] = array($i,$k);
            }
        }
        ksort ($date_format);
    }
    return $date_format;
}

/**
 * Deprecated function, kept for backwards compatibility
 */
function themify_theme_menu_nav() {
	themify_menu_nav( array( 'walker' => new Themify_Mega_Menu_Walker ) );
}


/**
 * Settings module extension for post and portfolio builder
 */
add_filter('themify_builder_module_settings_fields','themify_builder_module_settings_options',10,2);
function themify_builder_module_settings_options( $options,$module ) {
	if( is_object( $module ) && ( $module->slug==='post' || $module->slug==='portfolio' || $module->slug==='products') ){
		$module_type=$module->slug;
		$is_product = $module_type==='products';
		$list_large = array('value' => 'list-large-image', 'img' => THEME_URI . '/images/layout-icons/list-large-image.png', 'label' => __('List Large Image', 'themify'));
		$auto_tiles = array('value' => 'auto_tiles', 'img' => THEME_URI . '/images/layout-icons/auto-tiles.png', 'label' => __('Auto Tiles', 'themify'));
		$bindig = array(
			'not_empty' => array(
				'show' => array('post_content_layout','disable_masonry','post_gutter','portfolio_gutter')
			),
			'list-post' => array(
				'hide' => array('disable_masonry','post_gutter','portfolio_gutter')
			),
			'auto_tiles' => array(
				'hide' => array('disable_masonry','post_gutter','portfolio_gutter')
			)
		);
		
		foreach( $options as $k=>$opt ) {
			if( $is_product && $opt['id'] === 'list' ) {
				$options[$k]['fields'][0]['options'][] = $list_large;
				$options[$k]['fields'][0]['options'][] = $auto_tiles;
				break;
			} elseif( $opt['id'] === 'layout_' . $module_type ) {
				$options[$k]['options'][] = $list_large;
				$options[$k]['options'][] = $auto_tiles;
				$merge_bind = $module_type === 'post'
					? array(
						'list-large-image' => array(
							'hide' => array( 'post_content_layout', 'disable_masonry', 'post_gutter' )
						),
						'list-thumb-image' => array(
							'hide' => array( 'post_content_layout', 'disable_masonry', 'post_gutter' )
						),
						'grid2-thumb' => array(
							'hide' => array( 'post_content_layout', 'disable_masonry', 'post_gutter' )
						),
						'slider' => array( 'hide' => array( 'disable_masonry', 'post_gutter ') ) )
					: array(
						'fullwidth' => array( 'hide' => array( 'disable_masonry', 'portfolio_gutter' ) ) );
				$options[$k]['binding'] = array_merge( $bindig, $merge_bind );
				break;
			}
		}
		
		if( $is_product ) {
			return $options;
		}

		foreach( $options as $k => $opt ) {
			if ( isset( $opt['id'] ) && $opt['id'] === 'query_slug_' . $module_type ) {
				$index = $k;
				break;
			}
		}

		$post_content_layout = array('id' => $module_type.'_content_layout','type' => 'select','label' => __('Post Content Layout', 'themify'),'options' =>array('default'=>'Default','no' => __('Stacking', 'themify'),'overlay'=>'Overlay','polaroid'=>'Polaroid','boxed'=>'Boxed'));
		$disable_masonry = array('id' => 'disable_masonry','type' => 'select','label' => __('Post Masonry', 'themify'),'options' =>array('default' => __('Default', 'themify'),'yes'=>'Yes','no'=>'No'),'wrap_with_class' => 'tf-group-element tf-group-element-grid4 tf-group-element-grid3 tf-group-element-grid2 tf-group-element-list-large-image');
		$post_gutter = array('id' => $module_type.'_gutter','type' => 'select','label' => __('Post Gutter', 'themify'),'options' =>array('default' => __('Default', 'themify'),'gutter'=>'gutter','no-gutter'=>'No gutter'));
		array_splice( $options, $index + 1, 0, array( $post_content_layout, $disable_masonry, $post_gutter ) );
		
		if( in_array( $module_type, array( 'post', 'portfolio' ) ) ) {
			array_splice( $options, $index + 2, 0, array( array(
				'id' => 'post_filter',
				'type' => 'select',
				'label' => __( 'Post Filter', 'themify' ),
				'options' => array( 'yes' => __( 'Yes', 'themify' ), 'no' => __( 'No', 'themify' ) ),
				'wrap_with_class' => 'tf-group-element tf-group-element-category'
			) ) );
		}
	}
	
	return $options;
}

/**
 * Additional classes for post and portfolio builder
 */
add_filter( 'themify_builder_module_loops_wrapper', 'themify_add_builder_classes', 10, 3 );
function themify_add_builder_classes($classes,$mod,$slug){

	if(isset($mod['layout_' . $slug] ) &&( $slug === 'post' || $slug === 'portfolio' ) ) {

		$is_portfolio = $slug === 'portfolio';
		$layout = $mod['layout_' . $slug];
		$masonry = $gutter = $content_layout = false;
		$content_layout = !empty($mod[$slug . '_content_layout']) 
			&& $mod[$slug.'_content_layout'] !== 'no'
			&& ! in_array( $layout, array('list-large-image', 'list-thumb-image','grid2-thumb') ) 
				? $mod[$slug . '_content_layout'] : false;

		if( $content_layout === 'default' ) {
			$content_layout = themify_get( 'setting-' . $slug . '_content_layout' );
		}

		$gutter = ! empty( $mod[$slug . '_gutter'] )
			&& ! in_array( $layout
				, array(
					'list-post',
					'list-large-image',
					'list-thumb-image',
					'grid2-thumb',
					'slider',
					'fullwidth'
				) ) ? $mod[$slug . '_gutter'] : false;

		if( $gutter === 'default' ) {
			$gutter = themify_get( 'setting-' . $slug . '_gutter' );
		}

		$masonry = ( ! empty( $mod['disable_masonry'] ) 
			&& $mod['disable_masonry'] !== 'no'
			&& ! in_array( $layout
				, array(
					'list-post',
					'fullwidth',
					'auto_tiles',
					'list-large-image',
					'list-thumb-image',
					'grid2-thumb',
					'slider'
				) ) ) ? 'masonry' : false;
		if( $masonry && $mod['disable_masonry'] === 'default' ) {
			$masonry = $is_portfolio
				? themify_get( 'setting-portfolio_disable_masonry' )
				: themify_get( 'setting-disable_masonry' );
			$masonry = $masonry === 'yes' ? 'masonry' : false;
		}

		if( $content_layout ) {
			$classes.=' '.$content_layout;
		}

		if( $gutter ) {
			$classes.=' '.$gutter;
		}
		
		if( $masonry ) {
			$classes.=' '.$masonry;
		}
		
	}
	return $classes;
}

function themify_builder_post_module_filter_init( $props, $mod, $slug, $id ) {
	if( isset( $mod['layout_' . $slug] ) && in_array( $slug, array( 'post', 'portfolio' ) ) ) {
		global $themify;
		$themify->post_filter = ! empty( $themify->post_filter ) ? $themify->post_filter : false;
		$themify->post_filter = isset( $mod['post_filter'] ) && $mod['post_filter'] === 'yes';

		$themify->query_taxonomy = 'category';
		if( $slug === 'portfolio' ) {
			$themify->query_taxonomy = 'portfolio-' . $themify->query_taxonomy;
		} elseif ( $themify->post_filter ){
			$themify->post_filter = $mod['type_query_' . $slug] === 'category';
		}

		if( $themify->post_filter ) {
			add_action( 'themify_builder_before_template_content_render', 'themify_builder_post_module_filter' );
		}
	}

	return $props;
}
add_filter( 'themify_builder_module_container_props', 'themify_builder_post_module_filter_init', 10, 4 );

/**
 * Post module filter by category
 */
function themify_builder_post_module_filter() {
	remove_action( 'themify_builder_before_template_content_render', 'themify_builder_post_module_filter' );
	get_template_part( 'includes/filter', 'portfolio' );
}

add_action('themify_content_before','themify_theme_meta_boxes_query_posts_filter');
function themify_theme_meta_boxes_query_posts_filter(){
	global $themify;
	if( $themify->query_post_type === 'post' ) {
		$themify->post_filter = themify_get( 'post_filter' );
	}

}


/*
add category id class in post loop for masonary filter
*/
function themify_post_category_class( $classes ) {
	global $post;
	if($post->post_type==='post'){
		$categories = wp_get_object_terms($post->ID, 'category' );
		foreach ( $categories as $category ) {
			$classes[] =' cat-' . $category->term_id;
		}
	}
	return $classes;
}
add_filter( 'post_class', 'themify_post_category_class' );

function themify_theme_sticky_logo(){
     if(themify_theme_fixed_header()){
        global $themify_customizer;
        $logo = json_decode($themify_customizer->get_cached_mod('sticky_header_imageselect'));
        return isset($logo->src) && '' != $logo->src?$logo:false;
     }
     else{
         return false;
     }
}

if (!function_exists('themify_set_tiles_template')) {

    /**
     * Set template for auto tiled
     * @return array
     */
    function themify_set_tiles_template() {
        //Each elements must have unique char and length = 4. Otherwise the result can be unexpected. For example: can't be 1=>'AAAA' and 2=>'ABAB'
        // Reserved chars 'X', 'Y', 'Z', 'V', 'T', 'F', 'K' used in JS
        $knows_grids = array(1 => array("AAAA"),
            2 => array('BBCC', 'BBCC'),
            3 => array('DD..'),
            4 => array('.EEF', '.EEF')
        );
        if (!isset($knows_grids[5])) {
            $knows_grids[5] = $knows_grids[3];
            foreach ($knows_grids[2] as $v) {
                $knows_grids[5][] = $v;
            }
        }
        if (!isset($knows_grids[6])) {
            $knows_grids[6] = $knows_grids[4];
            foreach ($knows_grids[2] as $v) {
                $knows_grids[6][] = $v;
            }
        }
        if (!isset($knows_grids[7])) {
            $knows_grids[7] = $knows_grids[4];
            foreach ($knows_grids[3] as $v) {
                $knows_grids[7][] = $v;
            }
        }
        if (!isset($knows_grids[8])) {
            $knows_grids[8] = $knows_grids[7];
            foreach ($knows_grids[1] as $v) {
                $knows_grids[8][] = $v;
            }
        }
        if (!isset($knows_grids[9])) {
            $knows_grids[9] = $knows_grids[7];
            foreach ($knows_grids[2] as $v) {
                $knows_grids[9][] = $v;
            }
        }
        if (!isset($knows_grids[10])) {
            $knows_grids[10] = $knows_grids[7];
            $knows_grids[10][] = 'MMNN';
            $knows_grids[10][] = 'MMPP';
        }
        if (!isset($knows_grids[11])) {
            $knows_grids[11] = $knows_grids[10];
            foreach ($knows_grids[1] as $v) {
                $knows_grids[11][] = $v;
            }
        }
        if (!isset($knows_grids[12])) {
            $knows_grids[12] = $knows_grids[10];
            foreach ($knows_grids[2] as $v) {
                $knows_grids[12][] = $v;
            }
        }
        if (!isset($knows_grids[13])) {
            $knows_grids[13] = $knows_grids[10];
            $knows_grids[13][] = 'LSRR';
            $knows_grids[13][] = 'LSRR';
        }

        return apply_filters('themify_tiledata_template', $knows_grids);
    }

}

/**
 * Checks if Top Widgets header design is active
 *
 * @return bool
 */
function themify_is_header_top_widgets() {
	return
		themify_get( 'setting-header_design' ) === 'header-top-widgets' // global setting
		|| themify_get( 'header_design' ) === 'header-top-widgets'; // per-post option
}

// Portfolio comments filter
function portfolio_comments_open( $open, $post_id ) {
	$post = get_post( $post_id );
	! empty( $post ) && 'portfolio' === $post->post_type
		&& themify_check( 'setting-portfolio_comments' ) && ( $open = true );
	return $open;
}
add_filter( 'comments_open', 'portfolio_comments_open', 10, 2 );