<?php
function theme_excerpt_more($excerpt) {
	return str_replace('[...]', '...', $excerpt);
}
add_filter('wp_trim_excerpt', 'theme_excerpt_more');

function theme_exclude_category_feed() {
	$exclude_cats = theme_get_option('blog','exclude_categorys');
	if(is_array($exclude_cats)){
		foreach ($exclude_cats as $key => $cat) {
			$exclude_cats[$key] = -$cat;
		}
		if ( is_feed() ) {
			set_query_var("cat", implode(",",$exclude_cats));
		}
	}
}
add_filter('pre_get_posts', 'theme_exclude_category_feed');
if( theme_get_option('advance','show_post_thumbnail_on_feed')){
	function theme_show_post_thumbnail_on_feeds($content) {
		global $post;
		if(has_post_thumbnail($post->ID)) {
			$content = $content . '<div><a href="' . get_permalink($post->ID) . '">' . get_the_post_thumbnail($post->ID, 'thumbnail') . '</a></div>';
		}
		return $content;
	}
	add_filter('the_excerpt_rss', 'theme_show_post_thumbnail_on_feeds');
	add_filter('the_content_feed', 'theme_show_post_thumbnail_on_feeds');
}
/*
 * Remove Blog categories from category widget
 */
function theme_exclude_category_widget($cat_args)
{
	$exclude_cats = theme_get_option('blog','exclude_categorys');
	
	if(is_array($exclude_cats)){
		$cat_args['exclude'] = implode(",",$exclude_cats);
	}
 	return $cat_args;
}
add_filter('widget_categories_args', 'theme_exclude_category_widget');


function theme_exclude_the_categorys($thelist,$separator=' ') {
	if(!defined('WP_ADMIN')) {
		//Category IDs to exclude
		$exclude = theme_get_option('blog','exclude_categorys');

		$exclude2 = array();
		foreach($exclude as $c) {
			$exclude2[] = get_cat_name($c);
		}

		$cats = explode($separator,$thelist);
		$newlist = array();
		foreach($cats as $cat) {
			$catname = trim(strip_tags($cat));
			if(!in_array($catname,$exclude2))
				$newlist[] = $cat;
		}
		return implode($separator,$newlist);
	} else {
		return $thelist;
	}
}
add_filter('the_category','theme_exclude_the_categorys',10,2);

/*
 * add a span element for style in the page
 */
function theme_comment_style($return) {
	return str_replace($return, "<span></span>$return", $return);
}
add_filter('get_comment_author_link', 'theme_comment_style');

function theme_widget_title_remove_space($return){
	$return = trim($return);
	if('&nbsp;' == $return){
		return '';	
	}else{
		return $return;
	}
}
add_filter('widget_title', 'theme_widget_title_remove_space');

function theme_widget_text_shortcode($content) {
	$content = do_shortcode($content);
	$new_content = '';
	$pattern_full = '{(\[raw\].*?\[/raw\])}is';
	$pattern_contents = '{\[raw\](.*?)\[/raw\]}is';
	$pieces = preg_split($pattern_full, $content, -1, PREG_SPLIT_DELIM_CAPTURE);
	
	foreach ($pieces as $piece) {
		if (preg_match($pattern_contents, $piece, $matches)) {
			$new_content .= $matches[1];
		} else {
			$new_content .= do_shortcode($piece);
		}
	}

	return $new_content;
}
// Allow Shortcodes in Sidebar Widgets
add_filter('widget_text', 'theme_widget_text_shortcode');

function theme_mimes_add_ico($mime_types){
	$mime_types['ico'] = 'image/x-icon'; 
	return $mime_types;
}
add_filter('upload_mimes', 'theme_mimes_add_ico');
/*
 * Thank to Bob Sherron.
 * http://stackoverflow.com/questions/1155565/query-multiple-custom-taxonomy-terms-in-wordpress-2-8/2060777#2060777
 */
global $wp_version;
if(version_compare($wp_version, "3.1", '<')){
	function multi_tax_terms($where) {
		global $wp_query;
		global $wpdb;
		if (isset($wp_query->query_vars['term']) && (strpos($wp_query->query_vars['term'], ',') !== false && strpos($where, "AND 0") !== false) ) {
			// it's failing because taxonomies can't handle multiple terms
			//first, get the terms
			$term_arr = explode(",", $wp_query->query_vars['term']);
			foreach($term_arr as $term_item) {
				$terms[] = get_terms($wp_query->query_vars['taxonomy'], array('slug' => $term_item));
			}

			//next, get the id of posts with that term in that tax
			foreach ( $terms as $term ) {
				$term_ids[] = $term[0]->term_id;
			}

			$post_ids = get_objects_in_term($term_ids, $wp_query->query_vars['taxonomy']);

			if ( !is_wp_error($post_ids) && count($post_ids) ) {
				// build the new query
				$new_where = " AND $wpdb->posts.ID IN (" . implode(', ', $post_ids) . ") ";
				// re-add any other query vars via concatenation on the $new_where string below here

				// now, sub out the bad where with the good
				$where = str_replace("AND 0", $new_where, $where);
			} else {
				// give up
			}
		}
		return $where;
	}
	add_filter("posts_where", "multi_tax_terms");
}

/*
 * add menu order support for Single Portfolio Item Previous & Next Navigation
 */
$order = theme_get_option('portfolio','single_navigation_order');
if($order == 'menu_order'){
	function get_previous_portfolio_menu_order_where($where){
		global $post, $wpdb;
		if($post->post_type == 'portfolio'){
			$current_menu_order = $post->menu_order;
			$where = $wpdb->prepare("WHERE p.menu_order < %s AND p.post_type = 'portfolio' AND p.post_status = 'publish'", $current_menu_order);
		}
		return $where;
	}
	function get_next_portfolio_menu_order_where($where){
		global $post, $wpdb;
		if($post->post_type == 'portfolio'){
			$current_menu_order = $post->menu_order;
			$where = $wpdb->prepare("WHERE p.menu_order > %s AND p.post_type = 'portfolio' AND p.post_status = 'publish'", $current_menu_order);
		}
		return $where;
	}
	add_filter("get_previous_post_where", "get_previous_portfolio_menu_order_where");
	add_filter("get_next_post_where", "get_next_portfolio_menu_order_where");

	function get_previous_portfolio_menu_order_sort($sort){
		global $post;
		if($post->post_type == 'portfolio'){
			$sort = "ORDER BY p.menu_order DESC LIMIT 1";
		}
		return $sort;
	}
	function get_next_portfolio_menu_order_sort($sort){
		global $post;
		if($post->post_type == 'portfolio'){
			$sort = "ORDER BY p.menu_order ASC LIMIT 1";	
		}
		return $sort;
	}

	add_filter("get_previous_post_sort", "get_previous_portfolio_menu_order_sort");
	add_filter("get_next_post_sort", "get_next_portfolio_menu_order_sort");
}

function theme_exclude_category_post_join($join){
	global $post, $wpdb;
	if($post->post_type == 'post'){
		$exclude_cats = theme_get_option('blog','exclude_categorys');
		if(is_array($exclude_cats) && !empty($exclude_cats)){
			$join .= " INNER JOIN $wpdb->term_relationships AS tr ON p.ID = tr.object_id INNER JOIN $wpdb->term_taxonomy tt ON tr.term_taxonomy_id = tt.term_taxonomy_id";
			$join .= " AND tt.taxonomy = 'category' AND tt.term_id NOT IN (" . implode(',', $exclude_cats) . ")";
			if(theme_get_option('blog','single_navigation_category')){
				$cat_array = wp_get_object_terms($post->ID, 'category', array('fields' => 'ids'));
				$join .= " AND tt.term_id IN (" . implode(',', $cat_array) . ")";
			}
		}else{
			if(theme_get_option('blog','single_navigation_category')){
				$join .= " INNER JOIN $wpdb->term_relationships AS tr ON p.ID = tr.object_id INNER JOIN $wpdb->term_taxonomy tt ON tr.term_taxonomy_id = tt.term_taxonomy_id";
				$cat_array = wp_get_object_terms($post->ID, 'category', array('fields' => 'ids'));
				$join .= " AND tt.taxonomy = 'category' AND tt.term_id IN (" . implode(',', $cat_array) . ")";
			}
		}
	}
	return $join;
}
add_filter("get_previous_post_join", "theme_exclude_category_post_join");
add_filter("get_next_post_join", "theme_exclude_category_post_join");


add_filter('previous_posts_link_attributes','previous_posts_link_class');

function previous_posts_link_class() {
	return 'class="previouspostslink"';
}
add_filter('next_posts_link_attributes','next_posts_link_class');

function next_posts_link_class() {
	return 'class="nextpostslink"';
}
add_filter('previous_post_link','blog_nav_prev');

function blog_nav_prev($format){
	$matches=null;
	preg_match('/<img src=".*"\/>(.*)<\/a>/i',$format,$matches);
   
	if(!empty($matches) && (strlen($matches[1])>20)){
	$rep = substr($matches[1],0,17).'...';
	$format=preg_replace('/'.$matches[1].'/i',$rep,$format);
	}
	return $format;
}
add_filter('next_post_link','blog_nav_next');

function blog_nav_next($format){
	$matches=null;
	preg_match('/<a href=".*">(.*)<img src=".*"\/>/i',$format,$matches);
	if(!empty($matches) && (strlen($matches[1])>20)){
		$rep = substr($matches[1],0,17).'...';
	$format=preg_replace('/'.$matches[1].'/i',$rep,$format);
	}
	return $format;
}

add_filter( "single_template", "get_single_custom" ) ;

function get_single_custom($single_template) {
	global $post;
	$type = get_post_meta($post->ID, '_type', true);
	if ($post->post_type == 'attachment'){
		$single_template = THEME_DIR . '/single-attachment-template.php';
	}else if ($post->post_type == 'portfolio' && $type == 'gallery') {
		$single_template = THEME_DIR . '/single-gallery-template.php';
	}
	return $single_template;
}


function title_length($title){
	if(strlen($title)>30)
		$title = substr($title,0,30).'......';
	return $title;
}

function remove_post_current_css($css_class, $page=null){
	if(is_null($page))
		return array('page_item','page-item-0');
	else
		return array('page_item', 'page-item-'.$page->ID); 
}

function theme_shortcode_format($content){
	$column_tags = array(
		'one_half',
		'one_third',
		'one_fourth',
		'one_fifth',
		'one_sixth',
		'two_third',
		'three_fourth',
		'two_fifth',
		'three_fifth',
		'four_fifth',
		'five_sixth',
		'one_half_last',
		'one_third_last',
		'one_fourth_last',
		'one_fifth_last',
		'one_sixth_last',
		'two_third_last',
		'three_fourth_last',
		'two_fifth_last',
		'three_fifth_last',
		'four_fifth_last',
		'five_sixth_last',
	);
	$tagregexp = join( '|',$column_tags);

	$content = preg_replace ('@('. $tagregexp .')\]\s*<br />@', '$1]', $content);
	
	return $content;
}
add_filter( 'the_content', 'theme_shortcode_format',10);
function add_markup_pages($output) {
	if(! strpos($output,'<li>'))
		return $output;
	$output= preg_replace('/class="menu-item/', 'class="first menu-item', $output, 1);
	$output=substr_replace($output, "last-menu-item menu-item", strripos($output, "menu-item"), strlen("menu-item"));
    return $output;
}
add_filter('wp_nav_menu', 'add_markup_pages');

if(theme_get_option('advance','shortcode_comment')){
	add_filter('comment_text', 'do_shortcode');
}
if(theme_get_option('general','scroll_to_top')){
	add_filter('body_class','theme_add_scoll_to_top_body_class');
	function theme_add_scoll_to_top_body_class($classes) {
		$classes[] = 'scroll-to-top';
		return $classes;
	}
}
function theme_search_parse_query($query = false){
	if($query->is_search){
		$exclude_cats = theme_get_option('blog','exclude_categorys');
		foreach ($exclude_cats as $key => $value) {
			$exclude_cats[$key] = -$value;
		}
		if (isset($query->query_vars["cat"])) {
			$cat = $query->query_vars["cat"];
			if(!empty($cat) && '0' != $cat){
				$cat = ''.urldecode($cat).'';
				$cat = addslashes_gpc($cat );
				$cat_array = preg_split('/[,\s]+/', $cat);
				$req_cats = array();
				foreach ( (array) $cat_array as $c ) {
					$c = intval($c);
					if(!in_array($c, $exclude_cats))
					$req_cats[] = $c;
				}
				$exclude_cats = array_merge($exclude_cats,$req_cats);
			}
		}
		$query->set("cat",  implode(",",$exclude_cats));
	}
	return $query;
}
add_filter('parse_query', 'theme_search_parse_query');
/*
 * Single Portfolio Item Category Navigation
 */
if(theme_get_option('portfolio','single_navigation_category')){
	function get_adjacent_category_portfolio_join($join){
		global $post, $wpdb;
		if($post->post_type == 'portfolio'){
			$join .= " INNER JOIN $wpdb->term_relationships AS tr ON p.ID = tr.object_id INNER JOIN $wpdb->term_taxonomy tt ON tr.term_taxonomy_id = tt.term_taxonomy_id";

			$cat_array = wp_get_object_terms($post->ID, 'portfolio_category', array('fields' => 'ids'));
			$join .= " AND tt.taxonomy = 'portfolio_category' AND tt.term_id IN (" . implode(',', $cat_array) . ")";
			//$join .= " JOIN $wpdb->postmeta ON (p.ID = $wpdb->postmeta.post_id) ";
		}
		return $join;	
	}
	add_filter("get_previous_post_join", "get_adjacent_category_portfolio_join");
	add_filter("get_next_post_join", "get_adjacent_category_portfolio_join");
}


add_filter('body_class','theme_add_current_language_class_to_body');
function theme_add_current_language_class_to_body($classes) {
	if(function_exists('icl_get_languages')) {
		$classes[] =  'current-language-'.strtolower(ICL_LANGUAGE_NAME_EN);
	}
	return $classes;
}

