<?php
/**
 * Utility functions used by the Planet Foundation Theme
 *
 * @package ncp\wp\themes\planet_foundation
 *
 * @since Planet Foundation 1.0.0
 *
 */

/**
 * Removes hentry class from Wordpress default post classes
 *
 * Some posts do not have all the required hentry sub-classes.  If hentry is
 * used in this scenario, Google's structured data checker shows errors
 *
 * @since Planet Foundation 1.0.0
 *
 * @param array $post_classes Array of classes
 * @param string $additional_classes Space separated string of addition classes to add
 *
 * @return String of classes
 */
function pf_remove_hentry_class( $post_classes, $additional_classes ) {

	if( ( $key = array_search( 'hentry', $post_classes ) ) !== false )
		unset( $post_classes[$key] );

	$html = implode( ' ', $post_classes );
	$html = "$html $additional_classes";

	return $html;
}


/**
 * Returns HTML properly structured so it can be recognized as a date by Google
 *
 * @since Planet Foundation 1.0.0
 *
 * @param string $prefix String to prefix to date, default is 'Posted on'
 * @param string $format 'long' is like Monday, Feburary 18, 2012, otherwise 2/18/12
 *
 * @return string HTML
 */
function pf_get_the_date( $prefix='Posted on', $format='long' ) {
	if ( $format == 'long' ) {
		if ( $prefix == 'Posted on' ) {
			$html = '<time class="updated" datetime="'. get_the_time('c') .'" pubdate>'. sprintf(__("Posted on %s at %s.", 'planet-foundation'), get_the_time('l, F jS, Y'), get_the_time()) .'</time>';
		}
		else {
			$html = '<time class="updated" datetime="'. get_the_time('c') .'" pubdate>'. $prefix . ' ' . sprintf(__("%s at %s.", 'planet-foundation'), get_the_time('l, F jS, Y'), get_the_time()) .'</time>';
		}
	} 
	else if ( $format == 'short' ) {
		if ( $prefix == 'Posted on' ) {
			$html = '<time class="updated" datetime="'. get_the_time('c') .'" pubdate>'. sprintf(__("Posted on %s @ %s.", 'planet-foundation'), get_the_time('n/j/y'), get_the_time()) .'</time>';
		}
		else {
			$html = '<time class="updated" datetime="'. get_the_time('c') .'" pubdate>'. $prefix . ' ' . sprintf(__("%s @ %s.", 'planet-foundation'), get_the_time('n/j/y'), get_the_time()) .'</time>';
		}
	}
 
	return $html;
}

/**
 * Returns HTML properly structured so it can be recognized as an author by Google
 *
 * @since Planet Foundation 1.0.0
 *
 * @param string $prefix String to prefix to author info, default is 'Written by'
 * @param string $format 'short' is abbreviated for excerpts, otherwise a long version with pic and bio
 *
 * @return string HTML
 */
function pf_get_the_author( $prefix='Written by', $format='short' ) {

	$first_name= get_the_author_meta('first_name');;
	$last_name= get_the_author_meta('last_name');;
	$google_plus = get_the_author_meta('googleplus');
	$bio = get_the_author_meta('description');
	$email = get_the_author_meta('user_email');
	$id = get_the_author_meta( 'ID' );
	$avatar = get_avatar( $email );

	// formulate name
	$name="$first_name $last_name";
	if ( $name == ' ' )
		$name = get_the_author();

	$author_url = get_author_posts_url( $id );
	if ( ! $google_plus ) {
		$google_plus_url = "$author_url?rel=author";
	}
	else
		$google_plus_url = "$google_plus?rel=author";

	if ( $format == 'short' ) {
		if ( $prefix == "Written by" ) {
			return '<span class="pf-author-link-container byline vcard author">'. __('Written by', 'planet-foundation') .' <a class="fn" href="' . $google_plus_url . '" rel="author">' . $name . '</a></span>';
		}
		else {
			return '<span class="pf-author-link-container byline vcard author">'. $prefix .' <a class="fn" href="' . $google_plus_url . '" rel="author">' . $name . '</a></span>';
		}
	}
	else {
		$link_to_posts = '';
		if ( $format == 'bio_w_posts') {
			$link_to_posts = '<a class="pf-author-link-page" href="' . $author_url . '">' . sprintf( __( 'View other Posts by %s', 'planet-foundation'), $first_name ) . '</a>';
		}
		$html = '
			<div class="pf-author-info row">
				<div class="pf-author-avatar hide-for-small medium-2 large-2 columns">' .
					$avatar . '
				</div>
				<div class="pf-author-description medium-10 large-10 columns">
					<h2 class="pf-author-link-container pf-author-title byline vcard author">
						<a class="fn pf-author-link" href="' . $google_plus_url . '" rel="author">' . $name . '</a>
					</h2>
					<p class="pf-author-bio">' .
						$bio . '
					</p><!-- pf-author-bio -->' .
						$link_to_posts . '
				</div><!-- .pf-author-description -->

			</div><!-- .pf-author-info -->';

		return $html;
	}
}

/**
 * Retrieves html for header image
 *
 * Looks for the wpcf-header-image type on the post or page first.  
 * This custom type will allow authors to specify a header image
 * to go with the post or page.
 *
 * If custom type is not found, returns header image specified as part
 * of the theme options.
 *
 * If header not specified as part of them options, return null
 *
 * Will return html for a Foundation orbit slideshow on home page 
 * if such a slideshow is specified in the theme customizer.
 *
 * @since Planet Foundation 1.0.0
 *
 * @see http://codex.wordpress.org/Function_Reference/wp_make_link_relative wp_make_link_relative()
 * @see http://codex.wordpress.org/Function_Reference/get_post get_post()
 * @see http://codex.wordpress.org/Function_Reference/get_post_meta get_post_meta()
 * @see http://codex.wordpress.org/Function_Reference/get_header_image get_header_image()
 *
 * @uses pf_get_the_slideshow() To get the slideshow if configured
 *
 *
 * @return null|string Null if no header is found. html if header is found.
 *
 */
function pf_get_the_header() {

	$header_src = '';

	if ( is_front_page() && ( $html = pf_get_the_slideshow() ) )
		return $html;

	if ( have_posts() ) {
		global $wp_query;
		if ( $wp_query->found_posts == 1 ) {
			// First lets try to find a header that is specified in 
			// the post or page itself using the _pf_meta_header_image type
			while ( have_posts() ) {
				the_post();
				$post_id = get_the_ID();
				$header_src_array = get_post_meta( $post_id, "_pf_meta_header_image" );
				if ( $header_src_array ) {
					global $wpdb;
					global $pf_metabox_header_image;
					$meta = $pf_metabox_header_image->the_meta();
					$header_src = $meta['imgurl'];
					$query = "SELECT ID FROM {$wpdb->posts} WHERE guid='$header_src'";
					$attachment_id = $wpdb->get_var($query);
					$attachment = get_post( $attachment_id );
					$header_src = wp_make_link_relative( $header_src );
					$header_alt = get_post_meta($attachment->ID, '_wp_attachment_image_alt', true);
					$header_title = $attachment->post_excerpt;
				}
			}
			rewind_posts();
		}
	}

	if ( ! $header_src ) {
		global $wpdb;
		// If we did't fine a header above, use the one specified
		// in the theme options
		if ( $header_src = get_header_image() ) {
			// we want the all the attributes
			$query = "SELECT ID FROM {$wpdb->posts} WHERE guid='$header_src'";
			$attachment_id = $wpdb->get_var($query);
			$attachment = get_post( $attachment_id );
			$header_src = wp_make_link_relative( $header_src );
			$header_alt = get_post_meta($attachment_id, '_wp_attachment_image_alt', true);
			$header_title = $attachment->post_excerpt;
		}
	}

	if ( $header_src ) {
		$html = '<img itemprop="image" title="' . $header_title . '" alt="' . $header_alt . '" src="' . $header_src . '" />';
	}
	else 
		$html = '';

	return $html;

}

/**
 * Retrieves the url for the header image if there is one specified
 *
 * First looks for slideshow slide, then page/post header, then default.
 * Returns null if none are found
 *
 * @return Url of header image
 *
 */
function pf_get_header_url() {

	$header_src = null;

	if ( have_posts() ) {
		global $wp_query;
		if ( $wp_query->found_posts == 1 ) {
			// First lets try to find a header that is specified in 
			// the post or page itself using the _pf_meta_header_image type
			while ( have_posts() ) {
				the_post();
				$post_id = get_the_ID();
				$header_src_array = get_post_meta( $post_id, "_pf_meta_header_image" );
				if ( $header_src_array ) {
					global $pf_metabox_header_image;
					$meta = $pf_metabox_header_image->the_meta();
					$header_src = $meta['imgurl'];
					$header_src = wp_make_link_relative( $header_src );
				}
			}
			rewind_posts();
		}
	}

	if ( ! $header_src ) {
		// header not found yet, try the first slide of the slideshow
		$header_src = get_theme_mod( 'pf_slide_1' );
	}

	if ( ! $header_src ) {
		// If we did't fine a header above, use the one specified
		// in the theme options
		if ( $header_src = get_header_image() ) {
			$header_src = wp_make_link_relative( $header_src );
		}
	}

	return $header_src;

}


/**
 * Retrieves html for a slideshow designed to be used on a page header
 *
 * Will examine the parameters specified in the theme customize section Slideshow.
 * Returns html that is recognized by Zurb's Foundation Orbit javascript module.
 * 
 * Will return null if no slides are found or slideshow is turned off.
 *
 * Child themes may completely override this using the filter pf_get_the_slideshow_override
 * or modify the returned html using pf_get_the_slideshow_filter
 *
 * @since Planet Foundation 1.0.0
 *
 * @see http://codex.wordpress.org/Function_Reference/get_theme_mod get_theme_mod()
 * @see http://codex.wordpress.org/Function_Reference/apply_filters apply_filters()
 *
 * @link http://codex.wordpress.org/Function_Reference/add_filter add_filter()
 *
 * @return null|string Null if slideshow not configured. html if slideshow is turned on and slides specified.
 */
function pf_get_the_slideshow() {

	if ( ! ($effect = get_theme_mod ( 'pf_slideshow_effect' ) ) )
		return null;
	else if ( $effect == 'none' ) {
		return null;
	}

	$slide = get_theme_mod( 'pf_slide_1' );
	if ( ! $slide )
		return null;

	// allow a child theme author to override this function if they have their own slideshow
	$html = apply_filters('pf_get_the_slideshow_override', null);
	if ( $html ) 
		return $html;


	$slide_link = get_theme_mod( 'pf_slide_link_1' );

	if ( $effect == 'normal' ) {
		if ( ! ($timer_speed = get_theme_mod ( 'pf_timer_speed' ) ) )
			$timer_speed = 3000;

		if ( ! ($animation_speed = get_theme_mod ( 'pf_transition_speed' ) ) )
			$animation_speed = 1500;
		/* !! Note that this is not controlled here anymore.  We must control this
			with css.  Will add an action to wp_head for this */

		if ( ! ($pause_on_hover = get_theme_mod ( 'pf_pause_on_hover' ) ) )
			$pause_on_hover = 'false';
		else
			$pause_on_hover = 'true';

		if ( ! ($navigation_arrows = get_theme_mod ( 'pf_navigation_arrows' ) ) )
			$navigation_arrows = 'false';
		else
			$navigation_arrows = 'true';

		if ( ! ($slide_number = get_theme_mod ( 'pf_slide_number' ) ) )
			$slide_number = 'false';
		else
			$slide_number = 'true';


		if ( ! ($animation = get_theme_mod ( 'pf_animation' ) ) )
			$animation = 'animation:\'fade\';';
		else if ( $animation == 'slide' )
			$animation = '';
		else
			$animation = 'animation:fade;';

		$html = '';

		$html = $html . '<ul data-orbit data-options="timer_show_progress_bar:false;bullets:false; ' . esc_attr( $animation ) . ' timer_speed:' . intval ( $timer_speed ) . '; animation_speed:' . intval( $animation_speed ) . '; pause_on_hover:' . $pause_on_hover . '; navigation_arrows:' . $navigation_arrows . '; slide_number:' . $slide_number . ';" class="pf-slideshow">';

		$html = $html . '<li>';
		if ( $slide_link )
			$html = $html . '<a href="' . esc_url( $slide_link ) . '"><img src="' . $slide . '" alt="slide 1" /></a>';
		else
			$html = $html . '<img src="' . $slide . '" alt="slide 1" />';
		$html = $html . '</li>';

		$option_pre = 'pf_slide';
		for ($i=2; $i < 6; $i++) {
			$option = $option_pre . "_$i";
			$link_option = $option_pre . "_link_$i";
			$slide = get_theme_mod( $option );
			$slide_link = get_theme_mod( $link_option );
			if ( $slide  ) {
				$html = $html . '<li>';
				if ( $slide_link ) 
					$html = $html . '<a href="' . esc_url( $slide_link ) . '"><img src="' . $slide . '" alt="slide ' . $i . '" /></a>';
				else
					$html = $html . '<img src="' . $slide . '" alt="slide ' . $i . '" />';
				$html = $html . '</li>';
			}
		}
		$html = $html . '</ul><!-- .orbit-slides-container -->';
	}
	else if ( $effect == 'kenburns' ) {
		$html = $html . '<ul class="show-for-medium-up" data-ken-burns>';

		$slide = get_theme_mod( "pf_slide_1" );
		$kb_options = get_theme_mod( "pf_kb_options_1" );
		$slide_caption = get_theme_mod( "pf_slide_caption_1" );

		$option_pre = 'pf_slide';
		$link_option = $option_pre . "_link_1";
		$slide_link = get_theme_mod( $link_option );

		$html = $html . '<li data-options="' . $kb_options . '">';
		if ( $slide_link ) {
			$html = $html . '<a title="Click to learn more ..." href="' . $slide_link . '"><img src="' . $slide . '" alt="slide 1" /></a>';
		}
		else {
			$html = $html . '<img src="' . $slide . '" alt="slide 1" />';
		}
		$html = $html . '<p class="ken-burns-caption">' . $slide_caption;
		$html = $html . '</p>';
		$html = $html . '</li>';

		for ($i=2; $i < 6; $i++) {
			$slide = get_theme_mod( "pf_slide_$i" );
			$slide_caption = get_theme_mod( "pf_slide_caption_$i" );
			$kb_options = get_theme_mod( "pf_kb_options_$i" );
			$link_option = $option_pre . "_link_$i";
			$slide_link = get_theme_mod( $link_option );
			if ( $slide  ) {
				$html = $html . '<li data-options="' . $kb_options . '">';
				if ( $slide_link ) {
					$html = $html . '<a title="Click to learn more ..." href="' . $slide_link . '"><img src="' . $slide . '" alt="slide ' . $i . '" /></a>';
				}
				else {
					$html = $html . '<img src="' . $slide . '" alt="slide ' . $i . '" />';
				}
				$html = $html . '<p class="ken-burns-caption">' . $slide_caption;
				$html = $html . '</p>';
				$html = $html . '</li>';
			}
		}

		$html = $html . '</ul>';
	}

	return apply_filters( 'pf_get_the_slideshow_filter', $html );
}

if ( ! function_exists( 'pf_the_nav_menu' ) ) {
/**
 * Returns HTML for the main menu styled for Zurb Foundation's Top Bar module
 *
 * @since Planet Foundation 1.0.0
 *
 * @link http://foundation.zurb.com/docs/components/topbar.html Zurb's Foundation Top Bar
 *
 * @return string HTML ready for placement as is in your template file
 */

function pf_the_nav_menu () {
?>
  <div id="pf-topbar-container-row" class="row">
  	<div id="pf-topbar-container-column" class="large-12 columns">
  		<div class="contain-to-grid sticky">
				<nav style="margin-bottom:0;" class="top-bar" role="navigation" data-topbar data-options="is_hover: false">
					<ul class="title-area">
						<li class="name"></li>
						<li class="toggle-topbar menu-icon"><a href="#"><span></span></a></li>
					</ul>
          <section class="top-bar-section">

<?php
	wp_nav_menu( array(
	            'theme_location' => 'primary',
	            'container' => false,
	            'depth' => 0,
	            'items_wrap' => '<ul class="left">%3$s</ul>',
	            'fallback_cb' => '',
	            'walker' => new pf_walker( array(
	                'in_top_bar' => true,
	                'item_type' => 'li',
	                'menu_type' => 'main-menu'
	            ) ),
                   ) );
?>
          </section>
        </nav>
      </div>
    </div><!-- End large-12 columns -->
  </div><!-- End pf-topbar-container-row -->
<?php
}
}

/**
 * Returns HTML for categories styled using Zurb Foundation's button groups
 *
 * Can be used at the bottom posts to show the categories the posts are in.  Prints the output to UA
 *
 * @since Planet Foundation 1.0.0
 *
 * @link http://foundation.zurb.com/docs/components/button_groups.html Zurb's Foundation Button Groups
 *
 * @param string $prefix String to prefix to category list
 *
 */
function pf_categories( $prefix="Posted in:&nbsp;" ) {

	// Add categories
	$post_categories = wp_get_post_categories( get_the_ID() );
	echo '<ul style="padding-left:0" class="hide-for-small button-group">';
	echo "<li>$prefix</li>";
	foreach($post_categories as $key => $c){
		$link = get_category_link( $c );
		$cat = get_category( $c );
		echo '<li><a rel="tag" href="' . $link . '" class="tiny button">' . $cat->name . '</a></li>';
	}
	echo '</ul>';
}

/**
 * Returns HTML for tags styled using Zurb Foundation's button groups
 *
 * Can be used at the bottom posts to show the tags the posts are in.  Prints the output to UA
 *
 * @since Planet Foundation 1.0.0
 *
 * @link http://foundation.zurb.com/docs/components/button_groups.html Zurb's Foundation Button Groups
 *
 * @param string $prefix String to prefix to category list
 *
 */
function pf_tags( $prefix="Tags:&nbsp;" ) {

	// Add categories
	$post_tags = get_the_tags();
	if ( $post_tags ) {
		echo '<ul style="padding-left:0" class="hide-for-small button-group">';
		echo "<li>$prefix</li>";
		foreach($post_tags as $key => $tag){
			$link = get_tag_link( $tag->term_id );
			$name = $tag->name;
			echo '<li><a rel="tag" href="' . $link . '" class="tiny button">' . $name . '</a></li>';
		}
		echo '</ul>';
	}
}
    
/**
 * Returns HTML styled for Zurb Foundation's Off Canvas module.
 *
 * This implements the left and right sidebar as menus.
 *
 * @since Planet Foundation 1.0.0
 *
 * @see http://codex.wordpress.org/Function_Reference/get_theme_mod get_theme_mod()
 * @see http://codex.wordpress.org/Function_Reference/get_sidebar get_sidebar()
 *
 * @link http://foundation.zurb.com/docs/components/offcanvas.html Zurb's Foundation Off Canvas
 *
 * @return string HTML ready for placement in template files
 */
function pf_the_page_menu() {

  ?>

	<?php if ( is_active_sidebar( 'primary' ) || is_active_sidebar( 'left' ) ) : ?>

		<nav id="pf-page-menu" class="tab-bar">

			<?php	$display_sidebars = get_theme_mod( 'pf_display_sidebars' ); ?>

			<?php if ( is_active_sidebar( 'left' ) ) : ?>
				<section class="left-small">
					<?php if ( $display_sidebars ) : ?>
						<a class="show-for-medium-down left-off-canvas-toggle menu-icon" ><span></span></a>
					<?php else: ?>
						<a class="left-off-canvas-toggle menu-icon" ><span></span></a>
					<?php endif; ?>
				</section>
				<?php endif; ?>

				<?php if ( is_active_sidebar( 'primary' ) ) : ?>
					<section class="right-small">
					<?php if ( $display_sidebars ) : ?>
						<a class="show-for-medium-down right-off-canvas-toggle menu-icon"><span></span></a>
					<?php else: ?>
						<a class="right-off-canvas-toggle menu-icon"><span></span></a>
					<?php endif; ?>
					</section>
				<?php endif; ?>

		</nav>

		<?php if ( is_active_sidebar( 'left' ) ) : ?>

			<aside class="left-off-canvas-menu pf-left-sidebar">
				<?php get_sidebar( 'left' ); ?>
			</aside>
		<?php endif; ?>

		<?php if ( is_active_sidebar( 'primary' ) ) : ?>
			<aside class="right-off-canvas-menu pf-left-sidebar">
				<?php get_sidebar( 'primary' ); ?>
			</aside>
		<?php endif; ?>

	<?php endif; // end is_active_sidebar ?>

  <?php
}

/**
 * Checks if author wants the author displayed as part of the page or post
 *
 * @return false|true
 *
 */
function pf_show_author() {
	global $post;
	$value = get_post_meta( get_the_ID(), '_pf_show_author_key', true );
	$is_post = $post->post_type == 'post';

	// don't show author on pages and unless setting is set to on
	if ( (!$value && $is_post) || $value == 'On' )
		return true;
	else
		return false;

}

/**
 * Checks if author wants the title displayed as part of the page or post
 *
 * @return false|true
 *
 */
function pf_show_title() {
  $value = get_post_meta( get_the_ID(), '_pf_show_title_key', true );

	if ( !$value || $value == 'On' )
		return true;
	else
		return false;

}

/**
 * Checks if author wants the tags displayed as part of the page or post
 *
 * @return false|true
 *
 */
function pf_show_tags() {
  $value = get_post_meta( get_the_ID(), '_pf_show_tags_key', true );

	if ( !$value || $value == 'On' )
		return true;
	else
		return false;

}

/**
 * Get first image in a post
 *
 * Attempts to find an image in the post content.  Should be called within
 * the loop.
 *
 * @returns string image enclosed in img tags
 *
 */
function pf_get_first_image () {
	$content = get_the_content();
	if ( ! ( $output = preg_match('/<img .*>/i',$content,$matches) ) )
		return null;

	return $matches[0];
}


/**
 *
 * Adds css for orbit
 *
 * Orbit transition is now controlled with css.  This adds the css 
 * that will contol the transition speed based on the parameter
 * set in the theme customizer.
 *
 */
function pf_add_orbit_css() {
	$effect = get_theme_mod ( 'pf_slideshow_effect' );
	if ( ! ( $effect == 'normal' ) )
		return;

	if ( ! ($animation_speed = get_theme_mod ( 'pf_transition_speed' ) ) )
		$animation_speed = 1500;

?>
<style type="text/css" media="screen">
.orbit-container .orbit-slides-container.fade li.animate-in {
  transition: opacity <?php echo $animation_speed; ?>ms ease-in-out;
}
.orbit-container .orbit-slides-container.fade li.animate-out {
  transition: opacity <?php echo $animation_speed; ?>ms ease-in-out;
}
</style>
<?php
}
add_action('wp_head', 'pf_add_orbit_css' );
?>
