<?php
/***************************************************************************
 *  					Theme Functions
 * 	----------------------------------------------------------------------
 * 						DO NOT EDIT THIS FILE
 *	----------------------------------------------------------------------
 *
 *  					Copyright (C) Themify
 * 						https://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_after_setup_theme' );

// Enqueue scripts and styles required by theme
add_action( 'wp_enqueue_scripts', 'themify_theme_enqueue_scripts', 11 );

// Exclude CPT for sidebar
add_filter( 'themify_exclude_CPT_for_sidebar', 'themify_CPT_exclude_sidebar' );

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

if ( themify_get( 'setting-disable_responsive_design' ) == 'on' ) {
	add_action( 'init', 'themify_disable_responsive_design' );
}

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

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

/////// Filters ////////

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

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

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

	// Themify WooCommerce CSS
	if (themify_is_woocommerce_active()) {
		wp_enqueue_style('themify-woocommerce', themify_enque(THEME_URI . '/styles/woocommerce.css'));
	}

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

	// 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('themify-smartresize', THEME_URI . '/js/jquery.smartresize.min.js', array('jquery'), $theme_version, true);

	// Slide mobile navigation menu
	wp_enqueue_script( 'slide-nav', themify_enque(THEMIFY_URI . '/js/themify.sidemenu.js'), array( 'jquery' ), THEMIFY_VERSION, true );
	
	wp_enqueue_script( 'themify-nicescroll',THEME_URI . '/js/jquery.nicescroll.min.js', array( 'jquery' ), $theme_version, true );
	
	if(is_single()){

		//clip-path svg hack for IE 9-11,Edge ImageLoaded
		global $is_IE, $is_edge;
		$browser = $is_IE || $is_edge;
		if( $browser ) {
			wp_enqueue_script( 'themify-imageLoaded',	THEME_URI . '/js/imageLoaded.min.js', array( 'jquery' ), $theme_version, true );
		}

		if(strpos($themify->layout,'sidebar-left')===false){
			// Sticky social share
			wp_enqueue_script( 'themify-sticky-social-share',	THEME_URI . '/js/jquery.jsticky.min.js', array( 'jquery' ), $theme_version, true );
		}
	}
	else{
		wp_enqueue_script('themify-isotope', THEME_URI . '/js/jquery.isotope.min.js', array(), $theme_version, true);
	}
	
	wp_enqueue_script( 'infinitescroll', THEME_URI . '/js/jquery.infinitescroll.min.js', array('jquery'), false, true );
	
	// Themify internal scripts
	wp_register_script( 'theme-script',	themify_enque(THEME_URI . '/js/themify.script.js'), array( 'slide-nav','themify-nicescroll' ), $theme_version, true );
	

	// Prepare JS variables
	$themify_script_vars = array(
		'lightbox' => themify_lightbox_vars_init(),
		'lightboxContext' => apply_filters( 'themify_lightbox_context', '#pagewrap' ),
		'infiniteURL' => themify_check( 'setting-infinite-url' ) ? 1 : 0,
		'fixedHeader' => themify_theme_fixed_header(),
		'sticky_header'=>themify_theme_sticky_logo(),
		'loadingImg'   	=> THEME_URI . '/images/loading.gif',
		'maxPages'	   	=> $wp_query->max_num_pages,
		'autoInfinite' 	=> themify_check( 'setting-autoinfinite' ) ? 'no': 'auto',
	);
	// Pass variable values to JavaScript
	wp_localize_script( 'theme-script', 'themifyScript', apply_filters( 'themify_script_vars', $themify_script_vars ) );
	wp_enqueue_script('theme-script');
	// 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' );

	// Fix Mozilla clip path
	if( ( themify_is_query_page() || is_single() || is_page() ) && $is_gecko ) {
		$helper_style = '
			.loops-wrapper .post-image img, .single-post .post-image img {clip-path: url("#themifyClip")}
			.loops-wrapper.zig-zag .post:nth-of-type(2n) .post-image img, .loops-wrapper.zig-zag .post:nth-of-type(2n) .svg-image {clip-path: url("#themifyClipReverse")}
		';
		wp_add_inline_style( 'theme-style', $helper_style );
	}
}

/**
 * Load Google fonts used by the theme
 *
 * @return array
 */
function themify_theme_google_fonts( $fonts ) {
	/* translators: If there are characters in your language that are not supported by Poppins, translate this to 'off'. Do not translate into your own language. */
	if ( 'off' !== _x( 'on', 'Poppins font: on or off', 'themify' ) ) {
		$fonts['poppins'] = 'Poppins:400,500,600,700';
	}
	/* 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:400,300,700';
	}
	/* translators: If there are characters in your language that are not supported by Playfair Display, translate this to 'off'. Do not translate into your own language. */
	if ( 'off' !== _x( 'on', 'Playfair Display font: on or off', 'themify' ) ) {
		$fonts['playfair-display'] = 'Playfair+Display:400,400italic,700,700italic,900,900italic';
	}

	return $fonts;
}
add_filter( 'themify_google_fonts', 'themify_theme_google_fonts' );

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

/**
 * 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";
}
add_filter('comment_form_fields', 'themify_reorder_comment_fields',10,1 );
function themify_reorder_comment_fields( $fields ){
	
	$new_fields = array();
	$order = apply_filters('themify_order_comment_filds',array('author','email','url','comment')); 
	foreach( $order as $key ){
            $new_fields[ $key ] = $fields[ $key ];
            unset( $fields[ $key ] );
	}
	if( $fields ){
            foreach( $fields as $key => $val ){
                    $new_fields[ $key ] = $val;
            }
        }
	return $new_fields;
}
if( ! function_exists( 'themify_float_get_pagenav' ) ) :
/**
 * Returns page navigation
 * @param string $before Markup to show before pagination links
 * @param string $after Markup to show after pagination links
 * @param object $query WordPress query object to use
 * @return string
 * @since 1.2.4
 */
function themify_float_get_pagenav( $before = '', $after = '', $query = false ) {
    
	global $wp_query;

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

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

		if ($paged < $end_page) {
			$out .=  '<a href="'.get_pagenum_link($max_page).'" title="&raquo;" class="number"></a>';
		}
		$out .=  '</div>'.$after;
	}
	return $out;
}
endif;

add_filter( 'post_class', 'themify_get_portfolio_layout' );

// Add theme specific classes in body tag
add_filter( 'body_class', 'themify_theme_body_class' );

//get featured imaged by browser
function themify_float_get_feature_image($post_image){
	static $browser = null;
	global $themify, $is_IE, $is_edge;
	
	if( !isset($browser) 
		&& !empty($_SERVER['HTTP_USER_AGENT']) 
		&& !is_tax('portfolio') 
		&& $themify->query_post_type !== 'portfolio' ) {
		$browser = $is_IE || $is_edge;
    }
    if( $browser ): ?>
    	<svg class="post-media-svg" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    	<?php
    		$old_post_image = $post_image;
    		$src = preg_match('/< *img[^>]*src *= *["\']?([^"\']*)/i', $post_image, $matches);
        	$post_image = '<image width="100%" height="100%" class="svg-image" href="'.$matches[1].'" />';
	endif;

	if( 'yes' == $themify->unlink_image ):
		echo wp_kses_post( $post_image );
	else: ?>
		<a href="<?php echo themify_get_featured_image_link(); ?>">
        <?php
        	echo $post_image;
            themify_zoom_icon();
        ?>
        </a>
    <?php endif; // unlink image
	if( $browser ):?>
		</svg>
		<?php echo $old_post_image;
	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' => 'top-bar', // hides sticky header
			'img'   => 'images/layout-icons/header-top-bar.png',
			'title' => __( 'Header Top Bar', 'themify' ),
		),
		array(
			'value' => 'header-leftpane', // hides sticky header
			'img'   => 'images/layout-icons/header-left-pane.png',
			'title' => __( 'Header Left Pane', 'themify' ),
		),
		array(
			'value' => 'header-rightpane', // hides sticky header
			'img'   => 'images/layout-icons/header-right-pane.png',
			'title' => __( 'Header Right Pane ', 'themify' ),
		),
		array(
			'value' => 'none', // hides sticky header
			'img'   => 'images/layout-icons/none.png',
			'title' => __( 'No Header ', 'themify' ),
		)
	));
}


/**
 * Return portfolio size, large or small.
 *
 * @param $post_id
 *
 * @return mixed|string
 */
function themify_get_portfolio_layout( $class ) {
	$post_id = get_the_ID();
	if ( 'portfolio' == get_post_type( $post_id ) ) {

		$size = get_post_meta( $post_id, 'tile_layout', true );
		$class[] = $size ? $size : 'size-small image-left';

		$categories = wp_get_object_terms( $post_id, 'portfolio-category' );

		foreach ( $categories as $cat ) {
			$class[]= 'cat-' . $cat->term_id;
		}

	}

	return $class;
}


/**
 * Output required classes like transition setting, builder row scrolling setting.
 * In single views, check if there's a video and add class accordingly.
 *
 * @since 1.0.0
 *
 * @param array $classes
 *
 * @return array
 */
function themify_theme_body_class( $classes ) {
	

	if ( is_single() && '' != themify_get( 'video_url' ) ) {
		$classes[] = 'has-video';
	}

	if(themify_is_touch('tablet')){
		$classes[] = 'istablet';
	}
	// 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';
	}
	$is_singular = is_singular() || themify_is_shop();
	$header = $is_singular ? themify_get( 'header_design' ) : false;
	
	if(!$header || $header==='default'){
		$header = themify_get( 'setting-header_design' );
	}
	if($header==='top-bar' || $header==='default' || !$header){
		$menu_style = false;  
		if( $is_singular ){
			$menu_style =themify_get( 'menu_style' );
			if ('transparent' == themify_get( 'header_wrap' ) ) {
				$classes[] = 'transparent-header';
			}
		}
		
		if(!$menu_style){
			$menu_style = themify_get( 'setting-menu_style' );
		}
		if($menu_style!=='overlay-menu'){
			$classes[] = $menu_style;
		}
		
	}
	else{
		$classes[] = $header!='none'?$header:'header-none';
	}
        

	// Check if masonry is enabled
	$classes[] = themify_theme_is_masonry_enabled();

	return $classes;
}


/**
 * 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 = 'post' == get_post_type() ? '' : get_post_type() . '_';
		}
		if ( 'no' != themify_get( 'setting-' . $post_type . 'disable_masonry' ) ) {
			$do_masonry = 'masonry-enabled';
		}
	}
	return $do_masonry;
}



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 ( ( is_singular() && in_array( get_post_type(), array( 'post', 'page', 'portfolio') ) ) || themify_is_shop() ) {
			$post_id = get_the_ID();
			if ( is_page() || themify_is_shop() ) {
				if ( is_post_type_archive( 'product' ) ) {
					$entry_id = '.post-type-archive-product';
				} else {
					$entry_id = '.page-id-' . $post_id;
				}
			} else {
				$entry_id = '.postid-' . $post_id;
			}
			$headerwrap = $entry_id . ' #headerwrap';
			$site_logo = $entry_id . ' #site-logo';
			$site_description = $entry_id . ' #site-description';
			$main_nav = $entry_id . ' #main-nav';
			$social_widget = $entry_id . ' .social-widget';
			$css = array();
			$style = '';
			$rules = array();

			if ( 'transparent' != themify_get('header_wrap')) {
				$rules = array(
					$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'
							),
						),
					),
					"$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'
							),
					),
				);
			}

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

			$rules["$site_logo a, $site_description a, $social_widget a, $main_nav > li > a"] = array(
				array(
					'prop' => 'color',
					'key'  => 'headerwrap_link_color'
				),
			);

			foreach ( $rules as $selector => $property ) {
				foreach ( $property as $val ) {
					$prop = $val['prop'];
					$key = $val['key'];
					$plain_key = themify_get( $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' != $plain_key ) {
						if ( $prop == 'color' || stripos( $prop, 'color' ) ) {
							if($prop == 'background-color'){
								$css[$selector]['background'] = 'background: none;';
							}
							$css[$selector][$prop] = $prop . ': ' . themify_get_color( $key );
							
						}
						elseif ( $prop == 'background-image' && 'default' != $plain_key ) {
							$css[$selector][$prop] = $prop .': url(' . $plain_key . ')';
						}
						elseif ( $prop == 'background-repeat' && 'fullcover' == $plain_key ) {
							if ( isset( $val['dependson'] ) ) {
								if ( $val['dependson']['prop'] == 'background-image' && ( themify_check( $val['dependson']['key'] ) && 'default' != themify_get( $val['dependson']['key'] ) ) ) {
									$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' ) {
							$css[$selector][$prop] = $prop .': '. $plain_key;
							if ( ! in_array( $plain_key, themify_get_web_safe_font_list( true ) ) ) {
								$themify->google_fonts .= str_replace( ' ', '+', $plain_key.'|' );
							}
						}
						else {
							$css[$selector][$prop] = $prop .': '. $plain_key;
						}
					}
				}
				if ( ! empty( $css[$selector] ) ) {
					$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_after_setup_theme' ) ) {
	/**
	 * Register theme support.
	 *
	 * Initialize custom panel with its definitions.
	 * Custom panel definitions are located in admin/post-type-TYPE.php
	 *
	 * @since 1.0.7
	 */
	function themify_theme_after_setup_theme() {
            // Enable WordPress feature image
            add_theme_support('post-thumbnails');
            
            require_once( 'class-social-share.php' );
            // 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" );
            }

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

            themify_build_write_panels(apply_filters('themify_theme_meta_boxes', array(
                array(
                    'name' => __('Post Options', 'themify'),
                    'id' => 'post-options',
                    'options' => themify_theme_post_meta_box(),
                    'pages' => 'post'
                ),
				array(
					'name'    => __( 'Post Appearance', 'themify' ),
					'id'      => 'post-appearance',
					'options' => themify_theme_post_appearance_meta_box(),
					'pages'   => 'post'
				),
                array(
                    'name' => __('Page Options', 'themify'),
                    'id' => 'page-options',
                    'options' => themify_theme_page_meta_box(array(
                        'nav_menus' => $nav_menus,
                    )),
                    'pages' => 'page'
                ),
				array(
					'name'    => __( 'Page Appearance', 'themify' ),
					'id'      => 'page-appearance',
					'options' => themify_theme_page_appearance_meta_box(),
					'pages'   => 'page'
				),
                array(
                    'name' => __('Query Posts', 'themify'),
                    'id' => 'query-posts',
                    'options' => themify_theme_query_post_meta_box(),
                    'pages' => 'page'
                ),
                array(
                    'name' => __('Portfolio Options', 'themify'),
                    'id' => 'portfolio-options',
                    'options' => themify_theme_portfolio_meta_box(array(
                        'nav_menus' => $nav_menus,
                    )),
                    'pages' => 'portfolio'
                ),
				array(
					'name'    => __( 'Portfolio Appearance', 'themify' ),
					'id'      => 'page-appearance',
					'options' => themify_theme_portfolio_appearance_meta_box(),
					'pages'   => 'portfolio'
				),
                array(
                    'name' => __('Query Portfolios', 'themify'),
                    'id' => 'query-portfolio',
                    'options' => themify_theme_query_portfolio_meta_box(),
                    'pages' => 'page'
                ),
                            )
            ));
        }
}

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' => __( 'Social Widget', 'themify' ),
				'id' => 'social-widget',
				'before_widget' => '<div id="%1$s" class="widget %2$s">',
				'after_widget' => '</div>',
				'before_title' => '<strong>',
				'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 );
		}

		// Footer Sidebars
		themify_register_grouped_widgets();
	}
}

if ( ! function_exists( '_wp_render_title_tag' ) ) {
	/**
	 * Fallback to render title before WP 4.1
	 *
	 * @since 1.0.0
	 */
	function themify_theme_render_title() { ?>
		<title><?php wp_title(); ?></title>
	<?php
	}
	// Fallback WP Title
	add_action( 'wp_head', 'themify_theme_render_title' );
} else {
	// Add Title Tag support
	add_theme_support( 'title-tag' );
	/**
	 * Remove last part of title to keep the traditional Themify theme title.
	 *
	 * @since 1.0.0
	 *
	 * @param string $title
	 *
	 * @return string
	 */
	function themify_theme_title_tag( $title ) {
		if ( ! is_front_page() ) {
			$title = str_replace( get_bloginfo( 'name' ), '', $title );
		}
		return $title;
	}
	// Generate title
	add_filter( 'wp_title', 'themify_theme_title_tag', 10 );
}

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 =  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_CPT_exclude_sidebar') ) {
	/**
	 * Exclude Custom Post Types
	 */
	function themify_CPT_exclude_sidebar($CPT = array()) {
		
		$float = array('portfolio');
		
		if(empty($CPT)){
			$CPT = array('post', 'page', 'attachment', 'tbuilder_layout', 'tbuilder_layout_part', 'section');
		}
		
		if(themify_is_woocommerce_active()){
			$ultra[] = 'product';
		}

		$CPT = array_merge($CPT, $float);

		return $CPT;
	}
}

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


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

	if ( isset( $themify->query_post_type ) && ! in_array( $themify->query_post_type, array( 'post', 'page' ) ) ) {
		$class[] = $themify->query_post_type;
	}
	if(is_tax('portfolio-category')){
		$class[] = 'portfolio';
	}
       
	if ( themify_is_query_page() || is_archive() || is_search() || is_tax() || is_home() ) {
		if ( $temp_class = themify_theme_get( 'post_content_layout' ) ) {
			$class[] = $temp_class;
		}
			
		if ( $temp_class = themify_theme_get( 'more_posts', 'infinite' ) ) {
			$class[] = $temp_class;
		}
		if (!is_tax('portfolio-category') && themify_theme_is_masonry_enabled() ) {
			$class[] = 'masonry';
		}
		if ( 'no-gutter' == themify_theme_get( 'post_gutter' ) ) {
			$class[] = 'no-gutter';
		}
	}
	
	$class = array_unique($class);
	return implode( ' ', apply_filters( 'themify_theme_loops_wrapper_class', $class ) );
}


/**
 * 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 && '' != $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 && '' != $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 && '' != $value && 'default' != $value ) {
			return $value;
		}
	}

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


/* * ********************
 * Plugin Integration *
 * ******************** */
/** 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(
        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,
        ),
    );
    $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).
            '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('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;
        }
    }
}

add_action('admin_menu', 'themify_theme_required_plugins_admin_menu', 11);

/**
 * 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
 *
 * @since 1.0.0
 */
function themify_theme_tgmpa_mu_hide_activate_link() {
    global $hook_suffix;

    if (is_multisite() && 'appearance_page_themify-install-plugins' == $hook_suffix) {
        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.0.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');

/**
 * Miltiply infinity scroll for shortcodes themify_list_posts,themify_portfolio_posts
 */
add_filter('themify_list_posts_shortcode_query_args', 'themify_infinity_shortcode', 10, 2);
add_filter('themify_portfolio_shortcode_args', 'themify_infinity_shortcode', 10, 2);
add_action('wp_ajax_themify_shortcode_infinity', 'themify_shortcode_infinity');
add_action('wp_ajax_nopriv_themify_shortcode_infinity', 'themify_shortcode_infinity');
if (!function_exists('themify_infinity_shortcode')) {

    /**
     * Add infinite_scroll value in themify_list_posts shortcode
     * @return void
     */
    function themify_infinity_shortcode($query_args, $atts) {

        global $themify;
        $themify->infinity_query = $themify->infinity_count = false;
		
        if (isset($atts['load_more']) && $atts['load_more'] !== 'no' && (!defined('DOING_AJAX') || !DOING_AJAX)) {
            $args = $query_args;
            $args['fields'] = 'ids';
            $query = new WP_Query($args);
            $themify->infinity_count = $query->max_num_pages;
            foreach ($atts as $k => $v) {
                if ($v !== '') {
                    $themify->infinity_query[$k] = $v;
                }
            }
            wp_reset_postdata();
            add_filter('themify_get_shortcode_template', 'themify_add_shortcode_pagination', 10, 2);
		}

        return $query_args;
    }

    function themify_add_shortcode_pagination($html) {
        global $themify;
        if ($themify->is_isotop && !isset($themify->shortcode_query_taxonomy)) {
            $themify->shortcode_query_taxonomy = 'category';
            ob_start();
            locate_template('includes/filter.php', true, false);
            $html = ob_get_contents() . $html;
            ob_end_clean();
        } else {
            $themify->shortcode_query_taxonomy = null;
        }
        if ($themify->infinity_count > 1) {
            ob_start();
            locate_template('includes/pagination.php', true, false);
            $html.= ob_get_contents();
            ob_end_clean();
        }
        remove_filter('themify_get_shortcode_template', 'themify_add_shortcode_pagination', 10, 2);
        return $html;
    }

    function themify_shortcode_infinity() {
        if (isset($_GET['query'])) {
            $query = $_GET['query'];
            if (isset($query['load_more']) && $query['load_more'] !== 'no') {
                $is_portfolio = isset($query['is_portfolio']);
                $shortcode = $is_portfolio ? '[themify_portfolio_posts ' : '[themify_list_posts ';
                foreach ($query as $k => $v) {
                    if ($v || "$v"==='0') {
                        if (is_array($v)) {
                            $v = implode(',', $v);
                        }
                        $shortcode.=' ' . $k . '="' . esc_attr($v) . '"';
                    }
                }
                if (isset($_GET['paging']) && $_GET['paging'] > 1) {
                    $page = intval($_GET['paging']);
                    $limit = isset($query['limit']) && $query['limit'] > 0 ? intval($query['limit']) : get_option('posts_per_page');
                    $offset = $limit * ($page - 1);
                    $shortcode.=' offset="' . $offset . '"';
                }
                $shortcode.=' ]';
                echo do_shortcode($shortcode);
            }
        }
        wp_die();
    }

}

/**
 * Mozilla clip path helper
 *
 * @since 1.0.0
 *
 */
if( !function_exists( 'themify_mozilla_clip_helper' ) ):
	function themify_mozilla_clip_helper() {
		global $is_gecko;
		if( ( themify_is_query_page() || is_single() || is_page() ) && $is_gecko ) {
			echo '<svg height="0" width="0" class="clip-svg"><defs><clipPath id="themifyClip" clipPathUnits="objectBoundingBox"><polygon points="0 0.16, 1 0, 1 0.84, 0 1" /></clipPath></defs><defs><clipPath id="themifyClipReverse" clipPathUnits="objectBoundingBox"><polygon points="0 0, 1 0.16, 1 1, 0 0.84" /></clipPath></defs></svg>';
		}
	}
endif;
add_action( 'themify_body_start', 'themify_mozilla_clip_helper', 100 );

if ( ! function_exists( 'themify_theme_menu_nav' ) ) :
/**
 * Deprecated function, kept for backwards compatibility.
 *
 * @since 1.0.0
 */
function themify_theme_menu_nav() {
	themify_nav_menu();
}
endif;

function themify_builder_module_settings_options( $options, $module ) {

	if( is_object( $module ) && ($module->slug === 'portfolio' || $module->slug === 'post')) {
		$extra_options = $ids = array();
		foreach( $options as $k => $opt ){
			if( isset( $opt['id'] ) ) {
                            if($module->slug === 'portfolio'){
                                if( $opt['id'] === 'layout_' . $module->slug){
                                    $options[$k]['options'] = array_splice( $options[$k]['options'], 0, -2 );
                                    $options[$k]['options'][] = array('value' => 'grid5', 'img' => THEME_URI . '/images/layout-icons/grid5.png', 'label' => __('Grid 5', 'themify'));
                                }
                                $ids[] = $opt['id'];
                            }
                            elseif($opt['id'] === 'layout_' . $module->slug ){
                                $options[$k]['options'][] = array('value' => 'zig-zag', 'img' => THEME_URI.'/images/layout-icons/zig-zag.png', 'label' => __( 'Zig-Zag', 'themify' ));
                                break;
                            }
			}
		}
                if($module->slug === 'portfolio' ){
                    $index = (int) array_search( 'query_slug_' . $module->slug, $ids );
                    $ids = null;
                    // Filter
                    $extra_options[] = array(
                            'id' => $module->slug . '_filter',
                            'type' => 'select',
                            'label' => __( 'Post Filter', 'themify' ),
                            'options' => array(
                                    'default' => __( 'Default', 'themify' ),
                                    'yes' => __( 'Yes', 'themify' ),
                                    'no' => __( 'No', 'themify' )
                            ),
                            'wrap_with_class' => 'tf-group-element tf-group-element-category'
                    );

                    array_splice( $options, $index++, 0, $extra_options );
                }
	}

	return $options;
}

add_filter( 'themify_builder_module_settings_fields', 'themify_builder_module_settings_options', 10, 2 );

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', '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_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;
     }
}

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

// Display Extra module settings
if( ! function_exists( 'themify_builder_args' ) ) :
function themify_builder_args( $show, $mod, $builder_id, $identifier ) {
	global $themify;
	
	if( ! empty( $mod['mod_settings'] ) && ! empty( $mod['mod_name'] ) && $mod['mod_name'] === 'portfolio' ) {
		$slug = $mod['mod_name'];
		$settings = $mod['mod_settings'];

		// Filter
		if( ! empty( $settings[$slug . '_filter'] ) && $settings[$slug . '_filter'] === 'yes' ) {
			$themify->query_taxonomy = 'portfolio-category';
			add_action( 'themify_post_before', 'themify_builder_post_module_filter' );
		}
	}
	
	return $show;
}
endif;
add_filter( 'themify_builder_module_display', 'themify_builder_args', 10, 4 );

if( ! function_exists( 'themify_builder_post_module_filter' ) ) :
function themify_builder_post_module_filter() {
	global $themify;
	get_template_part( 'includes/filter' );
	remove_action( 'themify_post_before', 'themify_builder_post_module_filter' );
}
endif;