<?


function generate_calendar($year, $month, $days = array(), $day_name_length = 3, $month_href = NULL, $first_day = 0, $pn = array()) {
	$first_of_month = gmmktime(0,0,0,$month,1,$year);

	$day_names = array();
	for($n=0,$t=(3+$first_day)*86400; $n<7; $n++,$t+=86400) {
	 $day_names[$n] = ucfirst(gmstrftime("%A",$t));
	}

	list($month, $year, $month_name, $weekday) = explode(",",gmstrftime("%m,%Y,%B,%w",$first_of_month));
	$weekday = ($weekday + 7 - $first_day) % 7;
	$title = htmlentities(ucfirst($month_name))."&nbsp;$year";

	@list($p, $pl) = each($pn); 
	@list($n, $nl) = each($pn);
	if($p) { 
	 $prev = "<span class='calendar-prev'>";
	 if($pl) { $prev .= "<a href='".htmlspecialchars($pl)."'>$p</a>"; } else { $prev .= "$p"; }
	 $prev .= "</span>&nbsp;"; 
	}
	if($n) { 
	 $next = "&nbsp;<span class='calendar-next'>";
	 if($nl) { $next .= "<a href='".htmlspecialchars($nl)."'>$n</a>"; } else { $next .= "$n"; }
	 $next .= "</span>";
	}

	$calendar = "
	 <table class='calendar'>
	 <caption class='calendar-month'>$prev <a href='".htmlspecialchars($month_href)."'>$title</a> $next</caption>
	 <tr>
	";

	if($day_name_length) {
	 foreach($day_names as $d) {
	  $calendar .= "<th abbr='".htmlentities($d)."'>".htmlentities(substr($d,0,$day_name_length))."</th>";
	 }
	 $calendar .= "</tr><tr>";
	}

	if($weekday > 0) { $calendar .= "<td colspan='".$weekday."'>&nbsp;</td>"; }

	for($day=1,$days_in_month=gmdate('t',$first_of_month); $day<=$days_in_month; $day++,$weekday++) {
	 if($weekday == 7) {
	  $weekday = 0;
	  $calendar .= "</tr>\n<tr>";
	 }
	 if(isset($days[$day]) & is_array($days[$day])) {
	  @list($link, $classes, $content) = $days[$day];
	  if(is_null($content)) { $content = $day; }
	  $calendar .= "<td";
          if($classes) { $calendar .= " class='".htmlspecialchars($classes)."'>"; } else { $calendar .= ">"; }
	  if($link) { $calendar .= "<a href='".htmlspecialchars($link)."'>$content</a>"; } else { $calendar .= "$content"; }
	  $calendar .= "</td>";
	 } else {
	  $calendar .= "<td>$day</td>";
	 }
	}
	
	if($weekday != 7) { $calendar .= "<td colspan='".(7-$weekday)."'>&nbsp;</td>"; }

	return $calendar."</tr>\n</table>\n";
}



?>