<?php

/**
 * Motive Theme!
 * 
 * This is the typical theme initialization file. Sets up the Bunyad Framework
 * and the theme functionality.
 * 
 * ----
 * 
 * Code Locations:
 * 
 *  /          -  WordPress default template files
 *  lib/       -  Contains the core Bunyad framework files
 *  inc/       -  Theme related functionality
 *  admin/     -  Admin-only content
 *  partials/  -  Template parts (partials) called via get_template_part()
 *  
 * Note: If you're looking to edit HTML, look for default WordPress templates in
 * top-level / and in partials/ folder.
 * 
 */

// already initialized? some buggy plugin call?
if (class_exists('Bunyad_Core')) {
	return;
}

// initialize Framework
require_once get_template_directory() . '/lib/bunyad.php';

// fire up the theme - make available in Bunyad::get('motive')
Bunyad::register('motive', array(
	'class' => 'Bunyad_Theme_Motive',
	'init' => true
));

/**
 * Main Framework Configuration
 */
$bunyad_core = Bunyad::core()->init(apply_filters('bunyad_init_config', array(

	'theme_name' => 'motive',
	'meta_prefix' => '_bunyad',
	'theme_version' => '1.2.1',

	// widgets enabled
	'widgets'    => array('about', 'latest-posts', 'popular-posts', 'tabbed-recent', 'flickr', 'ads', 'latest-reviews', 'comments', 'twitter'),
	'post_formats' => array('gallery', 'image', 'video', 'audio'),

	'shortcode_config' => array(
		'font_icons' => true,
		'social_font' => true,
		'button_colors' => array(),
	),
	
	// enabled metaboxes and prefs - id is prefixed with _bunyad_ in init() method of lib/admin/meta-boxes.php
	'meta_boxes' => array(
		array('id' => 'post-options', 'title' => __('Post Options', 'bunyad'), 'priority' => 'high', 'page' => array('post')),
		array('id' => 'post-reviews', 'title' => __('Review', 'bunyad'), 'priority' => 'high', 'page' => array('post')),
		array('id' => 'page-options', 'title' => __('Page Options', 'bunyad'), 'priority' => 'high', 'page' => array('page')),
	)
)));


/**
 * Motive Theme!
 * 
 * Anything theme-specific that won't go into the core framework goes here. Rest goes into lib/core.php
 */
class Bunyad_Theme_Motive
{

	public function __construct() 
	{
		// setup plugins before init
		$this->setup_plugins();

		// init skins
		add_action('bunyad_core_post_init', array($this, 'init_skins'));
		
		// perform the after_setup_theme 
		add_action('after_setup_theme', array($this, 'theme_init'), 12);
		
		add_action('after_setup_theme', array($this, 'init_shortcodes'), 5);
		add_action('after_setup_theme', array($this, 'init_page_builder'), 5);
		
		// ready up the custom css handlers
		include locate_template('inc/custom-css.php');
	}
	
	/**
	 * Setup any skin data and configs
	 */
	public function init_skins()
	{
		// include our skins constructs
		if (Bunyad::options()->predefined_style) {
			include locate_template('inc/skins/' . sanitize_file_name(Bunyad::options()->predefined_style) .'.php');
		}
	}
	
	/**
	 * Setup enque data and actions
	 */
	public function theme_init()
	{
		include locate_template('inc/widgets-output.php');
		
		/*
		 * Enqueue assets (css, js)
		 * 
		 * Register Custom CSS at a lower priority for CSS specificity
		 */
		add_action('wp_enqueue_scripts', array($this, 'register_assets'));
		
		/*
		 * Featured images settings
		 */
		set_post_thumbnail_size(72, 60, true); // used in many more aspect ratios

		add_image_size('motive-grid-slider', 603, 362, true); // main slider image in grid slider - also used for main higlights
		add_image_size('motive-image-block', 333, 200, true); // gallery sizes used in sidebars and so on - also used in slider at 301x181
		
		add_image_size('motive-alt-slider', 740, 357, true); // alt slider image size
		add_image_size('motive-slider-full', 1206, 410, true); // alt slider full-width image size
		add_image_size('motive-slider-alt-block', 352, 169, true); // alt slider right slide blocks image
		
		add_image_size('motive-main-block', 252, 167, true); // main home block - used in 232x154 too
		add_image_size('motive-highlight-block', 359, 201, true); // also used in highlights blocks at 348x195

		// i18n
		load_theme_textdomain('bunyad', get_template_directory() . '/languages');
		
		// setup navigation menu with "main" key
		register_nav_menu('motive-main', __('Main Navigation', 'bunyad'));
		
		// fix html5 support
		add_theme_support('html5', array('search', 'gallery', 'caption'));
		
		/*
		 * Category meta 
		 */
		add_action('category_edit_form_fields', array($this, 'edit_category_meta'), 10, 2);
		add_action('category_add_form_fields', array($this, 'edit_category_meta'), 10, 2);
		
		add_action('edited_category', array($this, 'save_category_meta'), 10, 2);
		add_action('create_category', array($this, 'save_category_meta'), 10, 2);
		
		// user fields
		add_filter('user_contactmethods', array($this, 'add_profile_fields'));
		
		/*
		 * Reviews Support
		 */
		add_filter('the_content', array($this, 'add_review'));
		add_filter('bunyad_review_main_snippet', array($this, 'add_review_snippet'));
		
		// 3.5 has content_width removed, add it for oebmed
		global $content_width;
		
		if (!isset($content_width)) {
			$content_width = 740;
		}
		
		/*
		 * Register Sidebars
		 */
		add_action('widgets_init', array($this, 'register_sidebars'));

		/*
		 * Mega menu support
		 */
		add_filter('bunyad_custom_menu_fields', array($this, 'custom_menu_fields'));
		add_filter('bunyad_mega_menu_end_lvl', array($this, 'attach_mega_menu'));
		
		// menu sticky logo support
		add_filter('wp_nav_menu_items', array($this, 'add_navigation_logo'), 10, 2);
		
		
		/*
		 * Posts related filter
		 */
		
		// custom font icons for post formats
		add_action('bunyad_image_overlay', array($this, 'add_image_overlay'));
		
		// video format auto-embed
		add_filter('bunyad_featured_video', array($this, 'video_auto_embed'));
		
		// add custom category per_page limits, if any
		add_filter('pre_get_posts', array($this, 'add_category_limits'));
		
		// remove hentry microformat, we use schema.org/Article
		add_action('post_class', array($this, 'fix_post_class'));
		
		// ajax post content slideshow - add wrapper
		add_filter('the_content', array($this, 'add_post_slideshow_wrap'));
		
		// add image sizes to the editor
		if (is_admin()) {
			add_filter('image_size_names_choose', array($this, 'add_image_sizes_editor'));
		}
		
		// limit search to posts?
		if (Bunyad::options()->search_posts_only) {
			add_filter('pre_get_posts', array($this, 'limit_search'));
		}
		
		/*
		 * Prevent duplicate posts
		 */
		if (Bunyad::options()->no_home_duplicates) {
			
			// add to removal list on each loop
			add_filter('loop_end', array($this, 'update_duplicate_posts'));
			
			// exclude on blocks
			add_filter('bunyad_block_query_args', array($this, 'add_duplicate_exclude'));
			
			// exclude on widgets
			foreach (array('tabbed_recent', 'popular_posts', 'latest_posts') as $widget) {
				add_filter('bunyad_widget_' . $widget . '_query_args', array($this, 'add_duplicate_exclude'));
			}
		}
		
		// add "more" text for excerpts
		Bunyad::posts()->more_html = '<span class="read-more"><a href="%s" title="%s">'. __('More', 'bunyad') .'</a></span>';
		
		// set dynamic widget columns for footer
		add_filter('dynamic_sidebar_params', array($this, 'set_footer_columns'));
		
		// add comments snippet
		add_action('bunyad_comments_snippet', array($this, 'comments_snippet'));
		
		// add listing meta
		add_action('bunyad_listing_meta', array($this, 'listing_meta'));
		
		// breadcrumbs
		add_filter('bunyad_breadcrumbs_defaults', array($this, 'breadcrumbs'));
		
		// theme update hook
		add_action('bunyad_theme_version_change', array($this, 'theme_update'));
		
		// setup the init hook
		add_action('init', array($this, 'init'));
	}
	
	/**
	 * Action callback: Setup that needs to be done at init hook
	 */
	public function init() 
	{
		// init reviews
		Bunyad::reviews();
		
		// setup theme-specific shortcodes and blocks
		$this->setup_shortcodes();
		
		// load importer lib if needed
		if (is_admin()) {
			include_once locate_template('inc/import.php');
		}
	}
	
	/**
	 * Action callback: Extend Bunyad Shortcodes
	 */
	public function init_shortcodes()
	{
		if (!class_exists('Bunyad_ShortCodes')) {
			return;
		}
		
		// remove original
		$bunyad_sc = Bunyad_ShortCodes::getInstance();
		remove_action('after_setup_theme', array($bunyad_sc, 'setup'));
				
		// add extended class
		include_once locate_template('inc/shortcodes.php');
		add_action('after_setup_theme', array(Bunyad::get('motive_codes'), 'setup'), 10);
	}	
	
	/**
	 * Action callback: Initialize Visaul Composer page builder
	 */
	public function init_page_builder()
	{
		// plugin is not active?
		if (!class_exists('Vc_Manager')) {
			return;
		}
		
		include locate_template('inc/visual-composer.php');
	}
	
	/**
	 * Register and enqueue theme CSS and JS files
	 */
	public function register_assets()
	{
		if (!is_admin()) {
			
			// add jquery, theme js
			wp_enqueue_script('jquery');
			wp_enqueue_script('bunyad-theme', get_template_directory_uri() . '/js/bunyad-theme.js', array('jquery'), false, true);

		
			/*
			 * Add CSS styles
			 */
			
			// add google fonts
			$style = $this->get_style(Bunyad::options()->predefined_style);
			$args  = $style['font_args'];
			
			if (!Bunyad::options()->image_logo) {
				$args['family'] .= '|Roboto:900';			
			}
		
			if (Bunyad::options()->font_charset) {
				$args['subset'] = implode(',', array_keys(array_filter(Bunyad::options()->font_charset)));
			}
		
			wp_enqueue_style('motive-fonts', add_query_arg(urlencode_deep($args), (is_ssl() ? 'https' : 'http') . '://fonts.googleapis.com/css'), array(), null);

				
			// add core css
			if (is_rtl()) {
				wp_enqueue_style('motive-core', get_stylesheet_directory_uri() . '/css/rtl.css', array(), Bunyad::options()->get_config('theme_version'));
			}
			else {
				// use stylesheet_uri so that child theme's style.css is loaded
				wp_enqueue_style('motive-core', get_stylesheet_uri(), array(), Bunyad::options()->get_config('theme_version'));
			}

			// add lightbox to pages and single posts
			if (Bunyad::options()->enable_lightbox && (is_single() OR is_page())) {
				wp_enqueue_script('motive-lightbox', get_template_directory_uri() . '/js/lightbox.js', array(), false, true);
				wp_enqueue_style('motive-lightbox', get_template_directory_uri() . '/css/lightbox.css', array(), Bunyad::options()->get_config('theme_version'));
			}
			
			// add web fonts
			wp_enqueue_style('motive-font-awesome', get_template_directory_uri() . '/css/fontawesome/css/font-awesome.min.css', array(), Bunyad::options()->get_config('theme_version'));
			
			// predefined style
			if (!empty($style['css'])) {
				wp_enqueue_style('motive-skin', get_template_directory_uri() . '/css/' . $style['css'] . '.css', array(), Bunyad::options()->get_config('theme_version'));
			}
			
			// responsive
			if (!Bunyad::options()->no_responsive) {
				wp_enqueue_style('motive-responsive', get_template_directory_uri() . '/css/'. (is_rtl() ? 'rtl-' : '') . 'responsive.css', array(), Bunyad::options()->get_config('theme_version'));
				
				// add responsive overrides from skin, if any
				if (!empty($style['responsive-css'])) {
					wp_enqueue_style('motive-responsive-skin', get_template_directory_uri() . '/css/'. $style['responsive-css'] . '.css', array(), Bunyad::options()->get_config('theme_version'));
				}
			}
			
			
			// owl carousel to the footer
			wp_enqueue_script('motive-owl-carousel', get_template_directory_uri() . '/js/owl.carousel.min.js', array('jquery'), false, true);
		}
	}
	
	/**
	 * Setup the sidebars
	 */
	public function register_sidebars()
	{
	
		// register dynamic sidebar
		register_sidebar(array(
			'name' => __('Main Sidebar', 'bunyad'),
			'id'   => 'motive-primary-sidebar',
			'description' => __('Widgets in this area will be shown in the default sidebar.', 'bunyad'),
			'before_title' => '<h5 class="widget-title section-head cf main-color"><span class="title">',
			'after_title'  => '</span></h5>',
		));

		
		// register dynamic sidebar
		register_sidebar(array(
			'name' => __('Top Bar (Above Header)', 'bunyad'),
			'id'   => 'motive-top-bar',
			'description' => __('Please place only a single widget. Preferably a text widget.', 'bunyad'),
			'before_title' => '',
			'after_title'  => '',
			'before_widget' => '',
			'after_widget'  => ''
			
		));
		
		// register dynamic sidebar
		register_sidebar(array(
			'name' => __('Header Right', 'bunyad'),
			'id'   => 'motive-header-right',
			'description' => __('Please place only a single widget. Preferably text-widget. Not available on centered header.', 'bunyad'),
			'before_title' => '',
			'after_title'  => '',
			'before_widget' => '',
			'after_widget'  => ''
			
		));
		
		// register dynamic sidebar
		register_sidebar(array(
			'name' => __('Footer - Top', 'bunyad'),
			'id'   => 'motive-main-footer',
			'description' => __('Widgets in this area will be shown in the footer. Max 3 widgets or based on custom settings.', 'bunyad'),
			'before_title' => '<h3 class="widget-title">',
			'after_title'  => '</h3>',
			'before_widget' => '<li class="widget column %2$s">',
			'after_widget' => '</li>'
		));
		
		// register dynamic sidebar
		register_sidebar(array(
			'name' => __('Footer - Middle', 'bunyad'),
			'id'   => 'motive-mid-footer',
			'description' => __('Widgets in this area will be shown below the top footer. Max 3 widgets.', 'bunyad'),
			'before_title' => '<h3 class="widget-title">',
			'after_title'  => '</h3>',
			'before_widget' => '<li class="widget column %2$s">',
			'after_widget' => '</li>'
		));
		
		
		// register dynamic sidebar
		register_sidebar(array(
			'name' => __('Footer - Lower', 'bunyad'),
			'id'   => 'motive-lower-footer',
			'description' => __('Prefer simple text widgets here.', 'bunyad'),
			'before_title' => '',
			'after_title'  => '',
			'before_widget' => '',
			'after_widget'  => ''
		));
		
		// "Custom Sidebars" by WPMUDEV - add plugin defaults for compatibility
		if (is_admin() && class_exists('CustomSidebars')) {
			if (!get_option('cs_modifiable')) {
				update_option('cs_modifiable', array('modifiable' => array('motive-primary-sidebar')));
			}
		}
	}
	
	/**
	 * Filter callback: Override breadcrumbs defaults
	 * 
	 * @param array $options
	 */
	public function breadcrumbs($options = array())
	{
		$options = array_merge($options, array(
			'show_current' => (is_single() ? 0 : 1), // 1 - show current post/page title in breadcrumbs, 0 - don't show
			'delimiter' => '<span class="delim"><i class="fa fa-angle-right"></i></span>',
			'home_before' => '',
			'home_after' => '',
			
			'text' => array_merge((array) $options['text'], array(
				'category' => '%s',
			))
		));
		
		return $options;
	}
	
	/**
	 * Action callback: Save custom meta for categories
	 */
	public function save_category_meta($term_id)
	{
		// have custom meta?
		if ($_POST['meta'] && is_array($_POST['meta'])) 
		{
			$meta = $_POST['meta'];
			
			// editing?
			if (($option = Bunyad::options()->get('cat_meta_' . $term_id))) {
				$meta = array_merge($option, $_POST['meta']);
			}
			
			// save to _bunyad_cat_meta
			Bunyad::options()->update('cat_meta_' . $term_id, $meta);
			
			// clear custom css cache
			delete_transient('bunyad_custom_css_cache');
		}
	}
	
	/**
	 * Setup and recommend plugins
	 */
	public function setup_plugins()
	{
		if (!is_admin()) {
			return;
		}
		
		/**
		 * Packaged plugins info - save in registry to be used by plugin updater
		 */
		$plugins_info = array(
			'bunyad-shortcodes' => array(
				'version' => '1.0.6',
			),
			
			'bunyad-widgets' => array(
				'version' => '1.0.5',
			),
			
			'js_composer' => array(
				'version' => '4.3.5',
			),
		);
		
		Bunyad::registry()->set('packaged_plugins', $plugins_info);
		
		// load the plugin activation class and plugin updater
		require_once get_template_directory() . '/lib/vendor/tgm-activation.php';
		require_once get_template_directory() . '/inc/plugin-update.php';
		
		
		// recommended and required plugins
		$plugins = array(
			array(
				'name'     	=> 'Bunyad Shortcodes', // The plugin name
				'slug'     	=> 'bunyad-shortcodes', // The plugin slug (typically the folder name)
				'source'   	=> get_template_directory() . '/lib/vendor/plugins/bunyad-shortcodes.zip', // The plugin source
				'required' 	=> true, // If false, the plugin is only 'recommended' instead of required
				'force_activation' => false, // If true, plugin is activated upon theme activation and cannot be deactivated until theme switch
				'version'   => $plugins_info['bunyad-shortcodes']['version'],

			),
	
			array(
				'name'     	=> 'WPBakery Visual Composer',
				'slug'     	=> 'js_composer',
				'source'   	=> get_template_directory() . '/lib/vendor/plugins/js_composer.zip', 
				'required' 	=> true,
				'force_activation' => false,
				'version'   => $plugins_info['js_composer']['version'],

			),
			
			array(
				'name'      => 'Bunyad Widgets',
				'slug'      => 'bunyad-widgets',
				'source'    => get_template_directory() . '/lib/vendor/plugins/bunyad-widgets.zip',
				'required'  => true,
				'force_activation' => false,
				'version'   => $plugins_info['bunyad-widgets']['version'],
			),
			
			array(
				'name' => 'Custom sidebars',
				'slug' => 'custom-sidebars',
				'required' => false,			
			),
			
			array(
				'name' => 'WP Retina 2x',
				'slug' => 'wp-retina-2x',
				'required' => false,	
			),
			
			array(
				'name'   => 'Contact Form 7',
				'slug'   => 'contact-form-7',
				'required' => false,
			),
			
			array(
				'name'   => 'Social Count Plus',
				'slug'   => 'social-count-plus',
				'required' => false,
			)
	
		);

		tgmpa($plugins, array('is_automatic' => true));
		
	}
	
	/**
	 * Any layout blocks that are layout/page/theme-specific will be included to extend
	 * the default shortcodes supported by the Bunyad Shortcodes Plugin.
	 */
	public function setup_shortcodes()
	{
		if (!is_object(Bunyad::options()->shortcodes)) {
			return false;
		} 
		
		// default attributes shared amongst blocks
		$default_attribs = apply_filters('bunyad_default_block_attribs', array(
				'title'       => '', 
				'title_type'  => '',
				'view_all'    => 1,
				'main_color'  => '',
				'posts'       => 5, 
				'type'        => '', 
				'cat'         => '', 
				'tags'        => '',
				'sort_by'     => '', 
				'sort_order'  => '', 
				'taxonomy'    => '', 
				'offset'      => '',
				'link'		  => '', 
				'post_type'   => '', 
				'terms'       => '',
				'post_format' => '',
				'no_thumbs'   => 0,
				'excerpt_len' => '', 
		));
		
		
		// register blocks
		Bunyad::options()->shortcodes->add_blocks(array(
		
			// file based
			'blog' => array('render' => locate_template('blocks/blog.php'), 'attribs' => array_merge($default_attribs, array(
				'pagination' => 0, 'posts' => 6
			))),
			
			'highlights' => array('render' => locate_template('blocks/highlights.php'), 'attribs' => $default_attribs),
			
			'slider' =>  array('render' => locate_template('blocks/slider.php'), 'attribs' => $default_attribs),
			
			'review' => array('render' => locate_template('blocks/review.php'), 'attribs' => array('position' => 'bottom')),
			
			'main_highlights' => array('render' => locate_template('blocks/main-highlights.php'), 'attribs' => $default_attribs),

			'news_bar' => array('render' => locate_template('blocks/news-bar.php'), 'attribs' => $default_attribs),
			
			'multimedia' => array('render' => locate_template('blocks/multimedia.php'), 'attribs' => array_merge($default_attribs, array(
				'per_slide' => 3
			))),
			
			'latest_gallery' => array('render' => locate_template('blocks/latest-gallery.php'), 'attribs' => array_merge($default_attribs, array(
				'per_slide' => 3, 'show_nav' => true, 'title_pos' => '' 
			))), 
			
			// string based
			'main-color' => array('template' => '<span class="main-color">%text%</span>', 'attribs' => array('text' => '')),
		));
		
		// setup shortcode modifications
		add_filter('bunyad_shortcodes_list', array($this, 'shortcodes_list'));
		add_filter('bunyad_shortcodes_list_styles', array($this, 'shortcodes_list_styles'));
		
	}

	/**
	 * Styles and skins
	 */
	public function get_style($style = '')
	{		
		$styles = array(
			'magazine' => array(
				'font_args' => array('family' => 'Source Sans Pro:400,600,700|Open Sans:400,400italic,600,700'),
				'css' => 'layout-magazine',
			),
			 
			'news' => array(
				'font_args' => array('family' => 'Lora:400,700|Open Sans:400,600,700|Volkhov:400'),
			),
			
			'creative' => array(
				'font_args' => array('family' => 'Oswald:400,700|Lato:400,400italic,700|PT Serif:400italic'),
				'css' => 'layout-creative',
				'responsive-css' => 'responsive-creative'
			),
		);
		
		if (empty($styles[$style])) {
			return array();
		}
		
		return $styles[$style];
	}
	
	
	/**
	 * Action callback: Add form fields to category editing / adding form
	 */
	public function edit_category_meta($term = null)
	{
		// add required assets
		wp_enqueue_style('bunyad-cat-options', get_template_directory_uri() . '/admin/css/cat-options.css');
		wp_enqueue_style('wp-color-picker');
		wp_enqueue_script('wp-color-picker');
		
		// add media scripts
		wp_enqueue_media(); 
		
		wp_enqueue_script('bunyad-theme-options', get_template_directory_uri() . '/admin/js/options.js', array('jquery'));
		
		// get our category meta template
		include_once get_template_directory() . '/admin/category-meta.php';
	}
	
	public function shortcodes_list($list)
	{
		unset($list['default']['box']);
		return $list;
	}
	
	public function shortcodes_list_styles($styles)
	{
		$styles['arrow-right'] = $styles['arrow']; 
		unset($styles['arrow']);
		
		return $styles;
	}
	
	
	/**
	 * Filter callback: Custom menu fields
	 */
	public function custom_menu_fields($fields)
	{
		$fields = array(
			'mega_menu' => array(
				'label' => __('Mega Menu', 'bunyad'), 
				'element' => array(
					'type' => 'select',
					'class' => 'widefat',
					'options' => array(
						0 => __('Disabled', 'bunyad'), 
						'category' => __('Category Mega Menu (Subcats, Posts)', 'bunyad'),
						'category-featured' => __('Category Mega Menu (Subcats, Featured & Recent))', 'bunyad'),
						'normal' => __('Mega Menu for Links', 'bunyad')
					)
				),
				'parent_only' => true,
				'locations' => array('motive-main'),
			)
		);
		
		return $fields;
	}
	
	/**
	 * Filter Callback: Add our custom mega-menus
	 *
	 * @param array $args
	 */
	public function attach_mega_menu($args)
	{
		extract($args);
		
		/**
		 * @todo when not using a cache plugin, wrap in functions or cache the menu
		 */
		
		// category mega menu
		if ($item->mega_menu == 'category') {
			$template = 'partials/mega-menu/category.php';
		} 
		else if ($item->mega_menu == 'normal') {
			$template = 'partials/mega-menu/links.php';
		}
		else if ($item->mega_menu == 'category-featured') {
			$template = 'partials/mega-menu/category-featured.php';
		}
		
		if ($template) {
			ob_start();
			include locate_template($template);
			$output = ob_get_clean();
			
			return $output;
		}
		
		return $sub_menu;
	}
	
	/**
	 * Filter callback: Add logo to the sticky navigation
	 */
	public function add_navigation_logo($items, $args)
	{
		if (!Bunyad::options()->sticky_nav OR !Bunyad::options()->sticky_nav_logo OR $args->theme_location != 'motive-main') {
			return $items;
		}
		
		if (Bunyad::options()->image_logo_nav) {
			$logo = '<img src="' . esc_attr(Bunyad::options()->image_logo_nav) .'" />'; 
		}
		else {
			$logo = do_shortcode(Bunyad::options()->text_logo); // pre-sanitized with kses - valid html
		}
		
		
		$items = '<li class="sticky-logo"><a href="'. esc_url(home_url('/')) .'">' . $logo . '</a></li>' . $items;
		
		return $items;
	}
	
	/**
	 * Filter callback: Add theme-specific profile fields
	 */
	public function add_profile_fields($fields)
	{
		$fields = array_merge((array) $fields, array(
			'bunyad_twitter' => __('Twitter URL', 'bunyad'),
			'bunyad_gplus'   => __('Google+ URL', 'bunyad'),
			'bunyad_facebook' => __('Facebook URL', 'bunyad'),
			'bunyad_linkedin' => __('LinkedIn URL', 'bunyad'),
			'bunyad_dribbble' => __('Dribbble URL', 'bunyad'),
			'bunyad_public_email' => __('Public Email', 'bunyad'),
		));
		
		return $fields;
	}
	
	
	/**
	 * Action callback: Add the image overlay based on post-type
	 */
	public function add_image_overlay($term = '') 
	{	
		
		// which icon?
		switch (get_post_format()) {
			
			case 'image':
			case 'gallery':
				$icon = 'fa-picture-o';
				break;
			
			case 'video';
				$icon = 'fa-youtube-play';
				break;
				
			case 'audio':
				$icon = 'fa-music';
				break;
				
			default:
				$icon = 'fa-file-text-o';
				break;
		}
		
		?>
			<span class="image-overlay"></span>
			
			<span class="meta-overlay">
				<span class="meta">
				
				<span class="post-format <?php echo esc_attr(get_post_format()); ?>"><i class="fa <?php echo esc_attr($icon); ?>"></i></span>
				
				</span>
			</span>
		<?php

	}
	
	/**
	 * Filter callback: Auto-embed video using a link
	 * 
	 * @param string $content
	 */
	public function video_auto_embed($content) 
	{
		global $wp_embed;
		
		if (!is_object($wp_embed)) {
			return $content;
		}
		
		return $wp_embed->autoembed($content);
	}
	
	/**
	 * Filter callback: Add custom per page limits where set for individual category
	 * 
	 * @param object $query
	 */
	public function add_category_limits($query)
	{
		// bail out if incorrect query
		if (is_admin() OR !$query->is_category() OR !$query->is_main_query()) {
			return $query;
		}
		
		// permalinks have id or name?
		if ($query->get('cat')) {
			$category = get_category($query->get('cat'));
		}
		else {
			$category = get_category_by_slug($query->get('category_name'));	
		}
		
		// category meta
		$cat_meta = (array) Bunyad::options()->get('cat_meta_' . $category->term_id);
		
		// set user-specified per page
		if (!empty($cat_meta['per_page'])) {
			$query->set('posts_per_page', intval($cat_meta['per_page']));
		}
		
		return $query;
	}
	
	/**
	 * Add review/ratings to content
	 * 
	 * @param string $content
	 */
	public function add_review($content)
	{
		if (!is_single() OR !Bunyad::posts()->meta('reviews')) {
			return $content;
		}
		
		$position  = Bunyad::posts()->meta('review_pos');
		$shortcode = do_shortcode('[review position="'. esc_attr($position) .'"]');
		
		// based on placement
		if (strstr($position, 'top')) { 
			$content =  $shortcode . $content;
		}
		else if ($position == 'bottom') {
			$content .= $shortcode; 
		}
		
		return $content;
	}
	
	/**
	 * Filter callback: Add theme's default review snippet
	 * 
	 * @param string $content
	 */
	public function add_review_snippet($content)
	{
		if (!Bunyad::posts()->meta('reviews') OR !Bunyad::options()->review_show) {
			return $content;
		}
		
		// reviews enabled?
		if (Bunyad::posts()->meta('reviews')) {
			
			// star style reviews?
			if (Bunyad::options()->review_style == 'stars') 
			{
				return '
					<span class="review-meta stars">
						<span class="main-stars"><span style="width: '. Bunyad::reviews()->decimal_to_percent(Bunyad::posts()->meta('review_overall')) .'%;">
							<strong class="rating">' . Bunyad::posts()->meta('review_overall') . '</strong></span>
						</span>
					</span>';
			}
			
			if (Bunyad::options()->review_style == 'percent') {
				$rating = Bunyad::reviews()->decimal_to_percent(Bunyad::posts()->meta('review_overall')) . '<span class="percent">%</span>';
			}
			else {
				$rating = floatval(Bunyad::posts()->meta('review_overall')) . '/' . Bunyad::reviews()->rating_max;
			}
			
			return '<span class="review-meta"><span class="number">' . $rating . '</span></span>';
		}
	}
	
	/**
	 * Filter callback: Remove unnecessary classes
	 */
	public function fix_post_class($classes = array())
	{
		// remove hentry, we use schema.org
		$classes = array_diff($classes, array('hentry'));
		
		return $classes;
	}
	
	/**
	 * Filter callback: Add a wrapper to the content slideshow wrapper
	 * 
	 * @param string $content
	 */
	public function add_post_slideshow_wrap($content)
	{
		if (is_single() && Bunyad::posts()->meta('content_slider')) {
			return '<div class="content-page">' . $content . '</div>';
		}
		
		return $content;
	}
	
	/**
	 * Filter callback: Add custom image sizes to the editor image size selection
	 * 
	 * @param array $sizes
	 */
	public function add_image_sizes_editor($sizes) 
	{
		global $_wp_additional_image_sizes;
		
		if (empty($_wp_additional_image_sizes)) {
			return $sizes;
		}

		$motive_images = array('motive-grid-slider', 'motive-main-block', 'motive-highlights-block', 'motive-image-block', 'motive-slider-alt-block', 'motive-alt-slider', 'motive-slider-full');
		foreach ($_wp_additional_image_sizes as $id => $data) {

			if (in_array($id, $motive_images) && !isset($sizes[$id])) {
				$sizes[$id] = __('Theme - ', 'bunyad') . ucwords(str_replace('-', ' ', $id));
			}
		}
		
		return $sizes;
	}
	
	/**
	 * Filter callback: Limit search to posts only
	 * 
	 * @param object $query
	 */
	public function limit_search($query)
	{
		global $wp_query;
		
		// not in admin and not on bbpress search
		if (!is_admin() && $query->is_search && empty($wp_query->bbp_search_terms) && (!function_exists('is_woocommerce') OR !is_woocommerce())) {
			$query->set('post_type', 'post');
		}
		
		return $query;
	}
	
	/**
	 * Action callback: Add to list processed posts to handle duplicates
	 * 
	 * @param object $query
	 */
	public function update_duplicate_posts(&$query)
	{
		// the query must enable logging
		if (empty($query->query_vars['handle_duplicates']) OR !did_action('bunyad_pre_main_content')) {
			return;
		}

		// add to list
		foreach ($query->posts as $post) 
		{
			$duplicates = (array) Bunyad::registry()->page_duplicate_posts;
			array_push($duplicates, $post->ID); 
			
			Bunyad::registry()->page_duplicate_posts = $duplicates;
		}
	}
	
	/**
	 * Filter callback: Enable duplicate prevention on these query args
	 * 
	 * @param array $query  query arguments
	 */
	public function add_duplicate_exclude($query) 
	{
		if (!is_front_page()) {
			return $query;
		}
		
		if (!is_array(Bunyad::registry()->page_duplicate_posts)) {
			Bunyad::registry()->page_duplicate_posts = array();
		}
		
		$query['post__not_in'] = Bunyad::registry()->page_duplicate_posts;
		$query['handle_duplicates'] = true;
				
		return $query;
	}
	
	/**
	 * Action callback: Output comments overlay
	 */
	public function comments_snippet() {
						
		if (true /* have_comments() */):
		
		?>
			<a href="<?php echo esc_attr(get_comments_link()); ?>"><span class="comment-count"><?php echo get_comments_number(); ?></span></a>
		<?php 
		
		endif;
	}
	
	/**
	 * Action callback: Output common meta for listings
	 */
	public function listing_meta($type = '')
	{
		// default options
		$defaults = array('type' => '', 'review' => Bunyad::options()->listing_meta['review']);
		
		if (!is_array($type)) {
			$type = array('type' => $type);	
		}
		
		// override options
		$options = array_merge($defaults, $type);
		extract($options);
		
		echo '<span class="listing-meta">';
		
		// add the category meta? don't show on small type listings
		if (!strstr($type, 'small') && Bunyad::options()->listing_meta['category']) {
			
			// object has category taxonomy? i.e., is it a post?
			if (in_array('category', get_object_taxonomies(get_post_type()))) {
				
				// custom label selected?				
				if (($cat_label = Bunyad::posts()->meta('cat_label'))) {
					$category = get_category($cat_label);
				}
				else {
					$category = current(get_the_category());						
				}

				echo '<a href="'. get_category_link($category) .'" class="category main-color cat-color-'. esc_attr($category->term_id) .'">' . esc_html($category->cat_name) . '</a>';
			}
		}
		
		// add the date meta?
		if (Bunyad::options()->listing_meta['date']) {
			echo '<time datetime="' . esc_attr(get_the_date(DATE_W3C)) . '" itemprop="datePublished">' . get_the_date() . '</time>';	
		}
		
		if ($review && ($type != 'small-widget' OR Bunyad::options()->review_show_widgets)) {		
			echo apply_filters('bunyad_review_main_snippet', '');
		}
		
		echo '</span>';
	}	
	
	/**
	 * Filter callback: Set column for widgets where dynamic widths are set
	 * 
	 * @param array $params
	 * @see dynamic_sidebar()
	 */
	public function set_footer_columns($params)
	{
		static $count = 0, $columns, $last_id;
		
		if (empty($columns)) {
			$columns = array(
				'motive-main-footer' => $this->parse_column_setting(Bunyad::options()->footer_cols_upper),
				'motive-mid-footer'  => $this->parse_column_setting(Bunyad::options()->footer_cols_middle)
			);
		}
		
		/**
		 * Set correct column class for each widget in footer
		 */
		
		$id = $params[0]['id'];
		
		// reset counter if last sidebar id was different than current
		if ($last_id != $id) {
			$count = 0;
		}
		
		// skip everything but these
		if (in_array($params[0]['id'], array('motive-main-footer', 'motive-mid-footer'))) {

			if (isset($columns[$id][$count])) {
				$params[0]['before_widget'] = str_replace('column', $columns[$id][$count], $params[0]['before_widget']);
			}
			
			$count++;	
		}
		
		$last_id = $id;
	
		return $params;	
	}

	/**
	 * Action callback: Runs when theme version changes in admin
	 * 
	 * @see Bunyad_Admin_Options::check_version()
	 */
	public function theme_update()
	{
		// foce WordPress to re-check for plugin updates
		delete_site_transient('update_plugins');
	}
	
	/**
	 * Parse columns of format 1/2+1/4+1/4 into an array of col-X
	 * 
	 * @param   array  $cols
	 * @return  array  Example: array('col-6', 'col-3', ...)
	 */
	public function parse_column_setting($cols)
	{
		$columns = array();
		
		foreach (explode('+', $cols) as $col) 
		{			
			$col = explode('/', trim($col));
			
			if (!empty($col[0]) && !empty($col[1])) {
				
				$width = number_format($col[0] / $col[1], 2);
				
				// pre-parsed map to save computation time
				$map = array(
					'0.08' => 'col-1', '0.17' => 'col-2', '0.25' => 'col-3', '0.33' => 'col-4', 
					'0.42' => 'col-5', '0.50' => 'col-6', '0.58' => 'col-7', '0.67' => 'col-8', 
					'0.75' => 'col-9', '0.83' => 'col-10', '0.92' => 'col-11', '1.00' => 'col-12'
				);
				
				if (array_key_exists($width, $map)) {
					array_push($columns, $map[$width]);
				}
			}	
		}
		
		return $columns;
	}
	
	/**
	 * Get relative width for current block, based on parent column width in 
	 * relation to the whole container.
	 * 
	 * @return  float  column width in percent/100, i.e. 30% will be returned as 0.3
	 */
	public function block_relative_width()
	{
		// set current column width weight (width/100) - used to determine image sizing 
		$col_relative_width = 1;
		if (isset(Bunyad::registry()->layout['col_relative_width'])) {
			$col_relative_width = Bunyad::registry()->layout['col_relative_width'];
		}
	
		// adjust relative width if there's a sidebar
		if (Bunyad::core()->get_sidebar() != 'none') {
			$col_relative_width = ($col_relative_width * (8/12)); 
		}
		
		return $col_relative_width;
	}
		
}
