<?php
// Exit if accessed directly
if ( !defined('ABSPATH')) exit;

/* ********************
 * Load flowplayer skin if
 * a flv video is added to entry
 ******************************************************************** */
	  	
	function gabfire_flowplayerSkin() { /* Function gets executred within framework/functions/gabfire-media.php */
		wp_enqueue_style('flowplayer-skin', get_template_directory_uri() .'/inc/js/flowplayer/skin/playful.css');	
	}
	
	
/* ********************
 * Modify dynamic_sidebar widget function slightly to return a
 * variable and display name of widget zone to ste admin if the
 * option 'display widget map' is activated on theme control panel
 ******************************************************************** */
	function gabfire_dynamic_sidebar($widgetname)
	{
	  dynamic_sidebar($widgetname);  
	  if((of_get_option('of_widget', 0) == 1) and is_user_logged_in() ) { 
		echo '<span class="widgetmapname">'.$widgetname.'</span>'; 
	  }  
	}

/* ********************
 * Some navigations displays pages and cats side by side. If there is
 * not any registered category within site, 'No Categories' string shows
 * on navigation together with pages. gabfire_remove_nocats function is going
 * to hide 'no categories' string incase of this scenario.
 ******************************************************************** */
	function gabfire_remove_nocats($dont_display) {
	  if (!empty($dont_display)) {
		$dont_display = str_ireplace('<li>' .__( "No categories", 'gabfire' ). '</li>', "", $dont_display);
	  }
	  return $dont_display;
	}
	add_filter('wp_list_categories','gabfire_remove_nocats');

/* ********************
 * The site title that is displayed in header
 * between <title></title> tags
 ******************************************************************** */
add_filter( 'wp_title', 'gabfire_wp_title', 10, 3 );

function gabfire_wp_title( $old_title, $sep, $sep_location ) {
    global $page, $paged;
    /** Set initial title text */
    $title = get_bloginfo( 'name' );
    /** Add wrapping spaces to separator character */
    $sep = ' ' . $sep . ' ';

    $gab_title_text = $title;

    /** Add the blog description (tagline) for the home/front page */
    $site_tagline = get_bloginfo( 'description', 'display' );
    if ( $site_tagline && ( is_home() || is_front_page() ) )
        $gab_title_text = $title . $sep . $site_tagline;

    if ( is_page() || is_single() )
        $gab_title_text = get_the_title() . $sep . $title;

    if ( is_category() ) {
        $gab_title_text = sprintf( __( '%s Archive', 'gabfire' ), single_cat_title( '', false ) ) . $sep . $title;
    } elseif ( is_day() ) {
        $gab_title_text = sprintf( __( 'Archive for %s', 'gabfire' ), get_the_time( 'F jS, Y' ) ) . $sep . $title;
    } elseif ( is_month() ) {
        $gab_title_text = sprintf( __( 'Archive for %s', 'gabfire' ), get_the_time( 'F, Y' ) ) . $sep . $title;
    } elseif ( is_year() ) {
        $gab_title_text = sprintf( __( 'Archive for %s', 'gabfire' ), get_the_time( 'Y' ) ) . $sep . $title;
    } elseif ( is_search() ) {
        $gab_title_text = sprintf( __( 'Search Results for %s', 'gabfire' ), $_GET['s'] ) . $sep . $title;
    } elseif ( is_author() ) {
        $gab_title_text = __( 'Author Archive', 'gabfire' ) . $sep . $title;
    } elseif ( is_tag() ) {
        $gab_title_text = __( 'Tag Archive', 'gabfire' ) . $sep . $title;
    } elseif ( is_feed() ) {
        $gab_title_text ='';
    }

    /** Add a page number if necessary */
    if ( $paged >= 2 || $page >= 2 )
        $gab_title_text .= $sep . sprintf( __( 'Page %s', 'gabfire' ), max( $paged, $page ) );

    return $gab_title_text;
}

/* ********************
 * gabfire framework has support to display category based ads.
 * Using gabfire_current_catID; we check whether a file exist with
 * gabfire_current_catID.php name or not.
 ******************************************************************** */
	function gabfire_current_catID() {
		global $wp_query,  $cat_obj, $currentcat;

		if (is_category()) {	
			$cat_obj = $wp_query->get_queried_object();
			$currentcat = $cat_obj->term_id;
		} 
		elseif (is_single() and !is_attachment()) {
			$category = get_the_category();
			$currentcat = $category[0]->cat_ID;
		}
		
		return $currentcat;
	}

/* ********************
 * Category based ad function.
 * Using gabfire_current_catID function, we check if an ad file per cat
 * is available or not.
 ******************************************************************** */
 	function gabfire_categoryad($path) {
		if((is_single() or is_category()) and (file_exists(get_template_directory() . '/ads/'.$path.'/'. gabfire_current_catID() .'.php'))) {
			get_template_part('/ads/'.$path.'/'. gabfire_current_catID());
		} else {
			get_template_part('/ads/'.$path);
		}
	}

/* ********************
 * Limit post excerpts. Within theme files used as 
 * print gabfire_limit_words(get_the_excerpt(), 16);
 ******************************************************************** */
	function gabfire_limit_words($string, $word_limit) {
		global $post, $page;
		if( $post->post_excerpt ) {
			$word_limit = 999;
		}
		$words = explode(' ', $string, ($word_limit + 1));
		if(count($words) > $word_limit)
		array_pop($words);
		return implode(' ', $words);
	}

/* ********************
 * The post meta display below post excerpts on front page
 * default usage gabfire_postmeta(date, comment, permalink, edit-post)
 ******************************************************************** */
	function gabfire_permalink() { /* We first create a function to get the post permalink with read more anchor */
		echo '<span class="meta_permalink">';
		echo '<a href="'; the_permalink(); echo '" title="'; printf( esc_attr__( 'Permalink to %s', 'gabfire' ), the_title_attribute( 'echo=0' ) ); echo'" rel="bookmark">'; esc_attr_e('Read More', 'gabfire'); echo '</a>';
		echo '</span>';
	}
	function gabfire_postcomment() { /* We first create a function to get the post permalink with read more anchor */
		echo '<span class="meta_comment">';
		comments_popup_link(__('No Comment','gabfire'), __('1 Comment','gabfire'), __('% Comments','gabfire'));
		echo '</span>';
	}	
	
	function gabfire_postmeta($date = true,$comment = true,$permalink = true,$edit = true) {
		echo '<p class="postmeta">';
			echo (true === $date) ? '<span class="meta_date">' . get_the_date() . '</span>' : "";
			echo (true === $comment) ? gabfire_postcomment() : "";
			echo (true === $permalink) ?  gabfire_permalink() : "";
			(true === $edit) ? edit_post_link(__('#','gabfire'),'<span class="meta_edit">','</span>') : "";
		echo '</p>';
	}

/* ********************
 * Truncate post title. 
 * default usage gabfire_limit_posttitle(title length,string after title)
 ******************************************************************** */
    function gabfire_limit_posttitle($t_length,$t_end) {
        global $post;
        $thetitle = $post->post_title;
        if( function_exists('mb_strlen') ) {
            $getlength = mb_strlen($thetitle, 'UTF-8');
            $thelength = $t_length;
            echo mb_substr($thetitle, 0, $thelength, 'UTF-8');
        } else {
            $getlength = strlen($thetitle);
            $thelength = $t_length;
            echo substr($thetitle, 0, $thelength);
        }
        if ($getlength > $thelength) echo $t_end;
    }  
	
/* ********************
 * Create a user login form and set a function to display that login/signup
 * box using a lightbox plugin within GabfireThemes
 ******************************************************************** */
	function gabfire_register_loginform() { ?>
		<div class="hide">
			<div id="register-login">
				<div class="col left">
					<div class="title">
						<h3><?php _e('Register an Account','gabfire'); ?><span><?php _e('Sign Up and Contribute!','gabfire'); ?></span></h3>
					</div>
					
					<!-- Register Form -->
					<form method="post" action="<?php echo site_url('wp-login.php?action=register', 'login_post') ?>" id="registerform" name="registerform">
						<p>
							<label><?php _e('Username','gabfire'); ?><br />
							<input type="text" tabindex="10" size="20" value="" class="input" id="user_login_left" name="user_login" />
							</label>
						</p>
						<p>
							<label><?php _e('E-mail','gabfire'); ?><br />
							<input type="text" tabindex="20" size="25" value="" class="input" id="user_email" name="user_email" />
							</label>
						</p>
						
						<p id="reg_passmail"><?php _e('A password will be e-mailed to you.','gabfire'); ?></p>

						<p class="submit">
							<?php do_action('login_form', 'register'); ?>
							<input type="submit" tabindex="100" value="Register" class="button-primary" id="wp-submit_form" name="wp-submit" />
							<input type="hidden" name="redirect_to" value="<?php echo esc_url(home_url()); ?>/wp-admin/profile.php" />
							<input type="hidden" name="cookie" value="1" />
						</p>
					</form>
				</div>
				
				<div class="col right">
					<div class="title">
						<h3><?php _e('Have an Account?','gabfire'); ?><span><?php _e('Login Using This Form','gabfire'); ?></span></h3>
					</div>

					<?php 
					$args = array(
					'redirect' => home_url().'/wp-admin/profile.php', 
					'value_username' => NULL,
					'value_remember' => false 
					); 				
					
					wp_login_form($args);
					?>
				</div>  
			</div>	
		</div>
	<?php }

	function gabfire_userlogin() {
		if (is_user_logged_in()) {
			global $current_user;
			get_currentuserinfo();
				_e('Welcome','gabfire');
				if($current_user->user_firstname) {
					echo ' ' . $current_user->user_firstname . '!' . "\n";
				} else {
				echo ' ' . $current_user->user_login . '! - ' . "\n";
				}
			wp_loginout(); 
		} else { 
			echo '<a class="show register-button" href="#register-login">';
			_e('Contribute', 'gabfire');
			echo '</a>';
			
			gabfire_register_loginform();
		}
	}

/* ********************
 * Adding the Open Graph in the Language Attributes
 ******************************************************************** */
if (of_get_option('of_fbonhead', 0) == 1) {
add_filter('language_attributes', 'gabfire_add_og_xml_ns');
function gabfire_add_og_xml_ns($content) {
  return ' xmlns:og="http://ogp.me/ns#" ' . $content;
}
add_filter('language_attributes', 'gabfire_add_fb_xml_ns');

function gabfire_add_fb_xml_ns($content) {
  return ' xmlns:fb="https://www.facebook.com/2008/fbml" ' . $content;
}
	//Lets add Open Graph Meta Info
	function gabfire_facebookmeta_head() {
		global $post;
		if ( is_single() ) {
			echo '<meta property="og:title" content="' . get_the_title() . '"/>'."\n"; 
			echo '<meta property="og:type" content="article"/>'."\n"; 
			echo '<meta property="og:url" content="' . get_permalink() . '"/>'."\n"; 
			echo '<meta property="og:site_name" content="' . get_bloginfo('name') . '"/>'."\n"; 
			
			$thumbnail_src = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'medium' );
			echo '<meta property="og:image" content="' . esc_attr( $thumbnail_src[0] ) . '"/>';
		echo "\n";
		}
	}
	add_action( 'wp_head', 'gabfire_facebookmeta_head', 5 );
}

/* ********************
 * Innerpage Slider
 * single postpage slider that auto grabs all attached pictures
 * and displays them with a nice slider
 ******************************************************************** */
 function gabfire_innerslider() {
	global $post, $page;
	if (of_get_option('of_inslider') == 'sitewide') {
		get_template_part( 'inc/theme-gallery', '' );
	} 
	elseif (
			( of_get_option('of_inslider') == 'tagbased') and (has_tag(of_get_option('of_inslider_tag'))) and (of_get_option('of_inslider_tag') != '' ) 
			
			or 
			(  has_term( of_get_option('of_inslider_tag') , 'gallery-tag', '' )) ) 
		 
	{
		get_template_part( 'inc/theme-gallery', '' );
	}
} 

// check for a certain meta key on the current post and add a body class if meta value exists

/* ********************
 * Add video-post class
 * add video-post as a class into post_class function
 * based on custom fields defined within post.
 ******************************************************************** */
add_filter('post_class','gabfire_post_classes');

function gabfire_post_classes( $classes ) {
	if ( (get_post_meta( get_the_ID(), 'iframe', true )) or (get_post_meta( get_the_ID(), 'videoflv', true )) or (get_post_meta( get_the_ID(), 'adflv', true )) ) {
		$classes[] = 'video-post';
	}
	return $classes;
}

/* ********************
 * Post Pagination links 
 * Wrap post pagination links with a function
 ******************************************************************** */
function gabfire_postpagination() {
	$args = array(
		'before'           => '<p class="post-pagination">' . __('<strong>Pages:</strong>','gabfire'),
		'after'            => '</p>',
		'link_before'      => '<span>',
		'link_after'       => '</span>',
		'next_or_number'   => 'number',
		'nextpagelink'     => __('Next page', 'gabfire'),
		'previouspagelink' => __('Previous page', 'gabfire'),
		'pagelink'         => '%',
		'echo'             => 1
	);
	wp_link_pages($args);

	/* Call post pagination style to head of post or static pages */
	if (is_single() or is_page()) {
		wp_enqueue_style('gabfire-paginatepost', get_template_directory_uri() .'/framework/functions/css/paginate-post.css');
	}
}
							
/* ********************
 * Get the current post type in WordPress Admin
 * sample snippet to use
 * if ( gabfire_get_current_post_type() == 'post' ) { }
 ******************************************************************** */
	function gabfire_get_current_post_type() {
	  global $post, $typenow, $current_screen;
		
	  //we have a post so we can just get the post type from that
	  if ( $post && $post->post_type )
		return $post->post_type;
		
	  //check the global $typenow - set in admin.php
	  elseif( $typenow )
		return $typenow;
		
	  //check the global $current_screen object - set in sceen.php
	  elseif( $current_screen && $current_screen->post_type )
		return $current_screen->post_type;
	  
	  //lastly check the post_type querystring
	  elseif( isset( $_REQUEST['post_type'] ) )
		return sanitize_key( $_REQUEST['post_type'] );
		
	  //we do not know the post type!
	  return null;
	}

/* ********************
 * Send sticky posts to top every other entries
 ******************************************************************** */
 
if (is_archive()) { add_filter('the_posts', 'gabfire_stickyposts_first'); }
function gabfire_stickyposts_first($posts) {
    foreach($posts as $i => $post) {
        if(is_sticky($post->ID)) {
            $stickies[] = $post;
            unset($posts[$i]);
        }
    }
    return array_merge($stickies, $posts);
}