<?php
/**
 * Shortcode For Services 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 services post type plugin is active
if( class_exists( 'Symple_Services_Post_Type' ) ) :


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

	if(! function_exists( 'symple_services_shortcode' ) ) :

		function symple_services_shortcode($atts, $content = null) {
			
			// Define shortcode params
			extract(shortcode_atts(array(
					'count' => '-1',
					'columns' => '3',
					'filter' => '',
					'order' => 'DESC',
					'orderby' => 'date',
					'title' => 'true',
					'excerpt' => 'true',
					'read_more' => 'false',
					'read_more_text' => __('learn more','wpex'),
					'excerpt_length' => '15',
					'category_id' => '',
					'tag_id' => '',
					'pagination' => 'false',
					'filter_content' => 'false',
					'offset' => 0
				), $atts));
			
			
			//Give services a unique name
			$unique_classname = 'services-'. rand(1, 100);
			
			// Start Tax Query
			$tax_query = '';
			if( $category_id !=='' && $tag_id =='' ) {
				$tax_query = array(
					array(
						'taxonomy' => 'services_category',
						'field' => 'id',
						'terms' => $category_id
					),
				);
			} elseif( $tag_id !=='' && $category_id =='' ) {
				
				$tax_query = array(
					array(
						'taxonomy' => 'services_tag',
						'field' => 'id',
						'terms' => $tag_id,
						'operator' => 'IN'
					)
				);
			} elseif( $category_id !=='' && $tag_id !=='' ) {
				
				$tax_query = array(
					'relation' => 'AND',
					array(
						'taxonomy' => 'services_category',
						'field' => 'id',
						'terms' => $category_id
					),
					array(
						'taxonomy' => 'services_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_services_query = new WP_Query(
				array(
					'post_type' => 'services',
					'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_services_query->posts ) :
			
				// Load Masonry scripts		
				$services_isotope_class = NULL;		
				if ( $filter !== '' ) {
					wp_enqueue_script('isotope');
					wp_enqueue_script('wpex-isotope-services');
					$services_isotope_class = ' services-isotope no-transition';
				}
	
				//Filter
				$filter_class = $services_parent = NULL;
				if( $filter == 'false' ) $filter = NULL;
				if( $filter == 'true' ) $filter = 'category';
				if( $filter == 'category' || $filter == 'tag' ) {
					
					//Category Filter
					if ( $filter == 'category' )$services_parent = $category_id;
					
					//Tag filter
					if ( $filter == 'tag' ) $services_parent = $tag_id;
					
					//get services categories
					$terms = get_terms('services_'.$filter.'', array( 'hide_empty' => '1', 'child_of' => $services_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() {
										$(".services-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="services-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=".services-'. $term->slug .'"><span>'. $term->name .'</span></a></li>';
							endforeach;
						$output .= '</ul>';
					
					} // end $terms check
					
				} // end filter check
			
				// Main wrapper div
				$output .= '<div class="services-wrap clearfix grid-'. $columns.'-wrap '. $unique_classname . $services_isotope_class. '">';
			
				// Loop through posts
				$count=0;
				foreach ( $wpex_services_query->posts as $post ) :
				$count++;
				
					// Post vars
					$postid = $post->ID;
					$featured_img = wp_get_attachment_url( get_post_thumbnail_id( $postid ), 'full' );
					$post_title = get_the_title($postid);
					$url = wpex_service_url($postid);
					$read_more_text = get_post_meta( $postid,'wpex_services_entry_button_text', true );
					$post_icon = get_post_meta( $postid, 'wpex_services_icon', true );
					$post_icon_font = get_post_meta( $postid, 'wpex_services_icon_font', true );
					
					// Define Excerpt Length Default
					$excerpt_length = ( $excerpt_length ) ? $excerpt_length : '10';
					
					// Add extra class for services with icons for padding
					$extra_classes = ( $post_icon !=='' || $post_icon_font !=='Select' ) ? ' service-entry-with-icon' : NULL;
					
					// Set vars to remove margin on last item in row & clear floats
					if ( $filter == '' ) {
						$remove_margin = ( $count == $columns ) ? ' remove-margin' : NULL;
						$clear_floats = ( $count == $columns ) ? '<div class="clear-services clear"></div>' : NULL;
					} else { $remove_margin = $clear_floats = NULL; }
					
					// Reset counter
					if ( $count == $columns ) $count=0;
					
					// Get post terms
					if ( $filter !== '' ) {
						$cats = get_the_terms( $postid, 'services_category' );
						$tags = get_the_terms( $postid, 'services_tag' );
					} else { $cats = $tags = NULL; }
			
					// Services Post Output
					$output .= '<article class="services-entry entry-'. $postid .' clearfix grid-'.$columns . $extra_classes . $remove_margin .'';
						if($cats) foreach($cats as $cat) $output .= ' services-'. $cat->slug;
						if($tags) foreach($tags as $tag) $output .= ' services-'. $tag->slug;
					$output .= '">';
						
						$output .= '<a href="'. $url .'" title="'. $post_title  .'" class="services-entry-link">';
						
							// Display service icon => see functions/post_types_taxonomies/post-type-helpers.php
            				$output .=  wpex_service_icon( $postid );
						
							//Title
							if( $title == 'true' ) $output .= '<h3 class="services-entry-title">'. $post_title  .'</h3>';
						
						$output .= '</a>';
						
						//Excerpt
						if( $excerpt == 'true' ) {
							$output .= '<div class="services-entry-details">';
								if(!empty($post->post_excerpt) ) {
									$output .= apply_filters('the_content', $post->post_excerpt) ;
								} else {
									$output .= wp_trim_words( strip_shortcodes( $post->post_content ), $excerpt_length);
								}
								if( $read_more !== 'false' ){
									$output .= ' <a href="'. $url .'" title="'. $post_title .'" class="services-entry-readmore">';
									$output .= ( $read_more_text !== '' ) ? $read_more_text : __('learn more','wpex');
									$output .= '&rarr; </a>';
								}
							$output .= ' </div>';
						}
					
					$output .= '</article>';
					$output .= $clear_floats; //clear floats
				
				// End foreach loop
				endforeach;
				
				// Close main wrap
				$output .= '</div>';
				
				// Paginate Posts
				if( $pagination == 'true' ) {
					$total = $wpex_services_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 $wp_query->posts check
			
			
			// Set things back to normal
			wp_reset_postdata();
	
	
			// Return data
			return $output; 
			
		}
		add_shortcode("symple_services", "symple_services_shortcode");
		
		
		
		/*
		 * Add Editor Button
		 * @since v1.1
		*/
		
		//Creating TinyMCE buttons
		function symple_services_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_services_add_custom');
				add_filter('mce_buttons', 'symple_services_register_button');
			 }
		   }
		} 
		add_action('init', 'symple_services_editor_button');
		
		function symple_services_add_custom($plugin_array) {
			   $plugin_array['symple_services'] = get_template_directory_uri() .'/functions/shortcodes/mce/services-mce-button.js';
			   return $plugin_array;
		}
		
		function symple_services_register_button($buttons) {
		   array_push($buttons, "symple_services");
		   return $buttons;
		} 
		
	
		
	endif; // end symple_services_shortcode check

	
endif; // end Symple_Portfolio_Post_Type check