<?php
require_once(WPPersian::file_path('/inc/jalali-core.php'));
//require_once(WPPersian::file_path('/inc/widgets-core.php'));
/*
wp_get_jarchives
*/
function wp_get_jarchives($args = '') 
{
	JArchive::Monthly($args);
/*
	parse_str($args, $r);
	if (!isset($r['type'])) $r['type'] = '';
	if (!isset($r['limit'])) $r['limit'] = '';
	if (!isset($r['format'])) $r['format'] = 'html';
	if (!isset($r['before'])) $r['before'] = '';
	if (!isset($r['after'])) $r['after'] = '';
	if (!isset($r['show_post_count'])) $r['show_post_count'] = false;
	//_wpp_get_jarchives($r['type'], $r['limit'], $r['format'], $r['before'], $r['after'], $r['show_post_count']);
	_wpp_get_monthly_archives( $r['limit'], $r['format'], $r['before'], $r['after'], $r['show_post_count']);
	*/
}


/*
Jalali Date function by Milad Rastian (miladmovie AT yahoo DOT com)
jdf.farsiprojects.com
*/
function jdate($type,$maket="now",$forcelatinnums=false)
{
	$result="";
	if($maket=="now"){
		$year=date("Y");
		$month=date("m");
		$day=date("d");
		list( $jyear, $jmonth, $jday ) = gregorian_to_jalali($year, $month, $day);
		$maket=jmaketime(date("h")+_JDF_TZhours,date("i")+_JDF_TZminute,date("s"),$jmonth,$jday,$jyear);
	}else{
		$maket+=_JDF_TZhours*3600+_JDF_TZminute*60;
		$date=date("Y-m-d",$maket);
		list( $year, $month, $day ) = preg_split ( '/-/', $date );

		list( $jyear, $jmonth, $jday ) = gregorian_to_jalali($year, $month, $day);
	}

	$need= $maket;
	$year=date("Y",$need);
	$month=date("m",$need);
	$day=date("d",$need);
	$i=0;
	$skipnext = false;
	while($i<strlen($type))
	{
		$subtype=substr($type,$i,1);
		
		if ($skipnext) {
			$result .= $subtype;
			$skipnext = false;
			$i++;
			continue;
		}	
		
		
		switch ($subtype)
		{
			case "A":
				$result1=date("a",$need);
				if($result1=="pm") 
					$result.=_JDF_PM_LONG;
				else 
					$result.=_JDF_AM_LONG;
				break;

			case "a":
				$result1=date("a",$need);
				if($result1=="pm") 
					$result.=_JDF_PM_SHORT;
				else 
					$result.=_JDF_AM_SHORT;
				break;
			
			case "d":
				list( $jyear, $jmonth, $jday ) = gregorian_to_jalali($year, $month, $day);
				if($jday<10)
					$result1="0".$jday;
				else
					$result1=$jday;
				
				$result.=$result1;
				break;
			
			case "D":
				$result1=date("D",$need);
				if($result1=="Sat") $result1=_JDF_Sat_SHORT;
				else if($result1=="Sun") $result1=_JDF_Sun_SHORT;
				else if($result1=="Mon") $result1=_JDF_Mon_SHORT;
				else if($result1=="Tue") $result1=_JDF_Tue_SHORT;
				else if($result1=="Wed") $result1=_JDF_Wed_SHORT;
				else if($result1=="Thu") $result1=_JDF_Thu_SHORT;
				else if($result1=="Fri") $result1=_JDF_Fri_SHORT;
				$result.=$result1;
				break;
			
			case"F":
				list( $jyear, $jmonth, $jday ) = gregorian_to_jalali($year, $month, $day);
				$result.=jmonthname($jmonth);
				break;
			
			case "g":
				$result1=date("g",$need);
				$result.=$result1;
				break;
			
			case "G":
				$result1=date("G",$need);
				$result.=$result1;
				break;
			
			case "h":
				$result1=date("h",$need);
				$result.=$result1;
				break;
			
			case "H":
				$result1=date("H",$need);
				$result.=$result1;
				break;	
			
			case "i":
				$result1=date("i",$need);
				$result.=$result1;
				break;
			
			case "j":
				list( $jyear, $jmonth, $jday ) = gregorian_to_jalali($year, $month, $day);
				$result1=$jday;
				$result.=$result1;
				break;
			
			case "l":
				$result1=date("l",$need);
				if($result1=="Saturday") $result1=_JDF_Sat_LONG;
				else if($result1=="Sunday") $result1=_JDF_Sun_LONG;
				else if($result1=="Monday") $result1=_JDF_Mon_LONG;
				else if($result1=="Tuesday") $result1=_JDF_Tue_LONG;
				else if($result1=="Wednesday") $result1=_JDF_Wed_LONG;
				else if($result1=="Thursday") $result1=_JDF_Thu_LONG;
				else if($result1=="Friday") $result1=_JDF_Fri_LONG;
				$result.=$result1;
				break;
			
			case "m":
				list( $jyear, $jmonth, $jday ) = gregorian_to_jalali($year, $month, $day);
				if($jmonth<10) 
					$result1="0".$jmonth;
				else	
					$result1=$jmonth;
				$result.=$result1;
				break;
			
			case "M":
				list( $jyear, $jmonth, $jday ) = gregorian_to_jalali($year, $month, $day);
				$result.=jmonthname($jmonth);
				break;
			
			case "n":
				list( $jyear, $jmonth, $jday ) = gregorian_to_jalali($year, $month, $day);
				$result1=$jmonth;
				$result.=$result1;
				break;
			
			case "s":
				$result1=date("s",$need);
				$result.=$result1;
				break;
			
			case "S":
				$result.=_JDF_Suffix;
				break;
			
			case "t":
				$result.=lastday ($month,$day,$year);
				break;
			
			case "w":
				$result1=date("w",$need);
				$result.=$result1;
				break;
			
			case "y":
				list( $jyear, $jmonth, $jday ) = gregorian_to_jalali($year, $month, $day);
				$result1=substr($jyear,2,4);
				$result.=$result1;
				break;
			
			case "Y":
				list( $jyear, $jmonth, $jday ) = gregorian_to_jalali($year, $month, $day);
				$result1=$jyear;
				$result.=$result1;
				break;
			
			case "\\":
				$result.='';
				$skipnext = true;
				break;
										
			default:
				$result.=$subtype;
		}
		$i++;
	}
	
	//$mps_jd_optionsDB = get_option(MPS_JD_OPTIONS_NAME);
	//$mps_jd_farsinum_date = $mps_jd_optionsDB['mps_jd_farsinum_date'];
	
	//if ((!$forcelatinnums) && ($mps_jd_farsinum_date))
		//$result = farsi_num($result);
	
	return $result;
}

/*
get_jcalendar
*/
function get_jcalendar()
{
	global $wpdb, $m, $monthnum, $year, $timedifference, $month, $day,  $posts;
	
	if (!$posts) {
		$gotsome = $wpdb->get_var("SELECT ID from $wpdb->posts WHERE post_type='post' AND post_status = 'publish' ORDER BY post_date DESC LIMIT 1");
		if (!$gotsome) return;
	}

	$week_begins = intval(get_option('start_of_week'));
	$add_hours = intval(get_option('gmt_offset'));
	$add_minutes = intval(60 * (get_option('gmt_offset') - $add_hours));

	$input_is_gregorian = false;

	if (!empty($monthnum) && !empty($year)) {
		$thismonth = ''.zeroise(intval($monthnum), 2);
		$thisyear = ''.intval($year);
	}  elseif (!empty($m)) {
		$calendar = substr($m, 0, 6);
		$thisyear = ''.intval(substr($m, 0, 4));
		if (strlen($m) < 6) {
			$thismonth = '01';
		} else {
			$thismonth = ''.zeroise(intval(substr($m, 4, 2)), 2);
		}
	} else {
		$input_is_gregorian = true;
		$thisyear = gmdate('Y', current_time('timestamp') + get_option('gmt_offset') * 3600);
		$thismonth = gmdate('m', current_time('timestamp') + get_option('gmt_offset') * 3600);
		$thisday = gmdate('d', current_time('timestamp') + get_option('gmt_offset') * 3600);
	}

	if ($input_is_gregorian) {
		list($jthisyear,$jthismonth,$jthisday) = gregorian_to_jalali($thisyear,$thismonth,$thisday);
		$unixmonth = jmaketime(0, 0 , 0, $jthismonth, 1, $jthisyear);
	} else {
		$unixmonth = jmaketime(0, 0 , 0, $thismonth, 1, $thisyear);
		$jthisyear = $thisyear;
		$jthismonth = $thismonth;

	}

	$jnextmonth = $jthismonth + 1;
	$jnextyear = $jthisyear;
	if ($jnextmonth > 12) {
		$jnextmonth = 1;
		$jnextyear++;
	}
	//This is so important to change the table dir to RTL and keep it
	echo '<table id="wp-calendar" style="direction: rtl">
    <caption>' . jmonthname((int) $jthismonth ) . ' ' . jdate('Y', $unixmonth) . '</caption>
    <thead>
    <tr>';

	$day_abbrev = $weekday_initial;

	$myweek = array();

	for ($wdcount=0; $wdcount<=6; $wdcount++) {
		$myweek[]=jdayshortname(($wdcount+$week_begins)%7);
	}

	foreach ($myweek as $wd) {
		echo "\n\t\t<th abbr=\"$wd\" scope=\"col\" title=\"$wd\">" . $wd . '</th>';
	}

	echo '
    </tr>
    </thead>
	
    <tfoot>
    <tr>';
	$g_startdate = date("Y:m:d H:i:s",jmaketime(0,0,0,$jthismonth,1,$jthisyear));
	$g_enddate = date("Y:m:d H:i:s",jmaketime(0,0,0,$jnextmonth,1,$jnextyear));
	$prev = $wpdb->get_results("SELECT count(id) AS prev FROM $wpdb->posts
    								WHERE post_type='post'
    								AND post_date < '$g_startdate'
    								AND post_status = 'publish'
    								AND post_date < '" . current_time('mysql') . '\'', ARRAY_N);

	$next = $wpdb->get_results("SELECT count(id) AS next FROM $wpdb->posts
    								WHERE post_type='post'
    								AND post_date > '$g_enddate'
    								AND post_status = 'publish'
    								AND post_date < '" . current_time('mysql') . '\'', ARRAY_N);
	if ($prev[0][0] != 0) $is_prev = true; else $is_prev = false;
	if ($next[0][0] != 0) $is_next = true; else $is_next = false;

	$previous_month=0;
	if ($is_prev) {
		$previous_month = $jthismonth - 1;
		$previous_year = $jthisyear;
		if ($previous_month == 0) {
			$previous_month = 12;
			$previous_year --;
		}
	}
	if ($is_next) {
		$next_month = $jthismonth + 1;
		$next_year = $jthisyear;
		if ($next_month == 13) {
			$next_month = 1;
			$next_year ++;
		}
	}

	if ($is_prev) {
		echo "\n\t\t".'<td abbr="' . jmonthname(previous_month) . '" colspan="3" id="prev"><a href="' .
		get_month_link($previous_year, $previous_month) . '" title="' . sprintf(__('View posts for %1$s %2$s','wp-persian'), jmonthname($previous_month), jdate('Y', jmaketime(0, 0 , 0, $previous_month, 1, $previous_year))) . '">&laquo; ' . jmonthname($previous_month) . '</a></td>';
	} else {
		echo "\n\t\t".'<td colspan="3" id="prev" class="pad">&nbsp;</td>';
	}


	echo "\n\t\t".'<td class="pad">&nbsp;</td>';

	if ($is_next) {
		echo "\n\t\t".'<td abbr="' . jmonthname($next_month) . '" colspan="3" id="next"><a href="' .
		get_month_link($next_year, $next_month) . '" title="View posts for ' . jmonthname($next_month) . ' ' .
		jdate('Y', jmaketime(0, 0 , 0, $next_month, 1, $next_year)) . '">' . jmonthname($next_month) . ' &raquo;</a></td>';
	} else {
		echo "\n\t\t".'<td colspan="3" id="next" class="pad">&nbsp;</td>';
	}

	echo '
    </tr>
    </tfoot>

    <tbody>
    <tr>';

	$dayswithposts = $wpdb->get_results("SELECT DISTINCT DAYOFMONTH(post_date),MONTH(post_date),YEAR(post_date)
            FROM $wpdb->posts 
        	WHERE post_type='post' 
            AND post_date > '$g_startdate' AND post_date < '$g_enddate'
            AND post_status = 'publish'
            AND post_date < '" . current_time('mysql') . '\'', ARRAY_N);
	if ($dayswithposts) {
		foreach ($dayswithposts as $daywith) {
			//$daywithpost[] = $daywith[0];
			$daywithpost[] = jdate("j",mktime(0,0,0,$daywith[1],$daywith[0],$daywith[2]),true);
		}
	} else {
		$daywithpost = array();
	}

	if (strstr($_SERVER['HTTP_USER_AGENT'], 'MSIE') ||
	strstr(strtolower($_SERVER['HTTP_USER_AGENT']), 'camino') ||
	strstr(strtolower($_SERVER['HTTP_USER_AGENT']), 'safari')) {
		$ak_title_separator = "\n";
	} else {
		$ak_title_separator = ', ';
	}

	$ak_titles_for_day = array();
	$ak_post_titles = $wpdb->get_results(
	"SELECT post_title, DAYOFMONTH(post_date) as dom, MONTH(post_date) as month, YEAR(post_date) as year "
	."FROM $wpdb->posts "
	."WHERE post_type='post' AND post_date > '$g_startdate' AND post_date < '$g_enddate' "
	."AND 1=1 "
	."AND post_date < '".current_time('mysql')."' "
	."AND post_status = 'publish'"
	);



	if ($ak_post_titles) {
		$i = 0;
		while ($ak_post_titles[$i]){
			$ak_post_titles[$i] -> dom = jdate("j",mktime(0,0,0,$ak_post_titles[$i] ->month,$ak_post_titles[$i] ->dom,$ak_post_titles[$i] ->year),true);
			$i++;
		}
		foreach ($ak_post_titles as $ak_post_title) {
			if (empty($ak_titles_for_day['day_'.$ak_post_title->dom])) {
				$ak_titles_for_day['day_'.$ak_post_title->dom] = '';
			}
			if (empty($ak_titles_for_day["$ak_post_title->dom"])) { // first one
			$ak_titles_for_day["$ak_post_title->dom"] = str_replace('"', '&quot;', wptexturize($ak_post_title->post_title));
			} else {
				$ak_titles_for_day["$ak_post_title->dom"] .= $ak_title_separator . str_replace('"', '&quot;', wptexturize($ak_post_title->post_title));
			}
		}
	}

	// See how much we should pad in the beginning
	$pad = calendar_week_mod(jdate('w', $unixmonth,true)-$week_begins);
	if (0 != $pad) echo "\n\t\t".'<td colspan="'.$pad.'" class="pad">&nbsp;</td>';

	$daysinmonth = intval(jdate('t', $unixmonth,true));
	for ($day = 1; $day <= $daysinmonth; ++$day) {
		list($thiyear,$thismonth,$thisday) = jalali_to_gregorian($jthisyear,$jthismonth,$day);
		if (isset($newrow) && $newrow)
		echo "\n\t</tr>\n\t<tr>\n\t\t";
		$newrow = false;
		if ($thisday == gmdate('j', (time() + (get_option('gmt_offset') * 3600))) && $thismonth == gmdate('m', time()+(get_option('gmt_offset') * 3600)) && $thisyear == gmdate('Y', time()+(get_option('gmt_offset') * 3600)))
		echo '<td id="today">';
		else
		echo '<td>';
		
		$day_text = WPPersian::PersianNumbers($day);

				
		if (in_array($day, $daywithpost)) { // any posts today?
		echo '<a href="' . get_day_link($jthisyear, $jthismonth, $day) . "\" title=\"$ak_titles_for_day[$day]\">$day_text</a>";
		} else {
			echo $day_text;
		}
		echo '</td>';

		if (6 == calendar_week_mod(date('w', jmaketime(0, 0 , 0, $jthismonth, $day, $jthisyear))-$week_begins))
		$newrow = true;
	}

	$pad = 7 - calendar_week_mod(date('w', jmaketime(0, 0 , 0, $jthismonth, $day, $jthisyear))-$week_begins);
	if ($pad != 0 && $pad != 7)
	echo "\n\t\t".'<td class="pad" colspan="'.$pad.'">&nbsp;</td>';

	echo "\n\t</tr>\n\t</tbody>\n\t</table>";

}


?>