<?php

/**
 * Edition functions and definitions.
 *
 * Sets up the theme and provides some helper functions, which are used
 * in the theme. Others are attached to action and filter hooks in WordPress
 * to change core functionality.
 *
 * When using a child theme (see http://codex.wordpress.org/Theme_Development and
 * http://codex.wordpress.org/Child_Themes), you can override certain functions
 * (those wrapped in a function_exists() call) by defining them first in your child theme's
 * functions.php file. The child theme's functions.php file is included before the parent
 * theme's file, so the child theme functions would be used.
 *
 * For more information on hooks, actions, and filters, see http://codex.wordpress.org/Plugin_API.
 *
 * @package    WordPress
 * @subpackage Edition
 * @since      Edition 1.0
 */

// Get theme version - used for updating script versions on new releases
global $themewich_theme_info;
$themewich_theme_info = wp_get_theme( 'edition' );

// Check if ACF is activated
global $fields_installed;
$fields_installed = function_exists( 'get_field' );

// Define templates directory
define( 'TW_TEMPLATES_DIR', 'functions/templates' );
define( 'TW_SECTIONS_DIR', 'functions/templates/sections' );

// Edition only works in WordPress 3.8 or later.
if ( version_compare( get_bloginfo( 'version' ), '3.8', '<' ) ) {
	require get_template_directory() . '/backwards-compat.php';
}

/**
 * Set up the content width value based on the theme's design.
 *
 * @see   themewich_content_width()
 *
 * @since Edition 1.0
 */
if ( ! isset( $content_width ) ) {
	$content_width = 1170; // Matches featured image width
}

if ( ! function_exists( 'themewich_setup' ) ) :
	/**
	 * Edition theme setup.
	 *
	 * Set up theme defaults and registers support for various WordPress features.
	 *
	 * @uses  load_theme_textdomain() For translation/localization support.
	 * @uses  add_theme_support() To add support for post thumbnails, automatic feed links.
	 * @uses  register_nav_menu() To add support for navigation menus.
	 * @uses  set_post_thumbnail_size() To set a custom post thumbnail sizes.
	 *
	 * @since Edition 1.0
	 */
	function themewich_setup() {

		/**
		 * Include Options Framework
		 * @since Edition 1.0
		 */
		if ( ! class_exists( 'ReduxFramework' ) && file_exists( dirname( __FILE__ ) . '/theme-options/redux-framework/ReduxCore/framework.php' ) ) {
			require_once( dirname( __FILE__ ) . '/theme-options/redux-framework/ReduxCore/framework.php' );
		}

		/**
		 * Theme Options File
		 * @since Edition 1.0
		 */
		if ( ! isset( $redux_demo ) && file_exists( dirname( __FILE__ ) . '/theme-options/themewich-config.php' ) ) {
			require_once( dirname( __FILE__ ) . '/theme-options/themewich-config.php' );
		}

		/**
		 * Make theme available for translation
		 * @since Edition 1.0
		 */
		load_theme_textdomain( 'themewich', get_template_directory() . '/lang' ); // Load theme text comain

		/**
		 * Theme Support
		 * @since Edition 1.0
		 */
		add_theme_support( 'automatic-feed-links' ); // Adds RSS feed links to <head> for posts and comments.
		add_theme_support( 'post-thumbnails' );

		/*
	 * Let WordPress manage the document title.
	 * By adding theme support, we declare that this theme does not use a
	 * hard-coded <title> tag in the document head, and expect WordPress to
	 * provide it for us.
	 */
		add_theme_support( 'title-tag' );

		/**
		 * Thumbnail Sizes
		 * @since Edition 1.0
		 */
		add_image_size( 'tinyfeatured', 75, 75, true ); // Tiny Square thumbnail for widgets

		// Gallery & Slideshow Sizes
		add_image_size( 'gallery', 426, 351, true ); // For regular galleries
		add_image_size( 'fullslideshow', 1500, 550, true ); // Full Width Cropped
		add_image_size( 'fullslideshownc', 1500, '', false ); // Full Width UnCropped
		add_image_size( 'contentslideshow', 740, 400, true ); // Regular Width
		add_image_size( 'contentslideshownc', 740, '', false ); // Regular Width UnCropped

		// Regular Posts
		add_image_size( 'regular', 525, 300, true );

		// Grid Section Sizes
		add_image_size( 'half', 410, 441, true );
		add_image_size( 'big', 790, 425, true );

		// Related
		add_image_size( 'related', 525, 564, true );

		// This theme uses wp_nav_menu() in one location.
		register_nav_menus( array(
			'main_nav_menu' => __( 'Main Navigation Menu', 'themewich' )
		) );

		/**
		 * Switch default core markup for search form, comment form, and comments
		 * to output valid HTML5.
		 */
		add_theme_support( 'html5', array(
			'search-form',
			'comment-form',
			'comment-list',
		) );

		/**
		 * Add Woocommerce support
		 */
		add_theme_support( 'woocommerce' );
	}

	add_action( 'after_setup_theme', 'themewich_setup' );
endif;

/**
 * Fallback for older versions
 */
if ( ! function_exists( '_wp_render_title_tag' ) ) :
	function themewich_render_title() {
		?>
        <title><?php wp_title( '-', true, 'right' ); ?></title>
		<?php

	}

	add_action( 'wp_head', 'themewich_render_title' );
endif;

/**
 * Include additional function files
 * @since Edition 1.0
 */
include( "framework/framework.php" );        // Include Themewich framework
include( 'functions/acf-light.php' );            // Enable ACF Lite Mode

// Add theme customizer
if ( ! function_exists( 'themewich_theme_customizer' ) ) :
	function themewich_theme_customizer() {
		include( 'functions/css/custom-styles.php' ); // WP customizer CSS
	}

	add_action( 'after_setup_theme', 'themewich_theme_customizer' );
endif;

// Add theme widgets
if ( ! function_exists( 'themewich_widgets' ) ) :
	function themewich_widgets() {
		include( "functions/widgets/widget-news.php" );        // Add the News Custom Widget
		include( "functions/widgets/widget-ad125.php" );        // Add the Ad Widget
		include( "functions/widgets/widget-popular.php" );    // Add the Popular Posts Widget
	}

	add_action( 'after_setup_theme', 'themewich_widgets' );
endif;

if ( ! function_exists( 'themewich_content_width' ) ) :
	/**
	 * Adjust content_width value for image attachment template.
	 *
	 * @since Edition 1.0
	 *
	 * @return void
	 */
	function themewich_content_width() {
		if ( is_attachment() && wp_attachment_is_image() ) {
			$GLOBALS['content_width'] = 800;
		}
	}

	add_action( 'template_redirect', 'themewich_content_width' );
endif;

if ( ! function_exists( 'themewich_nav_menu' ) ) :
	/**
	 * Remove default menu container div
	 *
	 * @since Edition 1.0
	 */
	function themewich_nav_menu( $args = '' ) {
		$args['container'] = false;

		return $args;
	}

	add_filter( 'wp_nav_menu_args', 'themewich_nav_menu' );
endif;

if ( ! function_exists( 'themewich_tinyMCE' ) ) :
	/**
	 * Remove Items from WYSIWYG for SEO Purposes
	 *
	 * @since Edition 1.0
	 */
	function themewich_tinyMCE( $init ) {
		$init['theme_advanced_blockformats'] = 'h3,h4,h5,p,pre';

		return $init;
	}

	add_filter( 'tiny_mce_before_init', 'themewich_tinyMCE' );
endif;

if ( ! function_exists( 'themewich_image_caption_class' ) ) :
	/**
	 * Modify WordPress Caption to add class and remove inline styles.
	 *
	 * @param  array  $attr
	 * @param  string $content
	 *
	 * @return string
	 */
	function themewich_image_caption_class( $attr, $content = null ) {
		if ( ! isset( $attr['caption'] ) ) :
			// Set initial variables
			$captionclass = 'caption-normal';
			$widthstyle   = true;

			// Get the caption
			if ( preg_match( '#((?:<a [^>]+>\s*)?<img [^>]+>(?:\s*</a>)?)(.*)#is', $content, $matches ) ) {
				$content         = $matches[1];
				$attr['caption'] = trim( $matches[2] );
			}

			// Find parallaximg class
			if ( $c = preg_match_all( "/.*?(parallaximg)/is", $content, $matches ) ) {
				$captionclass = 'caption-' . $matches[1][0];
				$widthstyle   = false;
			}

			// Find fullimg class
			if ( $c = preg_match_all( "/.*?(fullimg)/is", $content, $matches ) ) {
				$captionclass = 'caption-' . $matches[1][0];
				$widthstyle   = false;
			}

			// Find fixedimg class
			if ( $c = preg_match_all( "/.*?(fixedimg)/is", $content, $matches ) ) {
				$captionclass = 'caption-' . $matches[1][0];
				$widthstyle   = false;
			}
		endif;

		$output = apply_filters( 'img_caption_shortcode', '', $attr, $content );

		if ( $output != '' ) {
			return $output;
		}

		extract( shortcode_atts( array(
			'id'      => '',
			'align'   => 'alignnone',
			'width'   => '',
			'caption' => ''
		), $attr ) );

		$widthstyle = ( $widthstyle == true ) ? 'style="width:' . $width . 'px;"' : '';

		if ( 1 > (int) $width || empty( $caption ) ) {
			return $content;
		}

		if ( $id ) {
			$id = 'id="' . esc_attr( $id ) . '" ';
		}

		return '<div ' . $id . 'class="wp-caption ' . esc_attr( $align ) . '" ' . $widthstyle . '>'
		       . do_shortcode( $content ) . '<p class="wp-caption-text ' . $captionclass . '"><span>' . $caption . '</span></p></div>';
	}

	add_shortcode( 'wp_caption', 'themewich_image_caption_class' );
	add_shortcode( 'caption', 'themewich_image_caption_class' );
endif;

if ( ! function_exists( 'themewich_addclass_to_images' ) ) :
	/**
	 * Add class to images based on alignment.
	 *
	 * @param  string      $html    string the html to insert into editor
	 * @param  integer     $id      image attachment id
	 * @param  string      $caption image caption
	 * @param  string      $alt     image alt attribute
	 * @param  string      $title   image title attribute
	 * @param  string      $align   image css alignment property
	 * @param  string      $url     image src url
	 * @param  string|bool $rel     image rel attribute
	 * @param  string      $size    image size (thumbnail, medium, large, full or added  with add_image_size() )
	 *
	 * @return string      the html to insert into editor
	 */
	function themewich_addclass_to_images( $html, $id, $caption, $title, $align, $url, $size, $alt = '' ) {
		switch ( $align ) {
			case 'parallax':
				$alignclass = 'parallaximg';
				break;
			case 'full':
				$alignclass = 'fullimg';
				break;
			case 'fixed':
				$alignclass = 'fixedimg';
				break;
			default:
				$alignclass = 'normal';
				break;
		}

		// Check for image tag in html content
		$found = preg_match( "/<img[^>]*>/", $html, $a_elem );

		// If no image, do nothing
		if ( $found <= 0 ) {
			return $html;
		}

		// Convert to string
		$a_elem = $a_elem[0];

		// If image already has class defined inject it to attribute
		if ( strstr( $a_elem, "class=\"" ) !== false ) {
			$a_elem_new = str_replace( "class=\"", "class=\"$alignclass ", $a_elem );
			$html       = str_replace( $a_elem, $a_elem_new, $html );
		} else { // If no class defined, just add class attribute
			$html = str_replace( "<img ", "<img class=\"$alignclass \" ", $html );
		}

		return $html;

	}

	add_filter( 'image_send_to_editor', 'themewich_addclass_to_images', 10, 8 );
endif;

if ( ! function_exists( 'themewich_gallery_shortcode' ) ) :
	/**
	 * Custom gallery html
	 *
	 * @param  array $attr Stores all shortcode properties
	 *
	 * @return string Modified gallery html
	 */
	function themewich_gallery_shortcode( $attr ) {
		global $tw_column_width;

		/**
		 * Initial default variables
		 */
		$post      = get_post();
		$posttype  = get_post_type( $post );
		$format    = get_post_format( $post->ID );
		$slidesize = 'gallery';
		$linked    = ( isset( $attr['link'] ) && $attr['link'] == 'none' ) ? false : true;

		/**
		 * Create output wrappings
		 */
		if ( isset( $attr['type'] ) ) :

			switch ( $attr['type'] ) :
				/**
				 * Slideshow Gallery
				 */
				case 'slideshow':

					// Get autoplay option
					if ( isset( $attr['autoplay'] ) && $attr['autoplay'] == 'yes' ) {
						$autoplay = 'autoplay';
					} else {
						$autoplay = 'no-autoplay';
					}

					// Get crop option
					if ( ( isset( $attr['crop'] ) && $attr['crop'] == 'nocrop' ) ) {
						$slidesize = 'contentslideshownc';
					} else {
						$slidesize = 'contentslideshow';
					}

					$type = "<div class='single-slideshow gallery-wrap info pager $autoplay'>";
					break;
			endswitch;

		else : // If no type is set, default to gallery
			$type = "<div class='single-gallery gallery-wrap fixed'>";
		endif;

		/**
		 * Start the creation of the gallery
		 * This is a modified version of WordPress'
		 * gallery function
		 */
		static $instance = 0;
		$instance ++;

		if ( ! empty( $attr['ids'] ) ) {
			// 'ids' is explicitly ordered, unless you specify otherwise.
			if ( empty( $attr['orderby'] ) ) {
				$attr['orderby'] = 'post__in';
			}
			$attr['include'] = $attr['ids'];
		}

		// Allow plugins/themes to override the default gallery template.
		$output = apply_filters( 'post_gallery', '', $attr );
		if ( $output != '' ) {
			return $output;
		}

		// We're trusting author input, so let's at least make sure it looks like a valid orderby statement
		if ( isset( $attr['orderby'] ) ) {
			$attr['orderby'] = sanitize_sql_orderby( $attr['orderby'] );
			if ( ! $attr['orderby'] ) {
				unset( $attr['orderby'] );
			}
		}

		extract( shortcode_atts( array(
			'order'      => 'ASC',
			'orderby'    => 'menu_order ID',
			'id'         => $post->ID,
			'itemtag'    => 'div',
			'icontag'    => 'div',
			'captiontag' => 'div',
			'columns'    => 3,
			'size'       => $slidesize, // set our thumbnail size
			'include'    => '',
			'exclude'    => ''
		), $attr ) );

		$id = intval( $id );

		// Set random order if it's set to random
		if ( 'RAND' == $order ) {
			$orderby = 'none';
		}

		if ( ! empty( $include ) ) {
			$_attachments = get_posts( array(
				'include'        => $include,
				'post_status'    => 'inherit',
				'post_type'      => 'attachment',
				'post_mime_type' => 'image',
				'order'          => $order,
				'orderby'        => $orderby
			) );
			$attachments  = array();
			foreach ( $_attachments as $key => $val ) {
				$attachments[ $val->ID ] = $_attachments[ $key ];
			}
		} elseif ( ! empty( $exclude ) ) {
			$attachments = get_children( array(
				'post_parent'    => $id,
				'exclude'        => $exclude,
				'post_status'    => 'inherit',
				'post_type'      => 'attachment',
				'post_mime_type' => 'image',
				'order'          => $order,
				'orderby'        => $orderby
			) );
		} else {
			$attachments = get_children( array(
				'post_parent'    => $id,
				'post_status'    => 'inherit',
				'post_type'      => 'attachment',
				'post_mime_type' => 'image',
				'order'          => $order,
				'orderby'        => $orderby
			) );
		}

		// If there's nothing, return nothing
		if ( empty( $attachments ) ) {
			return '';
		}

		if ( is_feed() ) {
			$output = "\n";
			foreach ( $attachments as $att_id => $attachment ) {
				$output .= wp_get_attachment_link( $att_id, $size, true ) . "\n";
			}

			return $output;
		}

		$itemtag    = tag_escape( $itemtag );
		$captiontag = tag_escape( $captiontag );
		$icontag    = tag_escape( $icontag );
		$valid_tags = wp_kses_allowed_html( 'post' );

		// set item tag
		if ( ! isset( $valid_tags[ $itemtag ] ) ) {
			$itemtag = 'div';
		}

		// set caption tag
		if ( ! isset( $valid_tags[ $captiontag ] ) ) {
			$captiontag = 'div';
		}

		// set icon tag
		if ( ! isset( $valid_tags[ $icontag ] ) ) {
			$icontag = 'div';
		}

		// sanitize number of columns
		$columns = intval( $columns );

		// set item width
		$itemwidth = $columns > 0 ? floor( 100 / $columns ) : 100;

		// set float if rtl
		$float = is_rtl() ? 'right' : 'left';

		// set selector
		$selector = "gallery-{$instance}";

		$gallery_style = $gallery_div = '';

		// use default gallery style
		if ( apply_filters( 'use_default_gallery_style', true ) ) {
			$gallery_style = "
		<style type='text/css' scoped='scoped'>
			#{$selector} .gallery-item {
				float: {$float};
				margin-top: 10px;
			}
			#{$selector} img {
				max-width:100% !important;
				height:auto !important;
			}
			#{$selector} .gallery-caption {
				margin-left: 0;
			}
		</style>";
		}

		// size class
		$size_class = sanitize_html_class( $size );

		// post type
		if ( $posttype == 'post' && $slidesize ) {
			$size_class = $slidesize;
		}

		// Set Slideshow Classes
		$slideshowclasses = 'pager nocaption nolink ';
		// Add type of slideshow class
		$slideshowclasses .= ( isset( $attr['type'] ) ) ? $attr['type'] . ' ' : '';
		// Add size and width classes too
		$slideshowclasses .= $slidesize . ' ';

		// Set wrapper
		if ( isset( $attr['type'] ) && ( $attr['type'] == 'slideshow' ) ) {
			$gallery_div = "$type <ul id='$selector' class='bxslider gallery galleryid-{$id} gallery-columns-{$columns} gallery-size-{$size_class} $slideshowclasses'>";
		} else {
			$gallery_div = "$type <div id='$selector' class='gallery galleryid-{$id} gallery-columns-{$columns} gallery-size-{$size_class}'>";
		}

		$output = apply_filters( 'gallery_style', $gallery_style . "\n\t\t" . $gallery_div );

		///////////////////////
		// Slideshow output //
		///////////////////////
		if ( isset( $attr['type'] ) && ( $attr['type'] == 'slideshow' ) ) :
			$i = 0;
			foreach ( $attachments as $id => $attachment ) :
				$default_attr = array(
					'title' => apply_filters( 'the_title', $attachment->post_title ),
				);
				$image        = wp_get_attachment_image( $id, $size, false, $default_attr );
				$image        = preg_replace( '/(width|height)=\"\d*\"\s/', "", $image );
				$link         = wp_get_attachment_url( $id );
				$output       .= "
				<li class='gallery-icon";
				$output       .= ( $linked ) ? ' linked' : ' notlinked';
				$output       .= "'>";
				$output       .= ( $link && $linked ) ? "<a href='$link' class='lightbox-gallery'>" : '';
				$output       .= "$image";
				if ( $captiontag && trim( $attachment->post_excerpt ) ) {
					$output .= "
					<div class='wp-caption-text gallery-caption'>
					  <span>
					" . wptexturize( strip_tags( $attachment->post_excerpt ) ) . "
					  </span>
					</div>";
				}
				$output .= ( $link && $linked ) ? "</a>" : "";
				$output .= "</li>";
			endforeach;

		/////////////////////////////
		// Regular Gallery Output //
		/////////////////////////////
		else :
			$i = 0;
			foreach ( $attachments as $id => $attachment ) :
				$default_attr = array(
					'title' => apply_filters( 'the_title', $attachment->post_title ),
				);
				$image        = wp_get_attachment_image( $id, $size, false, $default_attr );
				$image        = preg_replace( '/(width|height)=\"\d*\"\s/', "", $image );
				$link         = wp_get_attachment_url( $id );

				$output .= "<{$itemtag} class='gallery-item gallery-icon'>";
				// $output .= "<{$icontag} class='gallery-icon'>";
				$output .= "
			<{$icontag}  class='gallery-icon";
				$output .= ( $linked ) ? ' linked' : ' notlinked';
				$output .= "'>";
				$output .= ( $link && $linked ) ? "<a href='$link' class='lightbox-gallery no-ajaxy'>" : '';
				$output .= $image;
				if ( $captiontag && trim( $attachment->post_excerpt ) ) {
					$output .= "
					<{$captiontag} class='wp-caption-text gallery-caption'>
					  <span>
					" . wptexturize( strip_tags( $attachment->post_excerpt ) ) . "
					  </span>
					</{$captiontag}>";
				}
				$i ++;

				$output .= ( $link && $linked ) ? "</a>" : "";
				$output .= "</{$icontag}>";
				$output .= "</{$itemtag}>";
			endforeach;
		endif;

		// Add correct end
		$output .= ( isset( $attr['type'] ) && ( $attr['type'] == 'slideshow' ) ) ? '</ul><div class="clear"></div>' : '<div class="clear"></div></div>';

		// Close out container
		$output .= "</div>\n<div class='clear'></div>";

		return $output;
	}

	add_shortcode( 'gallery', 'themewich_gallery_shortcode' );
endif;

if ( ! function_exists( 'themewich_close_unclosed_tags' ) ) :
	/**
	 * Close unclosed html tags
	 *
	 * @since Edition 1.0
	 */
	function themewich_close_unclosed_tags( $unclosedString ) {
		preg_match_all( "/<([^\/]\w*)>/", $closedString = $unclosedString, $tags );
		for ( $i = count( $tags[1] ) - 1; $i >= 0; $i -- ) {
			$tag = $tags[1][ $i ];
			if ( substr_count( $closedString, "</$tag>" ) < substr_count( $closedString, "<$tag>" ) ) {
				$closedString .= "</$tag>";
			}
		}

		return $closedString;
	}
endif;

if ( ! function_exists( 'themewich_more_sizes' ) ) :
	/**
	 * Adds additional sizes to the gallery thumbnail dropdown
	 *
	 * @param  array $sizes Stores all the available sizes
	 *
	 * @return array Returns the new array with the additional sizes
	 */
	function themewich_more_sizes( $sizes ) {
		$sizes['fullslideshownc'] = __( 'Parallax Optimized', 'themewich' );

		return $sizes;
	}

	add_filter( 'image_size_names_choose', 'themewich_more_sizes', 4, 1 );
endif;

/**
 * Class to add additional optinos to image gallery popup
 *
 * @since  Edition 1.0
 */
if ( ! class_exists( 'Custom_Gallery_Setting' ) ) :
	class Custom_Gallery_Setting {
		/**
		 * Stores the class instance.
		 *
		 * @var Custom_Gallery_Setting
		 */
		private static $instance = null;

		/**
		 * Returns the instance of this class.
		 *
		 * It's a singleton class.
		 *
		 * @return Custom_Gallery_Setting The instance
		 */
		public static function get_instance() {
			if ( ! self::$instance ) {
				self::$instance = new self;
			}

			return self::$instance;
		}

		/**
		 * Initialises the plugin.
		 */
		public function init_plugin() {
			$this->init_hooks();
		}

		/**
		 * Initialises the WP actions.
		 */
		private function init_hooks() {
			add_action( 'wp_enqueue_media', array( $this, 'wp_enqueue_media' ) );
			add_action( 'print_media_templates', array( $this, 'print_media_templates' ) );
		}

		/**
		 * Enqueues the script.
		 */
		public function wp_enqueue_media() {
			if ( ! isset( get_current_screen()->id ) || get_current_screen()->base != 'post' ) {
				return;
			}
			wp_enqueue_script(
				'custom-gallery-settings',
				get_template_directory_uri() . '/functions/js/custom-gallery-setting.js',
				array( 'media-views' )
			);
		}

		/**
		 * Outputs the view template with the custom setting.
		 */
		public function print_media_templates() {
			if ( ! isset( get_current_screen()->id ) || get_current_screen()->base != 'post' ) {
				return;
			}

			?>
            <script type="text/html" id="tmpl-custom-gallery-type">
                <label class="setting gallery-type">
                    <span><?php _e( 'Gallery Type', 'themewich' ); ?></span>
                    <select class="type gallery-type" name="type" data-setting="type">
						<?php
						$types = array(
							'gallery'   => __( 'Gallery', 'themewich' ),
							'slideshow' => __( 'Slideshow', 'themewich' ),
							//'carousel' => __( 'Carousel', 'themewich' )
						);
						foreach ( $types as $value => $name ) { ?>
                            <option value="<?php echo esc_attr( $value ); ?>" <?php selected( $value, 'gallery' ); ?> >
								<?php echo esc_html( $name ); ?>
                            </option>
							<?php
						} ?>
                    </select>
                </label>
            </script>
            <script type="text/html" id="tmpl-custom-gallery-cropping">
                <label class="setting gallery-crop">
                    <span><?php _e( 'Cropping', 'themewich' ); ?></span>
                    <select class="type" name="crop" data-setting="crop">
						<?php
						$types = array(
							'crop'   => __( 'Crop Images', 'themewich' ),
							'nocrop' => __( 'Do Not Crop Images', 'themewich' )
						);
						foreach ( $types as $value => $name ) { ?>
                            <option value="<?php echo esc_attr( $value ); ?>" <?php selected( $value, 'slideshow' ); ?>>
								<?php echo esc_html( $name ); ?>
                            </option>
							<?php
						} ?>
                    </select>
                </label>
            </script>
            <script type="text/html" id="tmpl-custom-gallery-width">
                <label class="setting gallery-width">
                    <span><?php _e( 'Width', 'themewich' ); ?></span>
                    <select class="type" name="width" data-setting="width">
						<?php
						$types = array(
							'normal' => __( 'Normal Width', 'themewich' )
						);
						foreach ( $types as $value => $name ) { ?>
                            <option value="<?php echo esc_attr( $value ); ?>" <?php selected( $value, 'fixed' ); ?>>
								<?php echo esc_html( $name ); ?>
                            </option>
							<?php
						} ?>
                    </select>
                </label>
            </script>
            <script type="text/html" id="tmpl-custom-gallery-link">
                <label class="setting gallery-link">
                    <span><?php _e( 'Link', 'themewich' ); ?></span>
                    <select class="type" name="link" data-setting="link">
						<?php
						$types = array(
							'full' => __( 'Full Image', 'themewich' ),
							'none' => __( 'None', 'themewich' )
						);
						foreach ( $types as $value => $name ) { ?>
                            <option value="<?php echo esc_attr( $value ); ?>" <?php selected( $value, 'link' ); ?>>
								<?php echo esc_html( $name ); ?>
                            </option>
							<?php
						} ?>
                    </select>
                </label>
            </script>
			<?php

		}
	}

	add_action( 'admin_init', array( Custom_Gallery_Setting::get_instance(), 'init_plugin' ), 20 );
endif;

if ( ! function_exists( 'themewich_remove_comment_hash' ) ) :
	/**
	 * Removes hash from read-more buttons
	 *
	 * @param  string $link link to remove
	 *
	 * @return string       New link
	 */
	function themewich_remove_comment_hash( $link ) {
		return $link; // Manipulate comment link
	}

	add_filter( 'comment_link', 'themewich_remove_comment_hash', 10, 3 );
endif;

if ( ! function_exists( 'themewich_comment' ) ) :
	/**
	 * Comments template
	 * @since  v1.0
	 */
function themewich_comment( $comment, $args, $depth )
{
	$isByAuthor = false;
	if ( $comment->comment_author_email == get_the_author_meta( 'email' ) ) {
		$isByAuthor = true;
	}
	$GLOBALS['comment'] = $comment; ?>
    <li <?php comment_class(); ?> id="li-comment-<?php comment_ID() ?>">
        <div class="avatar" id="avatar-user-<?php echo esc_attr( $comment->user_id ); ?>">
			<?php echo get_avatar( $comment->comment_author_email, 65 ); ?>
        </div>
        <div id="comment-<?php comment_ID(); ?>" class="singlecomment">
            <p class="commentsmetadata">
                <cite><?php comment_date( 'F j, Y' ); ?></cite>
            </p>
            <div class="author">
                <div class="reply"><?php echo comment_reply_link( array(
						'depth'      => $depth,
						'max_depth'  => $args['max_depth'],
						'reply_text' => '<i class="icon-reply"></i> ' . __( 'Reply', 'themewich' )
					) ); ?></div>
                <div class="name"><?php comment_author_link() ?></div>
            </div>
			<?php if ( $comment->comment_approved == '0' ) : ?>
                <p class="moderation"><?php _e( 'Your comment is awaiting moderation.', 'themewich' ) ?></p>
			<?php endif; ?>
            <div class="commenttext">
				<?php comment_text() ?>
            </div>
        </div>
		<?php

		}
		endif;

if ( ! function_exists( 'themewich_theme_styles' ) ) :
/**
 * Loads themes stylesheets
 *
 * @since Edition 1.0
 */
function themewich_theme_styles() {
    if ( ! is_admin() ) {
        global $tw_options;

        // Edit CSS within their files
        wp_register_style( 'font-awesome', get_template_directory_uri() . '/css/font-awesome/css/font-awesome.min.css', false, '4.3.0' );
        wp_register_style( 'bootstrap', get_template_directory_uri() . '/css/bootstrap.min.css' );
        wp_register_style( 'theme-styles', get_stylesheet_uri(), array( 'bootstrap' ) );

        wp_enqueue_style( 'font-awesome' );
        wp_enqueue_style( 'theme-styles' );
    }
}

add_action( 'wp_enqueue_scripts', 'themewich_theme_styles' );
endif;

if ( ! function_exists( 'themewich_sticky_body_class' ) ) :
    /**
     * Adds body class if sticky nav is enabled
     *
     * @param  array $classes array of included body classes
     *
     * @return array          modified array of body classes
     */
    function themewich_sticky_body_class( $classes ) {
        global $tw_options;
        if ( isset( $tw_options['sticky-nav'] ) && $tw_options['sticky-nav'] ) {
            $classes[] = 'sticky-nav-enabled';
        }

        return $classes;
    }

    add_filter( 'body_class', 'themewich_sticky_body_class' );
endif;

if ( ! function_exists( 'themewich_custom_css' ) ) :
    /**
     * Adds inline styles from custom css box after theme styles
     * @return string
     */
    function themewich_custom_css() {
        global $tw_options;
        // Add theme options
        if ( isset( $tw_options['custom-css'] ) && $tw_options['custom-css'] ) {
            wp_add_inline_style( 'theme-styles', "/* Custom CSS */ \r\n " . $tw_options['custom-css'] );
        } else {
            return;
        }
    }

    add_action( 'wp_enqueue_scripts', 'themewich_custom_css' );
endif;

		if ( ! function_exists( 'themewich_register_js' ) ) :
			/**
			 * Registers and loads front-end javascript
			 *
			 * @since Edition 1.0
			 */
			function themewich_register_js() {
				if ( ! is_admin() ) {

					// Get theme version info
					global $themewich_theme_info;

					// Register theme javascript
					if ( ! wp_script_is( 'jquery' ) ) {
						wp_enqueue_script( 'jquery' );
					} // Load jquery if not already loaded
					wp_register_script( 'modernizr', get_template_directory_uri() . '/js/modernizr.custom.min.js', 'jquery', '2.6.2', false );
					wp_register_script( 'fitvids', get_template_directory_uri() . '/js/jquery.fitvids.js', 'jquery', '1.1', true );
					wp_register_script( 'isotope', get_template_directory_uri() . '/js/jquery.isotope.min.js', 'jquery', '2.2.0', true );
					wp_register_script( 'imagesloaded', get_template_directory_uri() . '/js/imagesloaded.pkgd.min.js', 'jquery', '3.1.8', true );
					wp_register_script( 'bxslider', get_template_directory_uri() . '/js/jquery.bxslider.min.js', 'jquery', '4.2.12', true );
					wp_register_script( 'magnificpopup', get_template_directory_uri() . '/js/jquery.magnific-popup.min.js', 'jquery', '1.0.0', true );
					wp_register_script( 'superfish', get_template_directory_uri() . '/js/superfish.min.js', 'jquery', '1.7.5', true );
					wp_register_script( 'mmenu', get_template_directory_uri() . '/js/jquery.mmenu.min.all.js', 'jquery', '5.0.4', true );
					wp_register_script( 'easing', get_template_directory_uri() . '/js/jquery.easing.1.3.js', 'jquery', '1.3', true );
					wp_register_script( 'custom', get_template_directory_uri() . '/js/custom.js', array(
						'jquery',
						'underscore'
					), $themewich_theme_info->Version, true );
					wp_register_script( 'backstretch', get_template_directory_uri() . '/js/jquery.backstretch.min.js', 'jquery', '2.0.4', true );
					wp_register_script( 'respond', get_template_directory_uri() . '/js/respond.min.js', 'jquery', '1.4.2', false );
					wp_register_script( 'fixto', get_template_directory_uri() . '/js/fixto.min.js', 'jquery', '0.3.0', false );

					// Localize the ajax script
					$variables_array = array(
						'ajaxurl'                    => admin_url( 'admin-ajax.php' ),
						'get_template_directory_uri' => get_template_directory_uri(),
						'nonce'                      => wp_create_nonce( 'ajax-nonce' )
					);
					wp_localize_script( 'custom', 'agAjax', $variables_array );

					// Enqueue javascript used on every page
					wp_enqueue_script( 'jquery' );
					wp_enqueue_script( 'modernizr' );
					wp_enqueue_script( 'superfish' );
					wp_enqueue_script( 'mmenu' );
					wp_enqueue_script( 'fitvids' );
					wp_enqueue_script( 'easing' );
					wp_enqueue_script( 'bxslider' );
					wp_enqueue_script( 'magnificpopup' );
					wp_enqueue_script( 'backstretch' );
					wp_enqueue_script( 'imagesloaded' );
					wp_enqueue_script( 'isotope' );
					wp_enqueue_script( 'fixto' );
					wp_enqueue_script( 'underscore' );

					wp_enqueue_script( 'custom' );

				}
			}

			add_action( 'wp_enqueue_scripts', 'themewich_register_js' );
		endif;

		if ( ! function_exists( 'themewich_tracking_code' ) ) :
			/**
			 * Prints tracking code to footer
			 * @return string Code from the theme options
			 */
			function themewich_tracking_code() {
				global $tw_options;
				if ( isset( $tw_options['tracking-code'] ) ) {
					echo htmlspecialchars_decode( esc_html( $tw_options['tracking-code'] ) ) ;
				}
			}

			add_action( 'wp_footer', 'themewich_tracking_code', 100 );
		endif;

		if ( ! function_exists( 'themewich_custom_js' ) ) :
			/**
			 * Prints custom js from theme options
			 * @return string js from the theme options
			 */
			function themewich_custom_js() {
				global $tw_options;
				if ( isset( $tw_options['custom-js'] ) ) {
					echo '<script type="text/javascript">' . $tw_options['custom-js'] . '</script>';
				}
			}

			add_action( 'wp_footer', 'themewich_custom_js', 999 );
		endif;

		/**
		 * @package nav-menu-custom-fields
		 * @version 0.1.0
		 */
		/*
 * Saves new field to postmeta for navigation
 */
		add_action( 'wp_update_nav_menu_item', 'custom_nav_update', 10, 3 );
		function custom_nav_update( $menu_id, $menu_item_db_id, $args ) {
			if ( isset( $_REQUEST['menu-item-custom'] ) ) {
				if ( is_array( $_REQUEST['menu-item-custom'] ) ) {
					if ( isset( $_REQUEST['menu-item-custom'][ $menu_item_db_id ] ) ) {
						$custom_value = $_REQUEST['menu-item-custom'][ $menu_item_db_id ];
						update_post_meta( $menu_item_db_id, '_menu_item_custom', $custom_value );
					}
				}
			} else {
				$custom_value = false;
				update_post_meta( $menu_item_db_id, '_menu_item_custom', $custom_value );
			}
		}

		/*
 * Adds value of new field to $item object that will be passed to     Walker_Nav_Menu_Edit_Custom
 */
		add_filter( 'wp_setup_nav_menu_item', 'custom_nav_item' );
		function custom_nav_item( $menu_item ) {
			$menu_item->custom = get_post_meta( $menu_item->ID, '_menu_item_custom', true );

			return $menu_item;
		}

		add_filter( 'wp_edit_nav_menu_walker', 'custom_nav_edit_walker', 10, 2 );
		function custom_nav_edit_walker( $walker, $menu_id ) {
			return 'Walker_Nav_Menu_Edit_Custom';
		}

		/**
		 * Copied from Walker_Nav_Menu_Edit class in core
		 *
		 * Create HTML list of nav menu input items.
		 *
		 * @package WordPress
		 * @since   3.0.0
		 * @uses    Walker_Nav_Menu
		 */
		class Walker_Nav_Menu_Edit_Custom extends Walker_Nav_Menu
		{
		/**
		 * @see   Walker_Nav_Menu::start_lvl()
		 * @since 3.0.0
		 *
		 * @param string $output Passed by reference.
		 */
		function start_lvl( &$output, $depth = 0, $args = array() ) {
		}
		/**
		 * @see   Walker_Nav_Menu::end_lvl()
		 * @since 3.0.0
		 *
		 * @param string $output Passed by reference.
		 */
		function end_lvl( &$output, $depth = 0, $args = array() ) {
		}
		/**
		 * @see   Walker::start_el()
		 * @since 3.0.0
		 *
		 * @param string $output Passed by reference. Used to append additional content.
		 * @param object $item   Menu item data object.
		 * @param int    $depth  Depth of menu item. Used for padding.
		 * @param object $args
		 */
		function start_el( &$output, $item, $depth = 0, $args = array(), $current_object_id = 0 )
		{
		global $_wp_nav_menu_max_depth;
		$_wp_nav_menu_max_depth = $depth > $_wp_nav_menu_max_depth ? $depth : $_wp_nav_menu_max_depth;
		$indent                 = ( $depth ) ? str_repeat( "\t", $depth ) : '';
		ob_start();
		$item_id        = esc_attr( $item->ID );
		$removed_args   = array(
			'action',
			'customlink-tab',
			'edit-menu-item',
			'menu-item',
			'page-tab',
			'_wpnonce',
		);
		$original_title = '';
		if ( 'taxonomy' == $item->type ) {
			$original_title = get_term_field( 'name', $item->object_id, $item->object, 'raw' );
			if ( is_wp_error( $original_title ) ) {
				$original_title = false;
			}
		} elseif ( 'post_type' == $item->type ) {
			$original_object = get_post( $item->object_id );
			$original_title  = $original_object->post_title;
		}
		$classes = array(
			'menu-item menu-item-depth-' . $depth,
			'menu-item-' . esc_attr( $item->object ),
			'menu-item-edit-' . ( ( isset( $_GET['edit-menu-item'] ) && $item_id == $_GET['edit-menu-item'] ) ? 'active' : 'inactive' ),
		);
		$title   = $item->title;
		if ( ! empty( $item->_invalid ) ) {
			$classes[] = 'menu-item-invalid';
			/* translators: %s: title of menu item which is invalid */
			$title = sprintf( __( '%s (Invalid)', 'themewich' ), $item->title );
		} elseif ( isset( $item->post_status ) && 'draft' == $item->post_status ) {
			$classes[] = 'pending';
			/* translators: %s: title of menu item in draft status */
			$title = sprintf( __( '%s (Pending)', 'themewich' ), $item->title );
		}
		$title = empty( $item->label ) ? $title : $item->label;
		?>
    <li id="menu-item-<?php echo (int) $item_id; ?>" class="<?php echo implode( ' ', $classes ); ?>">
        <dl class="menu-item-bar">
            <dt class="menu-item-handle">
                <span class="item-title"><?php echo esc_html( $title ); ?></span>
                <span class="item-controls">
						<span class="item-type"><?php echo esc_html( $item->type_label ); ?></span>
						<span class="item-order hide-if-js">
							<a href="<?php
							echo wp_nonce_url(
								esc_url(
									add_query_arg(
										array(
											'action'    => 'move-up-menu-item',
											'menu-item' => $item_id,
										),
										remove_query_arg( $removed_args, admin_url( 'nav-menus.php' ) )
									)
								),
								'move-menu_item'
							);
							?>" class="item-move-up"><abbr title="<?php esc_attr_e( 'Move up', 'themewich' ); ?>">&#8593;</abbr></a>
							|
							<a href="<?php
							echo wp_nonce_url(
								esc_url(
									add_query_arg(
										array(
											'action'    => 'move-down-menu-item',
											'menu-item' => $item_id,
										),
										remove_query_arg( $removed_args, admin_url( 'nav-menus.php' ) )
									)
								),
								'move-menu_item'
							);
							?>" class="item-move-down"><abbr title="<?php esc_attr_e( 'Move down', 'themewich' ); ?>">&#8595;</abbr></a>
						</span>
						<a class="item-edit" id="edit-<?php echo (int) $item_id; ?>" title="<?php esc_attr_e( 'Edit Menu Item', 'themewich' ); ?>" href="<?php
						echo ( isset( $_GET['edit-menu-item'] ) && $item_id == $_GET['edit-menu-item'] )
							? admin_url( 'nav-menus.php' )
							: esc_url(
								add_query_arg(
									'edit-menu-item',
									$item_id,
									esc_url(
										remove_query_arg(
											$removed_args,
											admin_url( 'nav-menus.php#menu-item-settings-' . $item_id )
										)
									)
								)
							);
						?>"><?php _e( 'Edit Menu Item', 'themewich' ); ?></a>
					</span>
            </dt>
        </dl>
        <div class="menu-item-settings" id="menu-item-settings-<?php echo (int)  $item_id; ?>">
			<?php if ( 'custom' == $item->type ) : ?>
                <p class="field-url description description-wide">
                    <label for="edit-menu-item-url-<?php echo (int) $item_id; ?>">
						<?php _e( 'URL', 'themewich' ); ?><br/>
                        <input type="text" id="edit-menu-item-url-<?php echo (int) $item_id; ?>" class="widefat code edit-menu-item-url" name="menu-item-url[<?php echo (int) $item_id; ?>]" value="<?php echo esc_attr( $item->url ); ?>"/>
                    </label>
                </p>
			<?php endif; ?>
            <p class="description description-thin">
                <label for="edit-menu-item-title-<?php echo (int) $item_id; ?>">
					<?php _e( 'Navigation Label', 'themewich' ); ?><br/>
                    <input type="text" id="edit-menu-item-title-<?php echo (int) $item_id; ?>" class="widefat edit-menu-item-title" name="menu-item-title[<?php echo (int) $item_id; ?>]" value="<?php echo esc_attr( $item->title ); ?>"/>
                </label>
            </p>
            <p class="description description-thin">
                <label for="edit-menu-item-attr-title-<?php echo (int) $item_id; ?>">
					<?php _e( 'Title Attribute', 'themewich' ); ?><br/>
                    <input type="text" id="edit-menu-item-attr-title-<?php echo (int) $item_id; ?>" class="widefat edit-menu-item-attr-title" name="menu-item-attr-title[<?php echo (int) $item_id; ?>]" value="<?php echo esc_attr( $item->post_excerpt ); ?>"/>
                </label>
            </p>
            <p class="field-link-target description">
                <label for="edit-menu-item-target-<?php echo (int) $item_id; ?>">
                    <input type="checkbox" id="edit-menu-item-target-<?php echo (int) $item_id; ?>" value="_blank" name="menu-item-target[<?php echo (int) $item_id; ?>]"<?php checked( $item->target, '_blank' ); ?> />
					<?php _e( 'Open link in a new window/tab', 'themewich' ); ?>
                </label>
            </p>
            <p class="field-css-classes description description-thin">
                <label for="edit-menu-item-classes-<?php echo (int) $item_id; ?>">
					<?php _e( 'CSS Classes (optional)', 'themewich' ); ?><br/>
                    <input type="text" id="edit-menu-item-classes-<?php echo (int) $item_id; ?>" class="widefat code edit-menu-item-classes" name="menu-item-classes[<?php echo (int) $item_id; ?>]" value="<?php echo esc_attr( implode( ' ', $item->classes ) ); ?>"/>
                </label>
            </p>
            <p class="field-xfn description description-thin">
                <label for="edit-menu-item-xfn-<?php echo (int) $item_id; ?>">
					<?php _e( 'Link Relationship (XFN)', 'themewich' ); ?><br/>
                    <input type="text" id="edit-menu-item-xfn-<?php echo (int) $item_id; ?>" class="widefat code edit-menu-item-xfn" name="menu-item-xfn[<?php echo (int) $item_id; ?>]" value="<?php echo esc_attr( $item->xfn ); ?>"/>
                </label>
            </p>
            <p class="field-description description description-wide">
                <label for="edit-menu-item-description-<?php echo (int) $item_id; ?>">
					<?php _e( 'Optional Content', 'themewich' ); ?><br/>
                    <textarea id="edit-menu-item-description-<?php echo (int) $item_id; ?>" class="widefat edit-menu-item-description" rows="3" cols="20" name="menu-item-description[<?php echo (int) $item_id; ?>]"><?php echo esc_html( $item->description ); // textarea_escaped
						?></textarea>
                    <span class="description"><?php _e( 'Add html, shortcodes or images here instead of submenu items.', 'themewich' ); ?></span>
                </label>
            </p>
			<?php

			/**
			 * Mega Menu Field
			 */
			?>
            <style>
                /* Inline to save on http requests */
                .mega-check {
                    display: none;
                }

                .menu-item-depth-0 .mega-check {
                    display: block;
                }
            </style>
            <p class="field-custom description description-wide mega-check">
                <label for="edit-menu-item-custom-<?php echo (int) $item_id; ?>">
					<?php _e( 'Make This Dropdown a Mega Menu', 'themewich' ); ?>
                    <input type="checkbox" style="float: left; margin-right: 5px;" id="edit-menu-item-custom-<?php echo (int) $item_id; ?>" value="on" name="menu-item-custom[<?php echo (int) $item_id; ?>]"<?php checked( $item->custom, 'on' ); ?> />
                </label>
            </p>
			<?php
			/*
			 * end Mega Menu Field
			 */
			?>
            <div class="menu-item-actions description-wide submitbox">
				<?php if ( 'custom' != $item->type && $original_title !== false ) : ?>
                    <p class="link-to-original">
						<?php printf( __( 'Original: %s', 'themewich' ), '<a href="' . esc_attr( $item->url ) . '">' . esc_html( $original_title ) . '</a>' ); ?>
                    </p>
				<?php endif; ?>
                <a class="item-delete submitdelete deletion" id="delete-<?php echo (int) $item_id; ?>" href="<?php
				echo wp_nonce_url(
					esc_url(
						add_query_arg(
							array(
								'action'    => 'delete-menu-item',
								'menu-item' => $item_id,
							),
							remove_query_arg( $removed_args, admin_url( 'nav-menus.php' ) )
						)
					),
					'delete-menu_item_' . (int) $item_id
				); ?>"><?php _e( 'Remove', 'themewich' ); ?></a> <span class="meta-sep"> | </span>
                <a class="item-cancel submitcancel" id="cancel-<?php echo (int) $item_id; ?>" href="<?php echo esc_url( add_query_arg( array(
					'edit-menu-item' => $item_id,
					'cancel'         => time()
				), remove_query_arg( $removed_args, admin_url( 'nav-menus.php' ) ) ) );
				?>#menu-item-settings-<?php echo (int) $item_id; ?>"><?php _e( 'Cancel', 'themewich' ); ?></a>
            </div>
            <input class="menu-item-data-db-id" type="hidden" name="menu-item-db-id[<?php echo (int) $item_id; ?>]" value="<?php echo (int) $item_id; ?>"/>
            <input class="menu-item-data-object-id" type="hidden" name="menu-item-object-id[<?php echo (int) $item_id; ?>]" value="<?php echo esc_attr( $item->object_id ); ?>"/>
            <input class="menu-item-data-object" type="hidden" name="menu-item-object[<?php echo (int) $item_id; ?>]" value="<?php echo esc_attr( $item->object ); ?>"/>
            <input class="menu-item-data-parent-id" type="hidden" name="menu-item-parent-id[<?php echo (int) $item_id; ?>]" value="<?php echo esc_attr( $item->menu_item_parent ); ?>"/>
            <input class="menu-item-data-position" type="hidden" name="menu-item-position[<?php echo (int) $item_id; ?>]" value="<?php echo esc_attr( $item->menu_order ); ?>"/>
            <input class="menu-item-data-type" type="hidden" name="menu-item-type[<?php echo (int) $item_id; ?>]" value="<?php echo esc_attr( $item->type ); ?>"/>
        </div><!-- .menu-item-settings-->
        <ul class="menu-item-transport"></ul>
		<?php
		$output .= ob_get_clean();
		}
		}

		if ( ! class_exists( 'Themewich_Mega_Walker' ) ) :
			class Themewich_Mega_walker extends Walker_Nav_Menu {
				function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {
					$indent      = ( $depth ) ? str_repeat( "\t", $depth ) : '';
					$class_names = $value = '';
					$classes     = empty( $item->classes ) ? array() : (array) $item->classes;
					$classes[]   = 'menu-item-' . $item->ID;
					$classes[]   = ( $item->custom == 'on' ) ? 'megamenu' : '';
					$classes[]   = ! empty( $item->description ) ? 'customsection' : '';

					/**
					 * Filter the CSS class(es) applied to a menu item's <li>.
					 *
					 * @since 3.0.0
					 *
					 * @param array  $classes The CSS classes that are applied to the menu item's <li>.
					 * @param object $item    The current menu item.
					 * @param array  $args    An array of arguments. @see wp_nav_menu()
					 */
					$class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item, $args ) );
					$class_names = $class_names ? ' class="' . esc_attr( $class_names ) . '"' : '';

					/**
					 * Filter the ID applied to a menu item's <li>.
					 *
					 * @since 3.0.1
					 *
					 * @param string The ID that is applied to the menu item's <li>.
					 * @param object $item The current menu item.
					 * @param array  $args An array of arguments. @see wp_nav_menu()
					 */
					$id             = apply_filters( 'nav_menu_item_id', 'menu-item-' . $item->ID, $item, $args );
					$id             = $id ? ' id="' . esc_attr( $id ) . '"' : '';
					$output         .= $indent . '<li' . $id . $value . $class_names . '>';
					$atts           = array();
					$atts['title']  = ! empty( $item->attr_title ) ? $item->attr_title : '';
					$atts['target'] = ! empty( $item->target ) ? $item->target : '';
					$atts['rel']    = ! empty( $item->xfn ) ? $item->xfn : '';
					$atts['href']   = ! empty( $item->url ) ? $item->url : '';

					/**
					 * Filter the HTML attributes applied to a menu item's <a>.
					 *
					 * @since 3.6.0
					 *
					 * @param array  $atts   {
					 *                       The HTML attributes applied to the menu item's <a>, empty strings are ignored.
					 *
					 * @type string  $title  The title attribute.
					 * @type string  $target The target attribute.
					 * @type string  $rel    The rel attribute.
					 * @type string  $href   The href attribute.
					 * }
					 *
					 * @param object $item   The current menu item.
					 * @param array  $args   An array of arguments. @see wp_nav_menu()
					 */
					$atts       = apply_filters( 'nav_menu_link_attributes', $atts, $item, $args );
					$attributes = '';
					foreach ( $atts as $attr => $value ) {
						if ( ! empty( $value ) ) {
							$value      = ( 'href' === $attr ) ? esc_url( $value ) : esc_attr( $value );
							$attributes .= ' ' . $attr . '="' . $value . '"';
						}
					}

					$item_output = $args->before;
					$item_output .= '<a' . $attributes . '>';

					/** This filter is documented in wp-includes/post-template.php */
					$item_output .= $args->link_before . apply_filters( 'the_title', $item->title, $item->ID ) . $args->link_after;
					$item_output .= '</a>';
					$item_output .= $args->after;

					/**
					 * Filter a menu item's starting output.
					 *
					 * The menu item's starting output only includes $args->before, the opening <a>,
					 * the menu item's title, the closing </a>, and $args->after. Currently, there is
					 * no filter for modifying the opening and closing <li> for a menu item.
					 *
					 * @since 3.0.0
					 *
					 * @param string $item_output The menu item's starting HTML output.
					 * @param object $item        Menu item data object.
					 * @param int    $depth       Depth of menu item. Used for padding.
					 * @param array  $args        An array of arguments. @see wp_nav_menu()
					 */
					$output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
				}
			}
		endif;

		if ( ! function_exists( 'themewich_wp_setup_nav_menu_item' ) ) :
			/**
			 * Re-Adds ability to have html in menu description
			 * @since Edition 1.0
			 */
			function themewich_wp_setup_nav_menu_item( $menu_item ) {
				if ( isset( $menu_item->post_content ) ) {
					$menu_item->description = apply_filters( 'nav_menu_description', $menu_item->post_content );
				}

				return $menu_item;
			}

			remove_filter( 'nav_menu_description', 'strip_tags' );
			add_filter( 'wp_setup_nav_menu_item', 'themewich_wp_setup_nav_menu_item' );
		endif;

		if ( ! function_exists( 'themewich_register_iecss' ) ) :
			/**
			 * Registers IE stylesheets
			 *
			 * @since Edition 1.0
			 */
			function themewich_register_iecss() {
				if ( ! is_admin() ) {
					global
					$wp_styles,
					$themewich_theme_info;

					// Edit IE CSS within their files
					wp_enqueue_style( "ie8", get_template_directory_uri() . "/css/ie8.css", false, $themewich_theme_info->Version, "all" );
					wp_enqueue_script( 'respond' );
					$wp_styles->add_data( "ie8", 'conditional', 'IE 8' );
				}
			}

			add_action( 'wp_enqueue_scripts', 'themewich_register_iecss' );
		endif;

		/**
		 * Register Edition widget areas
		 *
		 * @since  Edition 1.0
		 *
		 * @return void
		 */
		if ( ! function_exists( 'themewich_widgets_init' ) ) :
			function themewich_widgets_init() {
				register_sidebar( array(
					'name'          => 'Grid Section Sidebar',
					'id'            => 'grid-section-sidebar',
					'before_widget' => '<div id="%1$s" class="widget %2$s">',
					'after_widget'  => '</div><div class="clear"></div>',
					'before_title'  => '<h4 class="widget-title">',
					'after_title'   => '</h4>',
				) );
				register_sidebar( array(
					'name'          => 'Content Section Sidebar',
					'id'            => 'content-section-sidebar',
					'before_widget' => '<div id="%1$s" class="widget %2$s">',
					'after_widget'  => '</div><div class="clear"></div>',
					'before_title'  => '<h4 class="widget-title">',
					'after_title'   => '</h4>',
				) );
				register_sidebar( array(
					'name'          => 'Posts Section Sidebar',
					'id'            => 'posts-section-sidebar',
					'before_widget' => '<div id="%1$s" class="widget %2$s">',
					'after_widget'  => '</div><div class="clear"></div>',
					'before_title'  => '<h4 class="widget-title">',
					'after_title'   => '</h4>',
				) );
				register_sidebar( array(
					'name'          => 'Blog Sidebar',
					'id'            => 'blog-sidebar',
					'before_widget' => '<div id="%1$s" class="widget %2$s">',
					'after_widget'  => '</div><div class="clear"></div>',
					'before_title'  => '<h4 class="widget-title">',
					'after_title'   => '</h4>',
				) );
				register_sidebar( array(
					'name'          => 'Page Sidebar',
					'id'            => 'page-sidebar',
					'before_widget' => '<div id="%1$s" class="widget %2$s">',
					'after_widget'  => '</div><div class="clear"></div>',
					'before_title'  => '<h4 class="widget-title">',
					'after_title'   => '</h4>',
				) );
				register_sidebar( array(
					'name'          => 'Contact Sidebar',
					'id'            => 'contact-sidebar',
					'before_widget' => '<div id="%1$s" class="widget %2$s">',
					'after_widget'  => '</div><div class="clear"></div>',
					'before_title'  => '<h4 class="widget-title">',
					'after_title'   => '</h4>',
				) );

				// Specific woocommerce sidebar
				if ( class_exists( 'WooCommerce' ) ) {
					register_sidebar( array(
						'name'          => 'Shop Sidebar',
						'id'            => 'shop-sidebar',
						'before_widget' => '<div id="%1$s" class="widget %2$s">',
						'after_widget'  => '</div><div class="clear"></div>',
						'before_title'  => '<h3 class="widget-title">',
						'after_title'   => '</h3>',
					) );
				}

				register_sidebar( array(
					'name'          => 'Footer Left',
					'id'            => 'footer-left',
					'before_widget' => '<div id="%1$s" class="widget %2$s">',
					'after_widget'  => '</div><div class="clear"></div>',
					'before_title'  => '<h3 class="widget-title">',
					'after_title'   => '</h3>',
				) );
				register_sidebar( array(
					'name'          => 'Footer Center',
					'id'            => 'footer-center',
					'before_widget' => '<div id="%1$s" class="widget %2$s">',
					'after_widget'  => '</div><div class="clear"></div>',
					'before_title'  => '<h3 class="widget-title">',
					'after_title'   => '</h3>',
				) );
				register_sidebar( array(
					'name'          => 'Footer Right',
					'id'            => 'footer-right',
					'before_widget' => '<div id="%1$s" class="widget %2$s">',
					'after_widget'  => '</div><div class="clear"></div>',
					'before_title'  => '<h3 class="widget-title">',
					'after_title'   => '</h3>',
				) );
			}

			add_action( 'widgets_init', 'themewich_widgets_init' );
		endif;

		if ( ! function_exists( 'themewich_add_post_columns' ) ) :
			/**
			 * Add Column to Posts and Portfolio Admin Edit Screen
			 *
			 * @param  array $columns Array that stores the column number
			 *
			 * @return array          New array with added column
			 */
			function themewich_add_post_columns( $columns ) {
				$columns['featured'] = 'Featured';

				return $columns;
			}

			add_filter( 'manage_post_posts_columns', 'themewich_add_post_columns' );
			add_filter( 'manage_portfolio_posts_columns', 'themewich_add_post_columns' );
		endif;

		if ( ! function_exists( 'themewich_render_post_columns' ) ) :
			/**
			 * Render Custom Column
			 *
			 * @param  array   $column_name Name of column
			 * @param  integer $id          Id of the post
			 *
			 * @return echo                  Custom meta selection
			 */
			function themewich_render_post_columns( $column_name, $id ) {
				switch ( $column_name ) {
					case 'featured':
						// show widget set
						$featured = get_post_meta( $id, 'featured', true );
						if ( $featured ) :
							echo '<div id="featured-' . $id . '">' . $featured . '</div>';
						else :
							echo '<div id="featured-' . $id . '">' . __( 'No', 'themewich' ) . '</div>';
						endif;
				}
			}

			add_action( 'manage_posts_custom_column', 'themewich_render_post_columns', 10, 2 );
			add_action( 'manage_portfolio_custom_column', 'themewich_render_post_columns', 10, 2 );
		endif;

		if ( ! function_exists( 'themewich_add_quick_edit' ) ) :
			/**
			 * Adds featured option to quick edit menu
			 *
			 * @param  string $column_name Name of the column
			 * @param  string $post_type   Name of post type
			 *
			 * @return html                Dropdown html
			 */
			function themewich_add_quick_edit( $column_name, $post_type ) {
				if ( $column_name != 'featured' ) {
					return;
				} ?>
                <fieldset class="inline-edit-col-left">
                    <div class="inline-edit-col">
                        <span class="title"><?php _e( 'Featured', 'themewich' ); ?></span>
                        <input type="hidden" name="themewich_featured_noncename" id="themewich_featured_noncename" value=""/>
                        <select name='post_featured' id='post_featured'>
                            <option class='featured-option' value=''>- <?php _e( 'No Change', 'themewich' ); ?>-
                            </option>
                            <option class='featured-option' value='No'><?php _e( 'No', 'themewich' ); ?></option>
                            <option class='featured-option' value='Yes'><?php _e( 'Yes', 'themewich' ); ?></option>
                        </select>
                    </div>
                </fieldset>
				<?php

			}

			add_action( 'quick_edit_custom_box', 'themewich_add_quick_edit', 10, 2 );
			add_action( 'bulk_edit_custom_box', 'themewich_add_quick_edit', 10, 2 );
		endif;

		if ( ! function_exists( 'themewich_enqueue_edit_scripts' ) ) :
			/**
			 * Enqueue quickedit scripts
			 * @since Edition 1.0
			 */
			function themewich_enqueue_edit_scripts() {
				wp_enqueue_script(
					'themewich-admin-edit',
					get_template_directory_uri() . '/functions/js/quick_edit.js',
					array(
						'jquery',
						'inline-edit-post'
					),
					'',
					true
				);
			}

			add_action( 'admin_print_scripts-edit.php', 'themewich_enqueue_edit_scripts' );
		endif;

		if ( ! function_exists( 'themewich_save_quick_edit_data' ) ) :
			/**
			 * Saves quickedit info
			 *
			 * @param  integer $post_id ID of the post being saved
			 *
			 * @return integer          ID of post with featured data
			 */
			function themewich_save_quick_edit_data( $post_id ) {
				// verify if this is an auto save routine. If it is our form has not been submitted, so we dont want
				// to do anything
				if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
					return $post_id;
				}
				// Check permissions
				if ( isset( $_POST['post_type'] ) ) {
					if ( 'page' == $_POST['post_type'] ) {
						if ( ! current_user_can( 'edit_page', $post_id ) ) {
							return $post_id;
						}
					} else {
						if ( ! current_user_can( 'edit_post', $post_id ) ) {
							return $post_id;
						}
					}
				}
				// OK, we're authenticated: we need to find and save the data
				$post = get_post( $post_id );
				if ( isset( $_POST['post_featured'] ) && ( $post->post_type != 'revision' ) ) {
					$featured_id = esc_attr( $_POST['post_featured'] );
					if ( $featured_id ) {
						update_post_meta( $post_id, 'featured', $featured_id );
					} else {
						delete_post_meta( $post_id, 'featured' );
					}

					return $featured_id;
				}

			}

			add_action( 'save_post', 'themewich_save_quick_edit_data' );
		endif;

		if ( ! function_exists( 'themewich_save_bulk_edit' ) ) :
			/**
			 * Saves bulk edit data
			 * @since Edition 1.0
			 */
			function themewich_save_bulk_edit() {
				// get our variables
				$post_ids = ( isset( $_POST['post_ids'] ) && ! empty( $_POST['post_ids'] ) ) ? $_POST['post_ids'] : array();
				$featured = ( isset( $_POST['post_featured'] ) && ! empty( $_POST['post_featured'] ) ) ? $_POST['post_featured'] : null;
				// if everything is in order
				if ( ! empty( $post_ids ) && is_array( $post_ids ) && ! empty( $featured ) ) {
					foreach ( $post_ids as $post_id ) {
						update_post_meta( $post_id, 'featured', $featured );
					}
				}
			}

			add_action( 'wp_ajax_themewich_save_bulk_edit', 'themewich_save_bulk_edit' );
		endif;

		/**
		 * Add additional functionality for Qtranslate
		 * @since  Edition 1.0
		 */
		if ( function_exists( 'qtrans_modifyTermFormFor' ) ) {
			add_action( 'filter_add_form', 'qtrans_modifyTermFormFor' );
			add_action( 'filter_edit_form', 'qtrans_modifyTermFormFor' );
		}

		if ( ! function_exists( 'themewich_add_field_automatically' ) ) :
			/**
			 * Adds custom homepage order field on publish
			 * @since Edition 1.0
			 */
			function themewich_add_field_automatically( $post_ID ) {
				global $wpdb;
				if ( ! wp_is_post_revision( $post_ID ) ) {
					add_post_meta( $post_ID, 'homepage_order', '0', true );
				}
			}

			add_action( 'publish_post', 'themewich_add_field_automatically' );
		endif;

		if ( ! function_exists( 'themewich_get_attachment_link_filter' ) ) :
			/**
			 * Replace full size image in gallery with large
			 * @since  Edition 1.0
			 */
			function themewich_get_attachment_link_filter( $content, $post_id, $size, $permalink ) {
				// Only do this if we're getting the file URL
				if ( ! $permalink ) {
					// This returns an array of (url, width, height)
					$image       = wp_get_attachment_image_src( $post_id, 'large' );
					$new_content = preg_replace( '/href=\'(.*?)\'/', 'href=\'' . $image[0] . '\'', $content );

					return $new_content;
				} else {
					return $content;
				}
			}

			add_filter( 'wp_get_attachment_link', 'themewich_get_attachment_link_filter', 10, 4 );
		endif;

		/**
		 * This allows for the notification and installation of required
		 * plugins for the theme.
		 *
		 * @package    TGM-Plugin-Activation
		 * @subpackage gridstack
		 * @version    2.3.6
		 * @author     Thomas Griffin <thomas@thomasgriffinmedia.com>
		 * @author     Gary Jones <gamajo@gamajo.com>
		 * @copyright  Copyright (c) 2012, Thomas Griffin
		 * @license    http://opensource.org/licenses/gpl-2.0.php GPL v2 or later
		 * @link       https://github.com/thomasgriffin/TGM-Plugin-Activation
		 */

		// Include the TGM_Plugin_Activation class.
		require_once dirname( __FILE__ ) . '/framework/framework-functions/class-tgm-plugin-activation.php';

		if ( ! function_exists( 'themewich_register_required_plugins' ) ) :
			/**
			 * Register the required plugins for Edition.
			 *
			 * The variable passed to tgmpa_register_plugins() should be an array of plugin
			 * arrays.
			 *
			 * This function is hooked into tgmpa_init, which is fired within the
			 * TGM_Plugin_Activation class constructor.
			 *
			 * @since  Edition 1.0
			 */
			function themewich_register_required_plugins() {
				/**
				 * Array of plugin arrays. Required keys are name and slug.
				 * If the source is NOT from the .org repo, then source is also required.
				 */
				$plugins = array(
					// Include Shortcodes Plugin
					array(
						'name'               => 'Themewich Shortcodes',
						// The plugin name
						'slug'               => 'themewich-shortcodes',
						// The plugin slug (typically the folder name)
						'source'             => get_template_directory_uri() . '/functions/plugins/themewich-shortcodes.zip',
						// The plugin source
						'required'           => true,
						// If false, the plugin is only 'recommended' instead of required
						'version'            => '1.4.2',
						// E.g. 1.0.0. If set, the active plugin must be this version or higher, otherwise a notice is presented
						'force_activation'   => false,
						// If true, plugin is activated upon theme activation and cannot be deactivated until theme switch
						'force_deactivation' => false,
						// If true, plugin is deactivated upon theme switch, useful for theme-specific plugins
						'external_url'       => 'https://bitbucket.org/themewich/themewich-shortcodes',
						// If set, overrides default API URL and points to an external URL
					),

					// Include Sections Plugin
					array(
						'name'               => 'Themewich Sections',
						// The plugin name
						'slug'               => 'themewich-sections',
						// The plugin slug (typically the folder name)
						'source'             => get_template_directory_uri() . '/functions/plugins/themewich-sections.zip',
						// The plugin source
						'required'           => true,
						// If false, the plugin is only 'recommended' instead of required
						'version'            => '1.01',
						// E.g. 1.0.0. If set, the active plugin must be this version or higher, otherwise a notice is presented
						'force_activation'   => true,
						// If true, plugin is activated upon theme activation and cannot be deactivated until theme switch
						'force_deactivation' => false,
						// If true, plugin is deactivated upon theme switch, useful for theme-specific plugins
						'external_url'       => 'https://bitbucket.org/themewich/themewich-shortcodes',
						// If set, overrides default API URL and points to an external URL
					),

					// Include advanced custom fields plugin
					array(
						'name'               => 'Advanced Custom Fields',
						// The plugin name
						'slug'               => 'advanced-custom-fields',
						// The plugin slug (typically the folder name)
						'required'           => true,
						// If false, the plugin is only 'recommended' instead of required
						'version'            => '4.4.7',
						// E.g. 1.0.0. If set, the active plugin must be this version or higher, otherwise a notice is presented
						'force_activation'   => false,
						// If true, plugin is activated upon theme activation and cannot be deactivated until theme switch
						'force_deactivation' => false,
						// If true, plugin is deactivated upon theme switch, useful for theme-specific plugins
					),

					// Include sidebars add-on
					array(
						'name'               => 'Advanced Custom Fields Widget Add-On',
						// The plugin name
						'slug'               => 'advanced-custom-fields-widget-relationship-field-add-on',
						// The plugin slug (typically the folder name)
						'source'             => get_template_directory_uri() . '/functions/plugins/advanced-custom-fields-widget-relationship-field-add-on.zip',
						// The plugin source
						'required'           => true,
						// If false, the plugin is only 'recommended' instead of required
						'version'            => '1.4.0',
						// E.g. 1.0.0. If set, the active plugin must be this version or higher, otherwise a notice is presented
						'force_activation'   => false,
						// If true, plugin is activated upon theme activation and cannot be deactivated until theme switch
						'force_deactivation' => false,
						// If true, plugin is deactivated upon theme switch, useful for theme-specific plugins
						'external_url'       => 'http://wordpress.org/plugins/advanced-custom-fields-widget-relationship-field-add-on/',
						// If set, overrides default API URL and points to an external URL
					),

					// Include repeater add-on for review postings
					array(
						'name'               => 'Advanced Custom Fields Repeater',
						// The plugin name
						'slug'               => 'acf-repeater',
						// The plugin slug (typically the folder name)
						'source'             => get_template_directory_uri() . '/functions/plugins/acf-repeater.zip',
						// The plugin source
						'required'           => true,
						// If false, the plugin is only 'recommended' instead of required
						'version'            => '1.1.1',
						// E.g. 1.0.0. If set, the active plugin must be this version or higher, otherwise a notice is presented
						'force_activation'   => false,
						// If true, plugin is activated upon theme activation and cannot be deactivated until theme switch
						'force_deactivation' => false,
						// If true, plugin is deactivated upon theme switch, useful for theme-specific plugins
						'external_url'       => 'http://www.advancedcustomfields.com/add-ons/repeater-field/',
						// If set, overrides default API URL and points to an external URL
					),

					// Include redux framework
					array(
						'name'     => 'Redux Framework',
						// The plugin name
						'slug'     => 'redux-framework',
						// The plugin slug (typically the folder name)
						'required' => false,
						// If false, the plugin is only 'recommended' instead of required
						'version'  => '3.6.0.2',
						// E.g. 1.0.0. If set, the active plugin must be this version or higher, otherwise a notice is presented
					),

					// Socialfans counter
					array(
						'name'               => 'SocialFans Counter',
						// The plugin name
						'slug'               => 'socialfans-counter',
						// The plugin slug (typically the folder name)
						'source'             => get_template_directory_uri() . '/functions/plugins/socialfans-counter.zip',
						// The plugin source
						'required'           => true,
						// If false, the plugin is only 'recommended' instead of required
						'version'            => '5.0.2',
						// E.g. 1.0.0. If set, the active plugin must be this version or higher, otherwise a notice is presented
						'force_activation'   => false,
						// If true, plugin is activated upon theme activation and cannot be deactivated until theme switch
						'force_deactivation' => false,
						// If true, plugin is deactivated upon theme switch, useful for theme-specific plugins
						'external_url'       => 'http://codecanyon.net/item/socialfans-wp-responsive-social-counter-plugin/6217746',
						// If set, overrides default API URL and points to an external URL
					),

					// Envato Market
					array(
						'name'               => 'Envato Market',
						// The plugin name
						'slug'               => 'envato-market',
						// The plugin slug (typically the folder name)
						'source'             => get_template_directory_uri() . '/functions/plugins/envato-market.zip',
						// The plugin source
						'required'           => true,
						// If false, the plugin is only 'recommended' instead of required
						'version'            => '2.0.1',
						// E.g. 1.0.0. If set, the active plugin must be this version or higher, otherwise a notice is presented
						'force_activation'   => false,
						// If true, plugin is activated upon theme activation and cannot be deactivated until theme switch
						'force_deactivation' => false,
						// If true, plugin is deactivated upon theme switch, useful for theme-specific plugins
						'external_url'       => 'https://envato.com/market-plugin/',
						// If set, overrides default API URL and points to an external URL
					),

					array(
						'name'     => 'WP Most Popular',
						'slug'     => 'wp-most-popular',
						'version'  => '0.3.1',
						'required' => true,
					),

					array(
						'name'     => 'Ninja Forms',
						'slug'     => 'ninja-forms',
						'version'  => '2.9.51',
						'required' => true,
					),

					array(
						'name'     => 'Classic Editor',
						'slug'     => 'classic-editor',
						'version'  => '1.3',
						'required' => false,
					),

					array(
						'name'     => 'Regenerate Thumbnails',
						'slug'     => 'regenerate-thumbnails',
						'version'  => '2.2.6',
						'required' => false,
					),

					array(
						'name'     => 'WooCommerce',
						'slug'     => 'woocommerce',
						'version'  => '2.6.2',
						'required' => false,
					),

					array(
						'name'     => 'WooCommerce Quantity Increment',
						'slug'     => 'woocommerce-quantity-increment',
						'version'  => '1.0',
						'required' => false,
					),

					array(
						'name'     => 'WooCommerce Menu Cart',
						'slug'     => 'woocommerce-menu-bar-cart',
						'version'  => '2.5.7',
						'required' => false,
					),

					array(
						'name'     => 'Yoast SEO',
						'slug'     => 'wordpress-seo',
						'version'  => '3.3.4',
						'required' => false,
					),

					array(
						'name'     => 'Comet Cache',
						'slug'     => 'comet-cache',
						'version'  => '160706',
						'required' => false,
					),

					array(
						'name'     => 'Category and Taxonomy Order',
						'slug'     => 'taxonomy-terms-order',
						'version'  => '1.4.8',
						'required' => false,
					),

					/* Uncomment to Install */
					/* array(
				'name'      => 'Better WordPress Minify',
				'slug'      => 'bwp-minify',
				'version'	=> '1.2.3',
				'required'  => false,
			), */
				);

				// The theme text domain, used for internationalising strings
				$theme_text_domain = 'themewich';

				/**
				 * Array of configuration settings. Amend each line as needed.
				 */
				$config = array(
					'domain'       => $theme_text_domain,
					// Text domain - likely want to be the same as your theme.
					'default_path' => '',
					// Default absolute path to pre-packaged plugins
					//'parent_menu_slug'  => 'themes.php',                // Default parent menu slug
					//'parent_url_slug'   => 'themes.php',                // Default parent URL slug
					'menu'         => 'install-required-plugins',
					// Menu slug
					'has_notices'  => true,
					// Show admin notices or not
					'is_automatic' => true,
					// Automatically activate plugins after installation or not
					'message'      => '',
				);
				tgmpa( $plugins, $config );
			}

			add_action( 'tgmpa_register', 'themewich_register_required_plugins' );
		endif;

		if ( class_exists( 'WPSEO_Metabox' ) ) :
			/**
			 * Move yoast metabox to the bottom
			 * @since Edition 1.0
			 */
			function themewich_move_yoast() {
				return 'core';
			}

			add_filter( 'wpseo_metabox_prio', 'themewich_move_yoast' );
		endif;

		if ( ! function_exists( 'themewich_remove_yoast_metabox' ) ) :
			if ( class_exists( 'WPSEO_Metabox' ) ) :
				/**
				 * Removes yoast meta box from section page.
				 * @since Edition 1.0
				 */
				function themewich_remove_yoast_metabox() {
					remove_meta_box( 'wpseo_meta', 'section', 'normal' );
					wp_dequeue_script( 'wp-seo-metabox' );
				}

				add_action( 'add_meta_boxes', 'themewich_remove_yoast_metabox', 11 );
			endif;
		endif;

		/**
		 * Get Post Views if most popular function exists
		 * @since 1.0
		 */
		if ( function_exists( 'wp_most_popular_get_popular' ) ) :
			/**
			 * Function to display the post views
			 * @since 1.0
			 */
			if ( ! function_exists( 'themewich_get_post_views' ) ) :
				function themewich_get_post_views( $postID, $period = 'all_time' ) {
					global $wpdb;

					$views = ' ' . __( 'Views', 'themewich' );

					$sql = "
				SELECT
					*
				FROM
					{$wpdb->prefix}most_popular mp
				WHERE
					post_id = {$postID}
			";

					$result = $wpdb->get_row( $sql, 'ARRAY_A' );

					if ( is_array( $result ) ) {
						switch ( $period ) {
							case 'all_time':
								return $result['all_time_stats'] . $views;
								break;
							case 'daily':
								return $result['1_day_stats'] . $views;
								break;
							case 'weekly':
								return $result['7_day_stats'] . $views;
								break;
							case 'monthly':
								return $result['30_day_stats'] . $views;
								break;
							default:
								return $result['all_time_stats'] . $views;
								break;
						}
					} else {
						return 0 . $views;
					}
				}
			endif;
			if ( ! function_exists( 'themewich_remove_popular_widget' ) ) :
				/**
				 * Function to remove the default widget
				 * @since 1.0
				 */
				function themewich_remove_popular_widget() {
					unregister_widget( 'WMP_Widget' );
				}

				add_action( 'widgets_init', 'themewich_remove_popular_widget', 11 );
			endif;
		endif;

		/**
		 * Love Functionality
		 * Adapted from Tutsplus: "How to Create a Simple Post Rating System With WordPress and jQuery"
		 * http://wp.tutsplus.com/tutorials/how-to-create-a-simple-post-rating-system-with-wordpress-and-jquery/
		 *
		 * @since  1.0
		 */
		if ( ! function_exists( 'post_like' ) ) :
			$timebeforerevote = 43829; // Global variable in minutes before voting again is allowed set to 1 month
			/**
			 * Post like function
			 * @since Edition 1.0
			 */
			function post_like() {
				$nonce = $_POST['nonce'];

				// Verify Nonce
				if ( ! wp_verify_nonce( $nonce, 'ajax-nonce' ) ) {
					die( '...' );
				}

				if ( isset( $_POST['post_like'] ) ) {
					$ip      = $_SERVER['REMOTE_ADDR'];
					$post_id = $_POST['post_id'];

					$meta_IP = get_post_meta( $post_id, "voted_IP" );
					if ( isset( $meta_IP[0] ) ) {
						$voted_IP = $meta_IP[0];
					}
					if ( isset( $voted_IP ) ) {
						if ( ! is_array( $voted_IP ) ) {
							$voted_IP = array();
						}
					} else {
						$voted_IP = array();
					}

					$meta_count = get_post_meta( $post_id, "votes_count", true );
					if ( ! hasAlreadyVoted( $post_id ) ) {
						$voted_IP[ $ip ] = time();
						update_post_meta( $post_id, "voted_IP", $voted_IP );
						update_post_meta( $post_id, "votes_count", ++ $meta_count );

						echo (int) $meta_count;
					} else {
						echo "already";
					}
				}
				exit;
			}

			// Add our own handlers for the ajax request
			add_action( 'wp_ajax_nopriv_post-like', 'post_like' );
			add_action( 'wp_ajax_post-like', 'post_like' );
		endif;
		if ( ! function_exists( 'hasAlreadyVoted' ) ) :
			/**
			 * Checks to see if the user has already voted
			 * @since Edition 1.0
			 */
			function hasAlreadyVoted( $post_id ) {
				global $timebeforerevote;
				$meta_IP = get_post_meta( $post_id, "voted_IP" );
				if ( isset( $meta_IP[0] ) ) {
					$voted_IP = $meta_IP[0];
				}
				if ( isset( $voted_IP ) ) {
					if ( ! is_array( $voted_IP ) ) {
						$voted_IP = array();
					}
				} else if ( ! isset( $voted_IP ) ) {
					$voted_IP = array();
				}

				$ip = $_SERVER['REMOTE_ADDR'];

				if ( in_array( $ip, array_keys( $voted_IP ) ) ) {
					$time = $voted_IP[ $ip ];
					$now  = time();

					if ( round( ( $now - $time ) / 60 ) > $timebeforerevote ) {
						return false;
					}

					return true;
				}

				return false;
			}
		endif;

		if ( ! function_exists( 'themewich_vote_style' ) ) :
			function themewich_vote_style( $input ) {
				$input       = number_format( $input );
				$input_count = substr_count( $input, ',' );
				if ( $input_count != '0' ) {
					if ( $input_count == '1' ) {
						return substr( $input, 0, - 4 ) . 'k'; // thousand
					} else if ( $input_count == '2' ) {
						return substr( $input, 0, - 8 ) . 'm'; // million
					} else if ( $input_count == '3' ) {
						return substr( $input, 0, - 12 ) . 'b'; // billion
					} else {
						return;
					}
				} else {
					return $input;
				}
			}
		endif;
		if ( ! function_exists( 'getPostLoveLink' ) ) :
			/**
			 * Displays love icon
			 * @since Edition 1.0
			 */
			function getPostLoveLink( $post_id ) {
				$themename  = "edition";
				$vote_count = get_post_meta( $post_id, "votes_count", true );
				$has_voted  = hasAlreadyVoted( $post_id );
				if ( ! $vote_count ) {
					$vote_count = 0;
				}
				if ( $has_voted ) {
					$output = '<aside class="post-link love voted">';
				} else {
					$output = '<a href="#" class="post-like love" data-post_id="' . $post_id . '">';
				}
				$vote_count = themewich_vote_style( $vote_count );
				$output     .= '<div class="sharecircle count">' . $vote_count . '</div><i class="fa fa-heart-o"></i>';
				$output     .= '<span class="sharetitle" data-clicked="' . __( 'Loved', 'themewich' ) . '">';
				if ( $has_voted ) {
					$output .= __( 'Loved', 'themewich' );
				} else {
					$output .= __( 'Love', 'themewich' );
				}
				$output .= '</span>';
				if ( $has_voted ) {
					$output .= '</aside>';
				} else {
					$output .= '</a>';
				}

				return $output;
			}
		endif;

		/**
		 * Share Count Functionality
		 * Adapted from Tutsplus: "How to Create a Simple Post Rating System With WordPress and jQuery"
		 * http://wp.tutsplus.com/tutorials/how-to-create-a-simple-post-rating-system-with-wordpress-and-jquery/
		 *
		 * @since Edition 1.0
		 */
		if ( ! function_exists( 'post_share' ) ) :
			/**
			 * Displays share icon
			 * @since  Edition 1.0
			 */
			function post_share() {
				$nonce = $_POST['nonce'];

				// Verify Nonce
				if ( ! wp_verify_nonce( $nonce, 'ajax-nonce' ) ) {
					die( 'Reload Page' );
				}

				if ( isset( $_POST['post_share'] ) ) {
					$post_id = $_POST['post_id'];

					$meta_shares_count = get_post_meta( $post_id, "shares_count", true );
					update_post_meta( $post_id, "shares_count", ++ $meta_shares_count );

					echo (int) $meta_shares_count;
				}
				exit;
			}

			// Add our own handlers for the ajax request
			add_action( 'wp_ajax_nopriv_post-share', 'post_share' );
			add_action( 'wp_ajax_post-share', 'post_share' );
		endif;
		if ( ! function_exists( 'getPostShareLink' ) ) :
			/**
			 * Displays share icon
			 * @since  Edition 1.0
			 */
			function getPostShareLink( $post_id ) {
				$themename    = "edition";
				$shares_count = get_post_meta( $post_id, "shares_count", true );
				if ( ! $shares_count ) {
					$shares_count = 0;
				}
				$shares_count = themewich_vote_style( $shares_count );
				$output       = '<a href="#share-box" class="open-popup-link post-share share popup-with-move-anim';
				$output       .= '" data-post_id="' . $post_id . '">';
				$output       .= '<div class="sharecircle count">' . $shares_count . '</div>';
				$output       .= '<i class="fa fa-share-square-o"></i><span class="sharetitle" data-clicked="' . __( 'Shared', 'themewich' ) . '">' . __( 'Share', 'themewich' ) . '</span>
				  </a>';

				return $output;
			}
		endif;

		if ( ! function_exists( 'ag_get_related_post_args' ) ) :
			/**
			 * Gets related posts
			 *
			 * @param int $id Post ID
			 *
			 * @since Edition 1.0
			 */
			function ag_get_related_post_args( $id ) {
				global $relatedcatargs, $relatedargs;

				$rel_tagnames  = '';
				$rel_catnames  = '';
				$relatednumber = apply_filters( 'tw_related_posts', 2 );
				// Get related post tag names
				$rel_tags = get_the_tags( $id );

				if ( $rel_tags ) {
					// Get list of tag names and set arguments for loop
					foreach ( $rel_tags as $rel_tag ) {
						$rel_tagnames .= $rel_tag->slug . ',';
					}

					$rel_tagnames = rtrim( $rel_tagnames, "," );
					$relatedargs  = array(
						'ignore_sticky_posts' => 1,
						'tag'                 => $rel_tagnames,
						'post__not_in'        => array( $id ),
						'showposts'           => $relatednumber,
						'orderby'             => 'rand'
					);
				}
				// Get list of category names and set arguments for loop
				$post_cats = wp_get_post_categories( $id );
				foreach ( $post_cats as $post_cat ) {
					$cat          = get_category( $post_cat );
					$rel_catnames .= $cat->slug . ',';
				}
				$rel_catnames   = rtrim( $rel_catnames, "," );
				$relatedcatargs = array(
					'ignore_sticky_posts' => 1,
					'category_name'       => $rel_catnames,
					'post__not_in'        => array( $id ),
					'showposts'           => $relatednumber,
					'orderby'             => 'rand'
				);
			}
		endif;

		if ( ! function_exists( 'themewich_load_widget_posts' ) ) :
			/**
			 * Controls widget ajax
			 *
			 * @param int $id Post ID
			 *
			 * @since Edition 1.0
			 */
			function themewich_load_widget_posts( $id ) {
				if ( function_exists( 'wp_most_popular_get_popular' ) ) :
					global $numposts;
					// get the category ID we need to load from
					$query    = $_POST['query'];
					$numposts = $_POST['posts'];
					if ( ! $numposts || $numposts == '' ) {
						$numposts = '5';
					}
					$posts = wp_most_popular_get_popular( array(
						'limit'     => $numposts,
						'post_type' => 'post',
						'range'     => $query
					) );
					global $post;
					if ( count( $posts ) > 0 ) :
						foreach ( $posts as $post ) :
							setup_postdata( $post );
							$entry = array();
							// get the post's ID
							$entry['id'] = $post->ID;
							// get the post's title
							$entry['title'] = $post->post_title;
							// get the post link
							$entry['link']  = get_permalink( $post->ID );
							$entry['views'] = themewich_get_post_views( get_the_ID(), $query );
							// get the post image, alt text
							if ( has_post_thumbnail( $post->ID ) ) {
								$thumb        = get_post_meta( $post->ID, '_thumbnail_id', false ); // Get Image ID
								$alt          = get_post_meta( $thumb, '_wp_attachment_image_alt', true ); // Alt text of image
								$thumb1       = wp_get_attachment_image_src( $thumb[0], 'tinyfeatured', false );  // URL of Featured Full Image
								$entry['img'] = $thumb1[0];
							}
							// store the array as a variable
							$arr[] = $entry;
						endforeach;
						// then output in json format
						header( "Content-Type: application/json" );
						echo json_encode( $arr );
						exit;
					endif;
				endif;
			}

			// Add our own handlers for the ajax request
			add_action( 'wp_ajax_nopriv_themewich_load_widget_posts', 'themewich_load_widget_posts' );
			add_action( 'wp_ajax_themewich_load_widget_posts', 'themewich_load_widget_posts' );

		endif;

		/**
		 * Add class to next and previous post links
		 * @since  Edition 1.0
		 */
		if ( ! function_exists( 'themewich_next_posts_link_attributes' ) ) :
			function themewich_next_posts_link_attributes() {
				return 'class="hint--left righthint" data-hint="' . __( 'Older Posts', 'themewich' ) . '"';
			}

			add_filter( 'next_posts_link_attributes', 'themewich_next_posts_link_attributes' );
		endif;
		if ( ! function_exists( 'previous_posts_link_attributes' ) ) :
			function themewich_prev_posts_link_attributes() {
				return 'class="hint--left righthint" data-hint="' . __( 'Newer Posts', 'themewich' ) . '"';
			}

			add_filter( 'previous_posts_link_attributes', 'themewich_prev_posts_link_attributes' );
		endif;

		if ( ! function_exists( 'themewich_review_circle' ) ) :
			/**
			 * Add Column to Posts and Portfolio Admin Edit Screen
			 *
			 * @param  array $columns Array that stores the column number
			 *
			 * @return array          New array with added column
			 */
			function themewich_review_circle( $title = 'none', $link = true, $single = false ) {
				global $post, $fields_installed;

				$tw_entry = themewich_post_options();

				if ( $fields_installed && isset( $tw_entry->review_post ) && $tw_entry->review_post == 'yes' ) :

					// Set defaults
					$total   = 0;
					$counter = 0;

					if ( have_rows( 'review_criteria' ) ) : // check if the repeater field has rows of data
						while ( have_rows( 'review_criteria' ) ) : the_row(); // loop through the rows of data
							$total = $total + get_sub_field( 'rating' ); // display a sub field value
							$counter ++;
						endwhile;

						// Calculate average
						if ( $total && $total != 0 ) {
							$average = $total / $counter;
							$average = round( $average, 1 );
						} else {
							$average = 0;
						}

						$output = '';
						if ( $link ) {
							if ( is_single( $post ) ) {
								$output .= '<a href="#breakdown" class="inner-content text-center">';
							} else {
								$output .= '<a href="' . get_permalink( $post->ID ) . '" class="inner-content text-center">';
							}
						} else {
							$output .= '<div class="inner-content text-center">';
						}

						$output .= '<div class="c100 p' . $average * 10 . ' center">';

						if ( $single ) { // Microdata
							$output .= '<span itemprop="reviewRating" itemscope itemtype="http://schema.org/Rating">';
							$output .= '<span itemprop="ratingValue">' . $average . '</span><meta itemprop="bestRating" content="10"/>';
							$output .= '</span>';
						} else {
							$output .= '<span>' . $average . '</span>';
						}

						$output .= '<div class="slice"><div class="fill"></div>';
						$output .= '<div class="bar" style="-webkit-transform: rotate(' . round( $average * 10 * 3.6 ) . 'deg); -moz-transform: rotate(' . $average * 10 * 3.6 . 'deg); -ms-transform: rotate(' . $average * 10 * 3.6 . 'deg); -o-transform: rotate(' . $average * 10 * 3.6 . 'deg); transform: rotate(' . $average * 10 * 3.6 . 'deg);"></div>';
						$output .= '</div></div>';

						if ( $title != 'none' ) {
							$output .= '<p class="summary-title">' . $tw_entry->review_title . '</p>';
						}

						if ( $link ) {
							$output .= '</a>';
						} else {
							$output .= '</div>';
						}

						return $output; // return the output

					endif; // have_rows( 'review_criteria' )
				endif; // $tw_entry->review_post == 'yes'
			}
		endif;

		if ( ! function_exists( 'themewich_post_args' ) ) :
			/**
			 * Function to get latest posts - either featured, category, tag or latest
			 *
			 * @param  string $type Type of query
			 * @param  array  $args Additional arguments
			 *
			 * @return array            Returns array of arguments for query
			 */
			function themewich_post_args( $args ) {
				global $tw_section;

				$section_options = array(
					'tw_query'       => tw_issetor( $tw_section->section_query_tax ),  // Users Query
					'tw_query_type'  => tw_issetor( $tw_section->section_query_type ),    // Query Type
					'tw_taxonomy'    => tw_issetor( $tw_section->taxonomy ),        // Taxonomy
					'posts_per_page' => tw_issetor( $tw_section->section_post_number ),    // Set posts per page
				);

				if ( isset( $tw_section->section_type ) && $tw_section->section_type == 'section-full-post' ) {
					$section_options['posts_per_page'] = tw_issetor( $tw_section->full_section_post_number );
				}

				if ( isset( $section_options['tw_query'] ) ) :
					switch ( $section_options['tw_query'] ) {

						/**
						 * Tag Query
						 */
						case 'tag':
							$additional_query = array(
								'tag__in' => tw_issetor( $section_options['tw_taxonomy'] ),
								'orderby' => 'date', // Custom order value
							);
							break;

						/**
						 * Category Query
						 */
						case 'category':
							if ( isset( $section_options['tw_taxonomy'] ) && is_array( $section_options['tw_taxonomy'] ) ) {
								$section_options['tw_taxonomy'] = implode( ",", $section_options['tw_taxonomy'] );
							}
							$additional_query = array(
								'cat'     => tw_issetor( $section_options['tw_taxonomy'] ),
								'orderby' => 'date', // Custom order value
							);
							break;

						/**
						 * Product Query
						 */
						case 'products':
							// change post type to products
							$args['post_type'] = array( 'product' );
							break;

						/**
						 * Product Category Query
						 */
						case 'product-cat':

							// get selected products
							if ( isset( $section_options['tw_taxonomy'] ) && is_array( $section_options['tw_taxonomy'] ) ) {

								// add additional query
								$additional_query = array(
									'tax_query' => array(
										array(
											'taxonomy' => 'product_cat',
											'field'    => 'id',
											'terms'    => $section_options['tw_taxonomy']
										)
									),
									'orderby'   => 'date', // Custom order value
								);

								// change post type to products
								$args['post_type'] = array( 'product' );

							}

							break;

						/**
						 * Product tag query
						 */
						case 'product-tag':

							// get selected products
							if ( isset( $section_options['tw_taxonomy'] ) && is_array( $section_options['tw_taxonomy'] ) ) {

								// add additional query
								$additional_query = array(
									'tax_query' => array(
										array(
											'taxonomy' => 'product_tag',
											'field'    => 'id',
											'terms'    => $section_options['tw_taxonomy']
										)
									),
									'orderby'   => 'date', // Custom order value
								);

								// change post type to products
								$args['post_type'] = array( 'product' );

							}
							break;

						/**
						 * Add nothing by default
						 */
						default:
							$additional_query = array();
							break;
					}
				endif;

				if ( $section_options['tw_query'] == 'products' ||
				     $section_options['tw_query'] == 'product-tag' ||
				     $section_options['tw_query'] == 'product-cat' ) :

					$additional_type = array(
						'orderby' => 'date', // Custom order value
					);

				else :

					if ( isset( $section_options['tw_query_type'] ) ) :
						switch ( $section_options['tw_query_type'] ) {
							case 'featured':
								$additional_type = array(
									'orderby'    => 'meta_value_num', // Custom order value
									'meta_key'   => 'homepage_order', // Custom order field
									'order'      => 'ASC', // Order by ascending values
									'meta_query' => array(
										array( // Query only marked as featured
											'key'     => 'featured',
											'value'   => 'Yes',
											'compare' => '=='
										),
										array(
											'meta_key' => '_thumbnail_id'
										)
									)
								);
								break;
							// Latest Posts
							default:
								$additional_type = array(
									'orderby' => 'date', // Custom order value
								);
								break;
						}
					endif;

				endif;


				$args = isset( $section_options ) ? array_merge( $args, $section_options ) : $args;
				$args = isset( $additional_query ) ? array_merge( $args, $additional_query ) : $args;
				$args = isset( $additional_type ) ? array_merge( $args, $additional_type ) : $args;

				return apply_filters( 'tw_section_query', $args );
			}
		endif;


		//function tw_total_review( $post_id ) {
		//
		//	// bail early if no ACF data
		//    // if ( empty( $_POST['acf'] ) ) {
		//    //     return;
		//    // }
		//
		//	if ( have_rows( 'review_criteria', $post_id ) ) : // check if the repeater field has rows of data
		//
		//		while ( have_rows( 'review_criteria', $post_id ) ) : the_row(); // loop through the rows of data
		//			$total = $total + get_sub_field('rating'); // display a sub field value
		//			$counter++;
		//		endwhile;
		//
		//		// Calculate average
		//		if ( $total && $total != 0 ) {
		//			$average = $total / $counter;
		//			$average = round( $average, 1 );
		//		} else {
		//			$average = 0;
		//		}
		//
		//		// update post meta
		//		update_post_meta($post_id, 'total_rating', $average );
		//	endif;
		//
		//    // return the new ID
		//    return $post_id;
		//
		//}
		//// run after ACF saves the $_POST['acf'] data
		//add_action('save_post', 'tw_total_review');

		//// example on how to filter args for a specific section
		//function filter_args($args) {
		//	global $post;
		//
		//	// if it's section with an ID of 115, filter the args
		//	if ( $post->ID == 115 ) {
		//		$args['orderby']  = 'meta_value_num';
		//		$args['meta_key'] = 'total_rating'; // Custom order field
		//	}
		//
		//	return $args;
		//
		//}
		//add_filter( 'tw_section_query', 'filter_args' );


		if ( ! function_exists( 'themewich_section_admin_script' ) ) :
			/**
			 * These scripts convert radio buttons into tabs in the admin
			 *
			 * @since  Edition 1.0
			 * @return void
			 */
			function themewich_section_admin_script( $hook ) {
				global $post_type;

				$screen  = get_current_screen();
				$enqueue = false;

				if ( isset( $screen->post_type ) ) {
					if ( $screen->post_type == 'section' || $screen->post_type != 'page' ) {
						$enqueue = true;
					}
				}

				if ( ! $enqueue ) {
					return;
				} // only enqueue on section pages

				wp_enqueue_script( 'section-admin-script', get_template_directory_uri() . '/functions/js/section-admin.js' );
				wp_enqueue_style( 'section-admin', get_template_directory_uri() . '/functions/css/section-admin.css', '1.0' );
			}

			add_action( 'admin_enqueue_scripts', 'themewich_section_admin_script', 11 );
		endif;

		if ( ! function_exists( 'themewich_post_options' ) ) :
			/**
			 * Gets post options and maps it to an object
			 *
			 * @since  Edition 1.0
			 * @return void
			 */
			function themewich_post_options() {
				global $post;
				global $tw_options;

				////////////////////
				// Set defaults //
				////////////////////
				$tw_defaults = array(
					"post_columns"     => 2,        // Sidebar on/off
					"featured_image"   => 1,        // Full featured image on/off
					"auto_dropcap"     => 1,        // Auto Dropcap on/off
					"featured"         => 'No',    // Featured post
					"customize"        => 0,        // Customize this post
					"sharing"          => 1,        // Sharing on/off
					"author_box"       => 0,        // Author Box on/off
					"related"          => 1,        // Related Posts on/off
					"media"            => false,    // Media Box
					"has_media"        => false,    // Media Box enabled
					"review_post"      => 0,        // Review on/off
					"review_title"     => '',        // Review title
					"review_criteria"  => null,    // Review criteria
					"review_summary"   => '',        // Review description
					"review_placement" => 'bottom' // Review Placement
				);

				/////////////////////////////////////////////
				// Overwrite with individual post options //
				/////////////////////////////////////////////
				$tw_options_array = themewich_extract_options( $tw_defaults );
				$tw_entry         = (object) $tw_options_array; // Create Object

				/////////////////////////////
				// Get the theme options //
				/////////////////////////////
				if ( $tw_entry->customize == '0' ) { // if there's no customize set, overwrite theme options
					if ( isset( $tw_options['sharing'] ) ) {
						$tw_entry->sharing = $tw_options['sharing'];
					}
					if ( isset( $tw_options['related_posts'] ) ) {
						$tw_entry->related = $tw_options['related_posts'];
					}
					if ( isset( $tw_options['large-top-image'] ) ) {
						$tw_entry->featured_image = $tw_options['large-top-image'];
					}
					if ( isset( $tw_options['author_box'] ) ) {
						$tw_entry->author_box = $tw_options['author_box'];
					}
					if ( isset( $tw_options['post_columns'] ) ) {
						$tw_entry->post_columns = $tw_options['post_columns'];
					}
				}

				// Get dropcap option
				if ( isset( $tw_options['auto_dropcap'] ) ) {
					$tw_entry->auto_dropcap = $tw_options['auto_dropcap'];
				}

				////////////////////////////
				// Set the post classes //
				////////////////////////////
				$tw_entry->sidebar_class   = $tw_entry->post_columns == 2 ? 'has-sidebar' : 'no-sidebar';
				$tw_entry->thumbnail_class = has_post_thumbnail() ? 'has-thumbnail' : 'no-thumbnail';
				$tw_entry->featured_class  = (int) $tw_entry->featured_image == 1 ? 'has-full-image' : 'no-full-image';
				$tw_entry->review_class    = $tw_entry->review_post == 'yes' ? 'review' : 'no-review';
				$tw_entry->sharing_class   = $tw_entry->sharing ? 'sharing-enabled' : 'no-sharing';
				$tw_entry->related_class   = $tw_entry->related ? 'related-enabled' : 'no-related';
				$tw_entry->author_class    = $tw_entry->author_box ? 'author-box-enabled' : 'no-author-box';
				$tw_entry->dropcap_class   = $tw_entry->auto_dropcap ? 'dropcap-enabled' : 'no-dropcap';

				// Check for media entry
				$tw_entry->has_media = ( tw_issetor( $tw_entry->media ) && trim( $tw_entry->media ) != '' ) ? true : false;
				// If media is entered, use other layout
				$tw_entry->featured_class = $tw_entry->has_media ? 'no-full-image' : $tw_entry->featured_class;

				// Add custom highlight if it exists.
				$tw_categories             = ag_get_cats_array( 3 );   // get all post categories
				$tw_entry->highlight_class = isset( $tw_categories[0]->term_id ) ? 'highlight_category_' . $tw_categories[0]->term_id : '';

				$tw_entry->post_classes = array(
					$tw_entry->sidebar_class,
					$tw_entry->thumbnail_class,
					$tw_entry->featured_class,
					$tw_entry->review_class,
					$tw_entry->sharing_class,
					$tw_entry->author_class,
					$tw_entry->related_class,
					$tw_entry->dropcap_class,
					$tw_entry->highlight_class
				);

				return $tw_entry;

			}
		endif;

		/**
		 * This function merges section options with the
		 * defaults for that section.
		 *
		 * @param  array $default Default values
		 *
		 * @return array            Section options array
		 */
		if ( ! function_exists( 'themewich_extract_options' ) ) :
			function themewich_extract_options( $defaults ) {
				global $post, $fields_installed;

				// if defaults are set
				if ( isset( $defaults ) && is_array( $defaults ) ) {
					$options = array(); // set up the array

					if ( $fields_installed ) {
						foreach ( $defaults as $key => $default ) {
							$options[ $key ] = get_field( $key );
						}
					}

					// add any settings from $default to $options,
					// then select only the keys in both arrays
					$options = array_intersect_key( $options + $defaults, $defaults );

					return $options;
				}
			}
		endif;

		if ( ! function_exists( 'themewich_section_object' ) ) :
			/**
			 * This function maps the section options into an object
			 * in order to output into the theme.
			 *
			 * @param  string $type Section yype
			 *
			 * @return object       Section options object
			 */
			function themewich_section_object() {
				global
				$post,
				$tw_section;

				$fields = get_fields( $post->ID ); // Get all custom fields

				// Custom section override
				if ( is_object( $tw_section ) && ( tw_issetor( $tw_section->custom ) && tw_issetor( $tw_section->custom ) ) ) {
					$tw_section = (object) array_merge( (array) $fields, (array) $tw_section ); // Merge already set variables
				} else {
					$tw_section = (object) $fields; // Create Object
				}

				if ( ! tw_issetor( $tw_section->custom ) && isset( $tw_section->section_query_tax ) ) {

					switch ( $tw_section->section_query_tax ) {
						case 'category':
							$tw_section->taxonomy = isset( $tw_section->section_category ) ? $tw_section->section_category : false;  // get category
							break;
						case 'tag':
							$tw_section->taxonomy = isset( $tw_section->section_tag ) ? $tw_section->section_tag : false;       // get tag
							break;
						case 'product-cat':
							$tw_section->taxonomy = isset( $tw_section->section_product_category ) ? $tw_section->section_product_category : false;       // get tag
							break;
						case 'product-tag':
							$tw_section->taxonomy = isset( $tw_section->section_product_tag ) ? $tw_section->section_product_tag : false;       // get tag
							break;
					}

				}

				// Convert delay properly
				if ( isset( $tw_section->delay ) ) {
					$tw_section->delay = $tw_section->delay . '000';
				}

				// Special class for title inclusion
				if ( tw_issetor( $tw_section->section_title ) || tw_issetor( $tw_section->section_subtitle ) ) {
					$tw_section->title_class = 'has-title';
				} else {
					$tw_section->title_class = 'no-title';
				}

				return $tw_section;
			}
		endif;

		if ( ! function_exists( 'themewich_default_home' ) ) :
			/**
			 * This function gets values for the default homepage
			 *
			 * @param  string $type Section yype
			 *
			 * @return object       Section options object
			 */
			function themewich_default_home( $tw_section, $type ) {
				global $post_ID;

				switch ( $type ) {

					////////////////////
					// Slider Section //
					////////////////////
					case 'slider':

						$tw_section->section_custom      = true; // Using custom settings
						$tw_section->section_query_tax   = get_field( 'full_width_query', $post_ID ) ? get_field( 'full_width_query', $post_ID ) : 'all';
						$tw_section->section_query_type  = get_field( 'full_width_query_type', $post_ID ) ? get_field( 'full_width_query_type', $post_ID ) : 'featured';
						$tw_section->section_post_number = 8;
						$tw_section->autoplay            = 'autoplay';

						// Process category or tag
						if ( $tw_section->section_query_tax == 'category' ) {
							$tw_section->taxonomy = get_field( 'full_width_category', $post_ID ) ? get_field( 'full_width_category', $post_ID ) : null;
						}
						if ( $tw_section->section_query_tax == 'tag' ) {
							$tw_section->taxonomy = get_field( 'full_width_tag', $post_ID ) ? get_field( 'full_width_tag', $post_ID ) : null;
						}

						break;

					//////////////////
					// Grid Section //
					//////////////////
					case 'grid':

						$tw_section->section_custom      = true; // Using custom settings
						$tw_section->section_query_tax   = get_field( 'grid_query', $post_ID ) ? get_field( 'grid_query', $post_ID ) : 'all';
						$tw_section->section_query_type  = get_field( 'grid_query_type', $post_ID ) ? get_field( 'grid_query_type', $post_ID ) : 'latest';
						$tw_section->section_title       = get_field( 'grid_section_title', $post_ID ) ? get_field( 'grid_section_title', $post_ID ) : __( 'Latest Posts', 'themewich' );
						$tw_section->section_subtitle    = get_field( 'grid_section_subtitle', $post_ID ) ? get_field( 'grid_section_subtitle', $post_ID ) : __( 'Latest posts from our site.', 'themewich' );
						$tw_section->grid_sidebar        = get_field( 'grid_sidebar', $post_ID );
						$tw_section->section_pagination  = 'on';
						$tw_section->section_post_number = 5;

						// Process category or tag
						if ( $tw_section->section_query_tax == 'category' ) {
							$tw_section->taxonomy = get_field( 'grid_category', $post_ID ) ? get_field( 'grid_category', $post_ID ) : null;
						}
						if ( $tw_section->section_query_tax == 'tag' ) {
							$tw_section->taxonomy = get_field( 'grid_tag', $post_ID ) ? get_field( 'grid_tag', $post_ID ) : null;
						}

						break;

					////////////////
					// Ad Section //
					////////////////
					case 'ad':

						$ad_section_settings = array(
							'ad_type'  => 'code',
							'ad_code'  => false,
							'ad_url'   => false,
							'ad_image' => false,
						);

						// Get chosen items
						foreach ( $ad_section_settings as $key => $val ) {
							$tw_section->$key = get_field( $key, $post_ID ) ? get_field( $key, $post_ID ) : $val;
						}

						break;

					//////////////////
					// Full Section //
					//////////////////
					case 'full-section':

						// defaults
						$full_section_settings = array(
							'taxonomy_image'         => false,
							'full_feature_type'      => false,
							'featured_category_link' => false,
							'featured_tag_link'      => false,
							'featured_page_link'     => false,
							'taxonomy_headline'      => false,
							'taxonomy_subheadline'   => false,
							'taxonomy_button_text'   => false,
						);

						// Get chosen items
						foreach ( $full_section_settings as $key => $val ) {
							$tw_section->$key = get_field( $key, $post_ID ) ? get_field( $key, $post_ID ) : $val;
						}

						break;

					//////////////////////
					// Carousel Section //
					//////////////////////
					case 'carousel':

						// Section Options
						$tw_section->section_query_tax   = get_field( 'carousel_query', $post_ID ) ? get_field( 'carousel_query', $post_ID ) : 'all';
						$tw_section->section_query_type  = get_field( 'carousel_query_type', $post_ID ) ? get_field( 'carousel_query_type', $post_ID ) : 'latest';
						$tw_section->section_title       = get_field( 'carousel_section_title', $post_ID ) ? get_field( 'carousel_section_title', $post_ID ) : __( 'Latest Posts', 'themewich' );
						$tw_section->section_subtitle    = get_field( 'carousel_section_subtitle', $post_ID ) ? get_field( 'carousel_section_subtitle', $post_ID ) : __( 'Latest posts from our site.', 'themewich' );
						$tw_section->carousel_size       = 'half';
						$tw_section->carousel_width      = 'fixed';
						$tw_section->section_post_number = 8;
						$tw_section->autoplay            = false;
						$tw_section->delay               = false;

						// Process category or tag
						if ( $tw_section->section_query_tax == 'category' ) {
							$tw_section->taxonomy = get_field( 'carousel_category', $post_ID ) ? get_field( 'carousel_category', $post_ID ) : null;
						}
						if ( $tw_section->section_query_tax == 'tag' ) {
							$tw_section->taxonomy = get_field( 'carousel_tag', $post_ID ) ? get_field( 'carousel_tag', $post_ID ) : null;
						}

						break;

				}

				return $tw_section;
			}
		endif;

		if ( ! function_exists( 'tw_issetor' ) ) :
			/**
			 * Tests if a variable is set and then returns
			 *
			 * @since  Edition 1.0
			 * @return void
			 */
			function tw_issetor( &$var, $default = false ) {
				return isset( $var ) ? $var : $default;
			}
		endif;

		if ( ! function_exists( 'themewich_section_edit' ) ) :
			/**
			 * Echos edit section button
			 *
			 * @since  Edition 1.0
			 * @return void
			 */
			function themewich_section_edit() {

				// Dont' display if the user isn't logged in and can't edit posts
				if ( ! is_user_logged_in() || ! current_user_can( 'edit_posts' ) ) {
					return;
				}

				global $post;
				echo '<!-- Edit Post Button -->
		<div class="container">
			<div class="edit-section-button">
				<a href="' . get_edit_post_link() . '" class="post-edit-link">
					<i class="fa fa-pencil"></i>
					' . __( 'Edit Section', 'themewich' ) . '
					<i class="fa fa-arrow-right"></i>
				</a>
			</div>
		</div>';
			}
		endif;


		if ( ! function_exists( 'closeUnclosedTags' ) ) :
			/**
			 * Closes unclosed html tags
			 *
			 * @since  Edition 1.0
			 * @return void
			 */
			function closeUnclosedTags( $unclosedString ) {
				preg_match_all( "/<([^\/]\w*)>/", $closedString = $unclosedString, $tags );
				for ( $i = count( $tags[1] ) - 1; $i >= 0; $i -- ) {
					$tag = $tags[1][ $i ];
					if ( substr_count( $closedString, "</$tag>" ) < substr_count( $closedString, "<$tag>" ) ) {
						$closedString .= "</$tag>";
					}
				}

				return $closedString;
			}
		endif;

		if ( ! function_exists( 'ag_wp_trim_excerpt' ) ) :
			/**
			 * Automatic Excerpt Trim
			 *
			 * @since  Edition 1.0
			 * @return void
			 */
			function ag_wp_trim_excerpt( $text ) {
				global $post;
				$raw_excerpt = $text;

				if ( ! is_feed() ) {
					$excerpt_end = '<br /><a href="' . get_permalink( $post->ID ) . '" class="more-link">' . __( 'Read More', 'themewich' ) . '</a>';
				} else {
					$excerpt_end = '';
				}

				$allowed_tags = '<p>,<em>,<strong>,<b>,<ul>,<li>,<ol>,<blockquote>';

				if ( has_excerpt( $post->ID ) ) {
					return force_balance_tags( strip_tags( $text, $allowed_tags ) . $excerpt_end );
				} else {
					//Retrieve the post content.
					$text = get_the_content( '' );

					//Delete all shortcode tags from the content.
					$text = strip_shortcodes( $text );

					$text = apply_filters( 'the_content', $text );
					$text = str_replace( ']]>', ']]&gt;', $text );

					$allowed_tags = '<p>,<em>,<strong>,<b>,<ul>,<li>,<ol>,<blockquote>';
					/*** Add the allowed HTML tags separated by a comma.***/
					$text = strip_tags( $text, $allowed_tags );

					/*** change the excerpt word count to any integer you like.***/
					$excerpt_length = apply_filters( 'excerpt_length', 30 );

					if ( ! is_feed() ) {
						$excerpt_end = '... <br /><a href="' . get_permalink( $post->ID ) . '" class="more-link">' . __( 'Read More', 'themewich' ) . '</a>';
					} else {
						$excerpt_end = '';
					}

					/*** change the excerpt endind to something else.***/
					$excerpt_more = apply_filters( 'excerpt_more', ' ' . $excerpt_end );

					$words = preg_split( "/[\n\r\t ]+/", $text, $excerpt_length + 1, PREG_SPLIT_NO_EMPTY );

					if ( count( $words ) > $excerpt_length ) {
						array_pop( $words );
						$text = implode( ' ', $words );
						$text = $text . $excerpt_more;
						$text = force_balance_tags( wp_kses_post( $text ) ); //close any unclosed tags
					} else {
						$text = implode( ' ', $words );
					}
				}

				return apply_filters( 'wp_trim_excerpt', $text, $raw_excerpt );
			}

			remove_filter( 'get_the_excerpt', 'wp_trim_excerpt' );
			add_filter( 'get_the_excerpt', 'ag_wp_trim_excerpt' );
		endif;

		if ( ! function_exists( 'themewich_date' ) ) :
			/**
			 * Themewich Date Format
			 */
			function themewich_date( $format ) {
				global $post;
				if ( $format && $format == 'human' ) {
					$time = human_time_diff( get_the_time( 'U' ), current_time( 'timestamp' ) ) . ' ' . __( 'ago', 'themewich' );
				} else {
					$time = the_time( get_option( 'date_format' ) );
				}
				echo wp_kses_post( $time );
			}
		endif;

		if ( ! class_exists( 'themewich_help_page' ) ) :
			/**
			 * Create a help page
			 */
			class themewich_help_page {
				// Set our tabs
				public $tw_help_tabs = array(
					'setup'   => 'Set Up',
					'general' => 'General',
					'footer'  => 'Footer'
				);
			}

			$themewich_help_page = new themewich_help_page;
		endif;

		if ( ! function_exists( 'themewich_settings_page_init' ) ) :
			/**
			 * Add Settings Page
			 */
			function themewich_settings_page_init() {
				global $themewich_theme_info;
				$help_page = add_menu_page(
					esc_html( $themewich_theme_info->Name ) . ' Help',
					'Theme Help',
					'edit_theme_options',
					'theme-help',
					'themewich_settings_page',
					'dashicons-book',
					3
				);
			}

			add_action( 'admin_menu', 'themewich_settings_page_init' );
		endif;

		if ( ! function_exists( 'tw_remove_help' ) ) :
			/**
			 * Remove settings page if option is selected.
			 */
			function tw_remove_help() {
				global $tw_options;
				if ( isset( $tw_options['help_page'] ) && $tw_options['help_page'] != 1 ) {
					remove_menu_page( 'theme-help' ); // Dashboard
				}
			}

			add_action( 'admin_menu', 'tw_remove_help', 9999 );
		endif;

		if ( ! function_exists( 'themewich_help_load_styles' ) ) :
			/**
			 * Loads styles for help tab
			 * @return none
			 */
			function themewich_help_load_styles() {
				wp_enqueue_style( 'source-sans', '//fonts.googleapis.com/css?family=Open+Sans:400,800,700,600,300' );
				wp_enqueue_style( 'bootstrap', get_theme_file_uri('css/bootstrap.min.css') );
				wp_enqueue_style( 'themewich-docs', get_template_directory_uri() . '/functions/help/assets/css/docs.css' );
				wp_enqueue_style( 'themewich-custom-docs', get_template_directory_uri() . '/functions/help/assets/css/themewich-style.css' );
				wp_enqueue_style( 'google-code-prettify', get_template_directory_uri() . '/functions/help/assets/js/google-code-prettify/prettify.css' );
			}

			if ( isset( $_GET['page'] ) && $_GET['page'] == 'theme-help' ) {
				add_action( 'admin_enqueue_scripts', 'themewich_help_load_styles' );
			}
		endif;
		if ( ! function_exists( 'themewich_help_load_scripts' ) ) :
			/**
			 * Loads scripts for help tabs
			 * @return none
			 */
			function themewich_help_load_scripts() {
				wp_enqueue_script( 'themewich-docs-js', get_template_directory_uri() . '/functions/help/assets/js/docs.min.js', array( 'jquery' ), '1.0', true );
				wp_enqueue_script( 'jquery-code-prettify', get_template_directory_uri() . '/functions/help/assets/js/google-code-prettify/prettify.js', array( 'jquery' ), '1.0', true );
				wp_enqueue_script( 'bootstrap-js', get_theme_file_uri('js/bootstrap.min.js'), array( 'jquery' ), '3.1.1', true );
			}

			if ( isset( $_GET['page'] ) && $_GET['page'] == 'theme-help' ) {
				add_action( 'admin_enqueue_scripts', 'themewich_help_load_scripts' );
			}
		endif;
		if ( ! function_exists( 'themewich_load_settings_page' ) ) :
			/**
			 * Loads help settings page
			 * @return none
			 */
			function themewich_load_settings_page() {
				if ( isset( $_POST['ilc-settings-submit'] ) && $_POST["ilc-settings-submit"] == 'Y' ) {
					check_admin_referer( "ilc-settings-page" );
					$url_parameters = isset( $_GET['tab'] ) ? 'updated=true&tab=' . $_GET['tab'] : 'updated=true';
					wp_redirect( admin_url( 'themes.php?page=theme-help&' . $url_parameters ) );
					exit;
				}
			}
		endif;

		if ( ! function_exists( 'themewich_admin_tabs' ) ) :
			/**
			 * Outputs help tabs
			 *
			 * @param  string $current Current default page
			 *
			 * @return html          Markup for tabs
			 */
			function themewich_admin_tabs( $current = 'homepage' ) {
				$tw_help_tabs = array(
					'setup'          => 'Set Up',
					'adding-content' => 'Adding Content',
					'customization'  => 'Customization',
					'theme-files'    => 'Theme Files'
				);
				$links        = array();
				echo '<div id="icon-themes" class="icon32"><br></div>';
				echo '<h2 class="nav-tab-wrapper">';
				foreach ( $tw_help_tabs as $tab => $name ) {
					$class = ( $tab == $current ) ? ' nav-tab-active' : '';
					echo "<a class='nav-tab$class' href='?page=theme-help&tab=$tab'>$name</a>";
				}
				echo '</h2>';
			}
		endif;

		if ( ! function_exists( 'themewich_settings_page' ) ) :
			/**
			 * Creates theme help page
			 * @return none
			 */
			function themewich_settings_page() {
				global
				$pagenow,
				$themewich_theme_info;
				$help = get_option( "themewich_theme_settings" );
				?>

                <div class="wrap">
                    <h2><?php echo esc_html( $themewich_theme_info->Name ); ?> <?php _e( 'Theme Help', 'themewich' ); ?>
                        <small>v<?php echo esc_html( $themewich_theme_info->Version ); ?></small>
                    </h2>

					<?php
					if ( isset( $_GET['tab'] ) ) {
						themewich_admin_tabs( $_GET['tab'] );
					} else {
						themewich_admin_tabs( 'setup' );
					}
					?>
                    <div id="helpstuff">
						<?php
						wp_nonce_field( "ilc-settings-page" );
						if ( $pagenow == 'admin.php' && $_GET['page'] == 'theme-help' ) {

							if ( isset( $_GET['tab'] ) ) {
								$tab = $_GET['tab'];
							} else {
								$tab = 'setup';
							}
							require get_template_directory() . '/functions/help/' . $tab . '.php';

						}
						?>
                        <div class="clear"></div>

                        <p><?php echo esc_html( $themewich_theme_info->Name); ?> v<?php echo esc_html( $themewich_theme_info->Version) ; ?></p>
                    </div>
                </div>
				<?php

			}
		endif;

		/**
		 * Get Username and API Key from Theme Options
		 */
		if ( ! function_exists( 'themewich_get_update_info' ) ) :
			/**
			 * Gets username and api key from theme options
			 * @return none
			 */
			function themewich_get_update_info() {
				global $tw_options;

				$username = isset( $tw_options['tf_username'] ) ? $tw_options['tf_username'] : false;
				$api      = isset( $tw_options['tf_username'] ) ? $tw_options['tf_api'] : false;

				if ( $username && $username != '' ) {
					define( 'THEMEFOREST_USERNAME', $username );
				}
				if ( isset( $api ) && $api != '' ) {
					define( 'THEMEFOREST_APIKEY', $api );
				}
			}

			add_action( 'init', 'themewich_get_update_info' );
		endif;

		if ( ! function_exists( 'tw_breadcrumb' ) ) :
			/**
			 * Breadcrumbs function
			 * @return html Markup for breadcrumbs
			 */
			function tw_breadcrumb() {
				global $post;
				echo '<ul id="breadcrumbs">';
				if ( ! is_home() ) {
					echo '<li><a href="';
					echo get_home_url();
					echo '">';
					echo 'Home';
					echo '</a></li><li class="separator"> / </li>';
					if ( is_category() || is_single() ) {
						echo '<li>';
						the_category( ' </li><li class="separator"> / </li><li> ' );
						if ( is_single() ) {
							echo '</li><li class="separator"> / </li><li>';
							the_title();
							echo '</li>';
						}
					} elseif ( is_page() ) {
						if ( $post->post_parent ) {
							$anc   = get_post_ancestors( $post->ID );
							$title = get_the_title();
							foreach ( $anc as $ancestor ) {
								$output = '<li><a href="' . get_permalink( $ancestor ) . '" title="' . get_the_title( $ancestor ) . '">' . get_the_title( $ancestor ) . '</a></li> <li class="separator">/</li>';
							}
							echo wp_kses_post( $output );
							echo '<li><strong title="' . $title . '"> ' . $title . '</strong></li>';
						} else {
							echo '<li><strong> ' . get_the_title() . '</strong></li>';
						}
					}
				}
				echo '</ul>';
			}
		endif;

		function tw_add_media_field_to_feed( $content ) {
			if ( is_feed() ) {
				global $post;
				$media       = get_field( 'media', $post->ID ) ? get_field( 'media', $post->ID ) : '';
				$media_o     = wp_oembed_get( $media ) ? wp_oembed_get( $media ) : '';
				$media_short = do_shortcode( $media ) ? do_shortcode( $media ) : '';

				$content = $media_o . $media_short . $content;
			}

			return $content;
		}

		add_filter( 'the_content', 'tw_add_media_field_to_feed' );

		/*-----------------------------------------------------------------------------------*/
		/* Add Social Fields to Edit Post Page
/*-----------------------------------------------------------------------------------*/

		/**
		 * Adds a form field to the edit profile page.
		 *
		 * @author  Thomas Scholz http://toscho.de
		 * @version 1.2
		 * @license GPL
		 *
		 */
		if ( ! class_exists( 'T5_User_Profile_Addon' ) ) :
			class T5_User_Profile_Addon {

				public $settings = array(
					/* The name attribute. */
					'name'        => '',
					'label'       => '',
					'description' => ''

					/* You may use the following placeholder:
		 * %name%        - name attribute
		 * %label%       - label text
		 * %description% - additional text
		 * To use more placeholders, extend markup_filter().
		 */,
					'markup'      => ''
					/* If both are not FALSE, they will replace the 'markup', and a
		 * table will be created. Uses the same placeholders as 'markup'.
		 */,
					'th'          => false,
					'td'          => false
					/* Capabilities to show and edit the field.
		 * Useful, if want to add a field that only administrators or editors
		 * may edit or view.
		 */,
					'cap_show'    => 'read',
					'cap_save'    => 'edit_user'
				);

				/**
				 * Constructor
				 *
				 * @param array $args See settings. 'name' and 'markup' required.
				 */
				public function __construct( $args ) {
					$this->settings = array_merge( $this->settings, $args );

					// The id attribute should be different to name, otherwise it doesn't
					// work in Opera.
					empty( $this->settings['id'] )
					and $this->settings['id'] = $this->settings['name'] . '_id';

					false !== $this->settings['th'] and false !== $this->settings['td']
					                                    and $this->settings['markup'] = '<table class="form-table"><tr><th>'
					                                                                    . $this->settings['th'] . '</th><td>' . $this->settings['td']
					                                                                    . '</td></tr></table>';

					add_action( 'show_user_profile', array( $this, 'show' ) );
					add_action( 'edit_user_profile', array( $this, 'show' ) );
					add_action( 'personal_options_update', array( $this, 'save' ) );
					add_action( 'edit_user_profile_update', array( $this, 'save' ) );
				}

				/**
				 * Prints the form.
				 *
				 * @param  object $user
				 *
				 * @return void
				 */
				public function show( $user ) {
					if ( ! current_user_can( $this->settings['cap_show'], $user->ID ) ) {
						return;
					}

					$label   = "<label for='{$this->settings['id']}'>{$this->settings['label']}</label>";
					$markup  = strtr(
						$this->settings['markup'],
						array(
							'%name%'        => $this->settings['name'],
							'%id%'          => $this->settings['id'],
							'%label%'       => $label,
							'%description%' => $this->settings['description']
						)
					);
					$old_val = trim( get_the_author_meta( $this->settings['name'], $user->ID ) );
					$markup  = $this->markup_filter( $markup, $old_val );

					print wp_kses_post( $markup );
				}

				/**
				 * Saves the data.
				 *
				 * @param  int $user_id
				 *
				 * @return void
				 */
				public function save( $user_id ) {
					if ( ! current_user_can( $this->settings['cap_save'], $user_id ) ) {
						return;
					}

					$input = empty( $_POST[ $this->settings['name'] ] )
						? '' : $_POST[ $this->settings['name'] ];
					$input = $this->prepare_input( $input );

					update_user_meta( $user_id, $this->settings['name'], $input );
				}

				/**
				 * Prepares the user input. For extensions.
				 *
				 * @param  string $input
				 *
				 * @return string
				 */
				public function prepare_input( $input ) {
					return $input;
				}

				/**
				 * Prepares the form markup.
				 *
				 * @param  string $markup
				 * @param  string $old_val
				 *
				 * @return string
				 */
				public function markup_filter( $markup, $old_val ) {
					$old_val = htmlspecialchars( $old_val, ENT_QUOTES, 'utf-8', false );

					return str_replace( '%content%', $old_val, $markup );
				}
			}
		endif;

		global $social_links;

		if ( ! function_exists( 'init_profile_addons' ) ) :
			function init_profile_addons() {
				global $social_links;

				$social_links = array(
					'facebook'           => 'Facebook',
					'twitter'            => 'Twitter',
					'dribbble'           => 'Dribble',
					'youtube-play'       => 'Youtube',
					'vimeo-square'       => 'Vimeo',
					'linkedin'           => 'LinkedIn',
					'pinterest'          => 'Pinterest',
					'github'             => 'Github',
					'google-plus-square' => 'Google Plus',
					'instagram'          => 'Instagram',
					'stack-overflow'     => 'Stack Overflow',
					'trello'             => 'Trello',
					'tumblr'             => 'Tumblr',
				);

				foreach ( $social_links as $id => $title ) {
					$GLOBALS[ $id . '_url' ] = new T5_User_Profile_Addon(
						array(
							'name'   => $id . '_url',
							'label'  => $title . ' ' . __( 'URL', 'themewich' ),
							'markup' => '<table class="form-table"><tr><th>%label%<br /><br />%description%</th>
		            <td><input type="text" name="%name%" id="%id%" value="%content%" class="regular-text" /></td></tr></table>'
						)
					);
				}
			}

			add_action( 'init', 'init_profile_addons' );
		endif;

		if ( ! function_exists( 'tw_parse_url' ) ) :
			function tw_parse_url( $urlStr ) {
				if ( $urlStr ) {
					$parsed = parse_url( $urlStr );
					if ( empty( $parsed['scheme'] ) ) {
						$urlStr = "http://$urlStr";
					}

					return $urlStr;
				}
			}
		endif;

		if ( ! function_exists( 'tw_social_links' ) ) :
			function tw_social_links( $userId ) {

				global $social_links;

				$output = '';

				if ( isset( $social_links ) ) {
					foreach ( $social_links as $id => $title ) {
						$url = tw_parse_url( get_the_author_meta( $id . '_url', $userId ) );
						if ( $url ) {
							$output .= '<a href="' . $url . '" class="" target="_blank">';
							$output .= '<i class="fa fa-' . $id . '"></i>';
							$output .= '</a>';
						}
					}
				}

				return $output;
			}
		endif;

		if ( ! function_exists( 'tw_author_link' ) ) :
			function tw_author_link( $link ) {
				if ( $link == 'posts' ) {
					the_author_posts_link();
				} else {
					the_author_link();
				}
			}
		endif;

		/**
		 * Remove hentry from sections
		 */
		if ( ! function_exists( 'themewich_remove_hentry' ) ) :
			function themewich_remove_hentry( $classes ) {
				if ( get_post_type() == 'section' || is_front_page() ) {
					$classes = array_diff( $classes, array( 'hentry' ) );
				}

				return $classes;
			}

			add_filter( 'post_class', 'themewich_remove_hentry' );
		endif;

		/**
		 * WooCommerce Functions
		 */

		// remove crappy default wrappers
		remove_action( 'woocommerce_before_main_content', 'woocommerce_output_content_wrapper', 10 );
		remove_action( 'woocommerce_after_main_content', 'woocommerce_output_content_wrapper_end', 10 );

		// remove cart collaterals location to use custom location
		remove_action( 'woocommerce_cart_collaterals', 'woocommerce_cart_totals', 10 );

		if ( ! function_exists( 'tw_wrapper_start' ) ) :
			function tw_wrapper_start() {
				echo '<div class="container">';
			}

			add_action( 'woocommerce_before_main_content', 'tw_wrapper_start', 10 );
		endif;

		if ( ! function_exists( 'tw_wrapper_end' ) ) :
			function tw_wrapper_end() {
				echo '</div>';
			}

			add_action( 'woocommerce_after_main_content', 'tw_wrapper_end', 10 );
		endif;

		/**
		 * Change number of related products
		 */
		if ( ! function_exists( 'tw_related_products_args' ) ) :
			function tw_related_products_args( $args ) {

				$args['posts_per_page'] = 4; // 4 related products
				$args['columns']        = 4; // arranged in 2 columns

				return $args;
			}

			add_filter( 'woocommerce_output_related_products_args', 'tw_related_products_args' );
		endif;

		if ( ! function_exists( 'tw_cross_sells_columns' ) ) :
			function tw_cross_sells_columns( $columns ) {
				return 4;
			}

			add_filter( 'woocommerce_cross_sells_columns', 'tw_cross_sells_columns' );
		endif;
		/**
		 * Remove WooCommerce Breadcrumbs
		 */
		remove_action( 'woocommerce_before_main_content', 'woocommerce_breadcrumb', 20, 0 );

		/**
		 * Remove Default Add To Cart Button
		 */
		remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart', 20, 0 );

		/**
		 * Remove ratings on shop items loop
		 */
		remove_action( 'woocommerce_after_shop_loop_item_title', 'woocommerce_template_loop_rating', 5, 0 );

		/**
		 * Change the number of products per row depending on page template
		 */
		if ( ! function_exists( 'tw_loop_columns' ) ) {
			function tw_loop_columns() {
				global $shop_template;
				if ( 'template-full.php' == $shop_template ) {
					return 4;
				} else {
					return 3;
				}
			}

			add_filter( 'loop_shop_columns', 'tw_loop_columns' );
		}

		/**
		 * Filter for adding extensions to the Redux Panel
		 *
		 * @since 1.01
		 */
		if ( ! function_exists( 'tw_register_custom_extension_loader' ) ) :
			function tw_register_custom_extension_loader( $ReduxFramework ) {

				$path    = dirname( __FILE__ ) . '/theme-options/extensions/';
				$folders = scandir( $path, 1 );

				foreach ( $folders as $folder ) {

					if ( $folder === '.' or $folder === '..' or ! is_dir( $path . $folder ) ) {
						continue;
					}

					$extension_class = 'ReduxFramework_Extension_' . $folder;

					if ( ! class_exists( $extension_class ) ) {
						// In case you wanted override your override, hah.
						$class_file = $path . $folder . '/extension_' . $folder . '.php';
						$class_file = apply_filters( 'redux/extension/' . $ReduxFramework->args['opt_name'] . '/' . $folder, $class_file );
						if ( $class_file ) {
							require_once( $class_file );
							$extension = new $extension_class( $ReduxFramework );
						}
					}

				}
			}

			add_action( "redux/extensions/tw_options/before", 'tw_register_custom_extension_loader', 0 );
		endif;

	function tw_default_wp_pagination( $args ) {

		$args['paged'] = 1;
		if ( get_query_var( 'paged' ) ) {
			$args['paged'] = get_query_var( 'paged' );
		} else if ( get_query_var( 'page' ) ) {
			$args['paged'] = get_query_var( 'page' );
		}

		return $args;
	}

	add_filter( 'tw_section_query', 'tw_default_wp_pagination' );

		if ( ! function_exists( 'themewich_pagination' ) ) :
		/**
		 * Echos pagination
		 *
		 * @since  Edition 1.0
		 * @return void
		 */
		function themewich_pagination() {
		global
		$paged,
		$paged_section,
		$wp_query,
		$tw_section;
		// Don't print empty markup if there's only one page.
		if ( $GLOBALS['wp_query']->max_num_pages < 2 ) {
			return;
		}
		$big = 999999999;

		if ( get_query_var( 'paged' ) ) {
			$paged = get_query_var( 'paged' );
		} elseif ( get_query_var( 'page' ) ) {
			$paged = get_query_var( 'page' );
		} else {
			$paged = 1;
		}

		$links = paginate_links( array(
			'base'      => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
			'format'    => '?paged=%#%',
			'current'   => max( 1, $paged ),
			'total'     => $wp_query->max_num_pages,
			'prev_text' => '<i class="fa fa-angle-left"></i>',
			'next_text' => '<i class="fa fa-angle-right"></i>',
			'add_args'  => false
		) );
		if ( $links ) :
		?>
    <div class="pagination">
        <div class="pagenumbers">
			<?php echo wp_kses_post( $links ); ?>
        </div>
        <div class="divider"></div>
        <div class="clear"></div>
		<?php if ( ( isset( $tw_section->section_subtitle ) || isset( $tw_section->section_title ) ) && $tw_section->section_title != '' ) : // If there's a title ?>
            <div class="pageflip">
				<?php
				// Add prev/next text
				$links = str_replace( '<a class="next page-numbers"', '<a class="next page-numbers hint--left righthint fadeInDown animated" data-hint="' . __( 'Older Posts', 'themewich' ) . '"', $links );
				$links = str_replace( '<a class="prev page-numbers"', '<a class="next page-numbers hint--left righthint fadeInDown animated" data-hint="' . __( 'Newer Posts', 'themewich' ) . '"', $links );
				echo wp_kses_post( $links );
				?>
            </div>
		<?php endif; ?>
    </div>
<?php
endif;
}
endif;