<?php

	/*
	*	Gekko - Open Source Web Development Framework
	*	------------------------------------------------------------------------
	*	Copyright (C) 2004-2006, J. Carlos Nieto <xiam@users.sourceforge.net>
	*	This program is Free Software.
	*
	*	@package	Gekko
	*	@license	http://www.gnu.org/copyleft/gpl.html GNU/GPL License 2.0
	*	@author		J. Carlos Nieto <xiam@users.sourceforge.net>
	*	@link		http://www.gekkoware.org
	*/

	if (!defined("IN-GEKKO")) die("Get a life!");

	/*
		$cal = new Calendar(8, 2005);
		$cal->set_html(5, "<a href=\"#\">5</a>");
		echo $cal->make();
	*/

	class Calendar {
		var $month, $year, $month_days;
		var $day = Array();
		function Calendar($month, $year) {
			$this->month = $month;
			$this->year = $year;
			$this->month_days = date("t", mktime(0, 0, 0, $month, 1, $year));
			for ($i = 1; $i <= $this->month_days; $i++) {
				$this->day[$i] = "";
			}
		}
		function set_html($day, $html) {
			$this->day[$day] = $html;
		}
		function get_html($day) {
			return $this->day[$day];
		}
		function make_day($day) {
			if (isset($this->day[$day])) {
				return $this->day[$day] ? $this->day[$day] : $day;
			}
			return false;
		}
		function make() {

			/* 0 = sunday, 6 = saturday */
			$first = mktime(0, 0, 0, $this->month, 1, $this->year);
			$month_starts = date("w", $first);

			$html = "<table class=\"calendar\">\n";
			$html .= "<tr class=\"head\"><td colspan=\"7\">".htmlentities(ucfirst(strftime("%B %G", $first)))."</td></tr>";

			$head = $body = "";
			$capt = false;
			/* week */

			for ($i = $w = 0; $i <= $this->month_days; $w++) {
				/* week starts */
				if (!($w%7)) $body .= "<tr>";
				/* beggining of the month */
				if (!$i && $w == $month_starts) $i = 1;

				/* normal day */
				$body .= "<td>".($i ? $this->make_day($i) : "")."</td>";

				/* caching day names */
				if ($i) {
					if (!$capt) {
						$wd = strtoupper(substr(strftime("%a", mktime(0,0,0,$this->month,$i,$this->year)), 0, 1));

						if (!$head) {
							if (!($w%7)) {
								$head .= "<td>".$wd."</td>";
							}
						} else {
							if ($w%7 == 6) {
								$capt = true;
							}
							$head .= "<td>".$wd."</td>";
						}
					}
					$i++;
				}

				/* week ends */
				if ($w%7 == 6) $body .= "</tr>\n";
			}
			if ($w%7) {
				//$body .= str_repeat("	<td></td>\n", (7-($w%7)));
				$body .= "</tr>\n";
			}

			$head = "<tr class=\"head\">$head</tr>";

			$html .= $head.$body;

			$html .= "</table>\n";
			return $html;
		}

	}

?>