<?php

/*-----------------------------------------------------------------------------------*/
/* 
/*  Theme Framework Functions
/*
/*-----------------------------------------------------------------------------------*/

/*-----------------------------------------------------------------------------------*/
/* Add Visual Editor Style
/*-----------------------------------------------------------------------------------*/
add_editor_style();

/*-----------------------------------------------------------------------------------*/
/*	Include Drag and Drop Slide Order Functionality
/*-----------------------------------------------------------------------------------*/
include( get_template_directory() . '/framework/framework-functions/drag-drop-order.php');

/*-----------------------------------------------------------------------------------*/
/*	Load Text Domain
/*-----------------------------------------------------------------------------------*/
function theme_init(){
    load_theme_textdomain('themewich', get_template_directory() . '/lang');
}
add_action ('init', 'theme_init');

function addhttp($url) {
    if (!preg_match("~^(?:f|ht)tps?://~i", $url)) {
        $url = "http://" . $url;
    }
    return $url;
}

/*-----------------------------------------------------------------------------------*/
/*	Automatic Feed Links
/*-----------------------------------------------------------------------------------*/
if(function_exists('add_theme_support')) {
    add_theme_support('automatic-feed-links'); //WP Auto Feed Links
}

/*-----------------------------------------------------------------------------------*/
/*	Configure Excerpt String, Remove Automatic Periods
/*-----------------------------------------------------------------------------------*/
function ag_excerpt_more($excerpt) {
	return str_replace('[...]', '...', $excerpt); 
}
add_filter('wp_trim_excerpt', 'ag_excerpt_more');

/*-----------------------------------------------------------------------------------*/
/*	Add Browser Detection Body Class
/*-----------------------------------------------------------------------------------*/
add_filter('body_class','themewich_browser_body_class');

function themewich_browser_body_class($classes) {
	global $is_lynx, $is_gecko, $is_IE, $is_opera, $is_NS4, $is_safari, $is_chrome, $is_iphone;
        if($is_lynx) $classes[] = 'lynx';
        elseif($is_gecko) $classes[] = 'gecko';
        elseif($is_opera) $classes[] = 'opera';
        elseif($is_NS4) $classes[] = 'ns4';
        elseif($is_safari) $classes[] = 'safari';
        elseif($is_chrome) $classes[] = 'chrome';
        elseif($is_IE) {
                $classes[] = 'ie';
                if( isset( $_SERVER['HTTP_USER_AGENT'] ) && preg_match('/MSIE ([0-9]+)([a-zA-Z0-9.]+)/', $_SERVER['HTTP_USER_AGENT'], $browser_version))
                $classes[] = 'ie'.$browser_version[1];
        } else $classes[] = 'unknown';
        if($is_iphone) $classes[] = 'iphone';
        if ( isset( $_SERVER['HTTP_USER_AGENT'] ) && stristr( $_SERVER['HTTP_USER_AGENT'],"mac") ) {
                 $classes[] = 'osx';
           } elseif ( isset( $_SERVER['HTTP_USER_AGENT'] ) && stristr( $_SERVER['HTTP_USER_AGENT'],"linux") ) {
                 $classes[] = 'linux';
           } elseif ( isset( $_SERVER['HTTP_USER_AGENT'] ) && stristr( $_SERVER['HTTP_USER_AGENT'],"windows") ) {
                 $classes[] = 'windows';
           }
        return $classes;
}

/*-----------------------------------------------------------------------------------*/
/*	Comment Reply Javascript Action
/*-----------------------------------------------------------------------------------*/
function ag_enqueue_comment_reply() {
    // on single blog post pages with comments open and threaded comments
    if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) { 
        // enqueue the javascript that performs in-link comment reply fanciness
        wp_enqueue_script( 'comment-reply' ); 
    }
}
// Hook into wp_enqueue_scripts
add_action( 'wp_enqueue_scripts', 'ag_enqueue_comment_reply' );

/*-----------------------------------------------------------------------------------*/
/*	Add Widget Shortcode Support
/*-----------------------------------------------------------------------------------*/
add_filter('widget_text', 'shortcode_unautop');
add_filter('widget_text', 'do_shortcode');

/*-----------------------------------------------------------------------------------*/
/*	Add deconstructed URI as <body> classes in Admin
/*-----------------------------------------------------------------------------------*/

function add_to_admin_body_class($classes) {
	// get the global post variable
	global $post;
	$post_type = '';
	
	// instantiate, should be overwritten
	$mode = '';
	// get the current page's URI (the part /after/ your domain name)
	$uri = $_SERVER["REQUEST_URI"];
	// get the post type from WP
	if($post) {
		$post_type = get_post_type($post->ID);
	}
	// set the $mode variable to reflect the editorial /list/ page...
	if (strstr($uri,'edit.php')) {
		$mode = 'edit-list-';
	}
	// or the actual editor page
	if (strstr($uri,'post.php')) {
		$mode = 'edit-page-';
	}
	// append our new mode/post_type class to any existing classes
	if ($post_type) {
		$classes .= $mode . $post_type;
	} else {
		$classes .= '';
	}
	// and send them back to WP
	return $classes;
}
	
// add this filter to the admin_body_class hook
add_filter('admin_body_class', 'add_to_admin_body_class');

/*-----------------------------------------------------------------------------------*/
/* Add HTTP to links function
/*-----------------------------------------------------------------------------------*/
function ag_addhttp($url) {
    if (!preg_match("~^(?:f|ht)tps?://~i", $url)) {
        $url = "http://" . $url;
    }
    return $url;
}

/*-----------------------------------------------------------------------------------*/
/* Remove Dimensions from Thumbnails (for responsivity) and Gallery
/*-----------------------------------------------------------------------------------*/

function remove_thumbnail_dimensions( $html, $post_id, $post_image_id ) {
    $html = preg_replace( '/(width|height)=\"\d*\"\s/', "", $html );
    return $html;
}

add_filter( 'post_thumbnail_html', 'remove_thumbnail_dimensions', 10, 3 );


/*-----------------------------------------------------------------------------------*/
/* Remove More Link Jump
/*-----------------------------------------------------------------------------------*/

function ag_remove_more_jump_link($link) { 
	$offset = strpos($link, '#more-');
	if ($offset) { $end = strpos($link, '"',$offset); }
	if ($end) { $link = substr_replace($link, '', $offset, $end-$offset); }
	return $link;
}
add_filter('the_content_more_link', 'ag_remove_more_jump_link');

/*-----------------------------------------------------------------------------------*/
/* Get Attachment ID from the source
/*-----------------------------------------------------------------------------------*/

function get_attachment_id_from_src ($image_src) {
	global $wpdb;
	$query = "SELECT ID FROM {$wpdb->posts} WHERE guid='$image_src'";
	$id = $wpdb->get_var($query);
	return $id;
}
	
/*-----------------------------------------------------------------------------------*/
/* Wrap All Read More Tags In A Span
/*-----------------------------------------------------------------------------------*/	
function wrap_readmore($more_link)
{
	return '<span class="more-link">'.$more_link.'</span>';
}
add_filter('the_content_more_link', 'wrap_readmore', 10, 1);

/*-----------------------------------------------------------------------------------*/
/* Check for a Default Font
/*-----------------------------------------------------------------------------------*/
function ag_is_default($font) {
  if ($font == 'Arial' || $font == 'Georgia' || $font == 'Tahoma' || $font == 'Verdana' || $font == 'Helvetica') {
    $font = true;
  } else {
	$font = false;  
  }
  return $font;
}

/*-----------------------------------------------------------------------------------*/
/* Get a Specific Amount of Categories
/*-----------------------------------------------------------------------------------*/

/**
 * This function checks if there's a custom page set for a given category
 * @return string Custom Category URL
 */
function themewich_check_custom($cat) {
		$url = get_category_link( $cat->cat_ID );
	return $url;
}
function sortByOrder($a, $b) {
    return $a->term_order - $b->term_order;
}

function ag_get_cats($num, $list=NULL){
	
    $t=get_the_category();
    $count=count($t); 

    if ($list) {
    	$list = ', ';
    } else {
    	$list = '';
    }

    // If sorting is enabled
    if ( isset($t[0]->term_order) ) {
      usort($t, 'sortByOrder');
    }

    if ($count < $num) $num = $count;
    $cat_string = '';

    for($i=0; $i<$num; $i++) {
        $url = themewich_check_custom( $t[$i] );
        $cat_string.= '<a href="'. $url .'" class="category-'.$t[$i]->term_id.'" title="' . __('More', 'themewich') . ' ' . $t[$i]->cat_name . ' '  . __('Posts', 'themewich') . '">'.$t[$i]->cat_name.'</a>'.$list;
    }

    if ($list == ', ') {
    	$cat_string = rtrim($cat_string, ', ');	
    } else {
    	$cat_string .= '<div class="clear"></div>';
    }
	
    if ($cat_string) return $cat_string;
}

function ag_get_cats_array($num, $list=NULL){
  
    $t=get_the_category();
    $count=count($t); 

    // If sorting is enabled
    if ( isset($t[0]->term_order) ) {
      usort($t, 'sortByOrder');
    }

    return array_slice($t, 0, $num);
}

/*------------------------------------------------------------------------------*/
/*	Get Caption from Image ID
/*------------------------------------------------------------------------------*/

function the_post_thumbnail_info($thumbnail_id = NULL, $size = 'medium') {
  global $post;
  $info = (object)array();

  if ($thumbnail_id == NULL) $thumbnail_id    = get_post_thumbnail_id($post->ID);
  $thumbnail_image = get_posts(array('p' => $thumbnail_id, 'post_type' => 'attachment'));

  if ($thumbnail_image && isset($thumbnail_image[0])) {

  	$src = wp_get_attachment_image_src( $thumbnail_id, $size);
  	$info->src = $src[0];

  	//Show the thumbnail caption
    $info->caption = $thumbnail_image[0]->post_excerpt;
    $info->caption = str_replace('"', "", $info->caption); 

    //Show the thumbnail description
    $info->description = $thumbnail_image[0]->post_content; 
    
    //Show the thumbnail alt field
    $info->alt = get_post_meta($thumbnail_id, '_wp_attachment_image_alt', true);
    $info->alt = str_replace('"', "", $info->alt); 
  }

  return $info;
}

function get_the_post_thumbnail_fadein($size = 'medium') {
	global $post;

	$thumbnail = (object)array();
	$thumb = the_post_thumbnail_info(get_post_thumbnail_id($post->ID), $size);

	$thumbnail = '<div class="featured-image thumbnail-' . get_post_thumbnail_id($post->ID). '"><img src="' .$thumb->src .'" ';
	$thumbnail .= ($thumb->alt) ? 'alt="'. $thumb->alt . '" ' : 'alt="'.get_the_title().'" '; 
	$thumbnail .= ($thumb->caption) ? 'title="'. $thumb->caption .'" ' : '';
	$thumbnail .= 'class="scale-with-grid" /></div>';

	return $thumbnail;

}

/**
 * Automatically add lightbox to images linking to images.
 * 
 * @param  string $content
 * 
 * @return string Content html to filter
 */
if (!function_exists('themewich_add_lightbox')) :
    function themewich_add_lightbox($content) {

        //Check the page for link images direct to image (no trailing attributes)
        $string = '/<a href="(.*?).(jpg|jpeg|png|gif|bmp|ico)"><img(.*?)class="(.*?)wp-image-(.*?)" \/><\/a>/i';
        preg_match_all( $string, $content, $matches, PREG_SET_ORDER);

        //Check which attachment is referenced
        foreach ($matches as $val) :
            $post = get_post($val[5]);
            
            //Replace the instance with the lightbox and title(caption) references. Won't fail if caption is empty.
            $string = '<a href="' . $val[1] . '.' . $val[2] . '"><img' . $val[3] . 'class="' . $val[4] . 'wp-image-' . $val[5] . '" /></a>';
            $replace = '<a href="' . $val[1] . '.' . $val[2] . '" class="themewich-lightbox"><img' . $val[3] . 'class="' . $val[4] . 'wp-image-' . $val[5] . '" /></a>';
            $content = str_replace( $string, $replace, $content);
        endforeach;
		
        return $content;
    }
    add_filter('the_content', 'themewich_add_lightbox', 2);
endif;

/**
 * Hex to RGBA
 *
 * Function to convert hex to rgba
 * @since       1.0
 */ 
function hex2rgba($hex, $alpha) {
   $hex = str_replace("#", "", $hex);

   if(strlen($hex) == 3) {
      $r = hexdec(substr($hex,0,1).substr($hex,0,1));
      $g = hexdec(substr($hex,1,1).substr($hex,1,1));
      $b = hexdec(substr($hex,2,1).substr($hex,2,1));
   } else {
      $r = hexdec(substr($hex,0,2));
      $g = hexdec(substr($hex,2,2));
      $b = hexdec(substr($hex,4,2));
   }
   $rgba = array($r, $g, $b, $alpha);
   return implode(",", $rgba); // returns the rgb values separated by commas
  // return $rgba; // returns an array with the rgb values
}