<?php
/* $Id: view_avail.php,v 1.7 2006/04/16 14:40:44 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");
include(INCLUDEPATH . "mSelectBox.class.php");

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


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

/// NATYS ////

/////////////
// NATYS : temporaire:
//pour traiter le texte :
function text_process($text){
return $text;
}
///


$serial_week = (isset($_GET["serial_week"])) ? $_GET["serial_week"] : (IsSet($_POST["serial_week"]) ? $_POST["serial_week"] : "");
$serial_year = (isset($_GET["serial_year"])) ? $_GET["serial_year"] : (IsSet($_POST["serial_year"]) ? $_POST["serial_year"] : "");
//parties is a string containing participants (e.g. : 1|4|12|14 -> four participants)
$parties = (isset($_GET["parties"])) ? $_GET["parties"] : (IsSet($_POST["parties"]) ? $_POST["parties"] : "");

$date = (isset($_GET["date"])) ? $_GET["date"] : (IsSet($_POST["date"]) ? $_POST["date"] : "");
$gotodate = IsSet($_POST["gotodate"]) ? $_POST["gotodate"] : "";
if(isset($_GET["action"]) || isset($_POST["action"])) $action = (isset($_GET["action"])) ? $_GET["action"] : $_POST["action"];

$new = (isset($_GET["new"])) ? $_GET["new"] : (IsSet($_POST["new"]) ? $_POST["new"] : "");

$update = (isset($_GET["update"])) ? $_GET["update"] : (IsSet($_POST["update"]) ? $_POST["update"] : "");
$tsupdate = (isset($_GET["tsupdate"])) ? $_GET["tsupdate"] : (IsSet($_POST["tsupdate"]) ? $_POST["tsupdate"] : "");
$participants = (isset($_GET["participants"])) ? $_GET["participants"] : (IsSet($_POST["participants"]) ? $_POST["participants"] : array());

if (sizeof($participants)==0 && $parties!="") {
    //get array with participants:
	$participants=explode("|",$parties);
}
$parties ="";

$ind = (isset($_GET["ind"])) ? $_GET["ind"] : (IsSet($_POST["ind"]) ? $_POST["ind"] : "");
$appointment_attribute = (isset($_GET["appointment_attribute"])) ? $_GET["appointment_attribute"] : (IsSet($_POST["appointment_attribute"]) ? $_POST["appointment_attribute"] : "");

$appointment_start = (isset($_GET["appointment_start"])) ? $_GET["appointment_start"] : (IsSet($_POST["appointment_start"]) ? $_POST["appointment_start"] : "");
$appointment_end = (isset($_GET["appointment_end"])) ? $_GET["appointment_end"] : (IsSet($_POST["appointment_end"]) ? $_POST["appointment_end"] : "");

//Duration:
$appointment_duration = (isset($_GET["appointment_duration"])) ? $_GET["appointment_duration"] : (IsSet($_POST["appointment_duration"]) ? $_POST["appointment_duration"] : 0);
if (!isset($duration)) {
	/*if($appointment_duration!=0)*/
	//echo (date("H",$appointment_duration))." ".date("i",$appointment_duration);
	//echo "<BR>".date("H:i",mktime(0,30,0, 1, 1,1971));
	$duration = date("H",$appointment_duration)*3600+date("i",$appointment_duration)*60;
	//echo "<BR>".date("H:i",$duration+mktime(0,0,0, 1, 1,1971));
	//else $duration = 61;
}


// redirect to default view
if($_SESSION["MGW"]->settings["calendar_defaultview"]!="" && (!isset($_GET['submenu']) || $_GET['submenu']!="yes") &&
   empty($date) && empty($gotodate) && empty($action) && empty($new) &&
   empty($update) && empty($tsupdate) && trim($_SESSION["MGW"]->settings["calendar_defaultview"])!="index.php"){
    redirect($_SESSION["MGW"]->settings["calendar_defaultview"]."?".SID);
}

$timemask = $_SESSION["MGW"]->settings["timefmt"];

// get the settings
$holitemp      = $_SESSION["MGW"]->settings["calendar_holiday_system"];			// calendar holiday system (country)
$interval      = $_SESSION["MGW"]->settings["calendar_interval"];			// calender interval length in minutes
$interval_sec  = 60 * $interval;					// calender interval length in seconds
$starthour     = $_SESSION["MGW"]->settings["calendar_viewfrom"];			// start hour of day-view
$endhour       = $_SESSION["MGW"]->settings["calendar_viewto"];			// last  hour of day-view


$concat = $conn->Concat("'* '","firstname","' '","lastname");


if (isset($action)){

	switch($action)
		{
		case "choose" :	if (empty($date)) {
					    $date = mktime(0,0,0, date("m", time()), date("d", time()), date("Y", time()));
						}
						break;

		case "view" :   if (empty($date)) {
		                $date = get_weektimestamp($serial_week,$serial_year);
		                }
						break;

		}

}



// Set certain values for time-handling
$actual_date_arr = getdate($date);

// Start time (according to settings) of selected day
$start_time =  mktime(0,0,0, $actual_date_arr["mon"], $actual_date_arr["mday"], $actual_date_arr["year"]) + $starthour * 3600;
$app_start_time =  mktime(0,0,0, $actual_date_arr["mon"], $actual_date_arr["mday"], $actual_date_arr["year"]);

// End time (according to settings) of selected day
$end_time   =  mktime(0,0,0, $actual_date_arr["mon"], $actual_date_arr["mday"], $actual_date_arr["year"]) + $endhour   * 3600;
$app_end_time   =  mktime(0,0,0, $actual_date_arr["mon"], $actual_date_arr["mday"], $actual_date_arr["year"]) + 23.5 * 3600;





// ===========================================
// Show Template : form for Choosing to View availabity
// ===========================================
if ($action=="choose") {

	// according to settings : set current user available or selected:
	if ($_SESSION["MGW"]->settings['calendar_be_participant']==1) $sql_where = " WHERE id != '".$_SESSION["MGW"]->userid."'";
	else $sql_current = "";

	$sql  = "SELECT id as userid, ".$conn->Concat("firstname", "' '", "lastname")." AS name
		FROM mgw_users".
		$sql_where ."
		ORDER BY name"; // is $sql_where ever defined here?

	if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
	while ($row = $res->FetchRow()) {
		$smarty->append("partie", $row);
	}

	// according to settings : select current user by default:
	if ($_SESSION["MGW"]->settings['calendar_be_participant']==1) {
		$currentuser = array( 	"userid" => $_SESSION["MGW"]->userid ,
								"name" => $_SESSION["MGW"]->fullusername);
	$smarty->append("spartie", $currentuser);
	}

	// create selectboxes
	$sdate=getDate($date);

	//current week :
	$smarty->assign("week_sel",get_weeknumber($date));

	// years
	$syears = new mSelectBox("serial_year");
	$syears ->setHandler("OnChange", "keep_weeks_coherence()");
	$smarty->assign("serial_year", $syears->getSB_Year(date("Y",time()),date("Y",time())+30,$sdate["year"],false));



	//duration => a passer en parametre
	for( $t=mktime(0,30,0,1,1,1971); $t <= mktime(12,0,0,1,1,1971); $t+=$interval_sec) {
		$appointment_duration_list = array(
			"timestamp" 	=> $t,
			"time_label"  	=> date($timemask, $t),
			"sel" 		=> ($duration==$t ? " selected" : "")
		);
	//print_r($appointment_duration_list);
	$smarty->append("appointment_duration_list", $appointment_duration_list);
	}


	$smarty->assign("year53_list",get_year53_list(date("Y",time()),date("Y",time())+30));

	if (isset($week)) {
	    $smarty->assign("week_sel",$week);
	}

	//$smarty->assign('date',  $date);
	$smarty->assign('back',  "view_avail.php?date=$date&".SID);
	$smarty->assign('sname', "new");
	$smarty->assign('datum', date(Lang::getLanguageString("gentemp_date_format_php"), $date));
	$smarty->assign('temp_err_no_start', Lang::getLanguageString("temp_err_no_start"));
	$smarty->assign('temp_err_no_end', Lang::getLanguageString("temp_err_no_end"));
	$smarty->assign('temp_err_end_before', Lang::getLanguageString("temp_err_no_before"));
	$smarty->assign('temp_err_thema_long', Lang::getLanguageString("temp_err_thema_long"));
	$smarty->assign('temp_err_external_long', Lang::getLanguageString("temp_err_external_long"));

	//$smarty->assign('temp_i_will', Lang::getLanguageString("i_will_part"));
	//$smarty->assign('temp_will_selected', ($_SESSION["MGW"]->settings['calendar_be_participant']==1 ? true : false));
	$smarty->assign("temp_title", Lang::getLanguageString("temp_newappointment"));
	$smarty->assign("submenu", 7);
	$smarty->assign("suvalue", Lang::getLanguageString("gentemp_view_avail"));
	$smarty->assign("appointment_attribute",0);


	$smarty->assign("target","view_avail.php");

	$smarty->display('calendar_choose_avail.tpl'); //new.tpl
	////////////////

} // FIN IF CHOOSE



//===================================
// SHOW week with availability...
//===================================

if ($action=="view") {
	// show week with periods:
//echo "start: $start_time : ".date("H:i d-m-Y",$start_time)."<BR>";
//echo "end: $end_time : ".date("H:i d-m-Y",$end_time)."<BR>";

$actual_week_start_date     = $start_time - ($actual_date_arr["wday"]-1) * 3600 * 24 - $starthour*3600;
$actual_week_end_date       = $end_time   + (7-$actual_date_arr["wday"]) * 3600 * 24 - $endhour * 3600;

// Set day header in week-view
$woch_arr = array( Lang::getLanguageString("temp_weekday_abbr_1"), Lang::getLanguageString("temp_weekday_abbr_2"), Lang::getLanguageString("temp_weekday_abbr_3"), Lang::getLanguageString("temp_weekday_abbr_4"),
		   Lang::getLanguageString("temp_weekday_abbr_5"), Lang::getLanguageString("temp_weekday_abbr_6"), Lang::getLanguageString("temp_weekday_abbr_0"));

$w = $actual_week_start_date;
for ($i=0;$i<=6;$i++) {
    $j=$i+2;
    $colum = "d$j";
    if (get_celebrate_days($w, $holitemp) != "") $wday = get_celebrate_days($w, $holitemp);
    else if ($i <= 4) $wday = $woch_arr[$i] . ",&nbsp;"./* NATYS date*/date_lang( Lang::getLanguageString("gentemp_date_format_php"), $w) . "";
    else if ($i == 5) $wday = Lang::getLanguageString("gentemp_weekday_7");
    else if ($i == 6) $wday = Lang::getLanguageString("gentemp_weekday_1");
    $smarty->assign("$colum", "<a class=\"edit\" href=\"index.php?date=$w&amp;".SID."\">$wday</a>");
    $smarty->append("clm", array("date" => $w, "wkd"=> $woch_arr[$i]));
    $w += 24*3600;
}

$wst_d      = date("d/m",    $actual_week_start_date);
$wen_d      = date("d/m/Y",  $actual_week_end_date);
$sql_start = date("Ymd", $actual_week_start_date);
$sql_ende  = date("Ymd", $actual_week_end_date);

// =======================
//  calendar change
// =======================
if (isset($_POST["new_calendarid"])){
    if ($_POST["new_calendarid"]=="all") {
	$_SESSION['calendarid'] = "all";
	$_SESSION['calendarname'] = Lang::getLanguageString("calendarownerall"); // translated all
    }
    else {
	$sql = "SELECT id, $concat AS name FROM mgw_users WHERE NOT(level=".UDELETED.") AND id = ".$_POST["new_calendarid"];

	if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
	$row = $res->FetchRow();
	$_SESSION['calendarid']   = $row["id"];
	$_SESSION['calendarname'] = $row["name"];
    }
    unset($chgcal);
}


// ========================
// GET BIRTHDAYS
// ========================

if($_SESSION["MGW"]->settings["calendar_show_birthdays"]){

    $w = $actual_week_start_date;
    for ($i=1;$i<=7;$i++) {
	$bd_start = $conn->DBDate(mktime(0,0,1,date("m",$w),date("d",$w),date("Y",$w)));
	$bd_end = $conn->DBDate(mktime(23,59,59,date("m",$w),date("d",$w),date("Y",$w)));

	//$bdsql = "SELECT $concat AS jubilee FROM mgw_contacts WHERE SUBSTRING(birthday,6,5)='".date("m-d",$w)."' AND (ispublic='1' OR owner='".$_SESSION["MGW"]->userid."')";
	$bdsql = "SELECT $concat AS jubilee
	          FROM mgw_contacts
			  WHERE birthday >= $bd_start AND
				  birthday <= $bd_end AND
			  (ispublic='1' OR owner='".$_SESSION["MGW"]->userid."')";
	if(!$bdres = $conn->Execute($bdsql)) exit(showSQLerror($bdsql, $conn->ErrorMsg(), __LINE__, __FILE__));
	$br = "";
	$bd = array_fill(0,8,"");
	while($bdrow = $bdres->FetchRow()){
    $bd[$i] .= $bdrow["jubilee"].$br;
    $br = "<br />";
	}

	$nam = "klasse$i";
	if (get_celebrate_days(mktime(0,0,0, date("m",$actual_week_start_date),date("j",$actual_week_start_date)+$i-1,date("Y",$actual_week_start_date)), $holitemp) != "")
	    $$nam = "feiertag";
	else if ((date("w", mktime(0,0,0, date("m",$actual_week_start_date),date("j",$actual_week_start_date)+$i-1,date("Y",$actual_week_start_date))) == 0) || (date("w", mktime(0,0,0, date("m",$actual_week_start_date),date("j",$actual_week_start_date)+$i-1,date("Y",$actual_week_start_date))) == 6))
	    $$nam = "wochenende";
	else if (mktime(0,0,0, date("m",$actual_week_start_date),date("j",$actual_week_start_date)+$i-1,date("Y",$actual_week_start_date)) == mktime(0,0,0, date("m",time()),date("j",time()),date("Y",time())))
	    $$nam = "heute";
	else $$nam = "tab";

	$w += 24*3600; // WARNING !! use mktime instead !!
    }

    $zeile = array( "von" => "",
		    "mon" => $bd[1], "tue" => $bd[2], "wed" => $bd[3], "thu" => $bd[4], "fri" => $bd[5], "sat" => $bd[6], "sun" => $bd[7],
		    "klass2" => $klasse1, "klass3" => $klasse2, "klass4" => $klasse3, "klass5" => $klasse4, "klass6" => $klasse5, "klass7" => $klasse6, "klass8" => $klasse7);
    $smarty -> append("cw", $zeile);
}

// ========================
// ENTRY WEEKVIEW
// ========================
if(!isset($_GET["action"]) or $_GET["action"]=="view") {


//echo "w-start: $actual_week_start_date : ".date("H:i d-m-Y",$actual_week_start_date)."<BR>";
//echo "w-end: $actual_week_end_date : ".date("H:i d-m-Y",$actual_week_end_date)."<BR>";

	$color_avail_ok = "#C8FFB6";
	$color_avail_too_small = "#D18A76";
	$color_not_avail = "#CDD9E8";

	$smarty->assign("color_avail_ok",$color_avail_ok);
	$smarty->assign("color_avail_too_small",$color_avail_too_small);
	$smarty->assign("color_not_avail",$color_not_avail);

    if (!IsSet($_SESSION["calendar_month"]) && !IsSet($_SESSION["calendar_year"])) {
	$_SESSION['calendar_month'] = date("m", $date);
	$_SESSION['calendar_year'] = date("Y", $date);
	$_SESSION["calendar_month"] = $_SESSION['calendar_month'];
	$_SESSION["calendar_year"] = $_SESSION['calendar_year'];
    }

    ////////////////////////////////////////////////////////////////////////
    // set calenderid = userid if calendarid is not set
    ////////////////////////////////////////////////////////////////////////
    if (!isset($_SESSION["calendarid"])) {
	$_SESSION['calendarid']   = $_SESSION["MGW"]->userid;
	$_SESSION['calendarname'] = $_SESSION["MGW"]->fullusername;
    }

    ////////////////////////////////////////////////////////////////////////
    // show user list as possible calendar owners
    ////////////////////////////////////////////////////////////////////////
    $sql = "SELECT id, $concat AS name FROM mgw_users WHERE NOT(level=".UDELETED.") order by 2";

    if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));

    while ($row = $res->FetchRow()){
	$smarty->append("td2", $row);
    }

    $smarty->assign('action', "inh");

    /*// Selected entry all
    if ($_SESSION['calendarid']=="all") {
	$sql_owner_part="";
    }
    else {
	$sql_owner_part="userid = ".$_SESSION['calendarid']." AND";
    }
   */
   $nb_part = sizeof($participants);
   $sql_owner_part = "( ";

	for ($i=0;$i<$nb_part;$i++)
		{
		//format string with participants :
      	$parties .= $participants[$i].(($i==$nb_part-1) ? "" : "|");
		//format sql with participants
		$sql_owner_part.="userid = '".$participants[$i]."' OR ";
		}
   $sql_owner_part.=" (1=0) ) AND ";


   ////////////  list of participants:  ////////////////
   	   $sql_spart = "SELECT id as userid, ".$conn->Concat("firstname", "' '", "lastname")." AS name
			 		  FROM mgw_users
					  WHERE NOT(level=".UDELETED.") AND ( ";
		for ($i=0;$i<$nb_part;$i++)
			{
			//format sql with selected participants
			$sql_spart.="id = '".$participants[$i]."' OR ";
			}
	   $sql_spart.=" (1=0) )
			    	 ORDER BY lastname";

		if(!$res = $conn->Execute($sql_spart)) die(showSQLerror($sql_spart, $conn->ErrorMsg(), __LINE__, __FILE__));
		while ($row = $res->FetchRow()) {
			$smarty->append("spartie", $row);
		}
    //  $sql = "SELECT * FROM mgw_calendar WHERE $sql_owner_part SUBSTRING(date,1,8) >= '$sql_start' AND substring(date,1,8) <= '$sql_ende'	GROUP BY 1, date , userid , subject, location, private , duration, external, inituserid, day_ind, repeat_mode, rep_from, rep_until, dategroup_id, holiday_id ORDER BY 1";

	$sql = "SELECT date, duration FROM mgw_calendar
	        WHERE $sql_owner_part date >= ".$conn->DBTimeStamp(mktime(0,0,0, date("m",$actual_week_start_date), date("d",$actual_week_start_date), date("Y",$actual_week_start_date)) )." AND
            date <= ".$conn->DBTimeStamp( mktime(23,59,59, date("m",$actual_week_end_date), date("d",$actual_week_end_date), date("Y",$actual_week_end_date)))."
			GROUP BY 1, date , duration
			ORDER BY 1";


    if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
    $num = $res->RecordCount();

    $nb_opened_days = 5; // here : we don't want to make appointment on Sat or Sun
	$next_week_start_date = mktime(0,0,0,date("m",$actual_week_start_date),date("d",$actual_week_start_date)+$nb_opened_days,date("Y",$actual_week_start_date));

	$ar_appt =array();
	//fill an array containing all appointments (timestamps)
	while($row = $res->FetchRow()){

		$vmin  = $res->UnixTimeStamp($row["date"]);
	    $bmin  = $vmin + $row["duration"] * 60;

		for ($i=$vmin;$i<$bmin;$i+= $interval_sec)
			if (date("H",$i) >= $starthour && date("H",$i) <= $endhour) {
			    $ar_appt[]= $i;
			}
	} // while

	//print_r($ar_appt);
	$new_interval = 1;
	$continue_interval = 2;
	$too_small_interval = 3;
	$not_avail_interval = 4;

	$duration_remainder = 0;
	for ($ts=$actual_week_start_date; $ts<$next_week_start_date; $ts+=$interval_sec){

		// init for each:
		$duration_ok = false;
		$is_available = false;
		$type_interval = 0; // type_interval contain 0, 1, 2, 3


		// there is a free interval beetween starthour and endhour
		if(!in_array($ts, $ar_appt) && ((date("Hi",$ts)/100) >= $starthour && (date("Hi",$ts)/100) < $endhour))
			{
			 $is_available = true;
			}
		else {
			$is_available = false;
			$type_interval = $not_avail_interval;
			}

		if ($is_available) {
			$duration_ok = true;
			for ($i=$ts;$i<$ts+$duration && $i<$next_week_start_date ;$i+=$interval_sec)
				{
				$duration_ok = $duration_ok && !in_array($i, $ar_appt) && /*limit = endhour =>*/(date("Hi",$i)/100) < $endhour;
				//echo "i: $i, date: ".date("H:i d-m-Y", $i)." ok?: $duration_ok / ".!in_array($i, $ar_appt)."<BR>";
				}
		}

		if ($is_available)
			{
				if ($duration_ok) {
					$duration_remainder = $duration-$interval_sec;
					$type_interval = $new_interval;
				}
				else {
						if ($duration_remainder > 0) {
						     $duration_remainder = $duration_remainder-$interval_sec;
							 $type_interval = $continue_interval;
						  }
						else $type_interval = $too_small_interval;

					}
			}



		switch($type_interval)
			{
			case $new_interval :		$t_klasse = "edit";
										$datum = getdate($ts);
										$vzeit = date("His", $ts);
										$week[$datum["wday"]][$vzeit] = "<a href=\"index.php?action=new1&newtype=meeting&parties=$parties&date=$ts&end_date=".($ts+$duration-$interval_sec)."&".SID."\" class=\"edit\">".Lang::getLanguageString("gentemp_view_avail_available")."</a>";
										$bg_klasse[$datum["wday"]][$vzeit] = $color_avail_ok;
										break;

			case $continue_interval : 	$t_klasse = "edit";
										$datum = getdate($ts);
										$vzeit = date("His", $ts);
										$week[$datum["wday"]][$vzeit] = "<a href=\"index.php?action=new1&newtype=meeting&parties=$parties&date=".($ts-($duration-$duration_remainder-$interval_sec))."&end_date=".(($ts-($duration-$duration_remainder-$interval_sec))+$duration-$interval_sec)."&".SID."\" class=\"edit\">"."..."."</a>";
										$bg_klasse[$datum["wday"]][$vzeit] = $color_avail_ok;
										break;

			case $too_small_interval :	$t_klasse = "edit";
										$datum = getdate($ts);
										$vzeit = date("His", $ts);
										$week[$datum["wday"]][$vzeit] = Lang::getLanguageString("gentemp_view_avail_tooshort");
										$bg_klasse[$datum["wday"]][$vzeit] = $color_avail_too_small;
										break;

			case $not_avail_interval :	$t_klasse = "edit";
										$datum = getdate($ts);
										$vzeit = date("His", $ts);
										$bg_klasse[$datum["wday"]][$vzeit] = $color_not_avail;
										break;

			default : 	/*$t_klasse = "edit";
						$datum = getdate($ts);
						$vzeit = date("His", $ts);
						$week[$datum["wday"]][$vzeit] = "<a href=\"details.php?id=99999&".SID."\" class=\"edit\">".short_string(str_decode("000"),$max_subject_length)."</a>";
						*/
						//$bg_klasse[$datum["wday"]][$vzeit] = $color_not_avail;
						break;


			}


/*
	    if (get_celebrate_days($vmin, $holitemp) != "") $t_klasse = "feiertag";
	    else if ((date("w", $vmin) == 0) || (date("w", $vmin) == 6))   $t_klasse = "wochenende";
	    else if (mktime(0,0,0, date("m",$vmin),date("j",$vmin),date("Y",$vmin)) ==
		     mktime(0,0,0, date("m",time()),date("j",time()),date("Y",time()))) $t_klasse = "heute";
	    else $t_klasse = "edit";

//// NATYS : color of appointment : appointment type
	//----- appointment type :
	$id_appt_type = $row["id_appt_type"];
	$sql_appt_type = "SELECT * FROM mgw_calendar_appt_type WHERE id=$id_appt_type";
	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();
	$appointment_type = array( 	"text" => Lang::getLanguageString("gentemp_".$row_appt_type["type"]),
								"color"=> $row_appt_type["color"]
							 );
/////////////

	    for ($w = $vmin; $w < $bmin; $w += $interval_sec){
		$datum = getdate($w);
		$vzeit = date("His", $w);
		// NATYS : extracted from if and else :
		$klasse[$datum["wday"]][$vzeit] = "$t_klasse";
		$bg_klasse[$datum["wday"]][$vzeit] = $appointment_type["color"];
		if ($w == $vmin){
		    $myid = $row["id"];
		    //NATYS $klasse[$datum["wday"]][$vzeit] = "$t_klasse";

			if ($row["private"] == 1 && $_SESSION['calendarid'] != $_SESSION["MGW"]->userid){
				// private, not owner
				if (!isset($week[$datum["wday"]][$vzeit])) $week[$datum["wday"]][$vzeit] = Lang::getLanguageString("private");
				else if ( $week[$datum["wday"]][$vzeit] == "...")  $week[$datum["wday"]][$vzeit] = Lang::getLanguageString("private");
				else $week[$datum["wday"]][$vzeit] = "<a class=\"edit\" href=\"index.php?action=sel&ind=2&date=$vmin&".SID."\">".Lang::getLanguageString("temp_row_label_1")."</a>";
			}
		    else if ($row["private"] == 0 || $_SESSION['calendarid'] == $_SESSION["MGW"]->userid){
				// not private or owner
				//// NATYS ////
				//if (!isset($week[$datum["wday"]][$vzeit]))   $week[$datum["wday"]][$vzeit] = "<a href=\"details.php?id=$myid&".SID."\" class=\"edit\">".short_string($row["subject"],$max_subject_length)."</a>";
				if (!isset($week[$datum["wday"]][$vzeit]))   $week[$datum["wday"]][$vzeit] = "<a href=\"details.php?id=$myid&".SID."\" class=\"edit\">".short_string(str_decode($row["subject_summ"]),$max_subject_length)."</a>";
				//else if ( $week[$datum["wday"]][$vzeit] == "...") $week[$datum["wday"]][$vzeit] = "<a href=\"details.php?id=$myid&".SID."\" class=\"edit\">".$row["subject"]."</a>";
				else if ( $week[$datum["wday"]][$vzeit] == "...") $week[$datum["wday"]][$vzeit] = "<a href=\"details.php?id=$myid&".SID."\" class=\"edit\">".str_decode($row["subject_summ"])."</a>";
				//////////
				else if (isset($week[$datum["wday"]][$vzeit]))    $week[$datum["wday"]][$vzeit] = "<a href=\"index.php?action=sel&ind=2&date=$vmin&".SID."\" class=\"edit\">".Lang::getLanguageString("temp_row_label_1")."</a>";
		    }
		}
		else{
		    $week[$datum["wday"]][$vzeit] = "...";
		    //NATYS $klasse[$datum["wday"]][$vzeit] = "$t_klasse";
		}
	    } // end for

	*/
	}

	// NATYS : classes for header (days)
		$t=$app_start_time;
	    $zeits = date("His", $t);
	    for ($k=1;$k<=7;$k++){
		$head_klasse_nam = "head_klasse$k";
		if (!isset($klasse[$k]["$zeits"])){
		    if (get_celebrate_days( mktime(0,0,0, date("m",$actual_week_start_date),date("j",$actual_week_start_date)+$k-1,date("Y",$actual_week_start_date)), $holitemp) != "")
			$$head_klasse_nam = "feiertag";
		    else if ((date("w", mktime(0,0,0, date("m",$actual_week_start_date),date("j",$actual_week_start_date)+$k-1,date("Y",$actual_week_start_date))) == 0)
			     || (date("w", mktime(0,0,0, date("m",$actual_week_start_date),date("j",$actual_week_start_date)+$k-1,date("Y",$actual_week_start_date))) == 6))
			$$head_klasse_nam = "wochenende";

		    else if (mktime(0,0,0, date("m",$actual_week_start_date),date("j",$actual_week_start_date)+$k-1,date("Y",$actual_week_start_date)) ==
			     mktime(0,0,0, date("m",time()),date("j",time()),date("Y",time())))
			$$head_klasse_nam = "heute";
		    else $$head_klasse_nam = "tab";
		 }
		}

	$cw_header = array( "h_klass2"	=>	$head_klasse1,
						"h_klass3"	=>	$head_klasse2,
						"h_klass4"	=>	$head_klasse3,
						"h_klass5"	=>	$head_klasse4,
						"h_klass6"	=>	$head_klasse5,
						"h_klass7"	=>	$head_klasse6,
						"h_klass8"	=>	$head_klasse7
						);
	$smarty->assign("cw_header",$cw_header);
	//////////



	/// properties of each cell per line.
	for($t=$app_start_time; $t<$app_end_time; $t+=$interval_sec){
	    $zeits = date("His", $t);
	    for ($k=1;$k<=7;$k++){
		$nam = "klasse$k";
		$bg_nam = "bg_klasse$k";
		$$bg_nam = IsSet($bg_klasse[$k]["$zeits"]) ? $bg_klasse[$k]["$zeits"] : "";
//echo "<br><br>$bg_nam::-> ".$bg_klasse[$k]["$zeits"];
		if (!isset($klasse[$k]["$zeits"])){
		    if (get_celebrate_days( mktime(0,0,0, date("m",$actual_week_start_date),date("j",$actual_week_start_date)+$k-1,date("Y",$actual_week_start_date)), $holitemp) != "")
			$$nam = "feiertag";
		    else if ((date("w", mktime(0,0,0, date("m",$actual_week_start_date),date("j",$actual_week_start_date)+$k-1,date("Y",$actual_week_start_date))) == 0)
			     || (date("w", mktime(0,0,0, date("m",$actual_week_start_date),date("j",$actual_week_start_date)+$k-1,date("Y",$actual_week_start_date))) == 6))
			$$nam = "wochenende";

		    else if (mktime(0,0,0, date("m",$actual_week_start_date),date("j",$actual_week_start_date)+$k-1,date("Y",$actual_week_start_date)) ==
			     mktime(0,0,0, date("m",time()),date("j",time()),date("Y",time())))
			$$nam = "heute";
		    else {
				$$nam = "tab";
			}
		}
		else $$nam = $klasse[$k]["$zeits"];
	    }

	    if (!isset($klasse[0]["$zeits"])) $klasse7 = "wochenende";
	    else $klasse7 = $klasse[0]["$zeits"];

		// add some checking for content here KFISH
	    if (($t >= $start_time && $t < $end_time) || (isset($week[1][$zeits]) && $week[1][$zeits] != "") || (isset($week[2][$zeits]) && $week[2][$zeits] != "") || (isset($week[3][$zeits]) && $week[3][$zeits] != "") || (isset($week[4][$zeits]) && $week[4][$zeits] != "") || (isset($week[5][$zeits]) && $week[5][$zeits] != "") || (isset($week[6][$zeits]) && $week[6][$zeits] != "") || (isset($week[0][$zeits]) && $week[0][$zeits] != "") ){
		$zeile = array( "von" => date($timemask, $t)."&nbsp;-&nbsp;".date($timemask, $t+$interval_sec),
				"mon" => isset($week[1][$zeits]) ? $week[1][$zeits] : "",
				"tue" => isset($week[2][$zeits]) ? $week[2][$zeits] : "",
				"wed" => isset($week[3][$zeits]) ? $week[3][$zeits] : "",
				"thu" => isset($week[4][$zeits]) ? $week[4][$zeits] : "",
				"fri" => isset($week[5][$zeits]) ? $week[5][$zeits] : "",
				"sat" => isset($week[6][$zeits]) ? $week[6][$zeits] : "",
				"sun" => isset($week[0][$zeits]) ? $week[0][$zeits] : "",
				"klass2" => $klasse1,
				"klass3" => $klasse2,
				"klass4" => $klasse3,
				"klass5" => $klasse4,
				"klass6" => $klasse5,
				"klass7" => $klasse6,
				"klass8" => $klasse7,
				/// NATYS ///
				"bg_klass2"	=>	$bg_klasse1,
				"bg_klass3"	=>	$bg_klasse2,
				"bg_klass4"	=>	$bg_klasse3,
				"bg_klass5"	=>	$bg_klasse4,
				"bg_klass6"	=>	$bg_klasse5,
				"bg_klass7"	=>	$bg_klasse6,
				"bg_klass8"	=>	$bg_klasse7
				);
				/////////////
		$smarty -> append("cw", $zeile);
		//print_r($zeile);
		//echo "<BR>---<BR>";
	}
	}



    $kalender  = get_monthview_static( $date, $_SESSION['calendar_year'], $_SESSION['calendar_month']);
    $feiertag  = "(" . get_celebrate_days($date, $holitemp) .	")";
    if ($feiertag == "()") $feiertag = "";
    $gestern  = $date - 3600*168;
    $morgen   = $date + 3600*168;

    // wml-stuff -----------------------
    if($myEnv["output"]=="wml"){
	for($w=-5;$w<5;$w++)  {
	    $d=$date +($w*3600*168);
	    $skw["date"]=$d;
	    $skw["kw"]=get_weeknumber($d);
	    $smarty->append('skw', $skw);
	}
    }
    //----------------------------------

//// NATYS ////
/*
* calweek : texte "semaine n°"
* cur_week : N° de semaine actuelle
*
*/
///////////////

    $weiter = "<a class=\"navlink\" href=\"view_avail.php?action=view&date=$morgen&parties=$parties&appointment_duration=".(mktime(0,0,0,1,1,1971)+$duration)."&".SID."\" style=\"text-decoration:none;\">" . Lang::getLanguageString("forward"). " &gt;&gt;"  . "</a>";
	$zurueck= "<a class=\"navlink\" href=\"view_avail.php?action=view&date=$gestern&parties=$parties&appointment_duration=".(mktime(0,0,0,1,1,1971)+$duration)."&".SID."\" style=\"text-decoration:none;\">" . "&lt;&lt; " . Lang::getLanguageString("back"). "</a>";
    $text     = Lang::getLanguageString("calweek")." " . get_weeknumber($date) . "&nbsp;:&nbsp;&nbsp; $wst_d - $wen_d";

	$smarty->assign('duration_label',date("H:i",($duration+mktime(0,0,0, 1, 1,1971))));
    if ($duration>0) $show_duration = TRUE;
	else $show_duration = FALSE;
    $smarty->assign("show_duration",$show_duration);

	$smarty->assign('SID', SID);
    $smarty->assign('cur_week', "$wst_d-$wen_d");
    $smarty->assign('header_date', $text);
    $smarty->assign('first_header',Lang::getLanguageString("gentemp_view_avail"));
	$smarty->assign('kalender', $kalender);
    $smarty->assign('gestern', $gestern);
    $smarty->assign('morgen', $morgen);
    $smarty->assign('nav_links', $zurueck);
    $smarty->assign('nav_rechts', $weiter);
    $smarty->assign('calendar_owner', $_SESSION['calendarname']);
    $smarty->assign('date', $date);
    $smarty->assign('back', "view_avail.php?date=$gestern&".SID);
    $smarty->assign('weiter', "view_avail.php?date=$morgen&".SID);
    $smarty->assign('inh', "view_avail.php?action=inh&date=$date&".SID);
	$smarty->assign("submenu", 5);

    if ($_SESSION["MGW"]->userid == $_SESSION['calendarid']){
	$smarty->assign('ntext', " Neuer Termin ");
	$smarty->assign('new', "view_avail.php?action=new&date=$date&".SID);
    }

    $smarty->assign("timefmt", $_SESSION["MGW"]->settings["timefmt"]);
    $smarty->display('calendar_view_avail.tpl');
    $smarty->clear_assign('action');

}

}











?>