<?php
/* $Id: calendar_all.php,v 1.8 2006/02/05 16:28:29 leyeti Exp $ */
error_reporting  (E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
$myEnv["module"] = "calendar";
$myEnv["output"] = "html";

header('P3P: CP="NOI ADM DEV PSAi COM NAV OUR OTRo STP IND DEM"'); //MSIE6 P3P header

include("../../config.inc.php");
include(INCLUDEPATH . "container.inc.php");

// adding file revision into global array
if(function_exists("revisionInit")) revisionInit("\$Revision: 1.8 $", __FILE__);


//// NATYS //// Date langage :
include(CAL1_INC_DIR."date_lang.php");
$_SESSION["date_lang"] = array ("language" => $_SESSION["MGW"]->spkz,
								"lang_dir" => CAL1_DIR."lang/"
								);
///////////////


// ===================================
// step one month back in calendar
// ===================================
if (isset($_GET['action']) && $_GET['action']=="mback") {
	if ($_SESSION['calendar_month'] == 1) {
		$_SESSION['calendar_month'] = 12;
		$_SESSION['calendar_year']--;
	} else {
		$_SESSION['calendar_month']--;
	}
	 unset($_GET['action']);
}

// ===================================
// step one month forward in calendar
// ===================================
if (IsSet($_GET['action']) && $_GET['action']=="mforw") {
	if ($_SESSION['calendar_month'] == 12) {
		$_SESSION['calendar_month'] = 1;
		$_SESSION['calendar_year']++;
	} else {
		$_SESSION['calendar_month']++;
	}
	unset($_GET['action']);
}

// ===================================
// step one year back in calendar
// ===================================
if (IsSet($_GET['action']) && $_GET['action']=="yback") {
	$_SESSION['calendar_year']--;
	unset($_GET['action']);
}

// ===================================
// step one year forward in calendar
// ===================================
if (IsSet($_GET['action']) && $_GET['action']=="yforw") {
	$_SESSION['calendar_year']++;
	unset($_GET['action']);
}

// ---------------------------------------------
// set date to actual timestamp if not set
// ---------------------------------------------
$date_str = isset($_GET["date_str"]) ? $_GET["date_str"] : (isset($_POST["date_str"]) ? $_POST["date_str"] : ""); 
$date = $date_str != "" ? $date_str : (isset($_GET["date"]) ? $_GET["date"] : (isset($_POST["date"]) ? $_POST["date"] : "")); 
$datum = $date != "" ? mktime(0,0,0,substr($date,2,2),substr($date,0,2),substr($date,4,4)) : time(); 	


// ---------------------------------------------
// making an array of participants ids
// ---------------------------------------------
if (isset($_GET["parts"])) {
$participants = explode(".",$_GET["parts"]); 
//$participants[] = $_SESSION["MGW"]->userid;    
}
else if (isset($_POST["parts"])) {
$participants = $_POST["parts"];
}
else {
$participants[] = $_SESSION["MGW"]->userid;
}

if ($participants == array("all") || $participants == "all") {
    //fill array with all people :
	$participants = array();
	$sql = "SELECT id FROM mgw_users WHERE NOT(level=".UDELETED.")";
	if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
	while($row = $res->FetchRow()){
		$participants [] = $row["id"];	
	}
}
else if (sizeof($participants)==1) { // if only one part -> go to normal dayview
		$sql = "SELECT id, ".$conn->Concat("firstname", "' '", "lastname")." AS name FROM mgw_users WHERE NOT(level=".UDELETED.") AND id = ".(int)$participants[0];
		if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
		$row = $res->FetchRow();
		$_SESSION['calendarid'] = (int)$participants[0];	// Owner - ID of calendar
		$_SESSION['calendarname'] = $row["name"];	// Owner - Name of calendar
         redirect("index.php?date=$datum&".SID);
     }

// ---------------------------------------------
// position of uid in timesheet
// ---------------------------------------------
$uids = Array(); 
	

// ---------------------------------------------
// making where clausule for all participants
// ---------------------------------------------
$where 	= "";
$whereid 	= "";
for($i=0; $i<count($participants); $i++) {
	$where = $where." userid=".$participants[$i]." OR";
	$whereid = $whereid." id=".$participants[$i]." OR";
	$timesheet[$participants[$i]] = array(); //preparing array for future use
	$uids[$i] = $participants[$i];
}
$where = substr($where,0,-3);
$whereid = substr($whereid,0,-3);

// ---------------------------------------------
// getting calendar settings
// ---------------------------------------------
$intval = $_SESSION["MGW"]->settings["calendar_interval"];			// calender interval length in minutes
$min = $_SESSION["MGW"]->settings["calendar_viewfrom"];			// start hour of day-view
$max = $_SESSION["MGW"]->settings["calendar_viewto"];			// last  hour of day-view

// ------------------------------------------
// number of table columns
// ------------------------------------------
$num_of_cells = ($max-$min)/$intval*60;
$smarty->assign("num_of_cells", $num_of_cells+1);
$cols_grp = 60/$intval;
$smarty->assign("col_grp", $cols_grp);
	
// ---------------------------------------------
// creating empty table for selected Participants
// ---------------------------------------------
$sql = "SELECT lastname, firstname, id FROM mgw_users WHERE NOT(level=".UDELETED.") AND ".$whereid." ORDER BY firstname";
if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
	
for ($t=0; $t<$num_of_cells; $t++) {
	$cur_time = mktime($min, $t*$intval, 0, date("m", $datum), date("d", $datum), date("Y", $datum));
	$col_arr_hd[] = array(
		"time" => date("H:i", $cur_time),
		"hour" => date("H", $cur_time),
		"mins" => date("i", $cur_time)
	);
	$col_arr_std[date("H:i", $cur_time)] = 0;
} 
		
$ts_hd[] = array(
	"id"    => 0,
	"name"  => Lang::getLanguageString("gentemp_people_list"),
	"dates" => $col_arr_hd
);
                	  	
while ($row = $res->FetchRow()) {
	$timesheet[$row['id']][0] = $row['firstname']." ".$row['lastname'];
	$ts[] = array(
		"id"    => $row['id'],
		"name"  => $row['firstname']." ".$row['lastname'],
		"dates" => NULL
	);
} 

	
// ---------------------------------------------
// creating timetable for selected Participants
// ---------------------------------------------
$sql = "SELECT date, a.id, a.userid, a.duration, b.firstname, b.lastname 
	FROM  mgw_users b LEFT OUTER JOIN mgw_calendar a ON a.userid = b.id
	WHERE (".$where.") 
	AND date>".$conn->DBTimeStamp(mktime(0,0,0,date("m",$datum),date("d",$datum),date("Y",$datum)))."
	AND date<".$conn->DBTimeStamp(mktime(23,59,59,date("m",$datum),date("d",$datum),date("Y",$datum)))."
	AND a.id_class!='3' AND
	NOT(b.level=".UDELETED.")  
	ORDER BY a.userid, date";
	
if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
	
$old_user=0;
$tab_appt_id = array();
$tmp_tab_appt_id = array();
while ($row = $res->FetchRow()) {
	// ---------------------------------------------
	// initializing timetable for new participant
	// ---------------------------------------------
	if ($old_user != $row['userid']) {
		if ($old_user != 0) {
			$col_arr_new[$old_user] =  $col_arr_loc;
			$tab_appt_id[$old_user] = $tmp_tab_appt_id;
		}
		$col_arr_loc  = $col_arr_std;
	}	
			
	$cur_time_loc = $res->UnixTimeStamp($row['date']);
	$dur = ceil($row['duration']/$intval);
	$locmin = mktime(0,0,0, date("m", $datum), date("d", $datum), date("Y", $datum)) + $min * 3600;
	 		
	//echo $dur . " "; echo date("d.m.Y H:I", $cur_time_loc);
	// ---------------------------------------------
	// Marking appointment
	// ---------------------------------------------
	for ($i=0;$i<$dur;$i++){
		$tmp_time = mktime(date("H", $cur_time_loc), $i*$intval + date("i", $cur_time_loc), 0, date("m", $datum), date("d", $datum), date("Y", $datum)); 
		 		
		// ---------------------------------------------
		// Check, wether key exists in timetable
		// ---------------------------------------------
		
		if (!isset($col_arr_std[date("H:i", $tmp_time)])){
			// ---------------------------------------------
			// get greatest key smaller than appointment
			// ---------------------------------------------
			reset($col_arr_std);
			$key_arr = array_keys($col_arr_std);
			for ($j=1;$j<=sizeof($key_arr); $j++) {
				if ($key_arr[$j-1] <= date("H:i", $tmp_time) && $key_arr[$j]   > date("H:i", $tmp_time)) {
					$col_arr_loc[$key_arr[$j-1]] = 1;
					$tmp_tab_appt_id[$key_arr[$j-1]]= $row["id"];
				}
			}
		} else {
			$col_arr_loc[date("H:i", $tmp_time)] = 1;
			$tmp_tab_appt_id[date("H:i", $tmp_time)]= $row["id"];
		}
	}	
	$old_user = $row['userid']; 	

	
}
	
if ($old_user > 0) {
	$col_arr_new[$old_user] =  $col_arr_loc;
	$tab_appt_id[$old_user] = $tmp_tab_appt_id;
}
	
// ---------------------------------------------
// changing format of timesheet entry
// ---------------------------------------------
while(list($key, $val) = each($ts)) { 
	if (isset($col_arr_new[$val["id"]])) {
		$tmp_cpl = NULL;
		$old_apptid = -1;
		$old_userid = -1;
		while( list($nkey,$nval) = each($col_arr_new[$val["id"]])) {
		
			if($nval == "1") {
				$apptid = $tab_appt_id[$val["id"]][$nkey];
				$userid = $val["id"];
				
				/*echo "nkey:".$nkey." : val ".print_r($nval,TRUE)."<br>";
				print_r($tab_appt_id);
				print_r($col_arr_new);
				echo "<br>";
				echo $apptid."<br>".$userid."<br><br>";
				*/
				$sql = "SELECT * 
						FROM  mgw_calendar
						WHERE id='$apptid' AND userid='$userid'";
				if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
				
				$row = $res->FetchRow();
				
				
				// get type and color of appointment
					$appt_type_id = $row["id_appt_type"]; 
					$sql_appt_type = "SELECT * FROM mgw_calendar_appt_type WHERE id='$appt_type_id'";
					if(!$res_appt_type = $conn->Execute($sql_appt_type)) exit(showSQLerror($sql_appt_type, $conn->ErrorMsg(), __LINE__, __FILE__));
					$row_appt_type = $res_appt_type->FetchRow();
					$appt_type = Lang::getLanguageString("gentemp_".$row_appt_type["type"]);
					$bgcolor = $row_appt_type["color"];
						
						
					$id_class = $row["id_class"];
					if ($id_class!=2) {
					    // appointment is subjected or on standby:
						$sql_class = "SELECT * FROM mgw_calendar_class WHERE id=$id_class";
						if(!$res_class = $conn->Execute($sql_class)) exit(showSQLerror($sql_class, $conn->ErrorMsg(), __LINE__, __FILE__));
						$row_class = $res_class->FetchRow();
						$appt_type = $appt_type."&nbsp;:<BR>".Lang::getLanguageString("class_".$row_class["class"]);
						$bgcolor = $row_class["color"];
					}
								 
				
				if ($old_apptid == $apptid && $old_userid == $userid ) {
				    $display = 0;
					$private ="";
					$subject_summ ="";
					$location_text ="";
					$available ="";
					$avail_text ="";
				}
				else {
					$old_apptid = $apptid;
					$old_userid = $userid;
					$display = 1;
				
				// get privacy
				   	$private = $row["private"];
				// get subject_summ
					$subject_summ = str_decode($row["subject_summ"]);
				// get location type / location
					$id_loc = $row["id_location_type"];
					$sql_loc = "SELECT * FROM mgw_calendar_location_type WHERE id=$id_loc";
					if(!$res_loc = $conn->Execute($sql_loc)) exit(showSQLerror($sql_loc, $conn->ErrorMsg(), __LINE__, __FILE__));
					$row_loc = $res_loc->FetchRow();
					$location_type = Lang::getLanguageString("gentemp_".$row_loc["location_type"]);
					
					$location_text = $location_type.($row["location"]!="" ? ":&nbsp;".str_decode($row["location"]) : "");
				// get availability
					if($row["availability"]=="1") {
						$available = 1;
						$avail_text = Lang::getLanguageString("gentemp_can_be_disturbed").".&nbsp;".($row["telephone"]!="" ? Lang::getLanguageString("gentemp_telephone").":&nbsp;".str_decode($row["telephone"]) : "" );
					}
					else {
						$available = 0;
						$avail_text = Lang::getLanguageString("gentemp_can_not_be_disturbed");
					}
					
				} //end if old_appt==new_appt
			}
			else {
				$appt_type ="";
				$bgcolor ="";
				$private ="";
				$subject_summ ="";
				$location_text ="";
				$available ="";
				$avail_text ="";
				$display = 0;
			} // end if nval==1
			$tmp_cpl[] = array( "time" => $nkey, 
								"value" => $nval, // if =0 : no appt, else =1 : there is an appt
								"appt_type" => jsencode($appt_type),
								"bgcolor" => $bgcolor,
								"display" => $display,
								"private" => $private,
								"subject_summ" => jsencode($subject_summ),
								"location" => jsencode($location_text),
								"avail"		=> $available,
								"avail_text" => jsencode($avail_text)
								);
			//print_r($tmp_cpl);echo "<br>";
		}  	
	    	
		$ts_ergeb[] = array(
			"id"    => $val["id"],
			"name"    => $val["name"],
			"dates"    => $tmp_cpl
		);
	} else {   
		$tmp_cpl2 = NULL; 
		reset($col_arr_std);
		while(list($nkey,$nval) = each($col_arr_std)) {
			$tmp_cpl2[] = array( "time" => $nkey, "value" => $nval);
		}    
		$ts_ergeb[] = array(
			"id"    => $val["id"],
			"name"    => $val["name"],
			"dates"    => $tmp_cpl2
		);                	                 
	}				            
}

$smarty->assign("rows", $ts_ergeb);
$smarty->assign("rowhead", $ts_hd);
$smarty->assign("date", $date);

////////////////////////////////////////////////////////////////////////
// show user list as possible calendar owners
////////////////////////////////////////////////////////////////////////
include_once("inc/user_list.inc.php");

	$str_parts = implode(".",$participants);
// create monthview-calendar, based on $date
    $calendar = get_monthview_calendar_all( $datum, $_SESSION['calendar_year'], $_SESSION['calendar_month'],$str_parts);
/////////////

	$dfw =  str_pad( (date("d", $datum) + 1).date("m", $datum).date("Y", $datum),8,"0",STR_PAD_LEFT);
	$dbk =  str_pad( (date("d", $datum) - 1).date("m", $datum).date("Y", $datum),8,"0",STR_PAD_LEFT);
	
    // computation for assign variables
    $dayforward = "<a class=\"navlink\" href=\"calendar_all.php?date=$dfw&parts=$str_parts&".SID."\" style=\"text-decoration:none;\">". Lang::getLanguageString("temp_header_nav_forw"). " &gt;&gt;</a>";
    $dayback    = "<a class=\"navlink\" href=\"calendar_all.php?date=$dbk&parts=$str_parts&".SID."\" style=\"text-decoration:none;\">&lt;&lt; ".Lang::getLanguageString("temp_header_nav_back"). "</a>";
    $day_index  = "gentemp_weekday_" . (date("w", $datum) + 1);
    // NATYS //
	
	$text = Lang::getLanguageString("$day_index")."&nbsp; ".date_lang(Lang::getLanguageString("gentemp_date_format_php"), $datum)."&nbsp;";
    
    // assign variables to template
    $smarty->assign('month_calendar', 	$calendar);
    $smarty->assign("nav_links",	"$dayback");
    $smarty->assign("nav_rechts",	"$dayforward");
    $smarty->assign('header_date',	$text . " ".(isset($additionaltext) ? $additionaltext : ""));

//$smarty->assign("temp_title","titre");
//appt type legend :
$smarty->assign("appt_type_legend",get_appt_type_legend());
	
$smarty->display("calendar_all.tpl");


/****************************************************/

// ======================================================
// String get_monthview_static( timestamp date, Integer year, Integer, month)
//
// returns a HTML table representing a calendar month 
// liefert eine HTML-Tabelle zur Darstellung eines Kalendermonats
// ======================================================
function get_monthview_calendar_all($date, $year, $month, $str_parts){
	global $appconf, $conn, $calendarid;
	
	$today = date("Ymd", time());


	if ($_SESSION['calendarid']=="all") $sql_owner_part="";
	else $sql_owner_part="userid = ".$_SESSION['calendarid']." AND";

	$zeit = getdate($date);
	$day  = $zeit["mday"];						// Date im aktuellen Monat ?
	/// NATYS ///
	// no difference :
	/*
	if ($zeit["mon"] == $month  &&	$zeit["year"] == $year) {
		$header_class = "navlinkon"; // "stand";
	}	else {
		$header_class = "edit";
	}
	*/
	$header_class = "navlinkon";
	//// /NATYS ////
	
	// compute array for actual month holding the weekdays	
	$num_days = date("t",strtotime($month . "/1/". $year));

	$starts_at = 1; //0=su, 1=mo, ... from settings
	$trim_month = true; // from settings
	
	$days_before =  $starts_at-date("w",strtotime($month . "/1/". $year))+1;
	if($days_before>1) $days_before -= 7; 

	if($starts_at > 0) $ends_at = $starts_at - 1;
	else $ends_at = 6; 

	$days_after = $ends_at-date("w",strtotime("$month/$num_days/$year"));
	if($days_after < 0) $days_after += 7;

	$month_days = array();
	for($o=$days_before; $o<=$num_days+$days_after; $o++) {
		$day = array();
		$day["timestamp"] =  mktime(0,0,1,$month,$o,$year);
//		$day["sql_tag"] =  date("Ymd", $day["timestamp"]);
		$day["sql_tag"] =  $conn->DBTimeStamp($day["timestamp"]);
		$day["day_number"] =  date("j", $day["timestamp"]);
		$day["day_of_week"] =  date("w", $day["timestamp"]);

		$month_days[] = $day;
	}

    $mymonth = $month;
    if ($mymonth < 10 and strlen($mymonth) == 2) { $mymonth = substr($mymonth,1); }

	$date_str = str_pad( date("d", $date).date("m", $date).date("Y", $date),8,"0",STR_PAD_LEFT);
	
	// HTML-Tabelle Überschriften Monat / Jahr
	$out = "<table border=\"0\" width=\"180\" cellpadding=\"0\" cellspacing=\"0\">\n";
	$out .= "<tr><td class=\"lines\" width=\"1\" height=\"1\" colspan=\"10\"><img src=\"". $appconf["imgpathgeneral"] ."/space.gif\" alt=\"\" width=\"1\" height=\"1\" /></td></tr>";
	$out .= "<tr class=\"stand\" height=\"20\">";
	$out .= "	<td class=\"lines\" width=\"1\" height=\"1\"><img src=\"". $appconf["imgpathgeneral"] ."/space.gif\" alt=\"\" width=\"1\" height=\"1\" /></td>";
	$out .= "	<td class=\"subnavback\">&nbsp;<a class=\"$header_class\" href=\"calendar_all.php?action=mback&date=$date_str&parts=$str_parts&".SID."\" ><strong>&lt;&lt;&lt;</strong></a></td>";
	$out .= "	<td class=\"subnavback\" colspan=\"6\" align=\"center\">";
	$out .= "		<strong>".Lang::getLanguageString("gentemp_month_name_".$mymonth)."</strong>";
	$out .= "	</td>";
	$out .= "	<td class=\"subnavback\"><a class=\"$header_class\" href=\"calendar_all.php?action=mforw&date=$date_str&parts=$str_parts&".SID."\"> <strong>&gt;&gt;&gt;</strong></a>&nbsp;</td>";
	$out .= "	<td  class=\"lines\" width=\"1\" height=\"1\"><img src=\"". $appconf["imgpathgeneral"] ."/space.gif\" alt=\"\" width=\"1\" height=\"1\" /></td>";
	$out .= "</tr>\n";
	$out .= "<tr class=\"stand\" height=\"20\">";
	$out .= "	<td class=\"lines\" width=\"1\" height=\"1\"><img src=\"". $appconf["imgpathgeneral"] ."/space.gif\" alt=\"\" width=\"1\" height=\"1\" /></td>";
	$out .= "	<td class=\"subnavback\">&nbsp;<a class=\"$header_class\" href=\"calendar_all.php?action=yback&date=$date_str&parts=$str_parts&".SID."\"><strong>&lt;&lt;&lt;</strong></a></td>";
	$out .= "	<td class=\"subnavback\" colspan=\"6\" align=\"center\"><strong>$year</strong></td>";
	$out .= "	<td class=\"subnavback\"><a class=\"$header_class\" href=\"calendar_all.php?action=yforw&date=$date_str&parts=$str_parts&".SID."\"> <strong>&gt;&gt;&gt;</strong></a>&nbsp;</td>";
	$out .= "	<td class=\"lines\" width=\"1\" height=\"1\"><img src=\"". $appconf["imgpathgeneral"] ."/space.gif\" alt=\"\" width=\"1\" height=\"1\" /></td>";
	$out .= "</tr>\n";
	$out .= "<tr><td class=\"lines\" width=\"1\" height=\"1\" colspan=\"10\"><img src=\"". $appconf["imgpathgeneral"] ."/space.gif\" alt=\"\" width=\"1\" height=\"1\" /></td></tr>";

	$out .= "<tr class=\"stand\" height=\"20\">";
	$out .= "	<td class=\"lines\" width=\"1\" height=\"1\"><img src=\"". $appconf["imgpathgeneral"] ."/space.gif\" alt=\"\" width=\"1\" height=\"1\" /></td>";
	$out .= "	<td class=\"category\" align=\"center\">&nbsp;" . Lang::getLanguageString("calweek") . "&nbsp;</td>";

	for($i=$starts_at; $i<$starts_at+7; $i++) // prints names of days
		$out .= "<td class=\"category\" align=\"center\">&nbsp;". Lang::getLanguageString("temp_weekday_abbr_".$i%7) . "&nbsp;</td>";

	$out .="	<td class=\"lines\" width=\"1\" height=\"1\"><img src=\"". $appconf["imgpathgeneral"] ."/space.gif\" alt=\"\" width=\"1\" height=\"1\" /></td>
	</tr>\n";

	$out .= "<tr><td class=\"lines\" width=\"1\" height=\"1\" colspan=\"10\"><img src=\"". $appconf["imgpathgeneral"] ."/space.gif\" alt=\"\" width=\"1\" height=\"1\" /></td></tr>";
	
	for($i=0;$i<count($month_days);$i++) {
		// today
		$day_tag = date("Y",$month_days[$i]["timestamp"]).date("m",$month_days[$i]["timestamp"]).date("d",$month_days[$i]["timestamp"]);
		if($day_tag == $today) $klasse = "heute";
		//weekend
		elseif ($month_days[$i]["day_of_week"]==6 || $month_days[$i]["day_of_week"]==0) $klasse = "wochenende";
		//end of last/beginning of next month
		elseif ($i<(abs($days_before)+1) || $i>abs($days_before)+$num_days) $klasse = "tab";
		//holiday
		elseif (get_celebrate_days($month_days[$i]["timestamp"], $_SESSION["MGW"]->settings["calendar_holiday_system"]) != "") $klasse = "feiertag";
		//absolutely ordinary day :))
		else $klasse = "tab";

		if($i%7==0) {
			$out .= "<tr class=\"tab\"  height=20 bgcolor=\"#c8c9d4\">\n";
			$out .= "<td class=\"lines\" width=\"1\" height=\"1\"><img src=\"". $appconf["imgpathgeneral"] ."/space.gif\" alt=\"\" width=\"1\" height=\"1\" /></td>";
			$week_str = str_pad( date("d", $month_days[$i]["timestamp"]).date("m", $month_days[$i]["timestamp"]).date("Y", $month_days[$i]["timestamp"]),8,"0",STR_PAD_LEFT);		
			$out .= "<td bgcolor=\"#838899\" align=\"center\"><a class=\"subnavlink\" href=\"calendar_all.php?date=".$week_str."&parts=$str_parts&".SID."\">" . get_weeknumber($month_days[$i]["timestamp"]) . "</a></td>\n";
		}
		
//		if($trim_month &&)
//		$sqldate = $conn->DBTimeStamp(strtotime($month_days[$i]["sql_tag"]));
		$sqldate = $month_days[$i]["sql_tag"];
		$sqldate_end = $conn->DBTimeStamp(mktime(23,59,59, date("m",$month_days[$i]["timestamp"]), date("d",$month_days[$i]["timestamp"]), date("Y",$month_days[$i]["timestamp"])) );
//		$sql = "SELECT COUNT(*) AS appointment_count FROM mgw_calendar WHERE ".$sql_owner_part." SUBSTRING(date,1,8) = $sqldate GROUP BY date ORDER BY date";
		$sql = "SELECT COUNT(*) AS appointment_count 
        		FROM mgw_calendar 
				WHERE ".$sql_owner_part." date >= $sqldate AND
        				date <= $sqldate_end
				GROUP BY date 
				ORDER BY date";
		if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
		$row = $res->FetchRow();
		if($row["appointment_count"]>0) $markday = " style=\"font-weight:bold;\" title=\"".$row["appointment_count"]."\" alt=\"".$row["appointment_count"]."\"";
		else $markday = "";

		/***************************/
		/* *** OLD :
		if(!$trim_month || ($trim_month && ($i>0 && $i<=$num_days+abs($days_before)))) {		
			$out .= "<td class=\"$klasse\" align=\"center\"$markday>";
			$out .= "<a class=\"subnavlink\" href=\"index.php?date=".$month_days[$i]["timestamp"]."&".SID."\">".$month_days[$i]["day_number"]."</a></td>\n";
		} else {
			$out .= "<td class=\"stand\"></td>";
		}
		*** */
		
		/* *** NEW : */
		//timestamp of 1st day of current month :
		$ts_curr_month = mktime(0, 0, 0, $month , 1 , $year );
		//timestamp of 1st day of next month :
		$next_month = ($month==12) ? 1 : $month+1;
		$next_year = ($month==12) ? $year+1 : $year;
		$ts_next_month = mktime(0, 0, 0, $next_month , 1 , $next_year );
				
		if(!$trim_month || ($trim_month && ( ($i>0 or $month_days[$i]["timestamp"]==$ts_curr_month+1) && $i<=$num_days+abs($days_before)) && $month_days[$i]["timestamp"]<$ts_next_month )) {
			//the day don't belong to the month -> italic
			if ($month_days[$i]["timestamp"]<$ts_curr_month) {
				$out .= "<td class=\"stand\">";
				$month_str = str_pad( date("d", $month_days[$i]["timestamp"]).date("m", $month_days[$i]["timestamp"]).date("Y", $month_days[$i]["timestamp"]),8,"0",STR_PAD_LEFT);		
				$out .= "&nbsp;&nbsp;<a class=\"subnavlink\" href=\"calendar_all.php?date=".$month_str."&parts=$str_parts&".SID."\"><I>".$month_days[$i]["day_number"]."</I></a></td>\n";
			}
			else {
			$out .= "<td class=\"$klasse\" align=\"center\"$markday>";
			$month_str = str_pad( date("d", $month_days[$i]["timestamp"]).date("m", $month_days[$i]["timestamp"]).date("Y", $month_days[$i]["timestamp"]),8,"0",STR_PAD_LEFT);
			$out .= "<a class=\"subnavlink\" href=\"calendar_all.php?date=".$month_str."&parts=$str_parts&".SID."\">".$month_days[$i]["day_number"]."</a></td>\n";
			}
		} 
		else {
			$out .= "<td class=\"stand\"></td>";
		}
		
		/***************************/
			
		if(($i+1)%7==0) {
			$out .= "<td class=\"lines\" width=\"1\" height=\"1\"><img src=\"". $appconf["imgpathgeneral"] ."/space.gif\" alt=\"\" width=\"1\" height=\"1\" /></td>\n";
			$out .= "</tr>\n";
		}
	}

	//$out .= "<td class=\"lines\" width=\"1\" height=\"1\"><img src=\"". $appconf["imgpathgeneral"] ."/space.gif\" alt=\"\" width=\"1\" height=\"1\" /></td>";
	//$out .= "</tr>\n";
	$out .= "<tr><td class=\"lines\" width=\"1\" height=\"1\" colspan=\"10\"><img src=\"". $appconf["imgpathgeneral"] ."/space.gif\" alt=\"\" width=\"1\" height=\"1\" /></td></tr>";
	$out .= "</table>\n";

	return $out;
}

?>