<?php
/**
 * Shortcode For Portfolio Post Type
 * @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
 */

// Only show shortcode if portfolio post type plugin is active
if( class_exists( 'Symple_Portfolio_Post_Type' ) ) :

	/*
	 * Shortcode
	 * @since v1.1
	*/
	
	if(! function_exists( 'symple_portfolio_shortcode' ) ) :

		function symple_portfolio_shortcode($atts, $content = null) {
			
			// Define shortcode params
			extract(shortcode_atts(array(
					'count' => '-1',
					'columns' => '4',
					'order' => 'DESC',
					'orderby' => 'date',
					'thumbnail_hover' => 'icon_overlay',
					'thumbnail_crop' => 'true',
					'thumbnail_hard_crop' => 'true',
					'thumbnail_width' => '',
					'thumbnail_height' => '',
					'lightbox_only' => 'false',
					'title' => '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,
					'filter' => '',
				), $atts));
			
			// Give portfolio a unique name
			$unique_classname = 'portfolio-'. rand(1, 100);
			
			// Start Tax Query
			$tax_query = '';
			if( $category_id !=='' && $tag_id =='' ) {
				$tax_query = array(
					array(
						'taxonomy' => 'portfolio_category',
						'field' => 'id',
						'terms' => $category_id
					),
				);
			} elseif( $tag_id !=='' && $category_id =='' ) {
				
				$tax_query = array(
					array(
						'taxonomy' => 'portfolio_tag',
						'field' => 'id',
						'terms' => $tag_id,
						'operator' => 'IN'
					)
				);
			} elseif( $category_id !=='' && $tag_id !=='' ) {
				
				$tax_query = array(
					'relation' => 'AND',
					array(
						'taxonomy' => 'portfolio_category',
						'field' => 'id',
						'terms' => $category_id
					),
					array(
						'taxonomy' => 'portfolio_tag',
						'field' => 'id',
						'terms' => $tag_id,
						'operator' => 'IN'
					)
				);
			} else {
				$tax_query = '';
			}
			
			// Pagination var
			if( $pagination == 'true' ) {
				global $paged;
				if (get_query_var('paged')) {
					$paged = get_query_var('paged');
				} elseif (get_query_var('page') ) {
					$paged = get_query_var('page');
				} else {
					$paged = 1;
				}
			} else {
				$paged = null;
			}
			
			// The Query
			$wpex_portfolio_query = new WP_Query(
				array(
					'post_type' => 'portfolio',
					'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_portfolio_query->posts ) :
						
				// Load Masonry scripts		
				$portfolio_isotope_class = NULL;		
				if ( $filter !== '' && $filter !== 'false' || $thumbnail_hard_crop == 'false' ) {
					wp_enqueue_script('isotope');
					wp_enqueue_script('wpex-isotope-portfolio');
					$portfolio_isotope_class = 'portfolio-isotope';
				}
			
				//Filter
				$filter_class = $portfolio_parent = NULL;
				if( $filter == 'false' ) $filter = '';
				if( $filter == 'true' ) $filter = 'category';
				if( $filter == 'category' || $filter == 'tag' ) {
					
					//Category Filter
					if ( $filter == 'category' ) $portfolio_parent = $category_id;
					
					//Tag filter
					if ( $filter == 'tag') $portfolio_parent = $tag_id;
					
					//get portfolio categories
					$terms = get_terms('portfolio_'.$filter.'', array( 'hide_empty' => '1', 'child_of' => $portfolio_parent  ) );
					
					//show filter if categories exist
					if( $terms ) {
					
						// Output filter JS into the footer like a WP Jedi Master
						$output .='
							<script type="text/javascript">
								jQuery(function($){
									$(window).load(function() {
										$(".portfolio-filter a").click(function(){
										var selector = $(this).attr("data-filter");
										$(".'. $unique_classname .'").isotope({ filter: selector });
										$(this).parents("ul").find("a").removeClass("active");
										$(this).addClass("active");
										return false;
										});
									});
								});
							</script>';

						// Display filter links
						$output .= '<ul class="portfolio-filter clearfix">';
							$output .= '<li><a href="#" class="active" data-filter="*"><span>'. __('All', 'wpex') .'</span></a></li>';
							foreach ($terms as $term ) :
								$output .= '<li><a href="#" data-filter=".portfolio-'. $term->slug .'"><span>'. $term->name .'</span></a></li>';
							endforeach;
						$output .= '</ul>';
                    
					} // end $terms check
					
				} // end filter check
			
				// Main wrapper div
				$output .= '<div class="portfolio-wrap clearfix '. $unique_classname .' grid-'. $columns.'-wrap '. $portfolio_isotope_class .'">';
			
				// Loop through posts
				$count=0;
				foreach ( $wpex_portfolio_query->posts as $post ) :
				$count++;
				
					// Post vars/meta
					$postid = $post->ID;
					$url = wpex_portfolio_url($postid, $lightbox_only);
					$post_title = get_the_title($postid);
					$full_featured_img = wp_get_attachment_url( get_post_thumbnail_id($postid), 'full' );
					$featured_img = $full_featured_img;
				
					// Run custom function to return correct thumbnail dimensions ( width, height and crop )
					if( $thumbnail_crop !== 'false' ) {
						$featured_img = wpex_get_cropped_grid_image_url($postid, $columns, $thumbnail_width, $thumbnail_height, $thumbnail_hard_crop );
					}
					
					// Portfolio Post Style
					$post_style = 'Default';
					$post_style = get_post_meta( $postid, 'wpex_portfolio_post_style', true );
					
					// Lighbox Style
					$lightbox_class = ( $post_style == 'Lightbox' || $lightbox_only == 'true' ) ? 'fancybox-media' : NULL;
					$lightbox_group = ( $lightbox_only == 'true' ) ? 'data-fancybox-group="'. $unique_classname .'"' : NULL;
					
					// Define Excerpt Length Default
					$excerpt_length = ( $excerpt_length ) ? $excerpt_length : '10';
					
					// Set vars to remove margin on last item in row & clear floats
					$remove_margin = $clear_floats = NULL;
					if ( $filter == '' && $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;
					
					// Get post terms
					if ( $filter !== '' ) {
						$cats = get_the_terms( $postid, 'portfolio_category' );
						$tags = get_the_terms( $postid, 'portfolio_tag' );
					} else { $cats = $tags = NULL; }
			
					// Portfolio Post Output
					$output .= '<article class="portfolio-entry entry-'. $postid .' clearfix grid-'.$columns . $remove_margin;
						if( $cats ) foreach( $cats as $cat ) $output .= ' portfolio-'. $cat->slug;
						if( $tags ) foreach( $tags as $tag ) $output .= ' portfolio-'. $tag->slug;
					$output .= '">';
					
						// Image Wrap
						if( has_post_thumbnail($postid) ) {
							$output .= '<div class="portfolio-entry-media">';

							$output .= '<a href="'. $url .'" title="'. $post_title .'" class="portfolio-entry-img '. $thumbnail_hover .'-hover '. $lightbox_class .'" ' . $lightbox_group .'>';
								$output .= '<img src="'. $featured_img .'" alt="'. $post_title .'" />';
									
								// Hover Overlay
								$overlay_icon = wpex_portfolio_icon( $postid, $lightbox_only );
								if ( $thumbnail_hover == 'icon_overlay' ) {
									$output .= '<div class="portfolio-entry-overlay">';
										$output .= '<div class="portfolio-entry-overlay-inner">';
											$output .= '<div class="overlay-icon"><span class="icon-'.$overlay_icon.'"></span></div>';
										$output .= '</div>';
									$output .= '</div>';
								}
													
							$output .= '</a><!-- .portfolio-entry-img -->';
							$output .= '</div><!-- .portfolio-entry-media -->';
						
						} // End thumbnail check
					
						// Open details div
						if( $title == 'true' ||  $excerpt == 'true' ) $output .='<div class="portfolio-entry-details">';
						
							//Title
							if( $title == 'true' ) {
								if ( $lightbox_only == true || $post_style == 'Lightbox' ) {
									$lightbox_title_class = 'class="fancybox-media"';
								} else {
									$lightbox_title_class = NULL;
								}
								$output .= '<header class="portfolio-entry-title">';
									$output .= '<h3><a href="'. $url .'" title="'. $post_title .'" '. $lightbox_title_class .'>'. $post_title .'</a></h3>';
								$output .= '</header><!-- .portfolio-entry-title -->';
								
							}
							
							//Excerpt + Read More
							if( $excerpt == 'true' ) {
								$output .='<div class="portfolio-entry-excerpt">';
									
									// Excerpt
									!empty($post->post_excerpt) ? $output .= apply_filters('the_content', $post->post_excerpt) : $output .= wp_trim_words( strip_shortcodes( $post->post_content ), $excerpt_length);
									//Read More
									if( $read_more == 'true' && $lightbox_only !== true && $post_style !== 'Lightbox' ) {
										$output .= '<a href="'. $url .'" title="'. $read_more_text .'" class="portfolio-entry-readmore">'. $read_more_text .' &rarr;</a>';
									}
								$output .=' </div><!-- /portfolio-entry-excerpt -->';
							}
						
						// Close details div
						if( $post_title == 'true' || $excerpt == 'true' ) {
							$output .='</div><!-- .portfolio-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_portfolio_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_portfolio_query->posts check
			
			
			// Set things back to normal
			$wpex_portfolio_query = NULL;
			wp_reset_postdata();
	
			// Return data
			return $output; 
			
		}
		add_shortcode("symple_portfolio", "symple_portfolio_shortcode");
		
		
		
		/*
		 * Add Editor Button
		 * @since v1.1
		*/
		
		//Creating TinyMCE buttons
		function symple_portfolio_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_portfolio_add_custom');
				add_filter('mce_buttons', 'symple_portfolio_register_button');
			 }
		   }
		} 
		add_action('init', 'symple_portfolio_editor_button');
		
		function symple_portfolio_add_custom($plugin_array) {
			   $plugin_array['symple_portfolio'] = get_template_directory_uri() .'/functions/shortcodes/mce/portfolio-mce-button.js';
			   return $plugin_array;
		}
		
		function symple_portfolio_register_button($buttons) {
		   array_push($buttons, "symple_portfolio");
		   return $buttons;
		} 
		
	
		
	endif; // end symple_portfolio_shortcode check

	
endif; // end Symple_Portfolio_Post_Type check
