<?php

/////////////////////////////////////// File directories ///////////////////////////////////////

$gp_template_dir = get_template_directory();
$gp_template_dir_uri = get_template_directory_uri();
define( 'gp', $gp_template_dir . '/' );
define( 'gp_uri', $gp_template_dir_uri . '/' );
define( 'gp_css_uri', $gp_template_dir_uri . '/lib/css/' );
define( 'gp_images', $gp_template_dir_uri . '/lib/images/' );
define( 'gp_inc', $gp_template_dir . '/lib/inc/' );
define( 'gp_plugins', $gp_template_dir . '/lib/plugins/' );
define( 'gp_scripts', $gp_template_dir . '/lib/scripts/' );
define( 'gp_scripts_uri', $gp_template_dir_uri . '/lib/scripts/' );
define( 'gp_widgets', $gp_template_dir . '/lib/widgets/' );
define( 'gp_vc', $gp_template_dir . '/lib/vc-templates/' );
define( 'gp_wc', $gp_template_dir . '/woocommerce/' );


/////////////////////////////////////// Localisation ///////////////////////////////////////

load_theme_textdomain( 'gp_lang', gp . 'languages' );
$gp_locale = get_locale();
$gp_locale_file = gp . 'languages/$gp_locale.php';
if ( is_readable( $gp_locale_file ) ) { require_once( $gp_locale_file ); }
		
		
/////////////////////////////////////// Theme setup ///////////////////////////////////////

if ( ! function_exists( 'gp_theme_setup' ) ) {
	function gp_theme_setup() {

		global $content_width;
		
		// Set the content width based on the theme's design and stylesheet
		if ( ! isset( $content_width ) ) {
			$content_width = 810;
		}
		
		// Featured images
		add_theme_support( 'post-thumbnails' );
		set_post_thumbnail_size( 150, 150, true );

		// Background customizer
		add_theme_support( 'custom-background' );

		// Add shortcode support to Text widget
		add_filter( 'widget_text', 'do_shortcode' );

		// This theme styles the visual editor with editor-style.css to match the theme style
		add_editor_style( 'lib/css/editor-style.css' );

		// Add default posts and comments RSS feed links to <head>
		add_theme_support( 'automatic-feed-links' );

		// WooCommerce Support
		add_theme_support( 'woocommerce' );

		// Post formats
		add_theme_support( 'post-formats', array( 'quote', 'video', 'audio', 'gallery', 'link' ) );

		// Title support
		add_theme_support( 'title-tag' );
		
	}
}
add_action( 'after_setup_theme', 'gp_theme_setup' );


/////////////////////////////////////// Additional functions ///////////////////////////////////////

// Metaboxes
require_once( gp . 'lib/metaboxes/config.php' );

// Framework
if ( ! class_exists( 'ReduxFramework' ) && file_exists( gp . 'lib/redux-framework/ReduxCore/framework.php' ) ) {
    require_once( gp . 'lib/redux-framework/ReduxCore/framework.php' );
}
if ( ! isset( $gp ) && file_exists( gp_inc. 'theme-config.php' ) ) {
    require_once( gp_inc . 'theme-config.php' );
}

// Page settings
require_once( gp_inc . 'page-settings.php' );

// Page variables
require_once( gp_inc . 'page-variables.php' );

// Page headers
require_once( gp_inc . 'page-headers.php' );

// Ratings
require_once( gp_inc . 'ratings.php' );

// One click demo installer
require gp . 'lib/demo-installer/init.php';

// Image resizer
require_once( gp_inc . 'aq_resizer.php' );

// Follow items
if ( isset( $gp['hub_following_items'] ) && ( $gp['hub_following_items'] == 'both' OR ( is_user_logged_in() && $gp['hub_following_items'] == 'members' ) ) ) {
	require_once( gp_inc . 'follow-items.php' );
}

// Custom menu walker
require_once( gp . 'lib/menus/custom-menu-walker.php' );

// Custom menu fields
require_once( gp . 'lib/menus/menu-item-custom-fields.php' );

// Shortcodes
if ( function_exists( 'vc_set_as_theme' ) ) {
	require_once( gp_inc . 'theme-shortcodes.php' );
	require_once( gp_inc . 'default-vc-templates.php' );
	//require_once( gp_inc . 'old-theme-shortcodes.php' ); // Load in your child theme to load old shortcodes
}

// Woocommerce functions
if ( function_exists( 'is_woocommerce' ) ) {
	require_once( gp_wc . 'functions-woocommerce.php' );
}

// Ajax loop
require_once( gp_inc . 'ajax.php' );

// User ratings
require_once( gp_inc . 'user-ratings.php' );

// Create hub pages
if ( is_admin() ) {
	require_once( gp_inc . 'auto-hub-pages.php' );
}

// Theme convertor
if ( is_admin() ) {
	require_once( gp_inc . 'theme-convertor.php' );
}


/////////////////////////////////////// Enqueue Styles ///////////////////////////////////////

if ( ! is_admin() ) {

	if ( ! function_exists( 'gp_enqueue_styles' ) ) {
	
		function gp_enqueue_styles() { 

			global $gp;
			
			wp_enqueue_style( 'gp-style', get_stylesheet_uri() );
			
			wp_enqueue_style( 'gp-font-awesome', gp_uri . 'lib/fonts/font-awesome/css/font-awesome.min.css' );
			
			if ( function_exists( 'bp_is_active' ) OR function_exists( 'is_bbpress' ) ) {
				wp_enqueue_style( 'gp-buddypress', gp_css_uri . 'bp.css' );
			}
			
			wp_enqueue_style( 'gp-animations', gp_css_uri . 'animations.css' );

			if ( isset( $gp['lightbox'] ) && $gp['lightbox'] != 'disabled' ) {
				wp_enqueue_style( 'gp-prettyphoto', gp_scripts_uri . 'prettyPhoto/css/prettyPhoto.css' );
			}
						
			if ( isset( $gp['custom_stylesheet'] ) && ! empty( $gp['custom_stylesheet'] ) ) {
				wp_enqueue_style( 'gp-custom-style', gp_uri . $gp['custom_stylesheet'] );
			}
			
		}
	}
	
	add_action( 'wp_enqueue_scripts', 'gp_enqueue_styles' );
}


/////////////////////////////////////// Enqueue Scripts ///////////////////////////////////////
		
if ( ! is_admin() ) {

	if ( ! function_exists( 'gp_enqueue_scripts' ) ) {
	
		function gp_enqueue_scripts() {

			global $gp, $post;
			
			wp_enqueue_script( 'gp-modernizr', gp_scripts_uri . 'modernizr.js', false, '', true );
					
			if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) { 
				wp_enqueue_script( 'comment-reply' );
			}
			
			wp_enqueue_script( 'gp-stellar', gp_scripts_uri . 'jquery.stellar.min.js', array( 'jquery' ), '', true );
	
			if ( $gp['smooth_scrolling'] == 'gp-smooth-scrolling' ) { 
				wp_enqueue_script( 'gp-nicescroll', gp_scripts_uri . 'nicescroll.min.js', false, '', true );
			}
			
			wp_enqueue_script( 'gp-selectivizr', gp_scripts_uri . 'selectivizr.min.js', false, '', true );

			wp_enqueue_script( 'gp-placeholder', gp_scripts_uri . 'placeholders.min.js', false, '', true );
			
			if ( isset( $gp['lightbox'] ) && $gp['lightbox'] != 'disabled' ) {							
				wp_enqueue_script( 'gp-prettyphoto', gp_scripts_uri . 'prettyPhoto/js/jquery.prettyPhoto.js', array( 'jquery' ), '', true );
			}
			
			if ( $gp['back_to_top'] == 'gp-back-to-top' ) { 
				wp_enqueue_script( 'gp-back-to-top', gp_scripts_uri . 'jquery.ui.totop.min.js', array( 'jquery' ), '', true );
			}
			
			if ( ! function_exists( 'vc_set_as_theme' ) ) {
				wp_enqueue_script( 'gp-flexslider', gp_scripts_uri . 'jquery.flexslider-min.js', array( 'jquery' ), '', true );
			} else {
				wp_enqueue_script( 'flexslider' );
			}			
									
			if ( ! function_exists( 'vc_set_as_theme' ) ) {
				wp_enqueue_script( 'gp-isotope', gp_scripts_uri . 'isotope.pkgd.min.js', false, '', true );
			} else {
				wp_enqueue_script( 'isotope' );
			}
			
			wp_enqueue_script( 'gp-images-loaded', gp_scripts_uri . 'imagesLoaded.min.js', false, '', true );

			wp_register_script( 'gp-video-header', gp_scripts_uri . 'jquery.video-header.js', false, '', true );
			
			if ( is_page_template( 'images-template.php' ) ) {
				wp_enqueue_script( 'gp-lazyload', gp_scripts_uri . 'jquery.lazyload.min.js', array( 'jquery' ), '', true );
			}
																						
			wp_enqueue_script( 'gp-custom-js', gp_scripts_uri . 'custom.js', array( 'jquery' ), '', true );
	
			wp_localize_script( 'gp-custom-js', 'gp_script', array(
				'headerHeight' => $gp['main_header_height']['height'],
				'smallHeaderHeight' => $gp['main_header_height']['height'] / $gp['header_size_reduction'],
				'logoWidth' => $gp['logo_dimensions']['width'],
				'logoHeight' => $gp['logo_dimensions']['height'],
				'logoMarginTop' => $gp['logo_spacing']['margin-top'],
				'logoMarginBottom' => $gp['logo_spacing']['margin-bottom'],
				'headerSizeReduction' => $gp['header_size_reduction'],
				'lightbox' => $gp['lightbox'],
			) );	
				
		}
	}
	
	add_action( 'wp_enqueue_scripts', 'gp_enqueue_scripts' );
	
}


/////////////////////////////////////// Enqueue Admin Styles ///////////////////////////////////////

if ( ! function_exists( 'gp_enqueue_admin_styles' ) ) {
	function gp_enqueue_admin_styles( $hook ) {
		if ( 'edit.php' == $hook ) {
			wp_enqueue_style( 'gp-admin ', gp_css_uri . 'admin.css' );
		}
	}
}
add_action( 'admin_enqueue_scripts', 'gp_enqueue_admin_styles' );	


/////////////////////////////////////// Enqueue Admin Scripts ///////////////////////////////////////

if ( ! function_exists( 'gp_enqueue_admin_scripts' ) ) {
	function gp_enqueue_admin_scripts( $hook ) {
		if ( 'post.php' == $hook OR 'post-new.php' == $hook ) {
			wp_enqueue_script( 'gp-admin ', gp_scripts_uri . 'admin.js', '', '', true );
		}
	}
}
add_action( 'admin_enqueue_scripts', 'gp_enqueue_admin_scripts' );	


/////////////////////////////////////// WP Header Hooks ///////////////////////////////////////

if ( ! function_exists( 'gp_wp_header' ) ) {

	function gp_wp_header() {
	
		global $gp;
		
		// Title fallback for versions earlier than WordPress 4.1
		if ( ! function_exists( '_wp_render_title_tag' ) && ! function_exists( 'gp_render_title' ) ) {
			function gp_render_title() { ?>
				<title><?php wp_title( '|', true, 'right' ); ?></title>
			<?php }
		}
			
		if ( ! empty( $gp['favicon_ico']['url'] ) ) {
			echo '<link rel="shortcut icon" href="' . $gp['favicon_ico']['url'] . '" /><link rel="icon" href="' . $gp['favicon_ico']['url'] . '" type="image/vnd.microsoft.icon" />'; 
		}
				
		if ( ! empty( $gp['favicon_png']['url'] ) ) {
			echo '<link rel="icon" type="image/png" href="' . $gp['favicon_png']['url'] . '" />';
		}
				
		if ( ! empty( $gp['apple_icon']['url'] ) ) {
			echo '<link rel="apple-touch-icon" href="' . $gp['apple_icon']['url'] . '" />';
		}

		// Page settings
		gp_page_settings();
		
		// Style settings
		require_once( gp_inc . 'style-settings.php' );

		// Javascript code
		if ( isset( $gp['js_code'] ) && ( ! ctype_space( $gp['js_code'] ) && ! empty( $gp['js_code'] ) ) ) {
			$gp['js_code'] = str_replace( array( '<script>', '</script>' ), '', $gp['js_code'] );
			echo '<script>' . $gp['js_code'] . '</script>';
		}	
		
	}
	
}

add_action( 'wp_head', 'gp_wp_header' );


/////////////////////////////////////// Navigation Menus ///////////////////////////////////////

if ( ! function_exists( 'gp_register_menus' ) ) {
	function gp_register_menus() {
		register_nav_menus(array(
			'header-nav' => __( 'Main Header Navigation', 'gp_lang' ),
			'top-nav'    => __( 'Left Top Header Navigation', 'gp_lang' ),
			'right-top-nav' => __( 'Right Top Header Navigation', 'gp_lang' ),
			'footer-nav' => __( 'Footer Navigation', 'gp_lang' ),
		) );
	}
}
add_action( 'init', 'gp_register_menus' );


/////////////////////////////////////// Navigation User Meta ///////////////////////////////////////

if ( ! function_exists( 'gp_nav_user_meta' ) ) {
	function gp_nav_user_meta( $user_id = NULL ) {

		// These are the metakeys we will need to update
		$meta_key['menus'] = 'metaboxhidden_nav-menus';
		$meta_key['properties'] = 'managenav-menuscolumnshidden';

		// So this can be used without hooking into user_register
		if ( ! $user_id ) {
			$user_id = get_current_user_id(); 
		}
	
		// Set the default hiddens if it has not been set yet
		if ( ! get_user_meta( $user_id, $meta_key['menus'], true ) ) {
			$meta_value = array( 'add-gp_slides', 'add-gp_slide', 'add-gp_user_review' );
			update_user_meta( $user_id, $meta_key['menus'], $meta_value );
		}

		// Set the default properties if it has not been set yet
		if ( ! get_user_meta( $user_id, $meta_key['properties'], true) ) {
			$meta_value = array( 'link-target', 'xfn', 'description' );
			update_user_meta( $user_id, $meta_key['properties'], $meta_value );
		}
	
	}	
}
add_action( 'admin_init', 'gp_nav_user_meta' );


/////////////////////////////////////// Browser title ///////////////////////////////////////
		
if ( ! function_exists( 'gp_browser_title' ) ) {
	function gp_browser_title( $title ) {
		global $post, $gp;
		if ( is_singular() ) {
			$post_parent = $post->post_parent;
		} else {
			$post_parent = '';
		}			
		if ( ! function_exists( 'wpseo_auto_load' ) ) { 
			if ( is_tax() ) {		
				$title = single_cat_title( '', false ) . ' | ' . get_bloginfo( 'name' );
			} elseif ( is_page() && get_post_meta( $post_parent, '_wp_page_template', true ) == 'hub-template.php' && $gp['hub_prefix_child_pages'] == 'enabled' ) {	
				$title = the_title_attribute( array( 'echo' => false, 'post' => $post_parent ) ) . ' ' . the_title_attribute( array( 'echo' => false, 'post' => get_the_ID() ) ) . ' | ' . get_bloginfo( 'name' );
			} elseif ( is_page() && get_post_meta( $post_parent, '_wp_page_template', true ) == 'hub-template.php' ) {
				$title = the_title_attribute( array( 'echo' => false, 'post' => get_the_ID() ) ) . ' | ' . get_bloginfo( 'name' );
			}
		}	
		return $title;
	}
	add_filter( 'wp_title', 'gp_browser_title' );
}


/////////////////////////////////////// Get Hub ID ///////////////////////////////////////

if ( ! function_exists( 'gp_get_hub_id' ) ) {
	function gp_get_hub_id( $gp_post_id ) {	
		global $gp, $post;
		if ( is_singular() && $post->post_parent > 0 ) {
			$GLOBALS['gp_hub_id'] = $post->post_parent;
		} elseif ( is_singular( 'post' ) && get_post_meta( get_the_ID(), 'post_association', true ) && $gp['hub_header_posts'] == 'enabled' ) {
			$hub_id = get_post_meta( get_the_ID(), 'post_association', true );
			$GLOBALS['gp_hub_id'] = $hub_id[0];
		} elseif ( is_singular( 'gp_user_review' ) ) {
			$GLOBALS['gp_hub_id'] = get_post_meta( get_the_ID(), '_hub_page_id', true );	
		} else {
			$GLOBALS['gp_hub_id'] = get_the_ID();
		}
	}
}


/////////////////////////////////////// Sidebars/Widgets ///////////////////////////////////////

// Hub Categories Widget
require_once( gp_widgets . 'hub-categories.php' );
	
// Recent Comments Widget
require_once( gp_widgets . 'recent-comments.php' );

// Recent Posts Widget
require_once( gp_widgets . 'recent-posts.php' );

if ( ! function_exists( 'gp_widgets_init' ) ) {
	function gp_widgets_init() {

		// Sidebars
		register_sidebar( array( 
			'name'          => __( 'Standard Sidebar', 'gp_lang' ),
			'id'            => 'gp-standard-sidebar',
			'description'   => 'Displayed on posts, pages and post and video categories.',
			'before_widget' => '<div id="%1$s" class="widget %2$s">',
			'after_widget'  => '</div>',
			'before_title'  => '<h3 class="widgettitle">',
			'after_title'   => '</h3>',
		) );

		register_sidebar( array( 
			'name'          => __( 'Hub Sidebar', 'gp_lang' ),
			'id'            => 'gp-hub-sidebar',
			'description'   => 'Displayed on hub parent and child pages.',
			'before_widget' => '<div id="%1$s" class="widget %2$s">',
			'after_widget'  => '</div>',
			'before_title'  => '<h3 class="widgettitle">',
			'after_title'   => '</h3>',
		) );
		
		register_sidebar( array( 
			'name'          => __( 'Hub Categories Sidebar', 'gp_lang' ),
			'id'            => 'gp-hub-cat-sidebar',
			'description'   => 'Displayed on hub categories.',
			'before_widget' => '<div id="%1$s" class="widget %2$s">',
			'after_widget'  => '</div>',
			'before_title'  => '<h3 class="widgettitle">',
			'after_title'   => '</h3>',
		) );		
				  
		register_sidebar( array( 
			'name'          => __( 'WooCommerce Sidebar', 'gp_lang' ),
			'id'            => 'gp-woocommerce-sidebar',
			'description'   => 'Displayed on WooCommerce pages.',
			'before_widget' => '<div id="%1$s" class="widget %2$s">',
			'after_widget'  => '</div>',
			'before_title'  => '<h3 class="widgettitle">',
			'after_title'   => '</h3>',
		) );
	
		register_sidebar( array(
			'name'          => __( 'Footer 1', 'gp_lang' ),
			'id'            => 'gp-footer-1',
			'before_widget' => '<div id="%1$s" class="widget %2$s">',
			'after_widget'  => '</div>',
			'before_title'  => '<h3 class="widgettitle">',
			'after_title'   => '</h3>',
		) );        

		register_sidebar( array(
			'name'          => __( 'Footer 2', 'gp_lang' ),
			'id'            => 'gp-footer-2',
			'before_widget' => '<div id="%1$s" class="widget %2$s">',
			'after_widget'  => '</div>',
			'before_title'  => '<h3 class="widgettitle">',
			'after_title'   => '</h3>',
		) );        
	
		register_sidebar( array(
			'name'          => __( 'Footer 3', 'gp_lang' ),
			'id'            => 'gp-footer-3',
			'before_widget' => '<div id="%1$s" class="widget %2$s">',
			'after_widget'  => '</div>',
			'before_title'  => '<h3 class="widgettitle">',
			'after_title'   => '</h3>',
		) );        
	
		register_sidebar( array(
			'name'          => __( 'Footer 4', 'gp_lang' ),
			'id'            => 'gp-footer-4',
			'before_widget' => '<div id="%1$s" class="widget %2$s">',
			'after_widget'  => '</div>',
			'before_title'  => '<h3 class="widgettitle">',
			'after_title'   => '</h3>',
		) );      

		register_sidebar( array(
			'name'          => __( 'Footer 5', 'gp_lang' ),
			'id'            => 'gp-footer-5',
			'before_widget' => '<div id="%1$s" class="widget %2$s">',
			'after_widget'  => '</div>',
			'before_title'  => '<h3 class="widgettitle">',
			'after_title'   => '</h3>',
		) );
	
	}
}
add_action( 'widgets_init', 'gp_widgets_init' );


/////////////////////////////////////// Excerpts ///////////////////////////////////////

// Character Length
if ( ! function_exists( 'gp_excerpt_length' ) ) {
	function gp_excerpt_length( $gp_length ) {
		return 10000;
	}
}
add_filter( 'excerpt_length', 'gp_excerpt_length' );

// Excerpt Output
if ( ! function_exists( 'gp_excerpt' ) ) {
	function gp_excerpt( $gp_count ) {
		global $gp;
		if ( isset( $GLOBALS['gp_read_more_link'] ) && $GLOBALS['gp_read_more_link'] == 'enabled' ) {
			$gp_more_text = '...<a href="' .get_permalink( get_the_ID() ) . '" class="read-more more-link" title="' . the_title_attribute( 'echo=0' ) . '">[' . __( 'Read More', 'gp_lang' ) . ']</a>';
		} else {
			$gp_more_text = '...';
		}	
		$gp_excerpt = get_the_excerpt();
		
		if ( has_excerpt() ) { 
			$gp_excerpt = get_the_excerpt();
		} elseif ( get_post_meta( get_the_ID(), 'hub_synopsis', true ) ) {
			$gp_excerpt = get_post_meta( get_the_ID(), 'hub_synopsis', true );
		} 
				
		$gp_excerpt = strip_tags( $gp_excerpt );
		if ( function_exists( 'mb_strlen' ) && function_exists( 'mb_substr' ) ) { 
			if ( mb_strlen( $gp_excerpt ) > $gp_count ) {
				$gp_excerpt = mb_substr( $gp_excerpt, 0, $gp_count ) . $gp_more_text;
			}
		} else {
			if ( strlen( $gp_excerpt ) > $gp_count ) {
				$gp_excerpt = substr( $gp_excerpt, 0, $gp_count ) . $gp_more_text;
			}	
		}
		return $gp_excerpt;
	}
}


/////////////////////////////////////// Add Excerpt Support To Pages ///////////////////////////////////////

if ( ! function_exists( 'gp_add_excerpts_to_pages' ) ) {
	function gp_add_excerpts_to_pages() {
		 add_post_type_support( 'page', 'excerpt' );
	}
}
add_action( 'init', 'gp_add_excerpts_to_pages' );


/////////////////////////////////////// Add post tags to pages ///////////////////////////////////////	

if ( ! function_exists( 'gp_page_tags_support' ) ) {
	function gp_page_tags_support() {
		register_taxonomy_for_object_type( 'post_tag', 'page' );
	}
}
add_action( 'init', 'gp_page_tags_support' );

if ( ! function_exists( 'gp_page_tags_support_query' ) ) {
	function gp_page_tags_support_query( $wp_query ) {
		if ( $wp_query->get( 'tag' ) ) {
			$wp_query->set( 'post_type', 'any' );
		}	
	}
}
add_action( 'pre_get_posts', 'gp_page_tags_support_query' );


/////////////////////////////////////// Prefix hub title to child pages ///////////////////////////////////////	

if ( ! function_exists( 'gp_prefix_hub_title' ) ) {
	function gp_prefix_hub_title( $gp_post_id = '' ) {	
		global $gp, $post;
		if ( get_post_meta( $post->post_parent, '_wp_page_template', true ) == 'hub-template.php' && $gp['hub_prefix_child_pages'] == 'enabled' ) {	
			return the_title_attribute( array( 'echo' => false, 'post' => $post->post_parent ) ) . ' ' . the_title_attribute( array( 'echo' => false, 'post' => $gp_post_id ) );
		} else {
			return the_title_attribute( array( 'echo' => false, 'post' => $gp_post_id ) );
		}
	}
}


/////////////////////////////////////// Prefix hub and video categories ///////////////////////////////////////	

if ( ! function_exists( 'gp_add_prefix_to_terms' ) ) {
	function gp_add_prefix_to_terms( $term_id, $tt_id, $taxonomy ) {
		global $gp;
		if ( $taxonomy == 'gp_hubs' && ! empty( $gp['hub_cat_prefix_slug'] ) ) {
			$term = get_term( $term_id, $taxonomy );
			$args = array( 'slug' => $gp['hub_cat_prefix_slug'] . '-' . $term->slug );
			wp_update_term( $term_id, $taxonomy, $args );
		}
		if ( $taxonomy == 'gp_videos' && ! empty( $gp['video_cat_prefix_slug'] ) ) {
			$term = get_term( $term_id, $taxonomy );
			$args = array( 'slug' => $gp['video_cat_prefix_slug'] . '-' . $term->slug );
			wp_update_term( $term_id, $taxonomy, $args );
		}    
	}
}
add_action( 'created_term', 'gp_add_prefix_to_terms', 10, 3 );


/////////////////////////////////////// Get follow page link ///////////////////////////////////////

if ( ! function_exists( 'gp_following_link' ) ) {
	function gp_following_link() {
		$following_page = get_pages(
			array(
				'meta_key' => '_wp_page_template',
				'meta_value' => 'following-template.php'
			)
		);
		if ( $following_page ) {
			$following_page_id = $following_page[0]->ID;
			return get_permalink( $following_page_id );
		}	
	}
}


/////////////////////////////////////// Get author name ///////////////////////////////////////	

if ( ! function_exists( 'gp_author_name' ) ) {
	function gp_author_name( $gp_post_id = '', $gp_author_link = true ) {
		global $post;
		if ( get_post_meta( $gp_post_id, '_user_review_name', true ) ) {	
			echo get_post_meta( $gp_post_id, '_user_review_name', true );
		} elseif ( $gp_author_link == true ) {
			echo '<a href="' . get_author_posts_url( $post->post_author ) . '">' . get_the_author_meta( 'display_name', $post->post_author ) . '</a>';
		} else {
			echo get_the_author_meta( 'display_name', $post->post_author );
		}
	}
}


/////////////////////////////////////// Change Password Protect Post Text ///////////////////////////////////////	

if ( ! function_exists( 'gp_password_form' ) ) {
	function gp_password_form() {
		global $post;
		$gp_label = 'pwbox-' . ( empty( $post->ID ) ? rand() : $post->ID );
		$gp_o = '<form action="' . esc_url( site_url( 'wp-login.php?action=postpass', 'login_post' ) ) . '" method="post">
		<p>' . __( 'To view this protected post, enter the password below:', 'gp_lang' ) . '</p>
		<label for="' . $gp_label . '"><input name="post_password" id="' . $gp_label . '" type="password" size="20" maxlength="20" /></label> <input type="submit" class="pwsubmit" name="Submit" value="' . esc_attr__( 'Submit', 'gp_lang' ) . '" />
		</form>
		';
		return $gp_o;
	}
}
add_filter( 'the_password_form', 'gp_password_form' );


/////////////////////////////////////// Redirect Empty Search To Search Page ///////////////////////////////////////	

if ( ! function_exists( 'gp_empty_search' ) ) {
	function gp_empty_search( $gp_query ) {
		global $wp_query;
		if ( isset( $_GET['s'] ) && ( $_GET['s'] == '' ) ) {
			$wp_query->set( 's', ' ' );
			$wp_query->is_search = true;
		}
		return $gp_query;
	}
}
add_action( 'pre_get_posts', 'gp_empty_search' );


/////////////////////////////////////// Alter category queries ///////////////////////////////////////	

if ( ! function_exists( 'gp_category_queries' ) ) {
	function gp_category_queries( $query ) {
		global $gp;			
		if ( is_admin() OR ! $query->is_main_query() ) { 
			return;
		} else {
			if ( is_post_type_archive( 'gp_portfolio_item' ) OR is_tax( 'gp_portfolios' ) )  {
				$GLOBALS['gp_orderby'] = $gp['portfolio_cat_orderby'];
				$GLOBALS['gp_per_page'] = $gp['portfolio_cat_per_page'];
				$GLOBALS['gp_date_posted'] = $gp['portfolio_cat_date_posted'];
				$GLOBALS['gp_date_modified'] = $gp['portfolio_cat_date_modified'];
			} elseif ( is_post_type_archive( 'page' ) OR is_tax( 'gp_hubs' ) ) {
				$GLOBALS['gp_orderby'] = $gp['hub_cat_orderby'];
				$GLOBALS['gp_per_page'] = $gp['hub_cat_per_page'];
				$GLOBALS['gp_date_posted'] = $gp['hub_cat_date_posted'];
				$GLOBALS['gp_date_modified'] = $gp['hub_cat_date_modified'];
			} elseif ( is_post_type_archive( 'post' ) OR is_tax( 'gp_videos' ) ) {
				$GLOBALS['gp_orderby'] = $gp['video_cat_orderby'];
				$GLOBALS['gp_per_page'] = $gp['video_cat_per_page'];
				$GLOBALS['gp_date_posted'] = $gp['video_cat_date_posted'];
				$GLOBALS['gp_date_modified'] = $gp['video_cat_date_modified'];
			} elseif ( is_search() OR is_author() ) {
				$GLOBALS['gp_orderby'] = $gp['search_orderby'];
				$GLOBALS['gp_per_page'] = $gp['search_per_page'];
				$GLOBALS['gp_date_posted'] = $gp['search_date_posted'];
				$GLOBALS['gp_date_modified'] = $gp['search_date_modified'];
			} elseif ( is_home() OR is_archive() ) {
				$GLOBALS['gp_orderby'] = $gp['cat_orderby'];
				$GLOBALS['gp_per_page'] = $gp['cat_per_page'];
				$GLOBALS['gp_date_posted'] = $gp['cat_date_posted'];
				$GLOBALS['gp_date_modified'] = $gp['cat_date_modified'];
			}
			if ( isset( $GLOBALS['gp_per_page'] ) ) {
				gp_query_variables();
				$query->set( 'posts_per_page', $GLOBALS['gp_per_page'] );
				$query->set( 'orderby', $GLOBALS['gp_orderby_value'] );
				$query->set( 'order', $GLOBALS['gp_order'] );
				$query->set( 'meta_key', $GLOBALS['gp_meta_key'] );
				$query->set( 'date_query', array( $GLOBALS['gp_date_posted_value'], $GLOBALS['gp_date_modified_value'] ) );
				if ( is_author() ) { $query->set( 'post_type',  array( 'post', 'page' ) ); }
				return;
			}	
		}
	}
}	
add_action( 'pre_get_posts', 'gp_category_queries', 1 );


/////////////////////////////////////// Alter filter element queries ///////////////////////////////////////	

if ( ! function_exists( 'gp_filter_queries' ) ) {
	function gp_filter_queries( $query ) {
		global $gp;			
		if ( is_admin() OR ! $query->is_main_query() ) { 
			return;
		} else {
			if ( isset( $_POST['action'] ) && $_POST['action'] == 'gp_filter' ) {
				if ( isset( $_POST['date_posted'] ) ) {
					$GLOBALS['gp_date_posted'] = $_POST['date_posted'];
				} else {
					$GLOBALS['gp_date_posted'] = '';
				}	
				if ( isset( $_POST['date_modified'] ) ) {
					$GLOBALS['gp_date_modified'] = $_POST['date_modified'];
				} else {
					$GLOBALS['gp_date_modified'] = '';
				}	
				gp_query_variables();
				$query->set( 'date_query', array( $GLOBALS['gp_date_posted_value'], $GLOBALS['gp_date_modified_value'] ) );
				return;
			}	
		}
	}
}	
add_action( 'pre_get_posts', 'gp_filter_queries', 1 );


/////////////////////////////////////// Pagination ///////////////////////////////////////	

if ( ! function_exists( 'gp_pagination' ) ) {
	function gp_pagination( $gp_query ) {
		$gp_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;
		}
		return '<div class="pagination pagination-numbers standard-pagination">' . paginate_links( array(
			'base'      => str_replace( $gp_big, '%#%', esc_url( get_pagenum_link( $gp_big ) ) ),
			'format'    => '?paged=%#%',
			'current'   => max( 1, $paged ),
			'total'     => $gp_query,
			'type'      => 'list',
			'prev_text' => '',
			'next_text' => '',
		) ) . '</div>';
	}
}

if ( ! function_exists( 'gp_get_previous_posts_page_link' ) ) {
	function gp_get_previous_posts_page_link() {
		global $paged;
		$nextpage = intval( $paged ) - 1;
		if ( $nextpage < 1 ) {
			$nextpage = 1;
		}	
		if ( $paged > 1 ) {
			return '<a href="' . get_pagenum_link( $nextpage ) . '" class="prev"></a>';
		}
	}
}		

if ( ! function_exists( 'gp_get_next_posts_page_link' ) ) {
	function gp_get_next_posts_page_link( $max_page = 0 ) {
		global $paged;
		if ( ! $paged ) {
			$paged = 1;
		}	
		$nextpage = intval( $paged ) + 1;
		if ( ! $max_page || $max_page >= $nextpage ) {
			return '<a href="' . get_pagenum_link( $nextpage ) . '" class="next"></a>';
		}
	}
}


/////////////////////////////////////// Canonical, next and prev rel links on page templates ///////////////////////////////////////	

if ( ! function_exists( 'gp_rel_prev_next' ) && function_exists( 'wpseo_auto_load' ) ) {
	function gp_rel_prev_next( $max_page = 0 ) {
		if ( is_page_template( 'blog-template.php' ) OR is_page_template( 'news-template.php' ) OR is_page_template( 'videos-template.php' ) OR is_page_template( 'portfolio-template.php' ) ) {
		
			global $paged;
		
			if ( ! $paged ) {
				$paged = 1;
			}
		
			// Prev rel link
			$prevpage = intval( $paged ) - 1;
			if ( $prevpage < 1 ) {
				$prevpage = 1;
			}	
			if ( $paged > 1 ) {
				echo '<link rel="prev" href="' . get_pagenum_link( $prevpage ) . '">';
			}
		
			// Next rel link
			$nextpage = intval( $paged ) + 1;	
			//if ( ! $max_page OR $max_page >= $nextpage ) {
				echo '<link rel="next" href="' . get_pagenum_link( $nextpage ) . '">';
			//}
		
		}
	}
	add_action( 'wp_head', 'gp_rel_prev_next' );
}
	
if ( ! function_exists( 'gp_canonical_link' ) && function_exists( 'wpseo_auto_load' ) ) {	
	function gp_canonical_link() {
		if ( is_page_template( 'blog-template.php' ) OR is_page_template( 'news-template.php' ) OR is_page_template( 'videos-template.php' ) OR is_page_template( 'portfolio-template.php' ) ) {
			global $paged;		
			if ( ! $paged ) {
				$paged = 1;
			}
			return get_pagenum_link( $paged );
		} else {
			return '__return_true';
		}
	}
	add_filter( 'wpseo_canonical', 'gp_canonical_link' );
}
									
					
/////////////////////////////////////// Post category options ///////////////////////////////////////	

function gp_add_tax_fields( $tag ) {

	if ( isset( $tag->term_id ) ) {
		$t_id = $tag->term_id;
		$term_meta = get_option( "taxonomy_$t_id" );
	} else {
		$term_meta = null;
	} ?>
			
	<div class="form-field">

		<label for="category-bg-image"><?php _e( 'Background Image', 'gp_lang' ); ?></label>

		<input type="text" id="term_meta" name="term_meta[bg_image]" value="<?php echo esc_url( $term_meta['bg_image'] ? $term_meta['bg_image'] : '' ); ?>" />

		<p class="description"><?php _e( 'The background of the page title. <strong>Enter an image URL that must be uploaded to the Media Library.</strong>', 'gp_lang' ); ?></p>

	</div>
	
<?php }
add_action( 'category_add_form_fields', 'gp_add_tax_fields' );		

function gp_edit_tax_fields( $tag ) {

	$t_id = $tag->term_id;
	$term_meta = get_option( "taxonomy_$t_id" ); ?>

	<tr class="form-field">

		<th scope="row" valign="top">
			<label for="category-bg-image"><?php _e( 'Background Image', 'gp_lang' ); ?></label>
		</th>

		<td>

			<input type="text" id="term_meta" name="term_meta[bg_image]" value="<?php echo esc_url( $term_meta['bg_image'] ? $term_meta['bg_image'] : '' ); ?>" />
	
			<p class="description"><?php _e( 'The background of the large header page title. <strong>Enter an image URL that must be uploaded to the Media Library.</strong>', 'gp_lang' ); ?></p>

		</td>

	</tr>
	
<?php }
add_action( 'edit_category_form_fields', 'gp_edit_tax_fields' );	
	
function gp_save_tax_fields( $term_id ) {
	if ( isset( $_POST['term_meta'] ) ) {
		$t_id = $term_id;
		$term_meta = get_option( "taxonomy_$t_id" );
		$cat_keys = array_keys( $_POST['term_meta'] );
			foreach ( $cat_keys as $key ) {
			if ( isset( $_POST['term_meta'][$key] ) ) {
				$term_meta[$key] = $_POST['term_meta'][$key];
			}
		}
		update_option( "taxonomy_$t_id", $term_meta );
	}
}			
add_action( 'created_category', 'gp_save_tax_fields' );		
add_action( 'edit_category', 'gp_save_tax_fields' );
		

/////////////////////////////////////// Redirect wp-login.php to login form ///////////////////////////////////////	

if ( ! function_exists( 'gp_login_redirect' ) ) {
	function gp_login_redirect() {
		global $gp;
		if ( ( isset ( $gp['login_popup_box'] ) && $gp['login_popup_box'] == 'enabled' ) OR ( isset( $gp['register_popup_box'] ) && $gp['register_popup_box'] == 'enabled' ) ) {
			global $pagenow;
			if ( 'wp-login.php' == $pagenow ) {
				if ( isset( $_POST['wp-submit'] ) OR ( isset( $_GET['action'] ) && $_GET['action'] == 'logout' ) OR ( isset( $_GET['checkemail'] ) && $_GET['checkemail'] == 'confirm' ) OR ( isset( $_GET['checkemail'] ) && $_GET['checkemail'] == 'registered' ) OR ( isset( $_GET['action'] ) && $_GET['action'] == 'postpass' ) OR ( isset( $_GET['reauth'] ) && $_GET['reauth'] == '1' ) OR ( isset( $_GET['action'] ) && $_GET['action'] == 'register' ) ) return;
				else wp_redirect( home_url( '#login' ) );
				exit();
			}
		}	
	}
}
add_action( 'init', 'gp_login_redirect' );


/////////////////////////////////////// Remove hentry tag ///////////////////////////////////////	

if ( ! function_exists( 'gp_remove_hentry' ) ) {
	function gp_remove_hentry( $classes ) {
		$classes = array_diff( $classes, array( 'hentry' ) );
		return $classes;
	}
}
add_filter( 'post_class', 'gp_remove_hentry' );


/////////////////////////////////////// Get attachment ID from URL ///////////////////////////////////////	

// https://philipnewcomer.net/2012/11/get-the-attachment-id-from-an-image-url-in-wordpress/
function gp_get_attachment_id_from_url( $attachment_url = '' ) {
 
	global $wpdb;
	$attachment_id = false;

	if ( '' == $attachment_url )
		return;
 
	$upload_dir_paths = wp_upload_dir();

	if ( false !== strpos( $attachment_url, $upload_dir_paths['baseurl'] ) ) {
 
		$attachment_url = preg_replace( '/-\d+x\d+(?=\.(jpg|jpeg|png|gif)$)/i', '', $attachment_url );
 
		$attachment_url = str_replace( $upload_dir_paths['baseurl'] . '/', '', $attachment_url );
 
		$attachment_id = $wpdb->get_var( $wpdb->prepare( "SELECT wposts.ID FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta WHERE wposts.ID = wpostmeta.post_id AND wpostmeta.meta_key = '_wp_attached_file' AND wpostmeta.meta_value = '%s' AND wposts.post_type = 'attachment'", $attachment_url ) );
 
	}
 
	return $attachment_id;
	
}

 
/////////////////////////////////////// Add lightbox class to image links ///////////////////////////////////////	

if ( isset( $gp['lightbox'] ) && $gp['lightbox'] != 'disabled' ) {
	if ( ! function_exists( 'gp_lightbox_image_link' ) ) {
		function gp_lightbox_image_link( $content ) {	
			global $gp, $post;
			if ( $gp['lightbox'] == 'group_images' ) {
				$group = '[image-' . $post->ID . ']';
			} else {
				$group = '';
			}
			$pattern = "/<a(.*?)href=('|\")(.*?).(bmp|gif|jpeg|jpg|png)('|\")(.*?)>/i";
			$replacement = '<a$1data-rel="prettyPhoto' . $group . '" href=$2$3.$4$5$6>';
			$content = preg_replace( $pattern, $replacement, $content );
			return $content;
		}
		add_filter( 'the_content', 'gp_lightbox_image_link' );	
	}	
}

if ( isset( $gp['lightbox'] ) && $gp['lightbox'] != 'disabled' ) {
	if ( ! function_exists( 'gp_lightbox_gallery_link' ) ) {
		function gp_lightbox_gallery_link( $content ) {
			global $gp, $post;			
			if ( $gp['lightbox'] == 'group_images' ) {
				$group = '[image-' . $post->ID . ']';
			} else {
				$group = '';
			}
			$pattern = "/<a(.*?)href=('|\")(.*?).(bmp|gif|jpeg|jpg|png)('|\")(.*?)>/i";
			$replacement = '<a$1data-rel="prettyPhoto' . $group . '" href=$2$3.$4$5$6>';
			$content = preg_replace( $pattern, $replacement, $content );
			return $content;
		}
		add_filter( 'wp_get_attachment_link', 'gp_lightbox_gallery_link' );
	}
}


/////////////////////////////////////// Upload user review image ///////////////////////////////////////	

if ( ! function_exists( 'gp_insert_attachment' ) ) {	
	function gp_insert_attachment( $file_handler, $post_id ) {
		if ( $_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK )
			return false;		
		require_once( ABSPATH . "wp-admin" . '/includes/image.php' );
		require_once( ABSPATH . "wp-admin" . '/includes/file.php' );
		require_once( ABSPATH . "wp-admin" . '/includes/media.php' );
		$attach_id = media_handle_upload( $file_handler, $post_id );
		update_post_meta( $post_id, '_thumbnail_id', $attach_id );
		//set_post_thumbnail( $post_id, $attach_id );
		return $attach_id;
	}
}

	
/////////////////////////////////////// Editing user review meta ///////////////////////////////////////	

if ( ! function_exists( 'gp_my_review_links' ) ) {
	function gp_my_review_links() {
		global $gp;
		if ( is_page_template( 'my-reviews-template.php' ) ) { ?>
			<div class="entry-meta">
				<?php _e( 'User Rating:', 'gp_lang' ); ?> <?php echo get_post_meta( get_the_ID(), '_user_review_rating', true ); ?> | <?php echo get_the_title( get_post_meta( get_the_ID(), '_hub_page_id', true ) ); ?>
				<?php if ( $gp['write_a_review_editing'] != 'disabled' ) { ?>
					<div class="my-reviews-meta">
						<form action="<?php echo home_url( 'edit-a-review' ); ?>" method="post" class="edit-review-form">
							<input type="hidden" name="user_review_id" value="<?php the_ID(); ?>" />
							<button type="submit"><?php _e( 'Edit', 'gp_lang' ); ?></button>
						</form> |
						<form action="" method="post" class="delete-review-form" onSubmit="if ( confirm( '<?php _e( 'Are you sure you want to delete this review?', 'gp_lang' ); ?>' ) ) return true; else return false;">
							<input type="hidden" name="user_review_id" value="<?php the_ID(); ?>" />
							<button type="submit"><?php _e( 'Delete', 'gp_lang' ); ?></button>
						</form>
					</div>
				<?php } ?>	
			</div>	
		<?php }
	}
}

    
/////////////////////////////////////// Visual Composer ///////////////////////////////////////	

if ( function_exists( 'vc_set_as_theme' ) ) {
	vc_set_as_theme( $notifier = true ); // Disable auto updates
	vc_set_template_dir( gp_vc ); // Set templates directory
}		


/////////////////////////////////////// TMG Plugin Activation ///////////////////////////////////////	

if ( version_compare( phpversion(), '5.3.0', '>=' ) ) {
	require_once( gp_inc . 'class-tgm-plugin-activation.php' );
} else {
	function gp_php_notice() { ?>
	<div class="update-nag error">
		<p><?php _e( 'PHP version', 'gp_lang' ); ?> <strong>5.3</strong> <?php _e( 'or higher is required in order to use the plugin installer/updater that comes with this theme', 'gp_lang' ); ?> (<?php _e( 'you are using version', 'gp_lang' ) ?> <strong><?php echo phpversion(); ?></strong>). <?php _e( 'Please ask your web host to upgrade to version', 'gp_lang' ); ?> <strong>5.3</strong> <?php _e( 'or higher.', 'gp_lang' ); ?></p>
	</div>
	<?php }
	add_action( 'admin_notices', 'gp_php_notice' );
}

if ( ! function_exists( 'gp_register_required_plugins' ) ) {
	
	function gp_register_required_plugins() {

		$plugins = array(

			array(
				'name'               => 'Gauge Plugin',
				'slug'               => 'gauge-plugin',
				'source'             => gp_plugins . 'gauge-plugin.zip',
				'required'           => true,
				'version'            => '1.6',
				'force_activation'   => true,
				'force_deactivation' => false,
			),

			array(
				'name'               => 'WPBakery Visual Composer',
				'slug'               => 'js_composer',
				'source'             => gp_plugins . 'js_composer.zip',
				'required'           => true,
				'version'            => '4.5.2',
				'force_activation'	 => true,
				'force_deactivation' => false,
			),

			array(
				'name'               => 'Visual Composer Widgets',
				'slug'               => 'vc-widget-addon',
				'source'             => gp_plugins . 'vc-widget-addon.zip',
				'required'           => true,
				'version'            => '1.0.7',
				'force_activation'	 => true,
				'force_deactivation' => false,
			),

			array(
				'name'      => 'Post Views Counter',
				'slug'      => 'post-views-counter',
				'required' 	=> false,
			),
					
			array(
				'name'      => 'Contact Form 7',
				'slug'      => 'contact-form-7',
				'required' 	=> false,
			),

			array(
				'name'      => 'Social Login',
				'slug'      => 'oa-social-login',
				'required' 	=> false,
			),

			array(
				'name'      => 'Advanced Responsive Video Embedder',
				'slug'      => 'advanced-responsive-video-embedder',
				'required' 	=> false,
			),

			array(
				'name'      => 'Captcha',
				'slug'      => 'captcha',
				'required' 	=> false,
			),
																				
		);

		$config = array(
			'default_path' => '',                      // Default absolute path to pre-packaged plugins.
			'menu'         => 'tgmpa-install-plugins', // Menu slug.
			'has_notices'  => true,                    // Show admin notices or not.
			'dismissable'  => true,                    // If false, a user cannot dismiss the nag message.
			'dismiss_msg'  => '',                      // If 'dismissable' is false, this message will be output at top of nag.
			'is_automatic' => true,                   // Automatically activate plugins after installation or not.
			'message'      => '',                      // Message to output right before the plugins table.
		);
 
		tgmpa( $plugins, $config );

	}
	
}

add_action( 'tgmpa_register', 'gp_register_required_plugins' );

?>