<?php 
// Excerpt length
function bm_better_excerpt($length, $ellipsis) {
$text = get_the_content();
$text = strip_tags($text);
$text = substr($text, 0, $length);
$text = substr($text, 0, strrpos($text, " "));
$text = $text.$ellipsis;
return $text;
}
add_action('admin_menu', 'ptthemes_meta_box');
add_action('admin_head', 'ptthemes_header_inserts');
add_action('save_post', 'ptthemes_metabox_insert');

function relativeDate($posted_date) {
    $tz = 0;    // change this if your web server and weblog are in different timezones
                // see project page for instructions on how to do this
    $month = substr($posted_date,4,2);
    if ($month == "02") { // february
    	// check for leap year
    	$leapYear = isLeapYear(substr($posted_date,0,4));
    	if ($leapYear) $month_in_seconds = 2505600; // leap year
    	else $month_in_seconds = 2419200;
    }
    else { // not february
    // check to see if the month has 30/31 days in it
    	if ($month == "04" or 
    		$month == "06" or 
    		$month == "09" or 
    		$month == "11")
    		$month_in_seconds = 2592000; // 30 day month
    	else $month_in_seconds = 2678400; // 31 day month;
    }
  
/* 
some parts of this implementation borrowed from:
http://maniacalrage.net/archives/2004/02/relativedatesusing/ 
*/
    $in_seconds = strtotime(substr($posted_date,0,8).' '.
                  substr($posted_date,8,2).':'.
                  substr($posted_date,10,2).':'.
                  substr($posted_date,12,2));
    $diff = time() - ($in_seconds + ($tz*3600));
    $months = floor($diff/$month_in_seconds);
    $diff -= $months*2419200;
    $weeks = floor($diff/604800);
    $diff -= $weeks*604800;
    $days = floor($diff/86400);
    $diff -= $days*86400;
    $hours = floor($diff/3600);
    $diff -= $hours*3600;
    $minutes = floor($diff/60);
    $diff -= $minutes*60;
    $seconds = $diff;
    if ($months>0) {
        // over a month old, just show date ("Month, Day Year")
        echo ''; the_time('F jS, Y');
    } else {
        if ($weeks>0) {
            // weeks and days
            $relative_date .= ($relative_date?', ':'').$weeks.' '.__('week').''.($weeks>1?''.__('s').'':'');
            $relative_date .= $days>0?($relative_date?', ':'').$days.' '.__('day').''.($days>1?''.__('s').'':''):'';
        } elseif ($days>0) {
            // days and hours
            $relative_date .= ($relative_date?', ':'').$days.' '.__('day').''.($days>1?''.__('s').'':'');
            $relative_date .= $hours>0?($relative_date?', ':'').$hours.' '.__('hour').''.($hours>1?''.__('s').'':''):'';
        } elseif ($hours>0) {
            // hours and minutes
            $relative_date .= ($relative_date?', ':'').$hours.' '.__('hour').''.($hours>1?''.__('s').'':'');
            $relative_date .= $minutes>0?($relative_date?', ':'').$minutes.' '.get_option('ptthemes_relative_minute').''.($minutes>1?''.__('s').'':''):'';
        } elseif ($minutes>0) {
            // minutes only
            $relative_date .= ($relative_date?', ':'').$minutes.' '.get_option('ptthemes_relative_minute').''.($minutes>1?''.__('s').'':'');
        } else {
            // seconds only
            $relative_date .= ($relative_date?', ':'').$seconds.' '.get_option('ptthemes_relative_minute').''.($seconds>1?''.__('s').'':'');
        }
        // show relative date and add proper verbiage
    	echo ''.__('Posted').' '.$relative_date.' '.__('ago').'';
    }
}

function isLeapYear($year) {
        return $year % 4 == 0 && ($year % 400 == 0 || $year % 100 != 0);
}

if(!function_exists('how_long_ago')){
	function how_long_ago($timestamp){
		$difference = time() - $timestamp;

		if($difference >= 60*60*24*365){        // if more than a year ago
			$int = intval($difference / (60*60*24*365));
			$s = ($int > 1) ? ''.__('s').'' : '';
			$r = $int . ' '.__('year').'' . $s . ' '.__('ago').'';
		} elseif($difference >= 60*60*24*7*5){  // if more than five weeks ago
			$int = intval($difference / (60*60*24*30));
			$s = ($int > 1) ? ''.__('s').'' : '';
			$r = $int . ' '.__('month').'' . $s . ' '.__('ago').'';
		} elseif($difference >= 60*60*24*7){        // if more than a week ago
			$int = intval($difference / (60*60*24*7));
			$s = ($int > 1) ? ''.__('s').'' : '';
			$r = $int . ' '.__('week').'' . $s . ' '.__('ago').'';
		} elseif($difference >= 60*60*24){      // if more than a day ago
			$int = intval($difference / (60*60*24));
			$s = ($int > 1) ? ''.__('s').'' : '';
			$r = $int . ' '.__('day').'' . $s . ' '.__('ago').'';
		} elseif($difference >= 60*60){         // if more than an hour ago
			$int = intval($difference / (60*60));
			$s = ($int > 1) ? ''.__('s').'' : '';
			$r = $int . ' '.__('hour').'' . $s . ' '.__('ago').'';
		} elseif($difference >= 60){            // if more than a minute ago
			$int = intval($difference / (60));
			$s = ($int > 1) ? ''.__('s').'' : '';
			$r = $int . ' '.get_option('ptthemes_relative_minute').'' . $s . ' '.__('ago').'';
		} else {                                // if less than a minute ago
			$r = ''.get_option('ptthemes_relative_moments').' '.__('ago').'';
		}

		return $r;
	}
}
/* popular posts*/
$mostwanted_ver = "0.1.9v";
$total_hits = -1;
//$futureSpamOption = "";
$futureSpamOption = "and spam=0";
$cache_until = 0;
$cached_result = "";

// what's the table name?
$tablestattraq = $table_prefix . 'stattraq';


function rjb_mostwanted($top_n=5, $curtail=0, $showviews=false, $show_views_in_tt=true, $duration = null, $pre="<li>", $post="</li>", $method="ip", $as_percentage = false) {
    MostWanted::mostwanted($top_n, $curtail, $showviews, $show_views_in_tt, $duration, $pre, $post, $method, $as_percentage);
}
function mostwanted_conf() {
	global $tablestattraq;
?>
<div class="wrap">
	<h2>MostWanted Configuration</h2>
	<?php
		if ( isset($_POST['submit']) ) {
			MostWanted::fixstats($_POST['sleep']);
		} else { ?>
			<p>MostWanted uses the database tables from StatTraq to provide a list of the most popular articles.</p>
			<p>There is a small quirk in StatTraq that results in all page views showing up as &quot;Multiple Posts&quot; in cases where permalinks are used.  These stats are not lost, they&apos;re just incorrectly recorded, and can be fixed.</p>

			<p>Currently there are <?php 
			
			global $wpdb;
			
			$q = "SELECT count(*) FROM $tablestattraq WHERE article_id = '0' AND url LIKE '/index.php?name=%'";
			$potential = $wpdb->get_var( $q );
		_e( $potential );
			
			?> rows in your database that could be repaired.</p>
			
			<p>Between each update, the fix mechanism can pause in order to give the database a rest.  This is handy if you're running a live service and don't want the update to be noticed - a value of &quot;0&quot; can safely be used if you are the sole user of the DB and you just want to get the fix done.</p>
			<form action="" method="post" id="akismet-conf" style="margin: auto; width: 25em; ">
				<p>Pause time (in seconds)<input type="text" name="sleep" value="1" /></p>
				<p class="submit"><input type="submit" name="submit" value="Fix stats &raquo;" /></p>
			</form><?php 
		}
	?>
</div>
<?php	
}

class MostWanted {

	function config_page() {
		global $wpdb;
		if ( function_exists('add_submenu_page') )
			add_submenu_page('plugins.php', 'MostWanted Configuration', 'MostWanted Config', 1, basename(__FILE__), 'mostwanted_conf');
	}

	
	function mostwanted($top_n=5, $curtail=0, $showviews=false, $show_views_in_tt=true, $duration="", $pre="<li>", $post="</li>", $method="ip", $as_percentage = false, $timeout=1800){
		global $wpdb, $tablestattraq, $tableposts, $user_level, $mostwanted_ver, $total_hits, $cache_until, $cached_result;

		$time_now = time();
		if ($time_now > $cache_until) {
			// the cache_until time has been passed so the cache is invalid.
			// the content must therefore be regenerated.
			$cache_until = $time_now+$timeout;
			_e("<!-- MostWanted Generated ".$time_now." Expires ".$cache_until." -->");

			get_currentuserinfo();

   		$dateOption = "";
        	$durationExplained = "";
			if ($duration != "") {
				$dateOption .= "AND DATE_SUB(CURDATE(),INTERVAL ".$duration." DAY) < st.access_time";
				$durationExplained = " in the last ".$duration." days";
			}
			if ($method == "ip") {
				$method="ip_address";
			} else {
				$method="session_id";
			}

			$distinct = ($as_percentage?" of":"")." distinct viewers";

			$q = "SELECT p.post_title, st.article_id, COUNT( DISTINCT (st.$method) ) as cnt FROM $tablestattraq st, $tableposts p where p.ID=st.article_id AND p.post_status='publish' ".$futureSpamOption." AND st.user_agent_type='0' ".$dateOption." GROUP BY st.article_id ORDER BY cnt DESC LIMIT 0,$top_n";
			$output = $wpdb->get_results( $q );
			$cached_result="";

			_e("<!-- ");
			_e($q);
			_e(" -->");

        if (isset($output)) {
            foreach ($output as $line) {
                if ($showviews) {
                    $views = " ".MostWanted::getHits($as_percentage, $line->cnt, $dateOption)."";
                }
                if ($show_views_in_tt) {
                    $ttviews = " (".MostWanted::getHits($as_percentage, $line->cnt, $dateOption).$distinct.$durationExplained.")".$append;
                }
					 
                $short = MostWanted::curtail($line->post_title, $curtail) ;
                $t= str_replace("'","&apos;", $line->post_title);
                
					 $cached_result .= $pre . "<a title='". $t . $ttviews . "' href='" . get_permalink($line->article_id) . "'>" . ($short) . "</a>".$post;
            }
        } else {
            $cached_result .= $pre . "No results available.".$post;
        }
		} else {
			_e("<!-- MostWanted Cache Hit -->");
			// the cache is still valid
			// there no need to do anything 
		}
		echo $cached_result;

		// reset the hits value so it is checked once when
		// the next page is loaded.
		$total_hits = -1;
		return;
    }


	function getHits($as_percentage, $count, $dateOption) {
		global $total_hits, $wpdb;
		// start percentage lookup
		if ($as_percentage) {
			// get the total number of hits if it's not known already
			if ($total_hits == -1) {
				$q = "SELECT COUNT( * ) as cnt FROM $tablestattraq st where st.user_agent_type='0'" . $futureSpamOption." ".$dateOption;
				$total_hits = $wpdb->get_var( $q );
			}
			return "" . round((($count / $total_hits) * 100), 1) . "%";
		} else {
			return $count;
		}
		// end percentage lookup
	}


	// trims a message down so that it is shorter than the length
	// specified in the $trim_chars argument.
	function curtail($trim_this, $trim_chars=0) {
		if ($trim_chars > 0 && strlen($trim_this) > $trim_chars) {
			return substr($trim_this,0,($trim_chars-3)) . “…”;
		}
		return $trim_this;
	}


	// This utility method is not used by the main plugin.  It is as a
	// repair tool for stattraq data which may be incorrectly recorded
	// without an article_id, which means that the data can't show up
	// in the MostWanted output.
	//
	// If you've not hacked your stattraq plugin to fix this, then
	// a call to this method will repair all entries in your database.
    function fixstats($sleep = 1){
        global $wpdb, $tablestattraq, $tableposts;
        get_currentuserinfo();

        // calculate duration
        $output = $wpdb->get_results( "SELECT COUNT( DISTINCT (ID) ) as cnt FROM $wpdb->posts;" );
        foreach ($output as $line) {
            $duration = ($sleep * $line->cnt) /60;
        }
        _e("<p>MostWanted is now updating your stattraq database as a LOW_PRIORITY task.  This will probably take around " . $duration . " minutes.  Your previous statistics are being ever-so-slightly-repaired.  Every record of a post that was accessed using a permalink is having it's post id added to it.</p><ol>");
        _e("<p>This page shows the progress of that process.  If you wander off to another page, the process will continue in the background, but you won't know precicely when it's complete.</p>");
        $output = $wpdb->get_results( "SELECT id, post_name FROM $wpdb->posts where post_status = 'publish' ORDER BY id DESC;" );

        foreach ($output as $line) {
            $q = "SELECT count(*) from $tablestattraq WHERE (article_id = '0' and url like '%name=" . $line->post_name . "%');";
            $changes = $wpdb->get_var( $q );

				if ($changes > 0) {
	            $q = "UPDATE low_priority $tablestattraq SET article_id = '" . $line->id . "' WHERE (article_id = '0' and url like '%name=" . $line->post_name . "%');";
	            _e("<li class='active'><span class='name'>Converting " . $line->post_name);
   	         $o2 = $wpdb->get_results( $q );
					_e(" - $changes rows altered");
		   
	 				if ($sleep > 0) {
					 	_e(" - sleeping for " . $sleep . " seconds");
					}
					_e("</span></li>");
            	flush();
            	sleep($sleep);
				} else {
	            _e("<li>Skipping " . $line->post_name . " because no rows require update</li>");
				}
            ob_end_flush();
        }
        _e("</ol>");
        _e("<h1>Finished!</h1>");
       return;
    }
}
add_action('wp_head', array('MostWanted', 'signature'));
add_action('admin_menu', array('MostWanted', 'config_page'));

// NOTE the ">" symbol in the following line must
// be the last character in the file - do not add
// any spaces, tabs or newlines after it, or you
// will get "header already sent" errors.
/*
Plugin Name: WP-PageNavi 
Plugin URI: http://www.lesterchan.net/portfolio/programming.php 
*/ 

function wp_pagenavi($before = '', $after = '', $prelabel = '', $nxtlabel = '', $pages_to_show = 5, $always_show = false) {

	global $request, $posts_per_page, $wpdb, $paged;
	if(empty($prelabel)) {
		$prelabel  = '<strong>&laquo;</strong>';
	}
	if(empty($nxtlabel)) {
		$nxtlabel = '<strong>&raquo;</strong>';
	}
	$half_pages_to_show = round($pages_to_show/2);
	if (!is_single()) {
		if(is_tag()) {
			preg_match('#FROM\s(.*)\sGROUP BY#siU', $request, $matches);		
		} elseif (!is_category()) {
			preg_match('#FROM\s(.*)\sORDER BY#siU', $request, $matches);	
		} else {
			preg_match('#FROM\s(.*)\sGROUP BY#siU', $request, $matches);		
		}
		$fromwhere = $matches[1];
		$numposts = $wpdb->get_var("SELECT COUNT(DISTINCT ID) FROM $fromwhere");
		$max_page = ceil($numposts /$posts_per_page);
		if(empty($paged)) {
			$paged = 1;
		}
		if($max_page > 1 || $always_show) {
			echo "$before <div class='Navi'>";
			if ($paged >= ($pages_to_show-1)) {
				echo '<a href="'.str_replace('&paged','&amp;paged',get_pagenum_link()).'">&laquo;</a>';
			}
			previous_posts_link($prelabel);
			for($i = $paged - $half_pages_to_show; $i  <= $paged + $half_pages_to_show; $i++) {
				if ($i >= 1 && $i <= $max_page) {
					if($i == $paged) {
						echo "<strong class='on'>$i</strong>";
					} else {
						echo ' <a href="'.str_replace('&paged','&amp;paged',get_pagenum_link($i)).'">'.$i.'</a> ';
					}
				}
			}
			next_posts_link($nxtlabel, $max_page);
			if (($paged+$half_pages_to_show) < ($max_page)) {
				echo '<a href="'.str_replace('&paged','&amp;paged',get_pagenum_link($max_page)).'">&raquo;</a>';
			}
			echo "</div> $after";
		}
	}
}

// Use Noindex for sections specified in theme admin

function ptthemes_noindex_head() {
    if ((is_category() && get_option('ptthemes_noindex_category')) ||
	    (is_tag() && get_option('ptthemes_noindex_tag')) ||
		(is_day() && get_option('ptthemes_noindex_daily')) ||
		(is_month() && get_option('ptthemes_noindex_monthly')) ||
		(is_year() && get_option('ptthemes_noindex_yearly')) ||
		(is_author() && get_option('ptthemes_noindex_author')) ||
		(is_search() && get_option('ptthemes_noindex_search'))) {

		$meta_string .= '<meta name="robots" content="noindex,follow" />';
	}	
	echo $meta_string;
}
add_action('wp_head', 'ptthemes_noindex_head');

///////////NEW FUNCTIONS  START//////
function bdw_get_images($iPostID,$img_size='thumb') 
{
    $arrImages =& get_children('order=ASC&orderby=menu_order ID&post_type=attachment&post_mime_type=image&post_parent=' . $iPostID );
	//$images =& get_children( 'post_type=attachment&post_mime_type=image' );
	//$videos =& get_children( 'post_type=attachment&post_mime_type=video/mp4' );
	
	$return_arr = array();
	if($arrImages) 
	{		
       foreach($arrImages as $key=>$val)
	   {
	   		$id = $val->ID;
			if($img_size == 'large')
			{
				//$return_arr[] = '<img src="'.wp_get_attachment_url($id).'" alt="">';	// THE FULL SIZE IMAGE INSTEAD
				$img_arr = wp_get_attachment_image_src($id,'full');	// THE FULL SIZE IMAGE INSTEAD
				$return_arr[] = $img_arr[0];
			}
			elseif($img_size == 'medium')
			{
				//$return_arr[] = '<img src="'.wp_get_attachment_url($id, $size='medium').'" alt="">'; //THE medium SIZE IMAGE INSTEAD
				$img_arr = wp_get_attachment_image_src($id, 'medium'); //THE medium SIZE IMAGE INSTEAD
				$return_arr[] = $img_arr[0];
			}
			elseif($img_size == 'thumb')
			{
				//$return_arr[] = '<img src="'.wp_get_attachment_thumb_url($id).'" alt="">'; // Get the thumbnail url for the attachment
				$img_arr = wp_get_attachment_image_src($id, 'thumbnail'); // Get the thumbnail url for the attachment
				$return_arr[] = $img_arr[0];
				
			}
	   }
	  return $return_arr;
	}
}

function get_related_posts($postdata)
{
	$postCatArr = wp_get_post_categories($postdata->ID);
	$post_array = array();
	for($c=0;$c<count($postCatArr);$c++)
	{
		$category_posts=get_posts('category='.$postCatArr[$c]);
		foreach($category_posts as $post) 
		{
			if($post->ID !=  $postdata->ID)
			{
				$post_array[$post->ID] = $post;
			}
		}
	}
if($post_array)
{
?>
<div class="realated_post clearfix">
<h3><span><?php _e('Related Listing');?></span></h3>

<ul class="category_grid_view clearfix">
<?php
	$relatedprd_count = 0;
	foreach($post_array as $postval)
	{
		$product_id = $postval->ID;
		$post_title = $postval->post_title;
		$productlink = get_permalink($product_id);
		$post_date = $postval->post_date;
		$comment_count = $postval->comment_count;
		$text = $postval->post_content;
		$length = 100;
		$text = strip_tags($text);
		if(strlen($text)>$length)
		{
			$text = substr($text, 0, $length);
			$text = substr($text, 0, strrpos($text, " "));
			$text = $text.' ...';
		}
		if($postval->post_status == 'publish')
		{
			$post_images = bdw_get_images($postval->ID,'large');
			
			if($post_images[0]!='')
			{
				$relatedprd_count++;
			?>
            <li class="clearfix"> 
             <?php if($post_images[0]){ global $thumb_url;?>
       <a class="post_img" href="<?php echo $productlink; ?>"><img src="<?php echo bloginfo('template_url'); ?>/thumb.php?src=<?php echo $post_images[0];?>&amp;w=150&amp;h=100&amp;zc=1&amp;q=80<?php echo $thumb_url;?>" alt="<?php echo $post_title; ?>" title="<?php echo $post_title; ?>"  /> </a>  
<?php }?>
	<?php if(get_post_meta($postval->ID,'video',true)){?>
        <div class="video_main">
        <?php echo get_post_meta($postval->ID,'video',true);?>
        </div>
     <?php }?>
    
   <h3> <a href="<?php echo $productlink; ?>"><?php echo $post_title; ?></a></h3> 
                    <span class="rating"><?php echo get_post_rating_star($product_id);?></span>                    
                    <p><?php echo $text; ?> </p>
                
                 <p class="review clearfix">    
                 <a href="<?php echo $productlink; ?>#commentarea" class="pcomments" ><?php comments_number('0', '1', '%'); ?> </a>  
                 <span class="readmore"> <a href="<?php echo $productlink; ?>"><?php _e('read more');?> </a> </span>
                 </p>
     
            </li>
            <?php
			if($relatedprd_count==3){ break;}
			}
		}
	}
?>
</ul>
</div>
<?php
}
}



function recent_comments($g_size = 30, $no_comments = 10, $comment_lenth = 60, $show_pass_post = false) {
        global $wpdb, $tablecomments, $tableposts,$rating_table_name;
		$tablecomments = $wpdb->comments;
		$tableposts = $wpdb->posts;
		$request = "SELECT ID, comment_ID, comment_content, comment_author,comment_post_ID, comment_author_email FROM $tableposts, $tablecomments WHERE $tableposts.ID=$tablecomments.comment_post_ID AND post_status = 'publish' ";

        if(!$show_pass_post) { $request .= "AND post_password ='' "; }

        $request .= "AND comment_approved = '1' ORDER BY $tablecomments.comment_date DESC LIMIT $no_comments";
        $comments = $wpdb->get_results($request);

        foreach ($comments as $comment) {
		$comment_id = $comment->comment_ID;
		$comment_content = strip_tags($comment->comment_content);
		$comment_excerpt = mb_substr($comment_content, 0, $comment_lenth)."";
		$permalink = get_permalink($comment->ID)."#comment-".$comment->comment_ID;
		$comment_author_email = $comment->comment_author_email;
		$comment_post_ID = $comment->comment_post_ID;
		$post_title = get_the_title($comment_post_ID);
		$permalink = get_permalink($comment_post_ID);
		
   echo '<li class="clearfix">';
   echo "<span class=\"li".$comment_id."\">";
		if (function_exists('get_avatar')) {
					  if ('' == $comment->comment_type) {
						  echo  '<a href="'.$permalink.'">';
						 echo get_avatar($comment->comment_author_email, 60, $template_path . ''.get_bloginfo('template_directory').'/images/gravatar2.png');
						 echo '</a>';
					  } elseif ( ('trackback' == $comment->comment_type) || ('pingback' == $comment->comment_type) ) {
						 echo  '<a href="'.$permalink.'">';
						 echo get_avatar($comment->comment_author_url, 60, $template_path . ''.get_bloginfo('template_directory').'/images/gravatar2.png');
					  }
				   } elseif (function_exists('gravatar')) {
					  echo  '<a href="'.$permalink.'">';
					  echo "<img src=\"";
					  if ('' == $comment->comment_type) {
						 echo gravatar($comment->comment_author_email,60, $template_path . ''.get_bloginfo('template_directory').'/images/gravatar2.png');
						  echo '</a>';
					  } elseif ( ('trackback' == $comment->comment_type) || ('pingback' == $comment->comment_type) ) {
						echo  '<a href="'.$permalink.'">';
						echo gravatar($comment->comment_author_url,60, $template_path . ''.get_bloginfo('template_directory').'/images/gravatar2.png');
						 echo '</a>';
					  }
					  echo "\" alt=\"\" class=\"avatar\" />";
				   }
    echo "</span>\n";
    echo '' ;

           
 			echo  '<a href="'.$permalink.'">'.$post_title.'</a>';
			 $post_rating = $wpdb->get_var("select rating_rating from $rating_table_name where comment_id=\"$comment_id\"");
			 echo '<br />'.draw_rating_star($post_rating);
			 
 			echo "<a class=\"comment_excerpt\" href=\"" . $permalink . "\" title=\"View the entire comment\">";
			echo $comment_excerpt;
			echo "</a>";
			
			echo '</li>';

	            }

}

function excerpt($limit=10) {
  $excerpt = explode(' ', get_the_excerpt(),$limit);
  if (count($excerpt)>=$limit) {
    array_pop($excerpt);
    $excerpt = implode(" ",$excerpt).'...';
  } else {
    $excerpt = implode(" ",$excerpt);
  }	
  $excerpt = preg_replace('`\[[^\]]*\]`','',$excerpt);
  return $excerpt;
}
 
function content($limit) {
  $content = explode(' ', get_the_content(), $limit);
  if (count($content)>=$limit) {
    array_pop($content);
    $content = implode(" ",$content).'...';
  } else {
    $content = implode(" ",$content);
  }	
  $content = preg_replace('/\[.+\]/','', $content);
  $content = apply_filters('the_content', $content); 
  $content = str_replace(']]>', ']]&gt;', $content);
  return $content;
}

function is_user_can_add_event()
{
	global $current_user;
	//$current_user->ID
	return 1;	
}
function get_currency_sym()
{
	global $wpdb;
	if(get_option('currencysym'))
	{
		return stripslashes(get_option('currencysym'));
	}else
	{
		return '$';
	}
}
function get_currency_type()
{
	global $wpdb;
	if(get_option('currency'))
	{
		return stripslashes(get_option('currency'));
	}else
	{
		return 'USD';
	}
	
}
function get_site_emailId()
{
	if(get_option('site_email'))
	{
		return get_option('site_email');
	}else
	{
		return get_option('admin_email');
	}
}
function get_site_emailName()
{
	if(get_option('site_email_name'))
	{
		return stripslashes(get_option('site_email_name'));
	}else
	{
		return stripslashes(get_option('blogname'));
	}
}
function is_allow_user_register()
{
	if(get_option('is_allow_user_add')!='')
	{
		return get_option('is_allow_user_add');
	}else
	{
		return 1;
	}
}

function get_ssl_normal_url($url,$pid='')
{
	if($pid)
	{
		return $url;
	}else
	{
		if(get_option('is_allow_ssl')=='0')
		{
		}else
		{
			$url = str_replace('http://','https://',$url);
		}
	}
	return $url;
}
function get_property_price_info($pro_type='')
{
	global $price_db_table_name,$wpdb;
	if($pro_type)
	{
		$subsql = " and pid=\"$pro_type\"";	
	}
	$pricesql = "select * from $price_db_table_name where status=1 $subsql";
	$priceinfo = $wpdb->get_results($pricesql);
	$price_info = array();
	if($priceinfo)
	{
		foreach($priceinfo as $priceinfoObj)
		{
		$info = array();
		$info['title'] = $priceinfoObj->title;
		$info['price'] = $priceinfoObj->amount;
		$info['days'] = $priceinfoObj->days;
		$info['alive_days'] =$priceinfoObj->days;
		$info['cat'] =$priceinfoObj->cat;
		$price_info[] = $info;
		}
	}
	return $price_info;
}

function twentyten_term_list( $taxonomy, $glue = ', ', $text = '', $also_text = '' ) {
	global $wp_query, $post;
	$current_term = $wp_query->get_queried_object();
	$terms = wp_get_object_terms( $post->ID, $taxonomy );
	// If we're viewing a Taxonomy page..
	if ( isset( $current_term->taxonomy ) && $taxonomy == $current_term->taxonomy ) {
		// Remove the term from display.
		foreach ( (array) $terms as $key => $term ) {
			if ( $term->term_id == $current_term->term_id ) {
				unset( $terms[$key] );
				break;
			}
		}
		// Change to Also text as we've now removed something from the terms list.
		$text = $also_text;
	}
	$tlist = array();
	$rel = 'category' == $taxonomy ? 'rel="category"' : 'rel="tag"';
	foreach ( (array) $terms as $term ) {
		$tlist[] = '<a href="' . get_term_link( $term, $taxonomy ) . '" title="' . esc_attr( sprintf( __( 'View all posts in %s', 'twentyten' ), $term->name ) ) . '" ' . $rel . '>' . $term->name . '</a>';
	}
	if ( ! empty( $tlist ) )
		return sprintf( $text, join( $glue, $tlist ) );
	return '';
}
function get_payment_optins($method)
{
	global $wpdb;
	$paymentsql = "select * from $wpdb->options where option_name like 'payment_method_$method'";
	$paymentinfo = $wpdb->get_results($paymentsql);
	if($paymentinfo)
	{
		foreach($paymentinfo as $paymentinfoObj)
		{
			$option_value = unserialize($paymentinfoObj->option_value);
			$paymentOpts = $option_value['payOpts'];
			$optReturnarr = array();
			for($i=0;$i<count($paymentOpts);$i++)
			{
				$optReturnarr[$paymentOpts[$i]['fieldname']] = $paymentOpts[$i]['value'];
			}
			//echo "<pre>";print_r($optReturnarr);
			return $optReturnarr;
		}
	}
}

function get_property_default_status()
{
	if(get_option('approve_status'))
	{
		return get_option('approve_status');
	}else
	{
		return 'publish';
	}
}

function get_user_nice_name($fname,$lname='')
{
	global $wpdb;
	if($lname)
	{
		$uname = $fname.'-'.$lname;
	}else
	{
		$uname = $fname;
	}
	//$nicename = strtolower(str_replace(array("'",'"',"?",".","!","@","#","$","%","^","&","*","(",")","-","+","+"," "),array('-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-'),$uname));
	$nicename = strtolower(str_replace(array("'",'"',"?",".","!","@","#","$","%","^","&","*","(",")","-","+","+"," "),array('','','','-','','-','-','','','','','','','','','','-','-',''),$uname));
	$nicenamecount = $wpdb->get_var("select count(user_nicename) from $wpdb->users where user_nicename like \"$nicename\"");
	if($nicenamecount=='0')
	{
		return trim($nicename);
	}else
	{
		$lastuid = $wpdb->get_var("select max(ID) from $wpdb->users");
		return $nicename.'-'.$lastuid;
	}
}

function sendEmail($fromEmail,$fromEmailName,$toEmail,$toEmailName,$subject,$message,$extra='')
{
	$headers  = 'MIME-Version: 1.0' . "\r\n";
	$headers .= 'Content-type: text/html; charset=UTF-8' . "\r\n";
	
	// Additional headers
	$headers .= 'To: '.$toEmailName.' <'.$toEmail.'>' . "\r\n";
	$headers .= 'From: '.$fromEmailName.' <'.$fromEmail.'>' . "\r\n";

/*	echo "Header : headers <br>";
	echo "To : $fromEmail  Name : $fromEmailName <br>";
	echo "To : $toEmail  Name : $toEmailName <br>";
	echo "Subject $subject <br>";
	echo "$message";
	exit;*/
	// Mail it
	//wp_mail($toEmail, $subject, $message, $headers);
	@mail($toEmail, $subject, $message, $headers);
}
function get_image_phy_destination_path()
{	
	$today = getdate();
	if ($today['month'] == "January"){
	  $today['month'] = "01";
	}
	elseif ($today['month'] == "February"){
	  $today['month'] = "02";
	}
	elseif  ($today['month'] == "March"){
	  $today['month'] = "03";
	}
	elseif  ($today['month'] == "April"){
	  $today['month'] = "04";
	}
	elseif  ($today['month'] == "May"){
	  $today['month'] = "05";
	}
	elseif  ($today['month'] == "June"){
	  $today['month'] = "06";
	}
	elseif  ($today['month'] == "July"){
	  $today['month'] = "07";
	}
	elseif  ($today['month'] == "August"){
	  $today['month'] = "08";
	}
	elseif  ($today['month'] == "September"){
	  $today['month'] = "09";
	}
	elseif  ($today['month'] == "October"){
	  $today['month'] = "10";
	}
	elseif  ($today['month'] == "November"){
	  $today['month'] = "11";
	}
	elseif  ($today['month'] == "December"){
	  $today['month'] = "12";
	}
	global $upload_folder_path;
	$tmppath = $upload_folder_path;

	
	  $destination_path = ABSPATH . $tmppath.$today['year']."/".$today['month']."/";
      if (!file_exists($destination_path)){
      $imagepatharr = explode('/',$tmppath.$today['year']."/".$today['month']);
	   $year_path = ABSPATH;
		for($i=0;$i<count($imagepatharr);$i++)
		{
		  if($imagepatharr[$i])
		  {
			$year_path .= $imagepatharr[$i]."/";
			  if (!file_exists($year_path)){
				  mkdir($year_path, 0777);
			  }     
			}
		}
	}
	
	  return $destination_path;
	
}

//This function would return paths of folder to which upload the image 
function get_image_phy_destination_path_user()
{	
	global $upload_folder_path;
	$tmppath = $upload_folder_path;
	$destination_path = ABSPATH . $tmppath."users/";
      if (!file_exists($destination_path)){
      $imagepatharr = explode('/',$tmppath."users");
	   $year_path = ABSPATH;
		for($i=0;$i<count($imagepatharr);$i++)
		{
		  if($imagepatharr[$i])
		  {
			$year_path .= $imagepatharr[$i]."/";
			  if (!file_exists($year_path)){
				  mkdir($year_path, 0777);
			  }     
			}
		}
	}
	 return $destination_path;
	
}

//
function get_image_rel_destination_path_user()
{	
	global $upload_folder_path;
	$destination_path = get_option( 'siteurl' ) ."/".$upload_folder_path."users/";
	  return $destination_path;
	
}

function get_image_rel_destination_path()
{
	$today = getdate();
	if ($today['month'] == "January"){
	  $today['month'] = "01";
	}
	elseif ($today['month'] == "February"){
	  $today['month'] = "02";
	}
	elseif  ($today['month'] == "March"){
	  $today['month'] = "03";
	}
	elseif  ($today['month'] == "April"){
	  $today['month'] = "04";
	}
	elseif  ($today['month'] == "May"){
	  $today['month'] = "05";
	}
	elseif  ($today['month'] == "June"){
	  $today['month'] = "06";
	}
	elseif  ($today['month'] == "July"){
	  $today['month'] = "07";
	}
	elseif  ($today['month'] == "August"){
	  $today['month'] = "08";
	}
	elseif  ($today['month'] == "September"){
	  $today['month'] = "09";
	}
	elseif  ($today['month'] == "October"){
	  $today['month'] = "10";
	}
	elseif  ($today['month'] == "November"){
	  $today['month'] = "11";
	}
	elseif  ($today['month'] == "December"){
	  $today['month'] = "12";
	}
	global $upload_folder_path;
	$tmppath = $upload_folder_path;
	global $blog_id;
	if($blog_id)
	{
		return $user_path = $today['year']."/".$today['month']."/";
	}else
	{
		return $user_path = get_option( 'siteurl' ) ."/$tmppath".$today['year']."/".$today['month']."/";
	}
}
function get_image_tmp_phy_path()
{	
	global $upload_folder_path;
	$tmppath = $upload_folder_path;
	return $destination_path = ABSPATH . $tmppath."tmp/";
}

function move_original_image_file($src,$dest)
{
	copy($src, $dest);
	unlink($src);
	$dest = explode('/',$dest);
	$img_name = $dest[count($dest)-1];
	$img_name_arr = explode('.',$img_name);

	$my_post = array();
	$my_post['post_title'] = $img_name_arr[0];
	$my_post['guid'] = get_image_rel_destination_path().$img_name;
	return $my_post;
}
function get_image_size($src)
{
	$img = imagecreatefromjpeg($src);
	if (!$img) {
		echo "ERROR:could not create image handle ". $src;
		exit(0);
	}
	$width = imageSX($img);
	$height = imageSY($img);
	return array('width'=>$width,'height'=>$height);
	
}
function get_attached_file_meta_path($imagepath)
{
	$imagepath_arr = explode('/',$imagepath);
	$imagearr = array();
	for($i=0;$i<count($imagepath_arr);$i++)
	{
		$imagearr[] = $imagepath_arr[$i];
		if($imagepath_arr[$i] == 'uploads')
		{
			break;
		}
	}
	$imgpath_ini = implode('/',$imagearr);
	return str_replace($imgpath_ini.'/','',$imagepath);
}
function image_resize_custom($src,$dest,$twidth,$theight)
{
	global $image_obj;
	// Get the image and create a thumbnail
	$img_arr = explode('.',$dest);
	$imgae_ext = strtolower($img_arr[count($img_arr)-1]);
	if($imgae_ext == 'jpg' || $imgae_ext == 'jpeg')
	{
		$img = imagecreatefromjpeg($src);
	}elseif($imgae_ext == 'gif')
	{
		$img = imagecreatefromgif($src);
	}
	elseif($imgae_ext == 'png')
	{
		$img = imagecreatefrompng($src);
	}
	
	if($img)
	{
		$width = imageSX($img);
		$height = imageSY($img);
	
		if (!$width || !$height) {
			echo "ERROR:Invalid width or height";
			exit(0);
		}
		
		if(($twidth<=0 || $theight<=0))
		{
			return false;
		}
		$image_obj->load($src);
		$image_obj->resize($twidth,$theight);
		$new_width = $image_obj->getWidth();
		$new_height = $image_obj->getHeight();
		$imgname_sub = '-'.$new_width.'X'. $new_height.'.'.$imgae_ext;
		$img_arr1 = explode('.',$dest);
		unset($img_arr1[count($img_arr1)-1]);
		$dest = implode('.',$img_arr1).$imgname_sub;
		$image_obj->save($dest);
		
		
		return array(
					'file' => basename( $dest ),
					'width' => $new_width,
					'height' => $new_height,
				);
	}else
	{
		return array();
	}
}

function get_author_info($aid)
{
	global $wpdb;
	$infosql = "select * from $wpdb->users where ID=$aid";
	$info = $wpdb->get_results($infosql);
	if($info)
	{
		return $info[0];
	}
}
function set_property_status($pid,$status='publish')
{
	if($pid)
	{
		global $wpdb;
		$wpdb->query("update $wpdb->posts set post_status=\"$status\" where ID=\"$pid\"");
	}
}

function get_post_info($pid)
{
	global $wpdb;
	$productinfosql = "select ID,post_title,post_content from $wpdb->posts where ID=$pid";
	$productinfo = $wpdb->get_results($productinfosql);
	if($productinfo)
	{
		foreach($productinfo[0] as $key=>$val)
		{
			$productArray[$key] = $val; 
		}
	}
	return $productArray;
}
function bdw_get_images_with_info($iPostID,$img_size='thumb') 
{
    $arrImages =& get_children('order=ASC&orderby=menu_order ID&post_type=attachment&post_mime_type=image&post_parent=' . $iPostID );
	
	$return_arr = array();
	if($arrImages) 
	{		
       foreach($arrImages as $key=>$val)
	   {
	   		$id = $val->ID;
			if($img_size == 'large')
			{
				$img_arr = wp_get_attachment_image_src($id,'full');	// THE FULL SIZE IMAGE INSTEAD
				$imgarr['id'] = $id;
				$imgarr['file'] = $img_arr[0];
				$return_arr[] = $imgarr;
			}
			elseif($img_size == 'medium')
			{
				$img_arr = wp_get_attachment_image_src($id, 'medium'); //THE medium SIZE IMAGE INSTEAD
				$imgarr['id'] = $id;
				$imgarr['file'] = $img_arr[0];
				$return_arr[] = $imgarr;
			}
			elseif($img_size == 'thumb')
			{
				$img_arr = wp_get_attachment_image_src($id, 'thumbnail'); // Get the thumbnail url for the attachment
				$imgarr['id'] = $id;
				$imgarr['file'] = $img_arr[0];
				$return_arr[] = $imgarr;
				
			}
	   }
	  return $return_arr;
	}
}
function get_property_cat_id_name($postid='')
{
	global $wpdb;
	$bedcatid = get_cat_id_from_name(get_option('ptthemes_bedroomcategory'));
	$bedcatarr = getCategoryList($bedcatid);
	if($bedcatarr)
	{
		foreach($bedcatarr as $key=>$val)
		{
			if($val['ID'])
			{
				$bed_catid_arr[] = $val['ID'];
				$bed_catname_arr[$val['ID']] = $val['name'];
			}
		}
	}	
	$typecatid = get_cat_id_from_name(get_option('ptthemes_property_typecategory'));
	$typecatarr = getCategoryList($typecatid);
	if($typecatarr)
	{
		foreach($typecatarr as $key=>$val)
		{
			if($val['ID'])
			{
				$type_catid_arr[] = $val['ID'];
				$type_catname_arr[$val['ID']] = $val['name'];
			}
		}
	}	
	$loccatid = get_cat_id_from_name(get_option('ptthemes_locationcategory'));
	$loccatarr = getCategoryList($loccatid);
	if($loccatarr)
	{
		foreach($loccatarr as $key=>$val)
		{
			if($val['ID'])
			{
				$loc_catid_arr[] = $val['ID'];
				$loc_catname_arr[$val['ID']] = $val['name'];
			}
		}
	}
	/*$pricecatid = get_cat_id_from_name(get_option('ptthemes_pricecategory'));
	$pricecatarr = getCategoryList($pricecatid);
	if($pricecatarr)
	{
		foreach($pricecatarr as $key=>$val)
		{
			if($val['ID'])
			{
				$price_catid_arr[] = $val['ID'];
				$price_catname_arr[$val['ID']] = $val['name'];
			}
		}
	}*/
	$pn_categories_obj = $wpdb->get_var("SELECT GROUP_CONCAT(distinct($wpdb->terms.term_id)) as cat_ID 
	                            FROM $wpdb->term_taxonomy,  $wpdb->terms,  $wpdb->term_relationships
                                WHERE $wpdb->term_taxonomy.term_id =  $wpdb->terms.term_id AND $wpdb->term_taxonomy.taxonomy = 'category'
								and $wpdb->term_relationships.term_taxonomy_id=$wpdb->term_taxonomy.term_taxonomy_id and $wpdb->term_relationships.object_id=\"$postid\"");
								
	$post_cats_arr = explode(',',$pn_categories_obj);
	if($post_cats_arr)
	{
		for($i=0;$i<count($post_cats_arr);$i++)
		{
			if($bed_catid_arr && in_array($post_cats_arr[$i],$bed_catid_arr))
			{
				$post_cat_info['bed'] = array('id'=>$post_cats_arr[$i],'name'=>$bed_catname_arr[$post_cats_arr[$i]]);
			}
			if($loc_catid_arr && in_array($post_cats_arr[$i],$loc_catid_arr))
			{
				$post_cat_info['location'] = array('id'=>$post_cats_arr[$i],'name'=>$loc_catname_arr[$post_cats_arr[$i]]);
			}
			/*if($price_catid_arr && in_array($post_cats_arr[$i],$price_catid_arr))
			{
				$post_cat_info['price'] = array('id'=>$post_cats_arr[$i],'name'=>$price_catname_arr[$post_cats_arr[$i]]);
			}*/	
		}
	}
	return $post_cat_info;
}
function get_cat_id_from_name($catname)
{
	global $wpdb;
	if($catname)
	{
	return $pn_categories_obj = $wpdb->get_var("SELECT $wpdb->terms.term_id as cat_ID 
	                            FROM $wpdb->term_taxonomy,  $wpdb->terms
                                WHERE $wpdb->term_taxonomy.term_id =  $wpdb->terms.term_id AND $wpdb->terms.name like \"$catname\"
                                AND $wpdb->term_taxonomy.taxonomy = 'category'");
	}
}
function getCategoryList( $parent = 0, $level = 0, $categories = 0, $page = 1, $per_page = 1000 ) 
{
	$count = 0;
	if ( empty($categories) ) 
	{
		$args = array('hide_empty' => 0,'orderby'=>'id');
			
		$categories = get_categories( $args );
		if ( empty($categories) )
			return false;
	}		
	$children = _get_term_hierarchy('category');
	return _cat_rows1( $parent, $level, $categories, $children, $page, $per_page, $count );
}
function _cat_rows1( $parent = 0, $level = 0, $categories, &$children, $page = 1, $per_page = 20, &$count )
{
	//global $category_array;
	$start = ($page - 1) * $per_page;
	$end = $start + $per_page;
	ob_start();

	foreach ( $categories as $key => $category ) 
	{
		if ( $count >= $end )
			break;

		$_GET['s']='';
		if ( $category->parent != $parent && empty($_GET['s']) )
			continue;

		// If the page starts in a subtree, print the parents.
		if ( $count == $start && $category->parent > 0 ) {
			$my_parents = array();
			$p = $category->parent;
			while ( $p ) {
				$my_parent = get_category( $p );
				$my_parents[] = $my_parent;
				if ( $my_parent->parent == 0 )
					break;
				$p = $my_parent->parent;
			}

			$num_parents = count($my_parents);
			while( $my_parent = array_pop($my_parents) ) {
				$category_array[] = _cat_rows1( $my_parent, $level - $num_parents );
				$num_parents--;
			}
		}

		if ($count >= $start)
		{
			$categoryinfo = array();
			$category = get_category( $category, '', '' );
			$default_cat_id = (int) get_option( 'default_category' );
			$pad = str_repeat( '&#8212; ', max(0, $level) );
			$name = ( $name_override ? $name_override : $pad . ' ' . $category->name );
			$categoryinfo['ID'] = $category->term_id;
			$categoryinfo['name'] = $name;
			$category_array[] = $categoryinfo;
		}

		unset( $categories[ $key ] );
		$count++;
		if ( isset($children[$category->term_id]) )
			_cat_rows1( $category->term_id, $level + 1, $categories, $children, $page, $per_page, $count );
	}
	$output = ob_get_contents();
	ob_end_clean();
	return $category_array;
}

function get_blog_sub_cats_str($type='array')
{
	$catid_arr = get_option('ptthemes_blogcategory');
	$blogcatids = '';
	$subcatids_arr = array();
	for($i=0;$i<count($catid_arr);$i++)
	{
		if($catid_arr[$i])
		{
			$subcatids_arr = array_merge($subcatids_arr,array($catid_arr[$i]),get_term_children( $catid_arr[$i],'category'));
		}
	}
	if($subcatids_arr && $type=='string')
	{
		$blogcatids = implode(',',$subcatids_arr);
		return $blogcatids;	
	}else
	{
		return $subcatids_arr;
	}			
}

if (function_exists('add_theme_support')) {
	add_theme_support('post-thumbnails');
	set_post_thumbnail_size(588, 250, true); // Normal post thumbnails
	add_image_size('loopThumb', 588, 125, true);
}

function get_price_info($title='')
{
	global $price_db_table_name,$wpdb;
	$pricesql = "select * from $price_db_table_name where status=1";
	$priceinfo = $wpdb->get_results($pricesql);
	if($priceinfo)
	{
		$counter=1;
		foreach($priceinfo as $priceinfoObj)
		{
		?>
        <div class="package"><input type="radio" value="<?php echo $priceinfoObj->pid?>" <?php if($title==$priceinfoObj->pid || $counter==1){ echo 'checked="checked"';}?> name="price_select" id="price_select<?php echo $counter ?>" />&nbsp;<?php printf(__(PUBLISH_DAYS_TEXT),$priceinfoObj->title,$priceinfoObj->days,str_replace(' ','_',$priceinfoObj->title),$priceinfoObj->amount,get_currency_type());?></div>
        <?php $counter++;
		}
	}
}
function get_payable_amount_with_coupon($total_amt,$coupon_code)
{
	$discount_amt = get_discount_amount($coupon_code,$total_amt);
	if($discount_amt>0)
	{
		return $total_amt-$discount_amt;
	}else
	{
		return $total_amt;
	}
}
function is_valid_coupon($coupon)
{
	global $wpdb;
	$couponsql = "select option_value from $wpdb->options where option_name='discount_coupons'";
	$couponinfo = $wpdb->get_results($couponsql);
	if($couponinfo)
	{
		foreach($couponinfo as $couponinfoObj)
		{
			$option_value = unserialize($couponinfoObj->option_value);
			foreach($option_value as $key=>$value)
			{
				if($value['couponcode'] == $coupon)
				{
					return true;
				}
			}
		}
	}
	return false;
}
function get_discount_amount($coupon,$amount)
{
	global $wpdb;
	if($coupon!='' && $amount>0)
	{
		$couponsql = "select option_value from $wpdb->options where option_name='discount_coupons'";
		$couponinfo = $wpdb->get_results($couponsql);
		if($couponinfo)
		{
			foreach($couponinfo as $couponinfoObj)
			{
				$option_value = unserialize($couponinfoObj->option_value);
				foreach($option_value as $key=>$value)
				{
					if($value['couponcode'] == $coupon)
					{
						if($value['dis_per']=='per')
						{
							$discount_amt = ($amount*$value['dis_amt'])/100;
						}else
						if($value['dis_per']=='amt')
						{
							$discount_amt = $value['dis_amt'];
						}
					}
				}
			}
			return $discount_amt;
		}
	}
	return '0';			
}

function get_time_difference( $start, $pid )
{
	$alive_days = get_post_meta($pid,'alive_days',true);
	$uts['start']      =    strtotime( $start );
	$uts['end']        =    mktime(0,0,0,date('m',strtotime($start)),date('d',strtotime($start))+$alive_days,date('Y',strtotime($start)));

	$post_days = gregoriantojd(date('m'), date('d'), date('Y')) - gregoriantojd(date('m',strtotime($start)), date('d',strtotime($start)), date('Y',strtotime($start)));
	$days = $alive_days-$post_days;

	if($days>0)
	{
		return $days;	
	}
    return( false );
}

function get_image_cutting_edge($args=array())
{
	if($args['image_cut'])
	{
		$cut_post =$args['image_cut'];
	}else
	{
		$cut_post = get_option('ptthemes_image_x_cut');
	}
	if($cut_post)
	{		
		if($cut_post=='top')
		{
			$thumb_url .= "&amp;a=t";	
		}elseif($cut_post=='bottom')
		{
			$thumb_url .= "&amp;a=b";	
		}elseif($cut_post=='left')
		{
			$thumb_url .= "&amp;a=l";
		}elseif($cut_post=='right')
		{
			$thumb_url .= "&amp;a=r";
		}elseif($cut_post=='top right')
		{
			$thumb_url .= "&amp;a=tr";
		}elseif($cut_post=='top left')
		{
			$thumb_url .= "&amp;a=tl";
		}elseif($cut_post=='bottom right')
		{
			$thumb_url .= "&amp;a=br";
		}elseif($cut_post=='bottom left')
		{
			$thumb_url .= "&amp;a=bl";
		}
	}
	return $thumb_url;
}

function get_category_dl_options($selected)
{
		$cat_args = array('name' => 'scat', 'id' => 'scat', 'selected' => $selected, 'class' => 'select', 'orderby' => 'name', 'echo' => '0', 'hierarchical' => 1, 'taxonomy'=>CUSTOM_CATEGORY_TYPE1);
		$cat_args['show_option_none'] = __('Select Category');
		return wp_dropdown_categories(apply_filters('widget_categories_dropdown_args', $cat_args));
}

function  get_total_events_count()
{
	global $wpdb;
	return $wpdb->get_var("select count(ID) from $wpdb->posts where post_type='".CUSTOM_POST_TYPE1."' and post_status='publish'");
}
/////////////////////////////////////////////////////////////////////////
function get_the_post_content($type='listing_li',$file='')
{
	if($file)
	{
		include($file);	
	}elseif($type=='listing_li')
	{
		include(TEMPLATEPATH . '/library/includes/listing_li_content.php');
	}elseif($type=='author_listing_li')
	{
		include(TEMPLATEPATH . '/library/includes/author_listing_li_content.php');
	}			
}

function get_formated_date($date)
{
	return mysql2date(get_option('date_format'), $date);
}
function get_formated_time($time)
{
	return mysql2date(get_option('time_format'), $time, $translate=true);;
}

function get_add_to_calender($args=array('outlook'=>1,'google_calender'=>1,'yahoo_calender'=>1,'ical_cal'=>1))
{
	global $post;
	if($args)
	{
		$icalurl = get_event_ical_info($post->ID);
?>
<div class="i_addtocalendar"> <a href="#"><?php _e('Add to my calendar');?></a> 
<div class="addtocalendar">
<ul>
<?php if($args['outlook']){?><li class="i_calendar"><a href="<?php echo $icalurl['ical']; ?>"> <?php _e('Outlook Calendar');?></a> </li><?php }?>
<?php if($args['google_calender']){?><li class="i_google"><a href="<?php echo $icalurl['google']; ?>" target="_blank"> <?php _e('Google Calendar');?> </a> </li><?php }?>
<?php if($args['yahoo_calender']){?><li class="i_yahoo"><a href="<?php echo $icalurl['yahoo']; ?>" target="_blank"><?php _e('Yahoo! Calendar');?></a> </li><?php }?>
<?php if($args['ical_cal']){?><li class="i_calendar"><a href="<?php echo $icalurl['ical']; ?>"> <?php _e('iCal Calendar');?> </a> </li><?php }?>
</ul>
</div>
</div>
<?php
	}
}

function get_event_ical_info($post_id) {
	require_once(TEMPLATEPATH.'/library/ical/iCalcreator.class.php');
	$cal_post = get_post($post_id);
	if ($cal_post) {
		$location = get_post_meta($post_id,'address',true);
		$start_year = date('Y',strtotime(get_post_meta($post_id,'st_date',true)));
		$start_month = date('m',strtotime(get_post_meta($post_id,'st_date',true)));
		$start_day = date('d',strtotime(get_post_meta($post_id,'st_date',true)));
		
		$end_year = date('Y',strtotime(get_post_meta($post_id,'end_date',true)));
		$end_month = date('m',strtotime(get_post_meta($post_id,'end_date',true)));
		$end_day = date('d',strtotime(get_post_meta($post_id,'end_date',true)));
		
		$start_time = get_post_meta($post_id,'st_time',true);
		$end_time = get_post_meta($post_id,'end_time',true);
		if (($start_time != '') && ($start_time != ':')) { $event_start_time = explode(":",$start_time); }
		if (($end_time != '') && ($end_time != ':')) { $event_end_time = explode(":",$end_time); }
		
		$post_title = get_the_title($post_id);
		$v = new vcalendar();                          
		$e = new vevent();  
		$e->setProperty( 'categories' , 'Events' );                   
		
		if (isset($event_start_time)) { $e->setProperty( 'dtstart' 	,  $start_year, $start_month, $start_day, $event_start_time[0], $event_start_time[1], 00 ); } else { $e->setProperty( 'dtstart' ,  $start_year, $start_month, $start_day ); } // YY MM dd hh mm ss
		if (isset($event_end_time)) { $e->setProperty( 'dtend'   	,  $end_year, $end_month, $end_day, $event_end_time[0], $event_end_time[1], 00 );  } else { $e->setProperty( 'dtend' , $end_year, $end_month, $end_day );  } // YY MM dd hh mm ss
		$e->setProperty( 'description' 	, strip_tags($cal_post->post_excerpt) ); 
		if (isset($location)) { $e->setProperty( 'location'	, $location ); } 
		$e->setProperty( 'summary'	, $post_title );                 
		$v->addComponent( $e );                        
	
		$templateurl = get_bloginfo('template_url').'/cache/';
		$siteurl = get_bloginfo('url');
		$dir = str_replace($siteurl,'',$templateurl);
		$dir = str_replace('/wp-content/','wp-content/',$dir);
		
		$v->setConfig( 'directory', $dir ); 
		$v->setConfig( 'filename', 'event-'.$post_id.'.ics' ); 
		$v->saveCalendar(); 
		////OUT LOOK & iCAL URL//
		$output['ical'] = $templateurl.'event-'.$post_id.'.ics';
		////GOOGLE URL//
		$google_url = "http://www.google.com/calendar/event?action=TEMPLATE";
		$google_url .= "&text=".$post_title;
		if (isset($event_start_time) && isset($event_end_time)) { 
			$google_url .= "&dates=".$start_year.$start_month.$start_day."T".$event_start_time[0].$event_start_time[1]."00/".$end_year.$end_month.$end_day."T".$event_end_time[0].$event_end_time[1]."00"; 
			//$google_url .= "&dates=".$start_year.$start_month.$start_day."T".$event_start_time[0].$event_start_time[1]."00Z/".$end_year.$end_month.$end_day."T".$event_end_time[0].$event_end_time[1]."00Z"; 
		} else { 
			$google_url .= "&dates=".$start_year.$start_month.$start_day."/".$end_year.$end_month.$end_day; 
		}
		$google_url .= "&sprop=website:".$siteurl;
		$google_url .= "&details=".strip_tags($cal_post->post_excerpt);
		if (isset($location)) { $google_url .= "&location=".$location; } else { $google_url .= "&location=Unknown"; }
		$google_url .= "&trp=true";
		$output['google'] = $google_url;
		////YAHOO URL///
		$yahoo_url = "http://calendar.yahoo.com/?v=60&view=d&type=20";
		$yahoo_url .= "&title=".str_replace(' ','+',$post_title);
		if (isset($event_start_time)) 
		{ 
			$yahoo_url .= "&st=".$start_year.$start_month.$start_day."T".$event_start_time[0].$event_start_time[1]."00"; 
		}
		else
		{ 
			$yahoo_url .= "&st=".$start_year.$start_month.$start_day;
		}
		if(isset($event_end_time))
		{
			//$yahoo_url .= "&dur=".$event_start_time[0].$event_start_time[1];
		}
		$yahoo_url .= "&desc=".__('For+details,+link+').get_permalink($post_id).' - '.str_replace(' ','+',strip_tags($cal_post->post_excerpt));
		$yahoo_url .= "&in_loc=".str_replace(' ','+',$location);
		$output['yahoo'] = $yahoo_url;
	}
	return $output;
} 

?>