<?php
/**
 * Shortcode For Blog Posts
 * @package Symple Portfolio
 * @since 1.0
 * @author AJ Clarke : http://sympleplorer.com
 * @copyright Copyright (c) 2012, AJ Clarke
 * @link http://sympleplorer.com
 * @License: GNU General Public License version 3.0
 * @License URI: http://www.gnu.org/licenses/gpl-3.0.html
 */
 


/*
 * Shortcode
 * @since v1.1
*/


if(! function_exists( 'symple_blog_shortcode' ) ) :

	function symple_blog_shortcode($atts) {
		
		// Define shortcode params
		extract(shortcode_atts(array(
				'count' => '-1',
				'style' => 'default',
				'columns' => '3',
				'order' => 'DESC',
				'orderby' => 'date',
				'thumbnail_crop' => 'true',
				'thumbnail_hard_crop' => 'true',
				'thumbnail_width' => '',
				'thumbnail_height' => '',
				'title' => 'true',
				'meta' => 'true',
				'excerpt' => 'true',
				'excerpt_length' => '15',
				'read_more' => 'false',
				'read_more_text' => __('read more','wpex'),
				'category_id' => '',
				'tag_id' => '',
				'pagination' => 'false',
				'filter_content' => 'false',
				'offset' => 0
			), $atts));
		
		
		//Give portfolio a unique name
		$unique_classname = 'recent-posts-'. rand(1, 100);
		
		// Start Tax Query
		$tax_query = '';
		if( $category_id !=='' && $tag_id =='' ) {
			$tax_query = array(
				array(
					'taxonomy' => 'category',
					'field' => 'id',
					'terms' => $category_id
				),
			);
		} elseif( $tag_id !=='' && $category_id == '' ) {

			$tax_query = array(
				array(
					'taxonomy' => 'post_tag',
					'field' => 'id',
					'terms' => $tag_id,
					'operator' => 'IN'
				)
			);
			
		} elseif( $category_id !=='' && $tag_id !=='' ) {
			
			$tax_query = array(
				'relation' => 'AND',
				array(
					'taxonomy' => 'category',
					'field' => 'id',
					'terms' => $category_id
				),
				array(
					'taxonomy' => 'post_tag',
					'field' => 'id',
					'terms' => $tag_id,
					'operator' => 'IN'
				)
			);
		} else {
			$tax_query = '';
		}
		
		// Pagination var
		if( $pagination == 'true' ) {
			global $paged;
			$paged = get_query_var('paged') ? get_query_var('paged') : 1;
		} else {
			$paged = NULL;
		}
		
		// The Query
		$wpex_blog_query = new WP_Query(
			array(
				'post_type' => 'post',
				'posts_per_page' => $count,
				'offset' => $offset,
				'order' => $order,
				'orderby' => $orderby,
				'tax_query' => $tax_query,
				'filter_content' => $filter_content,
				'paged' => $paged
			)
		);

		$output = '';

		//Output posts
		if( $wpex_blog_query->posts ) :
			
			// Enque Isotope
			$isotope_class = NULL;
			if ( $thumbnail_hard_crop == 'false' ) {
				wp_enqueue_script('isotope');
				wp_enqueue_script('wpex-isotope-recent-posts');
				$isotope_class = "recent-posts-isotope";
			}
			
			// Style
			$style = ( $style ) ? $style : 'default';
		
			// Main wrapper div
			$output .= '<div class="recent-posts clearfix '. $unique_classname .' '. $isotope_class. ' style-'. $style .'">';
		
			// Loop through posts
			$count=0;
			foreach ( $wpex_blog_query->posts as $post ) :
			$count++;
			
				// Post VARS
				$postid = $post->ID;
				$featured_img = wp_get_attachment_url( get_post_thumbnail_id( $postid ), 'full' );
				$post_format = get_post_format( $postid );
				
				// Definate URL target
				$url = get_permalink($postid);
				$redirect_url = get_post_meta( $postid, 'wpex_post_url', true );
				if ( $post_format == 'link' && $redirect_url !== '' ) $url = $redirect_url;
				
				// Crop featured images if necessary
				if( $thumbnail_crop !== 'false' && $style !== 'news' ) {
					$featured_img = wpex_get_cropped_grid_image_url( $postid, $columns, $thumbnail_width, $thumbnail_height, $thumbnail_hard_crop );
				}
				
				// Set vars to remove margin on last item in row & clear floats
				$remove_margin = $clear_floats = NULL;
				if ( $thumbnail_hard_crop !== 'false' ) {
					$remove_margin = ( $count == $columns ) ? ' remove-margin' : NULL;
					$clear_floats = ( $count == $columns ) ? '<div class="clear-grid-floats clear"></div>' : NULL;
				}
				
				// Reset counter
				if ( $count == $columns ) $count=0;
	
				// Blog Post Output
				$output .= '<article class="recent-posts-entry entry-'. $postid .' grid-'.$columns.' fitvids clearfix '. $remove_margin .'">';
				
					// Media Wrap / don't show on news style shortcode
					if ( $style !== 'news' ) {
						$output .= '<div class="recent-posts-entry-media">';
						
							// Lightbox
							if( $post_format == 'image' ) {
								if( has_post_thumbnail($postid) ) {
									$output .= '<a href="'. wp_get_attachment_url( get_post_thumbnail_id($postid), 'full' ) .'" title="'. get_the_title($postid) .'" class="recent-posts-entry-img fancybox">';
										$output .= '<img src="'. $featured_img .'" alt="'. get_the_title($postid) .'" />';
									$output .= '</a><!-- .recent-posts-entry-img -->';
								} // End thumbnail check
							}
							
							// Regular Image
							else {
								
								if( has_post_thumbnail($postid) ) {
										
									$output .= '<a href="'. $url .'" title="'. get_the_title($postid) .'" class="recent-posts-entry-img">';
									$output .= '<img src="'. $featured_img .'" alt="'. get_the_title($postid) .'" />';
									$output .= '</a><!-- .recent-posts-entry-img -->';
									
								} // End thumbnail check
								
							} // End else
						
						$output .= '</div>';
					}
				
					// Open details div
					if( $title == 'true' ||  $excerpt == 'true' ) $output .='<div class="recent-posts-entry-details">';
					
						// Date for news Style
						if ( $style == 'news' ) {
							$output .= '<div class="recent-posts-entry-date"><span class="day">'. get_the_time('d', $postid) .'</span><span class="month">'. get_the_time('M', $postid) .'</span></div>';
						}
					
						// Title
						if( $title == 'true' ) {
							$output .= '<header class="recent-posts-entry-title">';
								$output .= '<h3><a href="'. $url .'" title="'. get_the_title($postid) .'">'. get_the_title($postid) .'</a></h3>';
							$output .= '</header><!-- .recent-posts-entry-title -->';
						}
						
						// Meta
						if ( $meta == 'true' && $style !== 'news' ) {
							 $output .= '<div class="recent-posts-entry-meta">'. get_the_time('F j, Y', $postid) .'</div>';
						}
						
						/** Show comments count => Not sure if I like this.
						if ( $meta == 'true' && $style == 'news' ) {
							if( comments_open() ) { 
								$num_comments = get_comments_number($postid);
								$output .= '<div class="recent-posts-entry-meta comments-count">';
										if ( $num_comments == 0 ) {
											$output .= __('0 Comments', 'wpex');
										} elseif ( $num_comments > 1 ) {
											$output .= $num_comments . __(' Comments','wpex');
										} else {
											$output .= __('1 Comment','wpex');
										}
								$output .= '</div>';
                            }
						} ***/
						
						// Excerpt
						if( $excerpt == 'true' ) {
							$output .='<div class="recent-posts-entry-excerpt">';
							
								if ( !empty($post->post_excerpt) ) {
									$output .= $post->post_excerpt .'...';
								} else {
									$output .= wp_trim_words( strip_shortcodes( $post->post_content ), $excerpt_length);
								}
								
								// Read More
								if( $read_more == 'true' ) { 
									if( $post_format == 'link' && $redirect_url !== '' ) {
										$output .= '<a href="'. $url .'" title="'. get_the_title($postid) .'" class="recent-posts-entry-readmore">'. __('Visit Site','wpex') .' &rarr;</a>';
									} else {
										$output .= '<a href="'. $url .'" title="'. get_the_title($postid) .'" class="recent-posts-entry-readmore">'. $read_more_text .' &rarr;</a>';
									}
								}
								
							$output .=' </div><!-- /recent-posts-entry-excerpt -->';
						}
					
					// Close details div
					if( $title == 'true' || $excerpt == 'true' ) {
						$output .='</div><!-- .recent-posts-entry-details -->';
					}
					
				// Close main wrap	
				$output .= '</article>';
				$output .= $clear_floats;
			
			// End foreach loop
			endforeach;
			
			// Close main wrap
			$output .= '</div>';
			
			// Paginate Posts
			if( $pagination == 'true' ) {
				$total = $wpex_blog_query->max_num_pages;
				$big = 999999999; // need an unlikely integer
				if( $total > 1 )  {
					 if( !$current_page = get_query_var('paged') )
						 $current_page = 1;
					 if( get_option('permalink_structure') ) {
						 $format = 'page/%#%/';
					 } else {
						 $format = '&paged=%#%';
					 }
					 $output .= paginate_links(array(
						'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
						'format' => $format,
						'current' => max( 1, get_query_var('paged') ),
						'total' => $total,
						'mid_size'	=> 2,
						'type' => 'list',
						'prev_text' => '&laquo;',
						'next_text' => '&raquo;',
					 ));
				}
			}
			
		
		endif; // End $wpex_blog_query->posts check
		
		
		// Set things back to normal
		$wpex_blog_query = NULL;
		wp_reset_postdata();

		// Return data
		return $output;
		
	}
	add_shortcode("symple_blog", "symple_blog_shortcode");
	
	
	
	/*
	 * Add Editor Button
	 * @since v1.1
	*/
	
	//Creating TinyMCE buttons
	function symple_blog_editor_button() {
	if ( current_user_can('edit_posts') &&  current_user_can('edit_pages') ) {
		if (get_user_option('rich_editing')) {
			add_filter('mce_external_plugins', 'symple_blog_add_custom');
			add_filter('mce_buttons', 'symple_blog_register_button');
			}
		}
	}
	add_action('init', 'symple_blog_editor_button');
	
	function symple_blog_add_custom($plugin_array) {
		$plugin_array['symple_blog'] = get_template_directory_uri() .'/functions/shortcodes/mce/blog-mce-button.js';
		return $plugin_array;
	}
	
	function symple_blog_register_button($buttons) {
		array_push($buttons, "symple_blog");
		return $buttons;
	} 

	
endif; // end symple_blog_shortcode check