<?php
/*=======================================================================
 *
 * appointment.php
 *
 * Autor: Marc Vollmann
 * 
 =======================================================================*/

include_once ("../include/mcglobal.inc.php");
include_once ("../include/auth.inc.php");
// include_once ("../include/html.inc.php");
include_once ("../include/inc_filters.inc.php");
include_once ('../include/email/htmlMimeMail.php');


// Check for authentication access and granted rights
$usrAccessArray["hq"] = "1";
authCheckForAccess($hq_id, $usr_id, $emp_id, "1", $customerId, $cscIdRoot, $cscIdActual);
authCheckEmployeeRights($emp_id, "0", "1");
authCheckEmployeeRights($emp_id, "11", "1");

getSecHttpVars("1", array("f_act", "viewMode", "selYear", "selMonth", "selDay", "selWeek", "f_text", 
                          "f_day", "f_month", "f_year", "f_day_to", "f_month_to", "f_year_to",
                          "f_hour", "f_minute", "f_hour_to", "f_minute_to", 
                          "f_day_from_apstat", "f_month_from_apstat", "f_year_from_apstat", "f_day_to_apstat", "f_month_to_apstat", "f_year_to_apstat",
                          "f_apId", "f_apIdToRemove", "f_apIdToUpdate", "f_apIdToConfirm", "f_usr_id", 
                          "f_selUsrId", "f_hq_id", "g_cs_eid", "csSpecial", "f_sendmail", "f_sendmail_cs", "f_emailAdrCs",
                          "f_ap_resubmission_id", "f_ap_resubmission_execdate", "f_ap_resubmission_enddate", 
                          "f_ap_resubmission_category_1", "f_ap_resubmission_category_2", "f_ap_resubmission_category_3", "f_ap_resubmission_category_4",
                          "f_ap_cat_1", "f_ap_cat_2", "f_ap_cat_3", "f_ap_cat_4",
                          "f_ap_cat_search_1", "f_ap_cat_search_2", "f_ap_cat_search_3", "f_ap_cat_search_4", "f_ap_visibility_search",
                          "f_mail_salutation", "f_mail_greetings", "workMode", "apId", "deactivateMenu", "displayState", "displayStateOverrule"));
getSecHttpVars("1", array("f_text_" . $f_apIdToUpdate));


getLanguage(__FILE__);

$pageTitel = getLngt("TERMINE UND VERTRIEB");
include_once ("../admin/menu.php");
include_once ("../include/html.inc.php");

// Initialisations
if ($selYear == "") : $selYear = date("Y"); endif;
if ($selMonth == "") : $selMonth = date("m"); endif;
if ($selWeek == "") : $selWeek = date("W"); endif;
if ($selDay == "") : $selDay = date("d"); endif;

// Check ranges of time. All fields have to be set
if ($f_hour == "" || $f_minute == "" || $f_hour_to == "" || $f_minute_to == "") :
    $f_hour = "00";
    $f_minute = "00";
    $f_hour_to = "23";
    $f_minute_to = "59";
endif;
$f_hour = pad($f_hour,2);
$f_minute = pad($f_minute,2);
$f_hour_to = pad($f_hour_to,2);
$f_minute_to = pad($f_minute_to,2);

// Time range
$fromTimeRange = " " . $f_hour . ":" . $f_minute . ":00";
$toTimeRange = " " . $f_hour . ":" . $f_minute . ":59";

// Date range
$fromDateRange = $f_year . "-" . pad($f_month,2) . "-" . pad($f_day,2) . $fromTimeRange;
$toDateRange = $f_year_to . "-" . pad($f_month_to,2) . "-" . pad($f_day_to,2) . $toTimeRange;


// The selected day WITH new appointments (= 0), the selected day (= 1), the selected week (= 2), the selected month (= 3), the selected year (= 4)
if ($viewMode == "") : $viewMode = "1"; endif; 

// Date filter for appointment statistics
if ($f_day_from_apstat == "" || $f_month_from_apstat == "" || $f_year_from_apstat == "" || $f_day_to_apstat == "" || $f_month_to_apstat == "" || $f_year_to_apstat == "") :
   $f_day_from_apstat = "01";
   $f_month_from_apstat = "01";
   $f_year_from_apstat = getDateTime("year");
   $f_day_to_apstat = getDateTime("day");
   $f_month_to_apstat = getDateTime("month");
   $f_year_to_apstat = getDateTime("year");
endif;


// Definiton of global calendar parameters and functions
include_once ("../include/inc_calendar.inc.php");
include_once ("../groupware/calendar.php");

getCurrentScript(__FILE__);

// Mandator filter
if ($f_hq_id == "") : $f_hq_id = array(); endif;
if (count($f_hq_id) == 0) : array_push($f_hq_id, $hq_id); endif;

// Display special buttons
$maskBtnCsReport = getParameterValue("0", "MASK_AP_BTN_CS_REPORT", "0");  // "Berichte"
$maskBtnCsStateChange = getParameterValue("0", "MASK_AP_BTN_CS_STATE_CHANGE", "0");  // "Kundenstatuswechsel"
$maskBtnCsMotivationCounter = getParameterValue("0", "MASK_AP_BTN_CS_MOTIVATION_COUNTER", "0");  // "Motivation-Counter"
$maskBtnCsNew = getParameterValue("0", "MASK_AP_BTN_CS_NEW", "0");  // "Neuer Kunde"

// Appointment categories
if ($f_ap_cat_1 == "") : $f_ap_cat_1 = "1"; endif;    // State: Business (default), private
if ($f_ap_cat_2 == "") : $f_ap_cat_2 = "1"; endif;    // Visibility: Participants, only author, everybody
if ($f_ap_cat_3 == "") : $f_ap_cat_3 = "1"; endif;    // Kind: Misc., Meeting, reminder, ...
// Deadline monitoring on/off
$constMaskApCat4Preset = getParameterValue("0", "MASK_AP_CATEGORY_4_PRESET", "0");
if ($f_ap_cat_4 == "") :
   $f_ap_cat_4 = "0";
   if ($constMaskApCat4Preset == "1") : $f_ap_cat_4 = "1"; endif;
endif;

// Search filter for appointment categories
if ($f_ap_cat_search_1 == "") : $f_ap_cat_search_1 = ""; endif;    // Corresponding to $f_ap_cat_1
if ($f_ap_cat_search_2 == "") : $f_ap_cat_search_2 = ""; endif;    // 
if ($f_ap_cat_search_3 == "") : $f_ap_cat_search_3 = ""; endif;    // Corresponding to $f_ap_cat_3
if ($f_ap_cat_search_4 == "") : $f_ap_cat_search_4 = ""; endif;    // Corresponding to $f_ap_cat_4

// Search filter for visibility
if ($f_ap_visibility_search == "" || count($f_ap_visibility_search) == 0) : 
   $f_ap_visibility_search = array("1","2","3","4","5","6","7","8");
endif;

mcTrim($f_text);
mcTrim($f_mail_salutation);
mcTrim($f_mail_greetings);
mcTrim($g_cs_eid);
mcIsSet($f_grp_id);
mcIsSet($f_cs_eid_out);

// Appointments were requested for a special customer
if ($csSpecial != "" && !is_numeric($csSpecial)) : $csSpecial = ""; endif;

if ($f_selUsrId == "" && $f_selUsrId != "0") : $f_selUsrId = $usr_id; endif;

// Flag email to participants (employees, internal)
if ($f_sendmail == "" || count($f_sendmail) == 0) :
   $f_sendmail = "0";
else: 
   $f_sendmail = "1";
endif;
// Flag email to special adress(es) (customer or guests, external)
if ($f_sendmail_cs == "" || count($f_sendmail_cs) == 0) :
   $f_sendmail_cs = "0";
else: 
   $f_sendmail_cs = "1";
endif;
// External email adresses
$f_emailAdrCs = trim($f_emailAdrCs);
if ($f_emailAdrCs != "") :
   $f_emailAdrCs = spliti(",", $f_emailAdrCs);
else :
   $f_emailAdrCs = array();
endif;

// Only for display toggler
if ($displayState == "" || $displayState == "1") : $displayState = "0"; endif;
if ($displayStateOverrule == "1") : $displayState = "1"; endif;

// Functions

// Prints the headline with the current day
// $selYear   : Selected year
// $selMonth  : Selected month
// $selDay    : Selected day
// $cellCol   : Colour of the cell
function printAppointmentHeader($selYear, $selMonth, $selDay, $selWeek, $cellCol = "77FF77") {
  global $calWeekDays,$calCurrentDayNumOfTheWeek, $calMonthNames, $calMonthDays;
  global $calCurrentWeekNum, $calCurrentWeekName, $calCurrentDayNumOfTheYear;
  global $viewMode;
  global $f_day_from_apstat, $f_month_from_apstat, $f_year_from_apstat, $f_day_to_apstat, $f_month_to_apstat, $f_year_to_apstat;
  $out = "";
  // Daily output
  if ($viewMode == "1") :
     $out .= "<tr>";	
     $out .= "<td align=\"left\" bgcolor=\"#" . $cellCol . "\"><b>";  
     $out .= $calWeekDays[$calCurrentDayNumOfTheWeek - 1] . ", ";           // Name of the week day             (E.g.: "Donnerstag")
     $out .= $selDay . ". " . $calMonthNames[$selMonth - 1] . " " . $selYear;   // Day, Name of the month and year  (E.g.: "29 Juni 2006")
     $out .= "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
     $out .= $calCurrentWeekName . " " . $calCurrentWeekNum;                // calendar week                    (E.g.: "KW 26")
     $out .= "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
     $out .= $calCurrentDayNumOfTheYear . getLngt(". Tag des Jahres");
     $out .= "</b></td>";
     $out .= "</tr>";
  endif;
  // Weekly output
  if ($viewMode == "2") :
     // Get the first day ("Monday") of the specified week and compute date interval of the week
     $firstDayOfWeek = calFirstDayNumOfWeek($selWeek, $selYear);
     $tmpDatetime = mktime(0, 0, 0, $firstDayOfWeek[1], $firstDayOfWeek[0] + 6, $firstDayOfWeek[2]);
     $out .= "<tr>";	
     $out .= "<td align=\"left\" bgcolor=\"#" . $cellCol . "\"><b>";  
     $out .= $calCurrentWeekName . " " . $selWeek;                // calendar week                    (E.g.: "KW 26")
     $out .= "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
     $out .= "[" . $selYear . "]";     
     $out .= "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
     $out .= $firstDayOfWeek[0] . "." . $firstDayOfWeek[1] . "." . ($firstDayOfWeek[2] != date("Y", $tmpDatetime) ? $firstDayOfWeek[2] : "") . " - " . date("d", $tmpDatetime) . "." . date("m", $tmpDatetime) . "." . ($firstDayOfWeek[2] != date("Y", $tmpDatetime) ? date("Y", $tmpDatetime) : "") . "&nbsp;";
     $out .= "</b></td>";
     $out .= "</tr>";
  endif;
  // Monthly output
  if ($viewMode == "3") :
     $out .= "<tr>";	
     $out .= "<td align=\"left\" bgcolor=\"#" . $cellCol . "\"><b>";
     $out .= $calMonthNames[$selMonth - 1] . " " . $selYear;   // Name of the month and year  (E.g.: "Juni 2006")
     $out .= "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
     $out .= "01." . $selMonth . ". - " . $calMonthDays[$selMonth - 1] . "." . $selMonth . ".";
     $out .= "</b></td>";
     $out .= "</tr>";
  endif;
  // Yearly output
  if ($viewMode == "4") :
     $out .= "<tr>";	
     $out .= "<td align=\"left\" bgcolor=\"#" . $cellCol . "\"><b>";
     $out .= $selYear;   // Name of the year  (E.g.: "2006")
     $out .= "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
     $out .= "01.01. - 31.12.";
     $out .= "</b></td>";
     $out .= "</tr>";
  endif;
  // Statistic: Yearly output
  if ($viewMode == "9") :
     $out .= "<tr>";	
     $out .= "<td align=\"left\" bgcolor=\"#" . $cellCol . "\"><b>";
     $out .= pad($f_day_from_apstat,2) . "." . pad($f_month_from_apstat,2) . "." . $f_year_from_apstat . " - " . pad($f_day_to_apstat,2) . "." . pad($f_month_to_apstat,2) . "." . $f_year_to_apstat;
     $out .= "</b></td>";
     $out .= "</tr>";
  endif;
  return $out;
}

// Prints the title of the output table
// $cellCol   : Colour of the cell
function printAppointmentTitle($cellCol = "FFFFFF") {
  global $emp_id, $usr_id, $f_selUsrId, $f_hq_id;
  global $viewMode;
  $out = "";
  // Daily output
  if ($viewMode == "1") :
     $out .= "<tr>";	
     $out .= "<td width=\"50\" align=\"center\" bgcolor=\"#" . $cellCol . "\"><b>" . getLngt("Beginn") . "</b></td>";
     $out .= "<td width=\"50\" align=\"center\" bgcolor=\"#" . $cellCol . "\"><b>" . getLngt("Ende") . "</b></td>";
     // $out .= "<td width=\"150\" align=\"left\" bgcolor=\"#" . $cellCol . "\"><b>" . getLngt("Ersteller") . "</b></td>";
     $out .= "<td width=\"150\" align=\"left\" bgcolor=\"#" . $cellCol . "\"><b>" . getLngt("Ersteller, Teilnehmer") . "</b></td>";
     $out .= "<td align=\"left\" bgcolor=\"#" . $cellCol . "\"><b>Beschreibung</b></td>";
     $out .= "<td width=\"200\" align=\"left\" bgcolor=\"#" . $cellCol . "\"><b>" . getLngt("Kunde") . "</b></td>";
     $out .= "<td width=\"80\" align=\"center\" bgcolor=\"#" . $cellCol . "\"><b>" . getLngt("Aktion") . "</b></td>";
     $out .= "</tr>";
  endif;
  // Weekly output
  if ($viewMode == "2") :
     $out .= "<tr>";
     $out .= "<td width=\"100\" align=\"center\" bgcolor=\"#" . $cellCol . "\"><b>" . getLngt("Tag") . "</b></td>";
     $out .= "<td width=\"50\" align=\"center\" bgcolor=\"#" . $cellCol . "\"><b>" . getLngt("Zeit") . "</b></td>";
     // $out .= "<td width=\"150\" align=\"left\" bgcolor=\"#" . $cellCol . "\"><b>" . getLngt("Ersteller") . "</b></td>";
     $out .= "<td width=\"150\" align=\"left\" bgcolor=\"#" . $cellCol . "\"><b>" . getLngt("Ersteller, Teilnehmer") . "</b></td>";
     $out .= "<td align=\"left\" bgcolor=\"#" . $cellCol . "\"><b>" . getLngt("Beschreibung") . "</b></td>";
     $out .= "<td width=\"200\" align=\"left\" bgcolor=\"#" . $cellCol . "\"><b>" . getLngt("Kunde") . "</b></td>";
     $out .= "<td width=\"80\" align=\"center\" bgcolor=\"#" . $cellCol . "\"><b>" . getLngt("Aktion") . "</b></td>";
     $out .= "</tr>";
  endif;  
  return $out;
}

// Prints the headline with the current day
// $selYear  : Selected year
// $selMonth : Selected month
// $selDay   : Selected day
// $cellCol  : Colour of the cell
// $csId     : Special customer
function printAppointmentsOfOneDay($selYear, $selMonth, $selDay, $csId = "", $cellCol = "FFFFFF") {
  global $db, $PHP_SELF;
  global $usr_id, $f_apIdToUpdate;

  // $apArray = getAppointmentsFromDB($selYear, $selMonth, $selDay);
  $apArray = getAppointmentsOfOneDay($selYear, $selMonth, $selDay, $csId);
  $lenApArray = count($apArray);

  $out = "<tr>";
  for ($j = 0; $j < $lenApArray; $j++) :
      $tmpId = $apArray[$j][0];
      $tmpText = $apArray[$j][1];
        $tmpText = nl2br($tmpText);
      $tmpExecDateTime = $apArray[$j][2];
        $tmpExecDate = substr($tmpExecDateTime,8,2) . "." . substr($tmpExecDateTime,5,2) . "." . substr($tmpExecDateTime,0,4);
        $tmpExecTime = substr($tmpExecDateTime,11,5);
      $tmpCmpId = trim($apArray[$j][3]);
      $tmpCmpComp = trim($apArray[$j][4]);
      $tmpCmpComp2 = trim($apArray[$j][5]);
      $tmpCsId = $apArray[$j][6];
      $tmpCsEid = $apArray[$j][7];
      $tmpEndDateTime = $apArray[$j][8];
        $tmpEndDate = substr($tmpEndDateTime,8,2) . "." . substr($tmpEndDateTime,5,2) . "." . substr($tmpEndDateTime,0,4);
        $tmpEndTime = substr($tmpEndDateTime,11,5);
      $tmpUsrId = trim($apArray[$j][9]);
      $tmpUsrFirstname = trim($apArray[$j][10]);
      $tmpUsrName = trim($apArray[$j][11]);
      $tmpParticipants = trim($apArray[$j][12]);
        $tmpParticipants = substr($tmpParticipants,1,-1);     // Remove commata from db-field
      $tmpConfirmed = trim($apArray[$j][13]);
        $tmpConfirmed = substr($tmpConfirmed,1,-1);           // Remove commata from db-field
      $tmpCsUsrName = trim($apArray[$j][14]);
      $tmpCsUsrFirstname = trim($apArray[$j][15]);
      $tmpCsUsrPhone = $apArray[$j][16];
      $tmpCsUsrPhone2 = $apArray[$j][17];
      $tmpApCat1 = $apArray[$j][18];
      $tmpApCat2 = $apArray[$j][19];
      $tmpApCat3 = $apArray[$j][20];
      $tmpApCat4 = $apArray[$j][21];

      // Dates (From, To)
      $out .= "<td width=\"90\" align=\"center\" valign=\"center\" bgcolor=\"#" . $cellCol . "\"><b>" . $tmpExecDate . "<br><br>" . $tmpExecTime . "</b>";
      if ($tmpApCat4 == "1") :
         $out .= "&nbsp;&nbsp;" . "<a href=\"javascript:confirmActionAppointmentFinishPage('setAppointmentFinished','" . $tmpId . "','" . getLngt("Möchten Sie den Termin als erledigt markieren?") . "');\"><img src=\"../images/ap_clock.png\" width=\"15\" height=\"15\" style=\"border:none;\"></a>";
      endif;
      $out .= "</td>";
      if ($tmpEndTime != "00:00") :
         $out .= "<td width=\"90\" align=\"center\" valign=\"center\" bgcolor=\"#" . $cellCol . "\"><b>" . $tmpEndDate . "<br><br>" . $tmpEndTime . "</b></td>";
      else :
         $out .= "<td width=\"90\" align=\"left\" valign=\"center\" bgcolor=\"#" . $cellCol . "\">&nbsp;</td>";
      endif;

      // Author and participants
      $out .= "<td width=\"150\" align=\"left\" bgcolor=\"#" . $cellCol . "\">";
      if ($tmpUsrId != "") :
         $out .= "<b>" . $tmpUsrName . "&nbsp;" . $tmpUsrFirstname . "</b>";
         $out .= "<br><img src=\"../images/spacer_black.jpg\" width=\"100%\" height=\"1\">";
      endif;
      if ($tmpParticipants != "") : 
         $tmpParticipants = spliti(",", $tmpParticipants);   // It has to be an array
         $tmpParticipantsLen = count($tmpParticipants);
         
         // Needs array of users confirmed the appointment
         $tmpConfirmed = spliti(",", $tmpConfirmed);
         
         for ($k = 0; $k < $tmpParticipantsLen; $k++) :
             $participantName = $db->getOne("SELECT CONCAT(usr_name,', ',usr_firstname) AS name FROM user WHERE usr_id = '" . $tmpParticipants[$k] . "'");

             $participantConfirmed = "[?]";
             $l = array_search($tmpParticipants[$k], $tmpConfirmed);
             if (!($l === FALSE)) :
                $participantConfirmed = "[" . getLngt("OK") . "]";
             else :
                if ($tmpParticipants[$k] == $tmpUsrId) :
                   $participantConfirmed =  "[" . getLngt("OK") . "]";
                elseif ($tmpParticipants[$k] == $usr_id) :   // Only the user has a link to confirm his/her own entry
                   $participantConfirmed =  "<a href=\"javascript:confirmAppointmentFinishPage('" . $tmpId . "');\">[" . getLngt("Bestätigen") . "]</a>";
                endif;
             endif;
             $out .= $participantName . "&nbsp;" . $participantConfirmed . "<br>";
         endfor;
      else :
         $out .= "&nbsp;";
      endif;
      $out .= "</td>";
      
      // Text
      $out .= "<td align=\"left\" valign=\"center\" bgcolor=\"#" . $cellCol . "\">";
      if ($tmpApCat3 != "" && $tmpApCat3 > 0) :
         $out .= "<b>" . getFieldValueFromClause("metatype","mt_value","mt_type = 'appointment_category_3' AND mt_sort = '" . $tmpApCat3 . "'") . "</b>";
         $out .= "<br><img src=\"../images/spacer_black.jpg\" width=\"100%\" height=\"1\">";
      endif;
      $out .= $tmpText;
      $out .= "</td>";
      
      // Potential customer relation (Company name and EID)
      if ($tmpCsId != "") :
         $out .= "<td width=\"205\" align=\"left\" valign=\"center\" bgcolor=\"#" . $cellCol . "\">" . $tmpCmpComp . "<br>" . ($tmpCmpComp2 != "" ? $tmpCmpComp2 . "<br>" : "") . $tmpCsEid . "<br>"
               . "<input type=\"button\" name=\"action\" value=\"Details\" onClick=\"openCustomerSpecial('" . $tmpCmpId . "');\">"
               . "<input type=\"button\" name=\"action\" value=\"Berichte\" onClick=\"getCsHistory('" . $tmpCsEid . "');\">"
               . "<input type=\"button\" name=\"action\" value=\"Statistik\" onClick=\"openCustomerStatistics('" . $tmpCsEid . "');\">"
               . "</td>";
      else :
         $out .= "<td width=\"200\" align=\"left\" valign=\"center\" bgcolor=\"#" . $cellCol . "\">&nbsp;</td>";
      endif;

      // Actions
      $out .= "<td width=\"110\" align=\"center\" valign=\"center\" bgcolor=\"#" . $cellCol . "\">";
      $out .= "<input type=\"button\" class=\"minwidth\" name=\"action\" value=\"" . getLngt("Bearbeiten") . "\" onClick=\"updateAppointment('" . $tmpId . "');\">";
      $out .= "<br>";
      $out .= "<input type=\"button\" class=\"minwidth\" name=\"action\" value=\"" . getLngt("Entfernen") . "\" onClick=\"removeAppointmentFinishPage('" . $tmpId . "');\">";
      $out .= "<br>";
      $out .= "<input type=\"button\" class=\"minwidth\" name=\"action\" value=\"" . getLngt("Wiedervorlage") . "\" onClick=\"openCalendar('1','" . $tmpId . "');\">";
      if ($tmpApCat4 == "1") :
         $out .= "<br>";
         $out .= "<input type=\"button\" class=\"minwidth\" name=\"action\" value=\"" . getLngt("Erledigt") . "\" onClick=\"confirmActionAppointmentFinishPage('setAppointmentFinished','" . $tmpId . "','" . getLngt("Möchten Sie den Termin als erledigt markieren?") . "');\">";
      endif;      
      $out .= "</td>";      
      if ($j < $lenApArray - 1) : $out .= "</tr><tr>"; endif;
  endfor;
  $out .= "</tr>";
  return $out;
}


// Prints the headline with the current week
// $selWeek  : Selected week
// $selYear  : Selected year
// $selMonth : Selected month
// $selDay   : Selected day
// $cellCol  : Colour of the cell
// $csId     : Special customer
function printAppointmentsOfOneWeek($selWeek, $selYear, $selMonth, $selDay, $csId = "", $cellCol = "FFFFFF") {
  global $db, $PHP_SELF;
  global $usr_id, $f_apIdToUpdate;
  global $calCurrentWeekNum, $calWeekDays;

/*
  if ($selWeek == "") : $selWeek = $calCurrentWeekNum; endif;  
  // Get the first day ("Monday") of the specified week
  $firstDayOfWeek = calFirstDayNumOfWeek($selWeek, $selYear);
  // Compute interval to week (eq. 7 days)
  $tmpDatetime = mktime(0, 0, 0, $firstDayOfWeek[1], $firstDayOfWeek[0] + 6, $firstDayOfWeek[2]);  
  $weekBeginDate = date("Y-m-d", mktime(0, 0, 0, $firstDayOfWeek[1], $firstDayOfWeek[0], $firstDayOfWeek[2]));
  $weekEndDate = date("Y-m-d", mktime(0, 0, 0, $firstDayOfWeek[1], $firstDayOfWeek[0] + 6, $firstDayOfWeek[2]));
  // Get appointments of the specified week
  $apArray = getAppointmentsFromDB($firstDayOfWeek[2], $firstDayOfWeek[1], $firstDayOfWeek[0], date("Y", $tmpDatetime), date("m", $tmpDatetime), date("d", $tmpDatetime));
  // Modifies array according to the appointments starting and ending on different days
  $apArray = modifyIntervalAppointments2SingleDayAppointments($apArray, $weekBeginDate, $weekEndDate);  
*/
  $firstDayOfWeek = calFirstDayNumOfWeek($selWeek, $selYear);
  $apArray = getAppointmentsOfOneWeek($selWeek, $selYear, $selMonth, $selDay, $csId);
  $lenApArray = count($apArray);

  $out = "<tr>";
  $tmpExecDateDayNumRemember = "1";  // Start with Monday
  $tmpExecDateDayNumRememberArray = array("1","0","0","0","0","0","0","0");
  if ($lenApArray == 0) :
     // Check execution dates of appointments for day names to be displayed (Monday, Tuesday, ... have to be displayed also without appointments)
     while ($tmpExecDateDayNumRemember <= 7) :
        $tmpMktime = mktime(0, 0, 0, $firstDayOfWeek[1], $firstDayOfWeek[0] + ($tmpExecDateDayNumRemember - 1), $firstDayOfWeek[2]);
        $tmpDayNum = date("w", $tmpMktime);
        if ($tmpDayNum == 0) : $tmpDayNum = "7"; endif;
        $out .= "<td width=\"50\" align=\"center\" valign=\"center\" bgcolor=\"#" . $cellCol . "\"><b>" . $calWeekDays[$tmpDayNum - 1] . "<br>" . date("d", $tmpMktime) . "." . date("m", $tmpMktime) . ".</b></td>";
        $out .= "<td bgcolor=\"#" . $cellCol . "\">&nbsp;</td>";
        // $out .= "<td bgcolor=\"#" . $cellCol . "\">&nbsp;</td>";
        $out .= "<td bgcolor=\"#" . $cellCol . "\">&nbsp;</td>";
        $out .= "<td bgcolor=\"#" . $cellCol . "\">&nbsp;</td>";
        $out .= "<td bgcolor=\"#" . $cellCol . "\">&nbsp;</td>";
        $out .= "<td bgcolor=\"#" . $cellCol . "\">&nbsp;</td>";
        $out .= "</tr><tr>";
        $tmpExecDateDayNumRemember++;
     endwhile;
  else :
     $tmpExecDateYearRemember = "";
     $tmpExecDateMonthRemember = "";
     $tmpExecDateDayRemember = "";  
     for ($j = 0; $j < $lenApArray; $j++) :
         $tmpId = $apArray[$j][0];
         $tmpText = $apArray[$j][1];
           $tmpText = nl2br($tmpText);
         $tmpExecDate = substr($apArray[$j][2],0,10);
         $tmpExecTime = substr($apArray[$j][2],11,5);
         $tmpExecDateYear = substr($apArray[$j][2],0,4);
         $tmpExecDateMonth = substr($apArray[$j][2],5,2);
         $tmpExecDateDay = substr($apArray[$j][2],8,2);
         $tmpExecDateDayNum = date("w", mktime(0, 0, 0, $tmpExecDateMonth, $tmpExecDateDay, $tmpExecDateYear));
         if ($tmpExecDateDayNum == 0) : $tmpExecDateDayNum = "7"; endif;
         $tmpExecTime = substr($apArray[$j][2],11,5);
         $tmpCmpId = trim($apArray[$j][3]);
         $tmpCmpComp = trim($apArray[$j][4]);
         $tmpCmpComp2 = trim($apArray[$j][5]);
         $tmpCsId = $apArray[$j][6];
         $tmpCsEid = $apArray[$j][7];
         $tmpEndDate = substr($apArray[$j][8],0,10);
         $tmpEndTime = substr($apArray[$j][8],11,5);
         $tmpUsrId = trim($apArray[$j][9]);
         $tmpUsrFirstname = trim($apArray[$j][10]);
         $tmpUsrName = trim($apArray[$j][11]);
         $tmpParticipants = trim($apArray[$j][12]);
           $tmpParticipants = substr($tmpParticipants,1,-1);     // Remove commata from db-field
         $tmpConfirmed = trim($apArray[$j][13]);
           $tmpConfirmed = substr($tmpConfirmed,1,-1);           // Remove commata from db-field
         $tmpApCat1 = $apArray[$j][18];
         $tmpApCat2 = $apArray[$j][19];
         $tmpApCat3 = $apArray[$j][20];
         $tmpApCat4 = $apArray[$j][21];
  
         $tmpOk = true;
         for ($d = 1; $d < $tmpExecDateDayNum; $d++) :
             if ($tmpExecDateDayNumRememberArray[$d] == "0") :
                $tmpOk = false;
             endif;
         endfor;
         if ($tmpOk) :
            $tmpExecDateDayNumRemember = $tmpExecDateDayNum;
         endif;

         // Check execution dates of appointments for day names to be displayed (Monday, Tuesday, ... have to be displayed also without appointments)
         while ($tmpExecDateDayNum > $tmpExecDateDayNumRemember) :
            if ($tmpExecDateDayNumRememberArray[$tmpExecDateDayNumRemember] == "0") :
               $tmpMktime = mktime(0, 0, 0, $firstDayOfWeek[1], $firstDayOfWeek[0] + ($tmpExecDateDayNumRemember - 1), $firstDayOfWeek[2]);
               $tmpDayNum = date("w", $tmpMktime);
               if ($tmpDayNum == 0) : $tmpDayNum = "7"; endif;
               $out .= "<td width=\"50\" align=\"center\" valign=\"center\" bgcolor=\"#" . $cellCol . "\"><b>" . $calWeekDays[$tmpDayNum - 1] . "<br>" . date("d", $tmpMktime) . "." . date("m", $tmpMktime) . ".</b></td>";
               $out .= "<td bgcolor=\"#" . $cellCol . "\">&nbsp;</td>";
               // $out .= "<td bgcolor=\"#" . $cellCol . "\">&nbsp;</td>";
               $out .= "<td bgcolor=\"#" . $cellCol . "\">&nbsp;</td>";
               $out .= "<td bgcolor=\"#" . $cellCol . "\">&nbsp;</td>";
               $out .= "<td bgcolor=\"#" . $cellCol . "\">&nbsp;</td>";
               $out .= "<td bgcolor=\"#" . $cellCol . "\">&nbsp;</td>";
               $out .= "</tr><tr>";
            endif;
            $tmpExecDateDayNumRememberArray[$tmpExecDateDayNumRemember] = "1";
            $tmpExecDateDayNumRemember++;            
         endwhile;

         // Date
         $out .= "<td width=\"50\" align=\"center\" valign=\"center\" bgcolor=\"#" . $cellCol . "\">";
         if ($tmpExecDateYearRemember != $tmpExecDateYear || $tmpExecDateMonthRemember != $tmpExecDateMonth || $tmpExecDateDayRemember != $tmpExecDateDay) :
            $out .= "<b>" . $calWeekDays[$tmpExecDateDayNum - 1] . "<br>" . $tmpExecDateDay . "." . $tmpExecDateMonth . ".</b>";
            $tmpExecDateYearRemember = $tmpExecDateYear;
            $tmpExecDateMonthRemember = $tmpExecDateMonth;
            $tmpExecDateDayRemember = $tmpExecDateDay;
            $tmpExecDateDayNumRememberArray[$tmpExecDateDayNum] = "1";
         endif;
         $out .= "</td>";

         // Times (From, To)
         $out .= "<td width=\"50\" align=\"center\" valign=\"center\" bgcolor=\"#" . $cellCol . "\"><b>" . $tmpExecTime . "</b>";         
         if ($tmpEndTime != "00:00") :
            $out .= "<b><br>-<br>" . $tmpEndTime . "</b>";
         endif;
         if ($tmpApCat4 == "1") :
            $out .= "<br><br>" . "<img src=\"../images/ap_clock.png\" width=\"15\" height=\"15\">";
         endif;
         $out .= "</td>";
   
         // Author and participants
         $out .= "<td width=\"150\" align=\"left\" valign=\"center\" bgcolor=\"#" . $cellCol . "\">";
         if ($tmpUsrId != "") :
            $out .= "<b>" . $tmpUsrName . "&nbsp;" . $tmpUsrFirstname . "</b>";
            $out .= "<br><img src=\"../images/spacer_black.jpg\" width=\"100%\" height=\"1\">";
         endif;
         if ($tmpParticipants != "") : 
            $tmpParticipants = spliti(",", $tmpParticipants);   // It has to be an array
            $tmpParticipantsLen = count($tmpParticipants);
            
            // Needs array of users confirmed the appointment
            $tmpConfirmed = spliti(",", $tmpConfirmed);
            
            for ($k = 0; $k < $tmpParticipantsLen; $k++) :
                $participantName = $db->getOne("SELECT CONCAT(usr_name,', ',usr_firstname) AS name FROM user WHERE usr_id = '" . $tmpParticipants[$k] . "'");
   
                $participantConfirmed = "[?]";
                $l = array_search($tmpParticipants[$k], $tmpConfirmed);
                if (!($l === FALSE)) :
                   $participantConfirmed = "[" . getLngt("OK") . "]";
                else :
                   if ($tmpParticipants[$k] == $tmpUsrId) :
                      $participantConfirmed =  "[" . getLngt("OK") . "]";
                   elseif ($tmpParticipants[$k] == $usr_id) :   // Only the user has a link to confirm his/her own entry
                      $participantConfirmed =  "<a href=\"javascript:confirmAppointmentFinishPage('" . $tmpId . "');\">[" . getLngt("Bestätigen") . "]</a>";
                   endif;
                endif;
                $out .= $participantName . "&nbsp;" . $participantConfirmed . "<br>";
            endfor;
         else :
            $out .= "&nbsp;";
         endif;
         $out .= "</td>";
         
         // Text (Edit, read only)
         $out .= "<td align=\"left\" valign=\"center\" bgcolor=\"#" . $cellCol . "\">";
         if ($tmpApCat3 != "" && $tmpApCat3 > 0) :
            $out .= "<b>" . getFieldValueFromClause("metatype","mt_value","mt_type = 'appointment_category_3' AND mt_sort = '" . $tmpApCat3 . "'") . "</b>";
            $out .= "<br><img src=\"../images/spacer_black.jpg\" width=\"100%\" height=\"1\">";
         endif;
         if ($f_apIdToUpdate == $tmpId) :
            $out .= "<textarea name=\"f_text_" . $tmpId . "\" cols=\"30\" rows=\"5\">" . $tmpText . "</textarea>";
         else :
            $out .= $tmpText;
         endif;
         $out .= "</td>";

         // Potential customer relation (Company name and EID)
         if ($tmpCsId != "") :
            $out .= "<td width=\"205\" align=\"left\" valign=\"center\" bgcolor=\"#" . $cellCol . "\">" . $tmpCmpComp . "<br>" . ($tmpCmpComp2 != "" ? $tmpCmpComp2 . "<br>" : "") . $tmpCsEid . "<br>"
                  . "<input type=\"button\" name=\"action\" value=\"" . getLngt("Details") . "\" onClick=\"openCustomerSpecial('" . $tmpCmpId . "');\">"
                  . "<input type=\"button\" name=\"action\" value=\"" . getLngt("Berichte") . "\" onClick=\"getCsHistory('" . $tmpCsEid . "');\">"
                  . "<input type=\"button\" name=\"action\" value=\"" . getLngt("Statistik") . "\" onClick=\"openCustomerStatistics('" . $tmpCsEid . "');\">"
                  . "</td>";
         else :
            $out .= "<td width=\"200\" align=\"left\" valign=\"center\" bgcolor=\"#" . $cellCol . "\">&nbsp;</td>";
         endif;

         // Actions
         $out .= "<td width=\"110\" align=\"center\" valign=\"center\" bgcolor=\"#" . $cellCol . "\">";
         $out .= "<input type=\"button\" class=\"minwidth\" name=\"action\" value=\"" . getLngt("Bearbeiten") . "\" onClick=\"updateAppointment('" . $tmpId . "');\">";
         $out .= "<br>";
         $out .= "<input type=\"button\" class=\"minwidth\" name=\"action\" value=\"" . getLngt("Entfernen") . "\" onClick=\"removeAppointmentFinishPage('" . $tmpId . "');\">";
         $out .= "<br>";
         $out .= "<input type=\"button\" class=\"minwidth\" name=\"action\" value=\"" . getLngt("Wiedervorlage") . "\" onClick=\"openCalendar('1','" . $tmpId . "');\">";
         if ($tmpApCat4 == "1") :
            $out .= "<br>";
            $out .= "<input type=\"button\" class=\"minwidth\" name=\"action\" value=\"" . getLngt("Erledigt") . "\" onClick=\"confirmActionAppointmentFinishPage('setAppointmentFinished','" . $tmpId . "','" . getLngt("Möchten Sie den Termin als erledigt markieren?") . "');\">";
         endif;      
         $out .= "</td>";

         if ($j < $lenApArray - 1) : $out .= "</tr><tr>"; endif;
     endfor;
     // Fill up the rest of the week
     if ($tmpExecDateDayNumRemember <= 7) :
        $out .= "</tr>";
        while ($tmpExecDateDayNumRemember <= 7) :
           if ($tmpExecDateDayNumRememberArray[$tmpExecDateDayNumRemember] == "0") :
              $tmpMktime = mktime(0, 0, 0, $firstDayOfWeek[1], $firstDayOfWeek[0] + ($tmpExecDateDayNumRemember - 1), $firstDayOfWeek[2]);
              $tmpDayNum = date("w", $tmpMktime);
              if ($tmpDayNum == 0) : $tmpDayNum = "7"; endif;
              $out .= "<td width=\"50\" align=\"center\" valign=\"center\" bgcolor=\"#" . $cellCol . "\"><b>" . $calWeekDays[$tmpDayNum - 1] . "<br>" . date("d", $tmpMktime) . "." . date("m", $tmpMktime) . ".</b></td>";
              $out .= "<td bgcolor=\"#" . $cellCol . "\">&nbsp;</td>";
              // $out .= "<td bgcolor=\"#" . $cellCol . "\">&nbsp;</td>";
              $out .= "<td bgcolor=\"#" . $cellCol . "\">&nbsp;</td>";
              $out .= "<td bgcolor=\"#" . $cellCol . "\">&nbsp;</td>";
              $out .= "<td bgcolor=\"#" . $cellCol . "\">&nbsp;</td>";
              $out .= "<td bgcolor=\"#" . $cellCol . "\">&nbsp;</td>";
              $out .= "</tr><tr>";
           endif;
           $tmpExecDateDayNumRemember++;
        endwhile;
     endif;
  endif;
  $out .= "</tr>";
  return $out;
}

// Prints the headline with the current month
// $selYear  : Selected year
// $selMonth : Selected month
// $cellCol  : Colour of the cell
// $csId     : Special customer
function printAppointmentsOfOneMonth($selYear, $selMonth, $csId = "", $cellCol = "FFFFFF") {
  global $db, $PHP_SELF;
  global $usr_id, $f_apIdToUpdate;
  global $calCurrentWeekNum, $calWeekDays;
  global $calMonthDays;
/*
  // Get the calendar week of the first day of the selected month
  $calFirstWeekNumofTheMonth = calFirstWeekNumofMonth($selMonth, $selYear);  
  // Get the number of the first day of the selected month
  $calFirstDayNumOfTheMonth = calFirstDayNumOfMonth($selMonth, $selYear);
  // Get appointments of the specified month
  $apArray = getAppointmentsFromDB($selYear, $selMonth, "1", $selYear, $selMonth, $calMonthDays[$selMonth - 1]);
  $lenApArray = count($apArray);  
  $monthBeginDate = date("Y-m-d", mktime(0, 0, 0, $selMonth, "1", $selYear));
  $monthEndDate = date("Y-m-d", mktime(0, 0, 0, $selMonth, $calMonthDays[$selMonth - 1], $selYear));  
  // Modifies array according to the appointments starting and ending on different days
  $apArray = modifyIntervalAppointments2SingleDayAppointments($apArray, $monthBeginDate, $monthEndDate);
*/  
  // Get the calendar week of the first day of the selected month
  $calFirstWeekNumofTheMonth = calFirstWeekNumofMonth($selMonth, $selYear);  
  // Get the number of the first day of the selected month
  $calFirstDayNumOfTheMonth = calFirstDayNumOfMonth($selMonth, $selYear);
  $apArray = getAppointmentsOfOneMonth($selYear, $selMonth, $csId);
  $lenApArray = count($apArray);

  $dayCounter = 1;
  $appointmentCounter = 0;
  $out = "<tr>";
  for ($i = 1; $i < 7; $i++) :
     // Display the calendar week
     $out .= "<td width=\"30\" align=\"center\" bgcolor=\"#AAFFAA\">";
     $out .= $calFirstWeekNumofTheMonth;
     $out .= "</td>";
     // Display the days of the calendar week
     for ($j = 1; $j <= 7; $j++) :
         if ((($i > 1) || ($i == 1 && $j >= $calFirstDayNumOfTheMonth)) && $dayCounter <= $calMonthDays[$selMonth - 1]) :
            $cellCol2 = $cellCol;
            if ($selYear == date("Y") && $selMonth == date("m") && $dayCounter == date("d")) :
               $cellCol2 = "FFFF00";  // Yellow
            endif;
            $out .= "<td align=\"left\" valign=\"top\" bgcolor=\"#" . $cellCol2 . "\">";
            $out .= "<span class=\"f8np1\">" . pad($dayCounter,2) . "." . pad($selMonth,2) . ".</span>";   // "&nbsp;&nbsp;&nbsp;" . substr($calWeekDays[$j - 1],0,2) . 

            // display appointments of the day
            for ($a = $appointmentCounter; $a < $lenApArray; $a++) :
                $tmpId = $apArray[$a][0];
                $tmpText = $apArray[$a][1];
                  $tmpText = nl2br($tmpText);
                $tmpExecDate = substr($apArray[$a][2],0,10);
                $tmpExecDateYear = substr($apArray[$a][2],0,4);
                $tmpExecDateMonth = substr($apArray[$a][2],5,2);
                $tmpExecDateDay = substr($apArray[$a][2],8,2);
                $tmpExecDateDayNum = date("w", mktime(0, 0, 0, $tmpExecDateMonth, $tmpExecDateDay, $tmpExecDateYear));
                if ($tmpExecDateDayNum == 0) : $tmpExecDateDayNum = "7"; endif;
                $tmpExecTime = substr($apArray[$a][2],11,5);
                $tmpCmpId = trim($apArray[$a][3]);
                $tmpCmpComp = trim($apArray[$a][4]);
                $tmpCmpComp2 = trim($apArray[$a][5]);
                $tmpCsId = $apArray[$a][6];
                $tmpCsEid = $apArray[$a][7];
                $tmpEndDate = substr($apArray[$a][8],0,10);
                $tmpEndTime = substr($apArray[$a][8],11,5);
                $tmpUsrId = trim($apArray[$a][9]);
                $tmpUsrFirstname = trim($apArray[$a][10]);
                $tmpUsrName = trim($apArray[$a][11]);
                $tmpParticipants = trim($apArray[$a][12]);
                  $tmpParticipants = substr($tmpParticipants,1,-1);     // Remove commata from db-field
                $tmpConfirmed = trim($apArray[$a][13]);
                  $tmpConfirmed = substr($tmpConfirmed,1,-1);           // Remove commata from db-field
                $tmpApCat4 = $apArray[$a][21];

                if ($tmpExecDateDay == $dayCounter) :
                   $out .= "<br><img src=\"../images/spacer_black.jpg\" width=\"100%\" height=\"1\">";
                   $out .= "<b>" . $tmpExecTime . " - " . $tmpEndTime . "</b>";
                   if ($tmpApCat4 == "1") :
                      $out .= "&nbsp;&nbsp;&nbsp;&nbsp;" . "<img src=\"../images/ap_clock.png\" width=\"15\" height=\"15\">";
                   endif;
                   $out .= "<br>";
                   $out .= "<b>" . $tmpText. "</b><br>";

                   // Customer buttons
                   if ($tmpCsId != "") :
                      $out .= "Kunde: " . $tmpCsEid . "<br>" . $tmpCmpComp . "&nbsp;" . ($tmpCmpComp2 != "" ? $tmpCmpComp2 : "") . "<br>"
                            . "<input class=\"smaller\" type=\"button\" name=\"action\" value=\"" . getLngt("Details") . "\" onClick=\"openCustomerSpecial('" . $tmpCmpId . "');\">"
                            . "<input class=\"smaller\" type=\"button\" name=\"action\" value=\"" . getLngt("Berichte") . "\" onClick=\"getCsHistory('" . $tmpCsEid . "');\">"
                            . "<input class=\"smaller\" type=\"button\" name=\"action\" value=\"" . getLngt("Statistik") . "\" onClick=\"openCustomerStatistics('" . $tmpCsEid . "');\">";
                   endif;
                   $out .= "<br>";

                   // Appointment buttons
                   $out .= "<input type=\"button\" class=\"smaller\" name=\"action\" value=\"" . getLngt("Bearbeiten") . "\" onClick=\"updateAppointment('" . $tmpId . "');\">"
                         . "<input type=\"button\" class=\"smaller\" name=\"action\" value=\"" . getLngt("Entfernen") . "\" onClick=\"removeAppointmentFinishPage('" . $tmpId . "');\">"
                         . "<input type=\"button\" class=\"smaller\" name=\"action\" value=\"" . getLngt("Wiedervorlage") . "\" onClick=\"openCalendar('1','" . $tmpId . "');\">";
                   if ($tmpApCat4 == "1") :
                      $out .= "<input type=\"button\" class=\"smaller\" name=\"action\" value=\"" . getLngt("Erledigt") . "\" onClick=\"confirmActionAppointmentFinishPage('setAppointmentFinished','" . $tmpId . "','" . getLngt("Möchten Sie den Termin als erledigt markieren?") . "');\">";
                   endif;

                   $appointmentCounter++;
                else :
                   break;
                endif;
            endfor;
            $out .= "</td>";

            $dayCounter++;
         else :
            $out .= "<td align=\"left\" valign=\"top\" bgcolor=\"#" . $cellCol . "\">&nbsp;</td>";
         endif;
     endfor;
     if ($i < 6) : $out .= "</tr><tr>"; endif;

     // Check especially for changing of the year
     if ($selMonth == 1 && $calFirstWeekNumofTheMonth >= 52) :
        $calFirstWeekNumofTheMonth = 0;
     endif;
     $calFirstWeekNumofTheMonth++;
     if ($selMonth == 12 && $calFirstWeekNumofTheMonth > calLastWeekNumofYear($selYear)) :
        $calFirstWeekNumofTheMonth = 1;
     endif;     
     
  endfor;
  $out .= "</tr>";
  return $out;
}

// Prints the headline with the current month
// $selYear  : Selected year
// $selMonth : Selected month
// $cellCol  : Colour of the cell
// $csId     : Special customer
function printAppointmentsOfOneYear($selYear, $csId = "", $cellCol = "FFFFFF") {
  global $db, $PHP_SELF;
  global $usr_id, $f_apIdToUpdate;
  global $calCurrentWeekNum, $calWeekDays;
  global $calMonthNames, $calMonthDays;
  
  $out = "";
  for ($j = 1; $j <= 12; $j++) :
      $out .= "<tr><td class=\"menu_bgcol\" colspan=\"8\"><br><b>" . $calMonthNames[$j - 1] . "</b><br></td></tr>";
      $out .= printAppointmentsOfOneMonth($selYear, $j, $csId);
  endfor;
  $out .= "<tr><td class=\"menu_bgcol\" colspan=\"8\"><br>&nbsp;<br></td></tr>";
  return $out;
}


function printAppointmentStatistic($csId = "", $cellCol = "FFFFFF") {
  global $db, $PHP_SELF;
  global $usr_id, $f_apIdToUpdate;
  global $calCurrentWeekNum, $calWeekDays;
  global $calMonthNames, $calMonthDays;
  global $f_day_from_apstat, $f_month_from_apstat, $f_year_from_apstat, $f_day_to_apstat, $f_month_to_apstat, $f_year_to_apstat;

  $out = "<table>\n";
  $out .= "<br>";
  $out .= "<tr><td>" . getLngt("Von:") . "\n";
  $out .= "<select name=\"f_day_from_apstat\" class=\"f8np1\" onchange=\"fillDateFields(0, 'maincontent', 'appointment', 'f_day_from_apstat', 'f_day_from_apstat', 'f_month_from_apstat', 'f_year_from_apstat', '', '', '')\"></select>\n";
  $out .= "<select name=\"f_month_from_apstat\" class=\"f8np1\" onchange=\"fillDateFields(0, 'maincontent', 'appointment', 'f_month_from_apstat', 'f_day_from_apstat', 'f_month_from_apstat', 'f_year_from_apstat', '', '', '')\"></select>\n";
  $out .= "<select name=\"f_year_from_apstat\" class=\"f8np1\" onchange=\"fillDateFields(0, 'maincontent', 'appointment', 'f_year_from_apstat', 'f_day_from_apstat', 'f_month_from_apstat', 'f_year_from_apstat', '', '', '')\"></select>\n";
  $out .= "&nbsp;&nbsp;" . getLngt("bis:") . "\n";
  $out .= "<select name=\"f_day_to_apstat\" class=\"f8np1\" onchange=\"fillDateFields(0, 'maincontent', 'appointment', 'f_day_to_apstat', 'f_day_to_apstat', 'f_month_to_apstat', 'f_year_to_apstat', '', '', '')\"></select>\n";
  $out .= "<select name=\"f_month_to_apstat\" class=\"f8np1\" onchange=\"fillDateFields(0, 'maincontent', 'appointment', 'f_month_to_apstat', 'f_day_to_apstat', 'f_month_to_apstat', 'f_year_to_apstat', '', '', '')\"></select>\n";
  $out .= "<select name=\"f_year_to_apstat\" class=\"f8np1\" onchange=\"fillDateFields(0, 'maincontent', 'appointment', 'f_year_to_apstat', 'f_day_to_apstat', 'f_month_to_apstat', 'f_year_to_apstat', '', '', '')\"></select>\n";
  /*
  $out .= "<select class=\"f8np1\" name=\"f_day_from_apstat\" class=\"f8np1\" onchange=\"fillDateFieldsCheck(0, 'maincontent', 'appointment', 'f_day_from_apstat', 'f_day_from_apstat', 'f_month_from_apstat', 'f_year_from_apstat', '', '', '', 'f_day_to_apstat', 'f_month_to_apstat', 'f_year_to_apstat', '', '', '')\"></select>\n";
  $out .= "<select class=\"f8np1\" name=\"f_month_from_apstat\" class=\"f8np1\" onchange=\"fillDateFieldsCheck(0, 'maincontent', 'appointment', 'f_month_from_apstat', 'f_day_from_apstat', 'f_month_from_apstat', 'f_year_from_apstat', '', '', '', 'f_day_to_apstat', 'f_month_to_apstat', 'f_year_to_apstat', '', '', '')\"></select>\n";
  $out .= "<select class=\"f8np1\" name=\"f_year_from_apstat\" class=\"f8np1\" onchange=\"fillDateFieldsCheck(0, 'maincontent', 'appointment', 'f_year_from_apstat', 'f_day_from_apstat', 'f_month_from_apstat', 'f_year_from_apstat', '', '', '', 'f_day_to_apstat', 'f_month_to_apstat', 'f_year_to_apstat', '', '', '')\"></select>\n";
  $out .= "&nbsp;&nbsp;";
  $out .= "<select class=\"f8np1\" name=\"f_day_to_apstat\" class=\"f8np1\" onchange=\"fillDateFieldsCheck(0, 'maincontent', 'appointment', 'f_day_to_apstat', 'f_day_from_apstat', 'f_month_from_apstat', 'f_year_from_apstat', '', '', '', 'f_day_to_apstat', 'f_month_to_apstat', 'f_year_to_apstat', '', '', '')\"></select>\n";
  $out .= "<select class=\"f8np1\" name=\"f_month_to_apstat\" class=\"f8np1\" onchange=\"fillDateFieldsCheck(0, 'maincontent', 'appointment', 'f_month_to_apstat', 'f_day_from_apstat', 'f_month_from_apstat', 'f_year_from_apstat', '', '', '', 'f_day_to_apstat', 'f_month_to_apstat', 'f_year_to_apstat', '', '', '')\"></select>\n";
  $out .= "<select class=\"f8np1\" name=\"f_year_to_apstat\" class=\"f8np1\" onchange=\"fillDateFieldsCheck(0, 'maincontent', 'appointment', 'f_year_to_apstat', 'f_day_from_apstat', 'f_month_from_apstat', 'f_year_from_apstat', '', '', '', 'f_day_to_apstat', 'f_month_to_apstat', 'f_year_to_apstat', '', '', '')\"></select>\n";
  */
  $out .= "<br><br>";
  $out .= "</td></tr>\n";
  $out .= "</table>\n";

  // $apArray = getAppointmentsFromDB($selYear, "1", "1", $selYear, $selMonth, $calMonthDays[$selMonth - 1]);
  $apArray = getAppointmentsFromDB($f_year_from_apstat, $f_month_from_apstat, $f_day_from_apstat, $f_year_to_apstat, $f_month_to_apstat, $f_day_to_apstat, $csId);
  $lenApArray = count($apArray);

  $statArray = array();
  $statUserArray = array();
  $statApCatArray = array();

  // Init arrays
  for ($j = 0; $j < $lenApArray; $j++) :
      $statUserArray[$j] = 0;
      $statApCatArray[1][$j] = 0;
      $statApCatArray[2][$j] = 0;
      $statApCatArray[3][$j] = 0;
      $statApCatArray[4][$j] = 0;
  endfor;

  for ($j = 0; $j < $lenApArray; $j++) :
      $tmpId = $apArray[$j][0];
      $tmpText = $apArray[$j][1];
        $tmpText = nl2br($tmpText);
      $tmpExecDateTime = $apArray[$j][2];
        $tmpExecDate = substr($tmpExecDateTime,8,2) . "." . substr($tmpExecDateTime,5,2) . "." . substr($tmpExecDateTime,0,4);
        $tmpExecTime = substr($tmpExecDateTime,11,5);
      $tmpCmpId = trim($apArray[$j][3]);
      $tmpCmpComp = trim($apArray[$j][4]);
      $tmpCmpComp2 = trim($apArray[$j][5]);
      $tmpCsId = $apArray[$j][6];
      $tmpCsEid = $apArray[$j][7];
      $tmpEndDateTime = $apArray[$j][8];
        $tmpEndDate = substr($tmpEndDateTime,8,2) . "." . substr($tmpEndDateTime,5,2) . "." . substr($tmpEndDateTime,0,4);
        $tmpEndTime = substr($tmpEndDateTime,11,5);
      $tmpUsrId = trim($apArray[$j][9]);
      $tmpUsrFirstname = trim($apArray[$j][10]);
      $tmpUsrName = trim($apArray[$j][11]);
      $tmpParticipants = trim($apArray[$j][12]);
        $tmpParticipants = substr($tmpParticipants,1,-1);     // Remove commata from db-field
      $tmpConfirmed = trim($apArray[$j][13]);
        $tmpConfirmed = substr($tmpConfirmed,1,-1);           // Remove commata from db-field
      $tmpCsUsrName = trim($apArray[$j][14]);
      $tmpCsUsrFirstname = trim($apArray[$j][15]);
      $tmpCsUsrPhone = $apArray[$j][16];
      $tmpCsUsrPhone2 = $apArray[$j][17];
      $tmpApCat1 = $apArray[$j][18];
      $tmpApCat2 = $apArray[$j][19];
      $tmpApCat3 = $apArray[$j][20];
      $tmpApCat4 = $apArray[$j][21];
/*
$retArray[] = array($row["ap_id"], $row["ap_text"], $row["ap_execdate"], $row["cmp_id"], $row["cmp_comp"], $row["cmp_comp2"], $row["cs_id"], $row["cs_eid"], $row["ap_enddate"], $row["usr_id"], $row["usr_firstname"], $row["usr_name"], $row["ap_participants"], $row["ap_confirmed"], $row["pt_cmp_comp"], $row["pt_cmp_comp2"], $row["pt_cs_eid"], $row["pt_id"], $row["ap_category_1"], $row["ap_category_2"], $row["ap_category_3"], $row["ap_category_4"]);

  1 alle Einträge
  2   selbst erstellte Einträge
  3      nur für mich sichtbar
  4      nur für Teilnehmer sichtbar
  5      für alle sichtbar
  6   Einträge anderer Mitarbeiter
  7      ich bin Teilnehmer
  8      alle weiteren freigegebenen

      // $j = array_search($f_usr_id, $usrIdArray);
      // if ($j === FALSE) :
*/

      if ($statArray[$tmpApCat1][$tmpApCat2][$tmpApCat3][$tmpApCat4] == "") : $statArray[$tmpApCat1][$tmpApCat2][$tmpApCat3][$tmpApCat4] = "0"; endif;
      $statArray[$tmpApCat1][$tmpApCat2][$tmpApCat3][$tmpApCat4]++;
      
      $statApCatArray[1][$tmpApCat1]++;
      $statApCatArray[2][$tmpApCat2]++;
      $statApCatArray[3][$tmpApCat3]++;
      $statApCatArray[4][$tmpApCat4]++;

  endfor;

  $tableEmptyLine = "<td colspan=\"3\">&nbsp;</td>\n";
  $tableSpacerCol = "<td>&nbsp;&nbsp;&nbsp;</td>";
  $out .= "<table>\n";
  $out .= "<tr><td>" . getLngt("Alle Termine") . "</td>" . $tableSpacerCol . "<td>" . $lenApArray . "</td></tr>\n";   // All appointments
  // Iterate appointment categories
  for ($i = 1; $i <= 4; $i++) :
      $out .= $tableEmptyLine;
      $numOfRows = getCountOfTable("metatype", "mt_type = 'appointment_category_" . $i . "'");
      for ($j = 0; $j <= $numOfRows; $j++) :
          $tmpOutText = getFieldValueFromClause("metatype","mt_value","mt_type = 'appointment_category_" . $i . "' AND mt_sort = '" . $j . "'");
          
          // Check for existence of another output text defined by parameter
          $maskApCatx_y = getParameterValue("0", "MASK_AP_CAT_" . $i . "_" . $j, "0");
          if ($maskApCatx_y != "") :
             $tmpOutText = $maskApCatx_y;
          endif;
          
          if ($tmpOutText != "") :
             $out .= "<tr><td>" . getLngt($tmpOutText) . "</td>" . $tableSpacerCol . "<td align=\"right\">" . $statApCatArray[$i][$j] . "</td></tr>\n";
          endif;
      endfor;
  endfor;
  $maskApCat4_1 = getParameterValue("0", "MASK_AP_CAT_4_9", "0");
  if ($maskApCat4_1 == "") :
     $maskApCat4_1 = getLngt("Deaktivierte Termine");
  endif;
  $out .= "<tr><td>" . getLngt($maskApCat4_1) . "</td>" . $tableSpacerCol . "<td align=\"right\">" . $statApCatArray[4][2] . "</td></tr>\n";    // Deactivated appointments
  $out .= $tableEmptyLine;
  $out .= "</table>\n";

  return $out;
}



// ***********
// * Actions *
// ***********

if ($f_act == "insertResubmissionAppointment") :
   if ($f_ap_resubmission_id != "") :
      $currentTime = getDateTime("0");
   
      // Get data of the appointment to be resubmitted   
      $tmpFields = getFieldsValueFromId("phoenix_group.appointment", "ap_id", $f_ap_resubmission_id, array("ap_participants","ap_text","cs_id","csc_id","pt_id"));
      $tmp_ap_participants = $tmpFields[0];
      $tmp_ap_text = $tmpFields[1];
      $tmp_cs_id = $tmpFields[2];
      $tmp_csc_id = $tmpFields[3];
      $tmp_pt_id = $tmpFields[4];
      
      insertStmt("phoenix_group.appointment", array("usr_id", $usr_id, "hq_id", $hq_id, "ap_participants", $tmp_ap_participants, "ap_text", $tmp_ap_text, 
                                                    "ap_category_1", $f_ap_resubmission_category_1, "ap_category_2", $f_ap_resubmission_category_2, 
                                                    "ap_category_3", $f_ap_resubmission_category_3, "ap_category_4", $f_ap_resubmission_category_4, 
                                                    "ap_execdate", $f_ap_resubmission_execdate, "ap_enddate", $f_ap_resubmission_enddate, 
                                                    "ap_modifytime", $currentTime, "cs_id", $tmp_cs_id, "csc_id", $tmp_csc_id, "pt_id", $tmp_pt_id));
   else:
      $statusMessage = getLngt("Der Termin kann nicht auf Wiedervorlage gelegt werden!");
   endif;
endif;

if ($f_act == "insertAppointment" || $f_act == "updateAppointment") :

   if ($f_text != "") :

      if ($f_year != "" && $f_month != "" && $f_day != "" && $f_hour != "" && $f_minute != "" && $f_year_to != "" && $f_month_to != "" && $f_day_to != "" && $f_hour_to != "" && $f_minute_to != "" &&
          date("YmdHis", mktime($f_hour,$f_minute,0,$f_month,$f_day,$f_year)) < date("YmdHis", mktime($f_hour_to,$f_minute_to,59,$f_month_to,$f_day_to,$f_year_to))) :

         $currentTime = getDateTime("0");
         $execDatetime = getDateTime("format",array($f_hour,$f_minute,0,$f_month,$f_day,$f_year),"Y-m-d H:i:s");
         $endDatetime = getDateTime("format",array($f_hour_to,$f_minute_to,0,$f_month_to,$f_day_to,$f_year_to),"Y-m-d H:i:s");
         $csId = "";
         $ptId = "";
         if ($g_cs_eid != "") :
            $csId = getFieldValueFromId("customer", "cs_eid", $g_cs_eid, "cs_id");
         endif;
         $f_usr_id_string = "";
         if ($f_usr_id != "" && count($f_usr_id) > 0) : 
            $f_usr_id_string = "," . implode(",", $f_usr_id) . ",";
         endif;

         // INSERT new appointment
         if ($f_act == "insertAppointment") :
            insertStmt("phoenix_group.appointment", array("usr_id", $usr_id, "hq_id", $hq_id, "ap_category_1", $f_ap_cat_1, "ap_category_2", $f_ap_cat_2,
                                                          "ap_category_3", $f_ap_cat_3, "ap_category_4", $f_ap_cat_4,
                                                          "ap_participants", $f_usr_id_string, "ap_text", $f_text, 
                                                          "ap_execdate", $execDatetime, "ap_enddate", $endDatetime, 
                                                          "ap_modifytime", $currentTime, "cs_id", $csId, "csc_id", "", "pt_id", $ptId));
            // $ap_id_new = getLastInsertId();
         endif;

         // UPDATE existing appointment
         if ($f_act == "updateAppointment") :
            if ($f_apIdToUpdate != "") :
               $f_text_update = ${"f_text_" . $f_apIdToUpdate};
               updateStmt("phoenix_group.appointment", "ap_id", $f_apIdToUpdate, array("usr_id", $usr_id, "hq_id", $hq_id, "ap_category_1", $f_ap_cat_1, "ap_category_2", $f_ap_cat_2, "ap_category_3", $f_ap_cat_3,"ap_category_4", $f_ap_cat_4,
                                                                                       "ap_participants", $f_usr_id_string, "ap_text", $f_text, "ap_execdate", $execDatetime, "ap_enddate", $endDatetime, 
                                                                                       "ap_modifytime", $currentTime, "cs_id", $csId, "csc_id", "", "pt_id", $ptId));
               $f_apIdToUpdate = "";  // Reset ID
            else:
              $statusMessage = getLngt("Eine Aktualisierung fand nicht statt!");
            endif;
         endif;
         
         // Send email to participants if requested
         if (($f_sendmail == "1" && $f_usr_id != "" && count($f_usr_id) > 0) ||
             ($f_sendmail_cs == "1" && count($f_emailAdrCs) > 0)) :
         
            $mailAddresses = array();
            // Get email address of the creator of the appointment
            $fromEmailAddress = getFieldValueFromId("user", "usr_id", $usr_id, "usr_email");
            if (checkEmailFormat($fromEmailAddress)) : 
               array_push($mailAddresses, $fromEmailAddress);
            endif;
            // Get email addresses of the participants (employees)
            $lenTmp = count($f_usr_id);
            for ($i = 0; $i < $lenTmp; $i++) :
                $toEmailAddress = getFieldValueFromId("user", "usr_id", $f_usr_id[$i], "usr_email");
                if (checkEmailFormat($toEmailAddress)) :
                   array_push($mailAddresses, $toEmailAddress);
                // else :
                //   $statusMessage .= getLngt("Nicht alle Empfänger haben eine gültige Emailadresse!");
                endif;
            endfor;
            // Check for external addresses
            if ($f_sendmail_cs == "1") :
               $mailAddresses = array_merge($mailAddresses, $f_emailAdrCs);            
            endif;
            $mailAddressesString = implode(",", $mailAddresses);
         
            $mailObj = new htmlMimeMail();
            
            // Format mailtext
            $mailtext  = "<html><head><meta text/html>";
            $mailtext .= "<style type=\"text/css\">";
            $mailtext .= ".f8np1 { font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 8pt; font-weight: normal; padding: 1px}";
            $mailtext .= ".f8bp1 { font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 8pt; font-weight: bold; padding: 1px}";
            $mailtext .= ".f8np1_red { font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 8pt; font-weight: normal; padding: 1px; color: #FF0000;}";
            $mailtext .= "</style>";
            $mailtext .= "</head><body><h4>";
            
            if ($f_mail_salutation == "") :
               $mailtext .= "<div class=\"f8bp1\">" . getLngt("Sehr geehrte Damen und Herren,") . "</div><br>";
            else :
               $mailtext .= "<div class=\"f8bp1\">" . $f_mail_salutation . "</div><br>";
            endif;
         
            if ($f_text != "") :
              // $f_text = str_replace("\n", '<br>', $f_text);
              $f_text = str_replace("\r", '<br>', $f_text);
            endif;
            $mailtext .= "<div class=\"f8bp1\">" . $f_text . "</div><br>";
            
            if ($f_mail_greetings == "") :
               $mailtext .= "<div class=\"f8bp1\">" . getLngt("Mit freundlichem Gruß!") . "</div><br>";
            else :
               $mailtext .= "<div class=\"f8bp1\">" . $f_mail_greetings . "</div><br>";
            endif;         
            
            // Logo
            $logoName = getParameterValue("0", "IMG_LOGO_NAME", $currentHqId);
            $logoHeight = getParameterValue("0", "IMG_LOGO_HEIGHT", $currentHqId);
            $logoWidth = getParameterValue("0", "IMG_LOGO_WIDTH", $currentHqId);
            if ($logoName != "" && $logoHeight != "" && $logoWidth != "") :
               $mailtext .= "<br><div><img src=\"../images/external/" . $logoName . "\" border=\"0\" height=\"" . $logoHeight . "\" width=\"" . $logoWidth . "\"></div><br><br>";
            endif;
            $mailtext .= "</body></html>";
         
            $mailObj->setHtml($mailtext, null, "./");
            // $mailObj->setHtml($f_text, null, "./");
         
            $mailObj->setFrom($fromEmailAddress);
            // $mailObj->setCc($mailCcAddress);
            // $mailObj->setBcc($mailBccAddress);
            $mailObj->setSubject("Neuer Termin: " . $execDatetime);
            $mailResult = $mailObj->send(array($mailAddressesString), 'smtp');
            if (!$mailResult) :
               $statusMessage .= getLngt("Die Nachricht konnte nicht gesendet werden!") . " ";
            endif;
            $mailObj = NULL;
         endif;
         
         // Reset parameters
         $f_ap_cat_1 = "1";
         $f_ap_cat_2 = "1";
         $f_ap_cat_3 = "1";
         $f_ap_cat_4 = "0";
         if ($constMaskApCat4Preset == "1") : $f_ap_cat_4 = "1"; endif;
      else :
         $statusMessage = getLngt("Die Zeitangaben sind nicht korrekt!");
      endif;
   else:
     $statusMessage = getLngt("Erfassen Sie bitte einen Text zum Termin!");
     $displayState = "1";
   endif;
endif;

if ($f_act == "removeAppointment") :
   if ($f_apIdToRemove != "") :
   
      // Get data of the appointment
      $tmpExecDatetime = getFieldValueFromId("phoenix_group.appointment", "ap_id", $f_apIdToRemove, "ap_execdate");
      $tmpText = getFieldValueFromId("phoenix_group.appointment", "ap_id", $f_apIdToRemove, "ap_text");
      $tmpParticipants = getFieldValueFromId("phoenix_group.appointment", "ap_id", $f_apIdToRemove, "ap_participants");
        $tmpParticipants = substr($tmpParticipants,1,-1);   // Remove commata from db-field
        $tmpParticipants = spliti(",", $tmpParticipants);   // It has to be an array   
   
      deleteStmt("phoenix_group.appointment","ap_id = ".$f_apIdToRemove);
      $f_apIdToRemove = "";  // Reset ID
      
      // Send email to participants if requested
      if ($f_sendmail == "1") :

         if ($tmpParticipants != "" && count($tmpParticipants) > 0) :

            $mailAddresses = array();
            // Get email address of the creator of the appointment
            $fromEmailAddress = getFieldValueFromId("user", "usr_id", $usr_id, "usr_email");
            if (checkEmailFormat($fromEmailAddress)) : 
               array_push($mailAddresses, $fromEmailAddress);
            endif;
            // Get email addresses of the participants
            $lenTmp = count($tmpParticipants);
            for ($i = 0; $i < $lenTmp; $i++) :
                $toEmailAddress = getFieldValueFromId("user", "usr_id", $tmpParticipants[$i], "usr_email");
                if (checkEmailFormat($toEmailAddress)) :
                   array_push($mailAddresses, $toEmailAddress);
                // else :
                //   $statusMessage .= getLngt("Nicht alle Empfänger haben eine gültige Emailadresse!");
                endif;
            endfor;
            $mailAddressesString = implode(",", $mailAddresses);
            
            $mailObj = new htmlMimeMail();

            // Format mailtext
            $mailtext  = "<html><head><meta text/html>";
            $mailtext .= "<style type=\"text/css\">";
            $mailtext .= ".f8np1 { font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 8pt; font-weight: normal; padding: 1px}";
            $mailtext .= ".f8bp1 { font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 8pt; font-weight: bold; padding: 1px}";
            $mailtext .= ".f8np1_red { font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 8pt; font-weight: normal; padding: 1px; color: #FF0000;}";
            $mailtext .= "</style>";
            $mailtext .= "</head><body><h4>";            
            
            $mailtext .= "<div class=\"f8bp1\">" . getLngt("Sehr geehrte Damen und Herren,") . "</div><br>";
            if ($tmpText != "") :
              // $f_text = str_replace("\n", '<br>', $f_text);
              $tmpText = str_replace("\r", '<br>', $tmpText);
            endif;
            $mailtext .= "<div class=\"f8bp1\">" . $tmpText . "</div><br>";
            $mailtext .= "<div class=\"f8bp1\">" . getLngt("Mit freundlichem Gruß!") . "</div><br>";
            // Logo
            $logoName = getParameterValue("0", "IMG_LOGO_NAME", $currentHqId);
            $logoHeight = getParameterValue("0", "IMG_LOGO_HEIGHT", $currentHqId);
            $logoWidth = getParameterValue("0", "IMG_LOGO_WIDTH", $currentHqId);
            if ($logoName != "" && $logoHeight != "" && $logoWidth != "") :
               $mailtext .= "<br><div><img src=\"../images/external/" . $logoName . "\" border=\"0\" height=\"" . $logoHeight . "\" width=\"" . $logoWidth . "\"></div><br><br>";
            endif;
            $mailtext .= "</body></html>";
            
            $mailObj->setHtml($mailtext, null, "./");
   
            $mailObj->setFrom($fromEmailAddress);
            // $mailObj->setCc($mailCcAddress);
            // $mailObj->setBcc($mailBccAddress);
            $mailObj->setSubject("Termin abgesagt: " . $tmpExecDatetime);
            $mailResult = $mailObj->send(array($mailAddressesString), 'smtp');
            if (!$mailResult) :
               $statusMessage .= getLngt("Die Nachricht konnte nicht gesendet werden!") . " ";
            endif;
            $mailObj = NULL;
         else :
           $statusMessage = getLngt("Es sind keine Teilnehmer eingetragen!");
         endif;
      endif;
   else:
     $statusMessage = getLngt("Es wurde kein Termin zum Löschen selektiert!");
   endif;
endif;

if ($f_act == "confirmAppointment") :
   if ($f_apIdToConfirm != "") :
      // Get confirmation string from appointment
      $tmpApConfirmed = getFieldValueFromId("phoenix_group.appointment", "ap_id", $f_apIdToConfirm, "ap_confirmed");
      $tmpApConfirmed = substr($tmpApConfirmed,1,-1);   // Remove commata from db-field
      $tmpApConfirmed = spliti(",", $tmpApConfirmed);   // It has to be an array
      $j = array_search($usr_id, $tmpApConfirmed);
      if ($j === FALSE) :
         if (count($tmpApConfirmed) == 1 && trim($tmpApConfirmed[0] == "")) :
            $tmpApConfirmed = array($usr_id);
         else :         
            array_push($tmpApConfirmed, $usr_id);
         endif;
         updateStmt("phoenix_group.appointment", "ap_id", $f_apIdToConfirm, array("ap_confirmed", "," . implode(",", $tmpApConfirmed) . ","));
      endif;

      $f_apIdToConfirm = "";  // Reset ID
   else:
     $statusMessage = getLngt("Die Teilnahme wurde nicht bestätigt!");
   endif;
endif;

if ($f_act == "setAppointmentFinished") :
   if ($f_apId != "") :
      $doUpdate = true;
      $constMaskApWarningDisablingQuestion = getParameterValue("0", "MASK_AP_WARNING_DISABLE_QUESTION_NO_REPORT_OF_SAME_DAY", "0");
      if ($constMaskApWarningDisablingQuestion == "1") :         
         $tmpFields = getFieldsValueFromId("phoenix_group.appointment", "ap_id", $f_apId, array("cs_id","ap_category_1"));
         $tmp_cs_id = $tmpFields[0];
         $tmp_ap_category_1 = $tmpFields[1];
         if ($tmp_cs_id != "" && $tmp_cs_id != "0" && $tmp_ap_category_1 == "1") :
            $doUpdate = false;
            // Check for report entry of the current day
            $currentDate = getDateTime("3");
            $tmp_rp_id = getFieldValueFromClause("phoenix_group.report_process","rp_id","rp_objtype = 'cs' AND rp_objid = '" . $tmp_cs_id . "' AND rp_createtime >= '" . $currentDate . " 00:00:00' AND rp_createtime <= '" . $currentDate . " 23:59:59'");
            if ($tmp_rp_id != "" && $tmp_rp_id != "0") :
               $doUpdate = true;
            endif;
         endif;
      endif;

      // Set appointment done
      if ($doUpdate) :
         updateStmt("phoenix_group.appointment", "ap_id", $f_apId, array("ap_category_4", "2"));
      else :
         $statusMessage = getLngt("Legen Sie bitte erst einen Bericht an zu diesem Termin!");
      endif;
      $f_apId = "";  // Reset ID
   else:
     $statusMessage = getLngt("Eine Deaktivierung konnte nicht stattfinden, weil keine Referenz zu einem Termin besteht!");
   endif;
endif;


// Init time values
$f_day = $selDay; 
$f_month = $selMonth;
$f_year = $selYear;
$f_day_to = $selDay; 
$f_month_to = $selMonth;
$f_year_to = $selYear;


// Output
$js_date = "";
$js_date .= "<script src=\"../include/lib_global.js\" type=\"text/javascript\">\n";
$js_date .= "</script>\n";
$js_date .= "\n";
$js_date .= "<script type=\"text/javascript\">\n";
$js_date .= "<!--\n";
$js_date .= "function initForm() {\n";
$js_date .= "  fillDateFields(1,\"maincontent\",\"appointment\",\"\",\"f_day\",\"f_month\",\"f_year\",\"\",\"\",\"\");\n";
$js_date .= "  setDateTimeFields(\"maincontent\",\"appointment\",".$f_day.",".$f_month.",".$f_year.", \"\", \"\", \"f_day\", \"f_month\", \"f_year\", \"\", \"\", \"\");\n";
$js_date .= "  fillDateFields(1,\"maincontent\",\"appointment\", \"\", \"f_day_to\", \"f_month_to\", \"f_year_to\", \"\", \"\", \"\");\n";
$js_date .= "  setDateTimeFields(\"maincontent\",\"appointment\",".$f_day_to.",".$f_month_to.",".$f_year_to.", \"\", \"\", \"f_day_to\", \"f_month_to\", \"f_year_to\", \"\", \"\", \"\");\n";
if ($viewMode == "9") :
   // Date fields for appointment statistic
   $js_date .= "  fillDateFields(1,\"maincontent\",\"appointment\",\"\",\"f_day_from_apstat\",\"f_month_from_apstat\",\"f_year_from_apstat\",\"\",\"\",\"\");\n";
   $js_date .= "  setDateTimeFields(\"maincontent\",\"appointment\",".$f_day_from_apstat.",".$f_month_from_apstat.",".$f_year_from_apstat.", \"\", \"\", \"f_day_from_apstat\", \"f_month_from_apstat\", \"f_year_from_apstat\", \"\", \"\", \"\");\n";
   $js_date .= "  fillDateFields(1,\"maincontent\",\"appointment\", \"\", \"f_day_to_apstat\", \"f_month_to_apstat\", \"f_year_to_apstat\", \"\", \"\", \"\");\n";
   $js_date .= "  setDateTimeFields(\"maincontent\",\"appointment\",".$f_day_to_apstat.",".$f_month_to_apstat.",".$f_year_to_apstat.", \"\", \"\", \"f_day_to_apstat\", \"f_month_to_apstat\", \"f_year_to_apstat\", \"\", \"\", \"\");\n";
endif;
$js_date .= "}\n";
$js_date .= "-->\n";
$js_date .= "</script>\n";
?>


<html>
<head>
<title><?php echo $pageTitel ?></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

<style type="text/css">
  <?php include_once ("../css/phoenix.css.php"); ?>
  <?php include_once ("../css/navigation.css.php"); ?>
  <?php include_once ("../css/mc.css.php"); ?>
</style>

<?php include_once ("../include/js_framework.inc.php"); ?>

<style type="text/css">
.divpadding10 { padding-top:10px; padding-bottom:10px; padding-left:10px; padding-right:10px;}
input.minwidth { min-width:110px; }
</style>

<script src="../include/checkFormTags.js" type="text/javascript"></script>

<script type="text/javascript">
<!--
// NAVIGATION
<?php echo $jsMenuOut; ?>

function finishPage() {
  document.forms[0].submit();
};

function loadPage(elemId) {
  if (elemId == 0) { // Currently NOP
	} else if (elemId == 1) { document.forms[0].viewMode.value=1; finishPage();
	} else if (elemId == 2) { document.forms[0].viewMode.value=2; finishPage();
	} else if (elemId == 3) { document.forms[0].viewMode.value=3; document.forms[0].selYear.value='<?php echo ec($selYear) ?>'; document.forms[0].selMonth.value='<?php echo ec($selMonth) ?>'; finishPage();
  } else if (elemId == 4) { document.forms[0].viewMode.value=4; document.forms[0].selYear.value='<?php echo ec($selYear) ?>'; finishPage();
	} else if (elemId == 5) { getCsHistory2('');
  } else if (elemId == 9) { document.forms[0].viewMode.value=9; document.forms[0].selYear.value='<?php echo ec($selYear) ?>'; document.forms[0].selMonth.value='<?php echo ec($selMonth) ?>'; finishPage();
  } else { // Currently NOP
  };
};

<?php if ($usedFramework == "2") : ?>

// Prototype.Request
function scan_request(specificURL, parms) {
    var myAjax = new Ajax.Request(
        specificURL,        
        {method: 'get', asynchronous: false, cache: false, parameters: parms}
    );
    eval(myAjax.transport.responseText);
}

<?php else : ?>

// JQuery.Request
function scan_request(url, data) {
  $.ajax({
     type: "GET",
     url: url,
     data: data,
     async: false,
     cache: false,
     success: function(msg){eval(msg);}
  });
}

<?php endif; ?>


function setResubmissionDate(selYear,selMonth,dayCounter) {
	var apId = '<?php echo $apId ?>';
	var fHour = padl(document.forms[0].f_hour.value,2,'0');
  var fMinute = padl(document.forms[0].f_minute.value,2,'0');
	var fHourTo = padl(document.forms[0].f_hour_to.value,2,'0');
  var fMinuteTo = padl(document.forms[0].f_minute_to.value,2,'0');
	if (confirm('<?php echo getLngt("Möchten Sie den Wiedervorlagetermin für den") ?>' + ' ' + dayCounter + '.' + selMonth + '.' + selYear + ' [' + fHour + ':' + fMinute + ' - ' + fHourTo + ':' + fMinuteTo + '] ' + '<?php echo getLngt("eintragen?") ?>')) {
     
     opener.document.forms[0].f_ap_resubmission_id.value = apId;
     opener.document.forms[0].f_ap_resubmission_execdate.value = selYear + "-" + selMonth + "-" + dayCounter + " " + fHour + ":" + fMinute;
     opener.document.forms[0].f_ap_resubmission_enddate.value = selYear + "-" + selMonth + "-" + dayCounter + " " + fHourTo + ":" + fMinuteTo;
     var tmpApCat = eval('document.forms[0].f_ap_cat_1');
     for(var j=0;j<tmpApCat.length;++j) {
        if (tmpApCat.options[j].selected == true) {
           opener.document.forms[0].f_ap_resubmission_category_1.value = tmpApCat.options[j].value;
        }
     }
     var tmpApCat = eval('document.forms[0].f_ap_cat_2');
     for(var j=0;j<tmpApCat.length;++j) {
        if (tmpApCat.options[j].selected == true) {
           opener.document.forms[0].f_ap_resubmission_category_2.value = tmpApCat.options[j].value;
        }
     }
     var tmpApCat = eval('document.forms[0].f_ap_cat_3');
     for(var j=0;j<tmpApCat.length;++j) {
        if (tmpApCat.options[j].selected == true) {
           opener.document.forms[0].f_ap_resubmission_category_3.value = tmpApCat.options[j].value;
        }
     }
     var tmpApCat = eval('document.forms[0].f_ap_cat_4');
     for(var j=0;j<tmpApCat.length;++j) {
        if (tmpApCat.options[j].selected == true) {
           opener.document.forms[0].f_ap_resubmission_category_4.value = tmpApCat.options[j].value;
        }
     }
     opener.document.forms[0].f_act.value='insertResubmissionAppointment';
     opener.document.forms[0].submit();
     this.close();
  };
};

function removeAppointmentFinishPage(apIdToRemove) {
  if (confirm('<?php echo getLngt("Möchten Sie den Termin wirklich löschen?") ?>')) {
  	 if (confirm('<?php echo getLngt("Möchten Sie die teilnehmenden Mitarbeiter per Email benachrichtigen?") ?>')) {
  	 	  document.getElementsByName('f_sendmail[]')[0].checked = true;
  	 }  	
     document.forms[0].f_act.value='removeAppointment';
     document.forms[0].f_apIdToRemove.value=apIdToRemove;
     document.forms[0].submit();
  }
};

function clearAppointmentEditFields() {
  // Begin date fields
  setSelectedValue('f_day', '<?php echo getdateTime("day") ?>');
  setSelectedValue('f_month', '<?php echo getdateTime("month") ?>');
  setSelectedValue('f_year', '<?php echo getdateTime("year") ?>');
  setSelectedValue('f_hour', '<?php echo getdateTime("hour") ?>');
  setSelectedValue('f_minute', '00');
  // End date fields
  setSelectedValue('f_day_to', '<?php echo getdateTime("day") ?>');
  setSelectedValue('f_month_to', '<?php echo getdateTime("month") ?>');
  setSelectedValue('f_year_to', '<?php echo getdateTime("year") ?>');
  setSelectedValue('f_hour_to', '<?php echo getdateTime("hour") ?>');
  setSelectedValue('f_minute_to', '00');
  // Categories
  setSelectedValue('f_ap_cat_1', '1');
  setSelectedValue('f_ap_cat_2', '1');
  setSelectedValue('f_ap_cat_3', '1');
  setSelectedValue('f_ap_cat_4', '0');
  // Participants
  var participantsLen = document.getElementsByName('f_usr_id[]').length;
  for (i = 0; i < participantsLen; i++) {
	  document.getElementsByName('f_usr_id[]')[i].checked = false;
  }  
  // Relations
  document.forms[0].g_cs_eid.value = '';
  // Text
  document.forms[0].f_text.value = '';
  // Toggle to edit mode
  // displayState = '1';
  // toggleDisplay('1');
  document.forms[0].f_apIdToUpdate.value = '';
}

function insertAppointmentFinishPage() {
	var doSubmit = true;

	// Check for appointments regarding the selected day for the new appointment
	var numOfApOfSameDayRegardingNewAp = '0';
  var tmpDayFrom = getSelectedValue('f_day');
  var tmpMonthFrom = getSelectedValue('f_month');
  var tmpYearFrom = getSelectedValue('f_year');
  if (tmpDayFrom != '' && tmpMonthFrom != '' && tmpYearFrom != '') {
  	 scan_request('../groupware/ajaxReqAppointment.php', 'mode=2&f_selUsrId=<?php echo $f_selUsrId ?>&f_day=' + tmpDayFrom + '&f_month=' + tmpMonthFrom + '&f_year=' + tmpYearFrom);
     if (retValue != '') {
        numOfApOfSameDayRegardingNewAp = retValue;
     }
  }
  if (numOfApOfSameDayRegardingNewAp > 0) {
  	 doSubmit = false;
  	 if (confirm(numOfApOfSameDayRegardingNewAp + ' ' + '<?php echo getLngt("Termin(e) haben Sie an dem Tag.") ?>' + ' ' + '<?php echo getLngt("Möchten Sie den Termin trotzdem einfügen?") ?>')) {
  	 	  doSubmit = true;
  	 }
  }

  if (doSubmit) {
	   var doAskForAnotherApCategory3Type = false;
	   var nameOfApCategory3Type = '';
	   var parItemMisc = '<?php echo getParameterValue("0", "MASK_AP_CATEGORY_3_MISC_ITEM", "0") ?>';
     for(i=0;i<document.forms[0].f_ap_cat_3.length;++i) {
        if (document.forms[0].f_ap_cat_3.options[i].selected == true) {     	
           if (document.forms[0].f_ap_cat_3.options[i].value == parItemMisc) {        	
              doAskForAnotherApCategory3Type = true;
              nameOfApCategory3Type = document.forms[0].f_ap_cat_3.options[i].text;
           };
        }
     }
     if (doAskForAnotherApCategory3Type) {
     	 doSubmit = false;
     	 if (confirm('<?php echo getLngt("Wollen Sie einen Termin Typs") ?> '  + nameOfApCategory3Type +  ' <?php echo getLngt("anfertigen?") ?>')) {
     	 	  doSubmit = true;
     	 }
     }
     // if (confirm('<?php echo getLngt("Möchten Sie den Termin wirklich einfügen?") ?>')) {
        if (doSubmit) {
           if (document.forms[0].f_apIdToUpdate.value == '') {
              document.forms[0].f_act.value='insertAppointment';
           } else {
              document.forms[0].f_act.value='updateAppointment';
           }
           document.forms[0].submit();
        }
     // }
  };
};

function confirmAppointmentParticipationFinishPage(apIdToConfirm) {
//	if (confirm('<?php echo getLngt("Teilnahme am Termin bestätigen?") ?>')) {
		 document.forms[0].f_act.value='confirmAppointment';
     document.forms[0].f_apIdToConfirm.value=apIdToConfirm;
     document.forms[0].submit();
//  }
};
function confirmAppointmentFinishPage(apIdToConfirm) {
/*
	if (confirm('<?php echo getLngt("Teilnahme am Termin bestätigen?") ?>')) {
		 document.forms[0].f_act.value='confirmAppointment';
     document.forms[0].f_apIdToConfirm.value=apIdToConfirm;
     document.forms[0].submit();
  }
*/
  vConfirmFuncPar('<?php echo getLngt("Teilnahme am Termin bestätigen?") ?>', confirmAppointmentParticipationFinishPage, 160, '', apIdToConfirm);
};


function actionAppointmentFinishPage(f_act, apId, confirmText) {	
	document.forms[0].f_act.value=f_act;
  document.forms[0].f_apId.value=apId;
  document.forms[0].submit();
};
function confirmActionAppointmentFinishPage(f_act, apId, confirmText) {
  vConfirmFuncPar(confirmText, actionAppointmentFinishPage, 160, '', f_act, apId, confirmText);
};


function updateAppointment(apIdToUpdate) {
  document.forms[0].f_apIdToUpdate.value=apIdToUpdate;
  scan_request('../groupware/ajaxReqAppointment.php', 'mode=1&apId=' + apIdToUpdate);
};

function searchCsCsc() {
  var f_act = 'search';
  var widthPopupWin = 950;
  var heightPopupWin = 600;
  var leftPopupWin = (screen.width / 2) - (widthPopupWin / 2) - 12;
  var topPopupWin = (screen.height / 2) - (heightPopupWin / 2) - 50;
  var popupWin;
  popupWin = window.open("../admin/cs_csc_list.php?f_act=" + f_act + "&allowAllCustomerTypes=1&generic=0000000000001",
    "","dependent=yes,width=" + widthPopupWin + ",height=" +
    heightPopupWin +",left=" + leftPopupWin + ",top=" + topPopupWin +
    ",scrollbars=yes");
};

function clearSpecialCustomer() {	
  document.forms[0].g_cs_eid.value='';
};

function setSpecialCustomer() {	
  document.forms[0].g_cs_eid.value='<?php echo $g_cs_eid ?>';
};

function searchPt() {
  var f_act = 'search';
  
  // Remove customer for prospect search
  clearSpecialCustomer();
  
  var widthPopupWin = 950;
  var heightPopupWin = 600;
  var leftPopupWin = (screen.width / 2) - (widthPopupWin / 2) - 12;
  var topPopupWin = (screen.height / 2) - (heightPopupWin / 2) - 50;
  var popupWin;
  popupWin = window.open("../admin/pt_list.php?f_act=" + f_act + "&generic=0000000010",
    "","dependent=yes,width=" + widthPopupWin + ",height=" +
    heightPopupWin +",left=" + leftPopupWin + ",top=" + topPopupWin +
    ",scrollbars=yes");
};

<?php if (!$hqCheckboxesExist) : ?>
function hqCheckAll(numOfHq) {
  for (i = 0; i < numOfHq; i++) {
	  document.getElementsByName('f_hq_id[]')[i].checked = true;
	}
}

function hqUncheckAll(numOfHq) {
  for (i = 0; i < numOfHq; i++) {
	  document.getElementsByName('f_hq_id[]')[i].checked = false;
  }
}
<?php endif; ?>

function getCsHistory2(gCsEid) {
  var widthPopupWin = 1024;
  var heightPopupWin = 768;
  var leftPopupWin = (screen.width / 2) - (widthPopupWin / 2) - 12;
  var topPopupWin = (screen.height / 2) - (heightPopupWin / 2) - 50;
  var popupWin;
  popupWin = window.open("../groupware/report.php?deactivateMenu=1&rpObjType=cs&g_cs_eid=" + gCsEid,
    "","dependent=yes,width=" + widthPopupWin + ",height=" +
    heightPopupWin +",left=" + leftPopupWin + ",top=" + topPopupWin +
    ",scrollbars=yes");
};

function getCsHistory(gCsEid) {
	if (gCsEid == '') {
     gCsEid = document.forms[0].g_cs_eid.value;
  };
  if (gCsEid != '') {
     var widthPopupWin = 1024;
     var heightPopupWin = 768;
     var leftPopupWin = (screen.width / 2) - (widthPopupWin / 2) - 12;
     var topPopupWin = (screen.height / 2) - (heightPopupWin / 2) - 50;
     var popupWin;
     popupWin = window.open("../groupware/report.php?deactivateMenu=1&rpObjType=cs&g_cs_eid=" + gCsEid,
       "","dependent=yes,width=" + widthPopupWin + ",height=" +
       heightPopupWin +",left=" + leftPopupWin + ",top=" + topPopupWin +
       ",scrollbars=yes");
  } else {
  	 alert('<?php echo getLngt("Wählen Sie bitte einen Kunden aus!") ?>');
  };
};

function openCustomerStatistics(gCsEid) {
	if (gCsEid == '') {
     gCsEid = document.forms[0].g_cs_eid.value;
  };
  if (gCsEid != '') {
  	 // Current date
     var now = new Date();
     var currentDay = now.getDate();
     var currentMonth = now.getMonth();
         currentMonth++;
     var currentYear = now.getFullYear();
  	 // Popup
     var widthPopupWin = 900;
     var heightPopupWin = 700;
     var leftPopupWin = (screen.width / 2) - (widthPopupWin / 2) - 12;
     var topPopupWin = (screen.height / 2) - (heightPopupWin / 2) - 50;
     var popupWin;
     popupWin = window.open("../statistic/statistic.php?deactivateMenu=1&f_act=calculate&f_category=3&f_statistic=61&g_cs_eid=" + gCsEid + "&day_from=01&month_from=01&year_from=2004&day_to=" + currentDay + "&month_to=" + currentMonth + "&year_to=" + currentYear + "&noStatisticMenu=1&outputColumnMode=0&outputTitle=<?php echo getLngt("Kundenstatistik") ?>&specialAligns=l,l,l,l,r,r","","dependent=yes,width=" + widthPopupWin + ",height=" + heightPopupWin +",left=" + leftPopupWin + ",top=" + topPopupWin + ",scrollbars=yes");
  } else {
  	 alert('<?php echo getLngt("Wählen Sie bitte einen Kunden aus!") ?>');
  }
}

function openCustomerSpecial(cmpId) {
  var widthPopupWin = 1200;
  var heightPopupWin = 900;
  var leftPopupWin = (screen.width / 2) - (widthPopupWin / 2) - 12;
  var topPopupWin = (screen.height / 2) - (heightPopupWin / 2) - 50;
  var popupWin;
  popupWin = window.open("../admin/customer_special.php?companyId=" + cmpId ,"","dependent=yes,width=" + widthPopupWin + ",height=" + heightPopupWin +",left=" + leftPopupWin + ",top=" + topPopupWin + ",scrollbars=yes");
};

function openCustomerSwitchCounter() {
  var widthPopupWin = 1200;
  var heightPopupWin = 900;
  var leftPopupWin = (screen.width / 2) - (widthPopupWin / 2) - 12;
  var topPopupWin = (screen.height / 2) - (heightPopupWin / 2) - 50;
  var popupWin;
  popupWin = window.open("../tools/customer_switch_counter.php?deactivateMenu=1","","dependent=yes,width=" + widthPopupWin + ",height=" + heightPopupWin +",left=" + leftPopupWin + ",top=" + topPopupWin + ",scrollbars=yes");
};

function openCustomerMotivationCounter() {
  var widthPopupWin = 1200;
  var heightPopupWin = 900;
  var leftPopupWin = (screen.width / 2) - (widthPopupWin / 2) - 12;
  var topPopupWin = (screen.height / 2) - (heightPopupWin / 2) - 50;
  var popupWin;
  popupWin = window.open("../tools/motivationcounter.php?deactivateMenu=1","","dependent=yes,width=" + widthPopupWin + ",height=" + heightPopupWin +",left=" + leftPopupWin + ",top=" + topPopupWin + ",scrollbars=yes");
};

function openProspectSpecial(ptId) {
  var widthPopupWin = 1200;
  var heightPopupWin = 900;
  var leftPopupWin = (screen.width / 2) - (widthPopupWin / 2) - 12;
  var topPopupWin = (screen.height / 2) - (heightPopupWin / 2) - 50;
  var popupWin;
  popupWin = window.open("../admin/prospect_special.php?companyId=" + ptId ,"","dependent=yes,width=" + widthPopupWin + ",height=" + heightPopupWin +",left=" + leftPopupWin + ",top=" + topPopupWin + ",scrollbars=yes");
};

function openCalendar(workMode, apId) {
  var widthPopupWin = 1200;
  var heightPopupWin = 600;
  var leftPopupWin = (screen.width / 2) - (widthPopupWin / 2) - 12;
  var topPopupWin = (screen.height / 2) - (heightPopupWin / 2) - 50;
  var popupWin;
  popupWin = window.open("../groupware/appointment.php?workMode=" + workMode + "&apId=" + apId + "&deactivateMenu=1","","dependent=yes,width=" + widthPopupWin + ",height=" + heightPopupWin +",left=" + leftPopupWin + ",top=" + topPopupWin + ",scrollbars=yes");
};

// Shows/Hides the header of the job list
var displayState = '<?php echo $displayState ?>';
function toggleDisplay(mode) {
	if (mode != '') {displayState = mode};
  if (displayState == '0') {
  	 myshow('calendarShow');
  	 myshow('appointmentShow');
  	 myhide('appointmentEdit');
  	 myhide('contacts');
  	 $("#page-header").text('<?php echo getLngt("KALENDER") ?>');
  } else if (displayState == '1') {
     myhide('calendarShow');
     myhide('appointmentShow');
  	 myshow('appointmentEdit');
  	 myhide('contacts');
  	 $("#page-header").text('<?php echo getLngt("TERMINE") ?>');
     setFocusEditAppointment();
  } else if (displayState == '2') {
  	 myhide('calendarShow');
  	 myhide('appointmentShow');
  	 myhide('appointmentEdit');
  	 myshow('contacts');
  	 $("#page-header").text('<?php echo getLngt("KONTAKTE") ?>');
     setFocusContactSearch();
  };
  document.forms[0].displayState.value = displayState;
}

function setAppointmentVisibilityConfig(val) {
	var len = 8;
  if (val == '1') {
     if (document.getElementsByName('f_ap_visibility_search[]')[0].checked == true) {
        for (i = 1; i < len; i++) {
	          document.getElementsByName('f_ap_visibility_search[]')[i].checked = true;
	      }
	   } else {
        for (i = 1; i < len; i++) {
	          document.getElementsByName('f_ap_visibility_search[]')[i].checked = false;
	      }
/*
	   	 if (document.getElementsByName('f_ap_visibility_search[]')[1].checked == true) {
           for (i = 2; i <= 4; i++) {
	             document.getElementsByName('f_ap_visibility_search[]')[i].checked = true;
	         }
	   	 }
	   	 if (document.getElementsByName('f_ap_visibility_search[]')[5].checked == true) {
           for (i = 6; i <= 7; i++) {
	             document.getElementsByName('f_ap_visibility_search[]')[i].checked = true;
	         }
	   	 }
*/
     }
  }
  if (val == '2') {
     if (document.getElementsByName('f_ap_visibility_search[]')[1].checked == true) {
        for (i = 2; i <= 4; i++) {
	          document.getElementsByName('f_ap_visibility_search[]')[i].checked = true;
	      }
	   } else {
        for (i = 2; i <= 4; i++) {
            document.getElementsByName('f_ap_visibility_search[]')[i].checked = false;
        }
        document.getElementsByName('f_ap_visibility_search[]')[0].checked = false;
     }
  }
  if (val == '6') {
     if (document.getElementsByName('f_ap_visibility_search[]')[5].checked == true) {
        for (i = 6; i <= 7; i++) {
	          document.getElementsByName('f_ap_visibility_search[]')[i].checked = true;
	      }
	   } else {
        for (i = 6; i <= 7; i++) {
            document.getElementsByName('f_ap_visibility_search[]')[i].checked = false;
        }
        document.getElementsByName('f_ap_visibility_search[]')[0].checked = false;
     }
  }
  if (val != '1' && val != '2' && val != '6') {
     if (document.getElementsByName('f_ap_visibility_search[]')[2].checked == false ||
         document.getElementsByName('f_ap_visibility_search[]')[3].checked == false ||
         document.getElementsByName('f_ap_visibility_search[]')[4].checked == false) {
     	 document.getElementsByName('f_ap_visibility_search[]')[1].checked = false;
     	 document.getElementsByName('f_ap_visibility_search[]')[0].checked = false;
     }
     if (document.getElementsByName('f_ap_visibility_search[]')[6].checked == false ||
         document.getElementsByName('f_ap_visibility_search[]')[7].checked == false) {
     	 document.getElementsByName('f_ap_visibility_search[]')[5].checked = false;
     	 document.getElementsByName('f_ap_visibility_search[]')[0].checked = false;
     }
     
     if (document.getElementsByName('f_ap_visibility_search[]')[2].checked == true &&
         document.getElementsByName('f_ap_visibility_search[]')[3].checked == true &&
         document.getElementsByName('f_ap_visibility_search[]')[4].checked == true) {
     	 document.getElementsByName('f_ap_visibility_search[]')[1].checked = true;
     }
     if (document.getElementsByName('f_ap_visibility_search[]')[6].checked == true &&
         document.getElementsByName('f_ap_visibility_search[]')[7].checked == true) {
     	 document.getElementsByName('f_ap_visibility_search[]')[5].checked = true;
     }
     if (document.getElementsByName('f_ap_visibility_search[]')[1].checked == true &&
         document.getElementsByName('f_ap_visibility_search[]')[5].checked == true) {
     	 document.getElementsByName('f_ap_visibility_search[]')[0].checked = true;
     }
  }

  // Check state of "all elements checked"
  if (document.getElementsByName('f_ap_visibility_search[]')[0].checked == false) {
  	 var allSet = true;
     for (i = 1; i < len; i++) {
     	   if (document.getElementsByName('f_ap_visibility_search[]')[i].checked == false) {
     	   	  allSet = false;
     	   }
	   }
	   if (allSet) {
        document.getElementsByName('f_ap_visibility_search[]')[0].checked = true;
	   }
	}
}
/*
Sichtbarkeit:
0 1 alle Einträge
1 2   selbst erstellte Einträge
2 3      nur für mich sichtbar
3 4      nur für Teilnehmer sichtbar
4 5      für alle sichtbar
5 6   Einträge anderer Mitarbeiter
6 7      ich bin Teilnehmer
7 8      alle weiteren freigegebenen
*/

function setFocusEditAppointment() {
  document.forms[0].f_text.focus();
};

// **************************
// * Javascript for contact *
// **************************

function setFocusContactSearch() {
  document.forms[0].f_search.focus();
};

function clearFields() {
  if (document.forms[0].f_search) {document.forms[0].f_search.value = ''};
};

function openMetaFieldSpecial(objId) {
  var widthPopupWin = 900;
  var heightPopupWin = 870;
  var leftPopupWin = (screen.width / 2) - (widthPopupWin / 2) - 12;
  var topPopupWin = (screen.height / 2) - (heightPopupWin / 2) - 50;
  var popupWin;
  popupWin = window.open("../admin/metafield_special.php?deactivateMenu=1&category=<?php echo ec(1); ?>&objId=" + objId ,"","dependent=yes,width=" + widthPopupWin + ",height=" + heightPopupWin +",left=" + leftPopupWin + ",top=" + topPopupWin + ",scrollbars=yes");
};

function removeMetaFieldObject(objId) {
	if (confirm('<?php echo getLngt("Möchten Sie den Eintrag wirklich löschen?") ?>')) {
	   document.forms[0].f_act_mtfl.value='remove';
	   document.forms[0].f_objIdRemove.value=objId;
	   document.forms[0].submit();
	};
};

function vCardOfMetaFieldObject(VCard) {
	// var outVCard = VCard.join("<br>");
	// document.forms[0].f_vcard_text.value = outVCard;
	document.forms[0].f_vcard_text.value = VCard;
};

function vCardSendPerMail(VCard,file_name,file_ext) {
	// vCardOfMetaFieldObject(VCard);
	email = document.forms[0].f_vcard_email.value;
	if (email != '') {
	   if (confirm('<?php echo getLngt("Die angezeigte VCard wird an die folgende Mailadresse gesendet:") ?> ' + email)) {
        var widthPopupWin = 700;
        var heightPopupWin = 300;
        var leftPopupWin = (screen.width / 2) - (widthPopupWin / 2) - 12;
        var topPopupWin = (screen.height / 2) - (heightPopupWin / 2) - 50;
        var popupWin;
        popupWin = window.open("../include/email_send.php?f_act=mailsend&f_closeWin=1&f_attachment=" + encodeURI(VCard) + "&f_subject=VCard&f_email=" + email + "&f_mimetype=text/x-vcard&f_fileName=" + encodeURI(file_name) + "&f_extension=" + file_ext ,"","dependent=yes,width=" + widthPopupWin + ",height=" + heightPopupWin +",left=" + leftPopupWin + ",top=" + topPopupWin + ",scrollbars=yes");
     }
  } else {
  	alert('<?php echo getLngt("Bitte tragen Sie eine Emailadresse ein!") ?>');
  }
};

function finishPageCalendarWeekLink(cWeek, cYear) {
	document.forms[0].viewMode.value = '<?php echo ec("2") ?>';
	document.forms[0].selYear.value = cYear;
	document.forms[0].selMonth.value = '<?php echo ec($selMonth) ?>';
	document.forms[0].selWeek.value = cWeek;
	document.forms[0].f_selUsrId.value = '<?php echo ec($f_selUsrId) ?>';
	document.forms[0].f_ap_cat_search_1.value = '<?php echo ec($f_ap_cat_search_1) ?>';
	// document.forms[0].f_ap_cat_search_2.value = '<?php echo ec($f_ap_cat_search_2) ?>';
	document.forms[0].f_ap_cat_search_3.value = '<?php echo ec($f_ap_cat_search_3) ?>';
	// document.forms[0].f_ap_cat_search_4.value = '<?php echo ec($f_ap_cat_search_4) ?>';
	document.forms[0].submit();
};

function finishPageCalendarDayLink(cDay) {
	document.forms[0].viewMode.value = '<?php echo ec("0") ?>';
	document.forms[0].selYear.value = '<?php echo ec($selYear) ?>';
	document.forms[0].selMonth.value = '<?php echo ec($selMonth) ?>';
  document.forms[0].selDay.value = cDay;
	document.forms[0].f_selUsrId.value = '<?php echo ec($f_selUsrId) ?>';
	document.forms[0].f_ap_cat_search_1.value = '<?php echo ec($f_ap_cat_search_1) ?>';
	// document.forms[0].f_ap_cat_search_2.value = '<?php echo ec($f_ap_cat_search_2) ?>';
	document.forms[0].f_ap_cat_search_3.value = '<?php echo ec($f_ap_cat_search_3) ?>';
	// document.forms[0].f_ap_cat_search_4.value = '<?php echo ec($f_ap_cat_search_4) ?>';
	document.forms[0].submit();
};

function searchContactPrefix(letter) {
  document.forms[0].f_act_mtfl.value = 'search';
  document.forms[0].f_letter.value = letter;
  document.forms[0].submit();
}

function selUsersByGroupSelection() {
  var f_grp_id = getSelectedValue('f_grp_id');
  scan_request('../groupware/ajaxReqAppointment.php', 'mode=3&grpId=' + f_grp_id);
  var usrIdArrLen = retArray.length;
  if (usrIdArrLen > 0) {
     var fUsrIdLen = document.getElementsByName('f_usr_id[]').length;
     for (i = 0; i < usrIdArrLen; i++) {
         for (j = 0; j < fUsrIdLen; j++) {
	         if (document.getElementsByName('f_usr_id[]')[j].value == retArray[i]) {
	            document.getElementsByName('f_usr_id[]')[j].checked = true;
	         }
         }
     }
  }
}

function activateAllParticipants() {
  var fUsrIdLen = document.getElementsByName('f_usr_id[]').length;
  for (i = 0; i < fUsrIdLen; i++) {
	    document.getElementsByName('f_usr_id[]')[i].checked = true;
  }
}

function deactivateAllParticipants() {
  var fUsrIdLen = document.getElementsByName('f_usr_id[]').length;
  for (i = 0; i < fUsrIdLen; i++) {
	    document.getElementsByName('f_usr_id[]')[i].checked = false;
  }
}

function execBodyOnLoad() {
  <?php if ($workMode == "0") : ?>
    toggleDisplay('<?php echo $displayState; ?>');
	  initForm();	  
	<?php endif; ?>
  <?php echo $phpCurrentNavigationOnLoad ?>
  <?php if ($displayStateOverrule == "1") : echo "setSpecialCustomer();"; endif; ?>
  displayStatusMessage();
}
-->
</script>

<?php echo $js_date ?>

</head>

<body bgcolor="#FFFFFF" text="#000000" onLoad="execBodyOnLoad();">


<?php echo $phpMenuOut ?>
<?php echo $phpReducedMenuOut ?>
<?php echo $phpPageTitelOut ?>

<div class="mc_page-header" id="page-header">
  <?php echo getLngt("KALENDER") ?>
</div>

<?php echo defineButtonType10(getLngt("Kalender"), "action_ap2cal", "toggleDisplay('0');", "170", "left", "0"); ?>
<?php echo defineButtonType10(getLngt("Terminbearbeitung"), "action_ap2ap", "toggleDisplay('1');", "170", "left", "0"); ?>
<?php echo defineButtonType10(getLngt("Kontakte"), "action_ap2ct", "toggleDisplay('2');", "170", "left", "0"); ?>
<?php echo htmlDivLineSpacer("20px"); ?>

<div class="maincontent mc_elem" name="maincontent" id="maincontent">		

<form name="appointment" action="../groupware/appointment.php" method="post">

  <input type="hidden" name="f_act" value="">
  <input type="hidden" name="displayState" value="<?php echo ec($displayState) ?>">
  
  <input type="hidden" name="workMode" value="<?php echo $workMode ?>">
  <input type="hidden" name="apId" value="<?php echo $apId ?>">
  
  <input type="hidden" name="viewMode" value="<?php echo ec($viewMode) ?>">
  <input type="hidden" name="selYear" value="<?php echo ec($selYear) ?>">
  <input type="hidden" name="selMonth" value="<?php echo ec($selMonth) ?>">
  <input type="hidden" name="selDay" value="<?php echo ec($selDay) ?>">
  <input type="hidden" name="selWeek" value="<?php echo ec($selWeek) ?>">
  <input type="hidden" name="f_apId" value="">
  <input type="hidden" name="f_apIdToRemove" value="">
  <input type="hidden" name="f_apIdToUpdate" value="">
  <input type="hidden" name="f_apIdToConfirm" value="">
  
  <input type="hidden" name="f_ap_resubmission_id" value="">
  <input type="hidden" name="f_ap_resubmission_execdate" value="">
  <input type="hidden" name="f_ap_resubmission_enddate" value="">
  <input type="hidden" name="f_ap_resubmission_category_1" value="">
  <input type="hidden" name="f_ap_resubmission_category_2" value="">
  <input type="hidden" name="f_ap_resubmission_category_3" value="">
  <input type="hidden" name="f_ap_resubmission_category_4" value="">

  <?php echo $phpCurrentNavigationInputHidden ?>
  <input type="hidden" name="deactivateMenu" value="<?php echo ec($deactivateMenu) ?>">

  <input type="hidden" name="csSpecial" value="<?php echo ec($csSpecial) ?>">
  
<div>
  <?php 
    $hqCheckboxesExist = false;
    if (authCheckEmployeeRights($emp_id, "10")) :
       echo getHeadquartersCheckboxes($f_hq_id); 
       echo htmlDivLineSpacer("20px");
       $hqCheckboxesExist = true;
    endif;
  ?>
</div>


<!-- CALENDAR -->

<div class="divpadding10" border="1">

  <?php if ($workMode == "1") : ?>

    <!-- Resubmission mode -->

    <input type="hidden" name="f_selUsrId" value="<?php echo $f_selUsrId ?>">
    <input type="hidden" name="f_ap_cat_search_1" value="<?php echo $f_ap_cat_search_1 ?>">
    <input type="hidden" name="f_ap_cat_search_2" value="<?php echo $f_ap_cat_search_2 ?>">
    <input type="hidden" name="f_ap_cat_search_3" value="<?php echo $f_ap_cat_search_3 ?>">
    <input type="hidden" name="f_ap_cat_search_4" value="<?php echo $f_ap_cat_search_4 ?>">

    <table border="0">
      <tr>
        <td>
          <table align="left" bgcolor="#000000">
            <?php
              echo printMonthYearHeader($selYear, $selMonth, "30", "7777FF");
              echo printWeekDayHeader($calWeekDays, "1", "30", "7777FF");
              echo printWeekDays($selYear, $selMonth, "30", "AAAAFF", "2", "", $csSpecial);
              echo printActionFields($selYear, $selMonth, "30", "7777FF");
            ?>
          </table>
        </td>
        <td>
        	&nbsp;&nbsp;
        </td>
        <td align="center">
          <table>
            <tr>
              <td valign="top">Von:</td>
              <td>
                <select class="f8np1" name="f_hour"> <?php echo addOptionsFromRange(0, 23, ((date("H") + 1) == "24" ? "00" : (date("H") + 1)), "", 2, "0"); ?> </select>&nbsp;            
                <select class="f8np1" name="f_minute"> <?php echo addOptionsFromArray($minuteArray, "", ""); ?> </select> Uhr<br><br>
              </td>
            </tr>
            <tr>
              <td valign="top">Bis:</td>
              <td class="f8np1">
                <select class="f8np1" name="f_hour_to"> <?php echo addOptionsFromRange(0, 23, ((date("H") + 2) == "24" ? "00" : ((date("H") + 2) == "25" ? "01" : (date("H") + 2))), "1", 2, "0"); ?> </select>&nbsp;
                <select class="f8np1" name="f_minute_to"> <?php echo addOptionsFromArray($minuteArray, "", ""); ?> </select> Uhr&nbsp;&nbsp;
              </td>
            </tr>
            <tr>
              <td class="f8np1" colspan="2">
              	<br>
                <?php echo defineButtonType10(getLngt("Termin eintragen"), "action_resubmission", "setResubmissionDate('" . $selYear . "','" . $selMonth . "','" . $selDay . "');", "170", "", ""); ?>
              </td>
            </tr>
          </table>
        </td>
        <td>
        	&nbsp;&nbsp;
        </td>
        <td align="center">
          <table>
            <tr>
              <td class="f8np1" colspan="2">
              	<table>
              		<tr>
              			<td><?php echo getLngt("Status") ?>:</td>
              	    <td><?php echo "<select class=\"f8np1\" name=\"f_ap_cat_1\">" . addOptionsFromTable("metatype","mt_sort","mt_value","mt_sort","mt_type = 'appointment_category_1'",$f_ap_cat_1) . "</select>"; ?></td>
              	  </tr>
              		<tr>
              			<td><?php echo getLngt("Sichtbarkeit") ?>:</td>
              			<td><?php echo "<select class=\"f8np1\" name=\"f_ap_cat_2\">" . addOptionsFromTable("metatype","mt_sort","mt_value","mt_sort","mt_type = 'appointment_category_2'",$f_ap_cat_2) . "</select>"; ?></td>
              	  </tr>
              		<tr>
              			<td><?php echo getLngt("Terminart") ?>:</td>
              			<td><?php echo "<select class=\"f8np1\" name=\"f_ap_cat_3\">" . addOptionsFromTable("metatype","mt_sort","mt_value","mt_value","mt_type = 'appointment_category_3'",$f_ap_cat_3) . "</select>"; ?></td>
              	  </tr>
              		<tr>
              			<td><?php echo getLngt("Kontrolle") ?>:</td>
              			<td><?php echo "<select class=\"f8np1\" name=\"f_ap_cat_4\">" . addOptionsFromTable("metatype","mt_sort","mt_value","mt_sort","mt_type = 'appointment_category_4'",$f_ap_cat_4) . "</select>"; ?></td>
              	  </tr>
              	</table>
              </td>
            </tr>
          </table>
        </td>
      </tr>
    </table>
    <br><br>
    <table align="left" border="0" width="100%">
      <tr>
        <td>
          <table align="left" bgcolor="#000000" border="0" width="100%">
          <?php
            $viewMode = "1";  // Daily view only
            echo printAppointmentHeader($selYear, $selMonth, $selDay, $selWeek);
          ?>
          </table>
        </td>
      </tr>
      <tr>
        <td>  
          <table align="left" bgcolor="#000000" border="0" width="100%">
          <?php
            echo printAppointmentTitle("FFFFFF");
            echo printAppointmentsOfOneDay($selYear, $selMonth, $selDay, $csSpecial);
          ?>
          </table>
        </td>
      </tr>
    </table>

  <?php else : ?>

    <!-- Normal mode -->

    <div id="calendarShow" name="calendarShow">    	

      <table width="100%" border="0">
        <tr>
          <td width="280" valign="top">
            <table align="left" bgcolor="#000000">
               <?php
                 echo printMonthYearHeader($selYear, $selMonth, "30", "7777FF");
                 echo printWeekDayHeader($calWeekDays, "1", "30", "7777FF");
                 echo printWeekDays($selYear, $selMonth, "30", "AAAAFF", "1", "1", $csSpecial);
                 echo printActionFields($selYear, $selMonth, "30", "7777FF");
               ?>
            </table>
          </td>

          <td align="center" valign="top" width="190">
            <!-- <?php echo defineButtonType10("Terminerfassung", "action_edit", "loadPage(0);", "170", "", ""); ?> -->
            <?php echo defineButtonType10(getLngt("Tagesübersicht"), "action_day", "loadPage(1);", "170", "", ""); ?>
            <?php echo htmlDivLineSpacer("5px"); ?>
            <?php echo defineButtonType10(getLngt("Wochenübersicht"), "action_week", "loadPage(2);", "170", "", ""); ?>
            <?php echo htmlDivLineSpacer("5px"); ?>
            <?php echo defineButtonType10(getLngt("Monatsübersicht"), "action_month", "loadPage(3);", "170", "", ""); ?>
            <?php echo htmlDivLineSpacer("5px"); ?>
            <?php echo defineButtonType10(getLngt("Jahresübersicht"), "action_year", "loadPage(4);", "170", "", ""); ?>
            <?php echo htmlDivLineSpacer("12px"); ?>
            <?php echo defineButtonType10(getLngt("Terminstatistik"), "action_statistic", "loadPage(9);", "170", "", ""); ?>
            <?php // echo htmlDivLineSpacer("12px"); ?>
            <?php // echo defineButtonType10(getLngt("Kontakte"), "action_contacts", "toggleDisplay('2');", "170", "", ""); ?>
            <?php // echo htmlDivLineSpacer("5px"); ?>
            <?php // echo defineButtonType10(getLngt("Terminbearbeitung"), "action_ap_new", "toggleDisplay('1');", "170", "", ""); ?>
          </td>

          <td align="center" valign="top" width="190">
            <?php // echo defineButtonType10(getLngt("Berichte"), "action_report_cs", "loadPage(5);", "170", "", ""); ?>
            <?php 
              if ($maskBtnCsReport == "1") :
                 echo defineLinkButtonType10(getLngt("Berichte"), "action_report_cs", "../groupware/report.php?deactivateMenu=1&rpObjType=cs", "170", "", "");
                 echo htmlDivLineSpacer("5px");
              else :
                 echo "<div></div>\n";
              endif;
            ?>
            <?php 
              if ($maskBtnCsStateChange == "1") :
                 echo defineButtonType10(getLngt("Kundenstatuswechsel"), "action_cs_state", "openCustomerSwitchCounter();", "170", "", "");
                 echo htmlDivLineSpacer("5px");
              else :
                 echo "<div></div>\n";
              endif;
            ?>
            <?php 
              if ($maskBtnCsMotivationCounter == "1") :
                 echo defineButtonType10(getLngt("Motivation-Counter"), "action_mtvt_count", "openCustomerMotivationCounter();", "170", "", "");
                 echo htmlDivLineSpacer("5px");
              else :
                 echo "<div></div>\n";
              endif;
            ?>
            <?php 
              if ($maskBtnCsNew == "1") :
                 echo defineButtonType10(getLngt("Neuer Kunde"), "action_cs_new", "openCustomerSpecial('');", "170", "", "");
                 echo htmlDivLineSpacer("12px");
              else :
                 echo "<div></div>\n";
              endif;
            ?>
            <!-- <?php echo defineButtonType10(getLngt("Aufgaben"), "action_edit", "loadPage(7);", "170", "", ""); ?> -->
            
            <?php echo defineButtonType10(getLngt("Aktualisieren"), "action_submit", "finishPage();", "170", "", ""); ?>
          </td>

          <td align="left" valign="top" width="20">

          </td>

          <td align="left" valign="top" width="220">
            <div>
              <div><b>Ersteller, Teilnehmer:</b></div>
              <?php echo htmlDivLineSpacer("5px"); ?>
              <div>
                <?php echo "<select class=\"f8np1\" name=\"f_selUsrId\"><option value=\"0\" " . ($f_selUsrId == "0" ? "selected" : "") . "> " . getLngt("Alle") . "</option>\n" . addOptionsFromTable("user AS usr, headquarters AS hq","usr.usr_id","CONCAT(usr_name,', ',usr_firstname,' [',hq_mnemonic,']') AS usr_name","usr.usr_name","usr.usr_type = '1' AND usr.hq_id = hq.hq_id AND usr.hq_id IN " . getSQLMandatorArray($f_hq_id),$f_selUsrId) . "</select>"; ?>
              </div>
            </div>
            <?php echo htmlDivLineSpacer("10px"); ?>
            <div>
              <div><b>Status:</b></div>
              <?php echo htmlDivLineSpacer("5px"); ?>
              <div>
                <?php echo "<select class=\"f8np1\" name=\"f_ap_cat_search_1\"><option value=\"\">" . getLngt("Keine Einschränkung") . "</option>" . addOptionsFromTable("metatype","mt_sort","mt_value","mt_sort","mt_type = 'appointment_category_1'",$f_ap_cat_search_1) . "</select>"; ?>
              </div>
            </div>
            <?php echo htmlDivLineSpacer("10px"); ?>
            <div>
              <div><b>Terminart:</b></div>
              <?php echo htmlDivLineSpacer("5px"); ?>
              <div>
                <?php echo "<select class=\"f8np1\" name=\"f_ap_cat_search_3\"><option value=\"\">" . getLngt("Keine Einschränkung") . "</option>" . addOptionsFromTable("metatype","mt_sort","mt_value","mt_value","mt_type = 'appointment_category_3'",$f_ap_cat_search_3) . "</select>"; ?>
              </div>
            </div>
            <?php echo htmlDivLineSpacer("10px"); ?>
          </td>

          <td align="left" valign="top" width="10">

          </td>

          <td align="left" valign="top">
            <div>
              <div><b>Sichtbarkeit:</b></div>
              <?php echo htmlDivLineSpacer("5px"); ?>
              <div>
                <?php echo addCheckboxesFromTable("f_ap_visibility_search","metatype","mt_sort","mt_value","mt_sort","mt_type = 'appointment_visibility_search'",$f_ap_visibility_search, "<br>", "", "1", "setAppointmentVisibilityConfig"); ?>
              </div>
            </div>
            <?php echo htmlDivLineSpacer("10px", "", "left"); ?>
          </td>
        </tr>

        <?php if ($csSpecial != "") : ?>
        <tr>
          <td colspan="7">
            <!-- Special customer only? -->
            <?php 
              $tmpCsEid = getFieldValueFromId("customer", "cs_id", $csSpecial, "cs_eid");
              $tmpCmpId = getFieldValueFromId("customer", "cs_id", $csSpecial, "cmp_id");
              $tmpCmpComp = getFieldValueFromId("company", "cmp_id", $tmpCmpId, "cmp_comp");
            ?>
            <span class="f12bp1"><?php echo getLngt("KUNDE") . ": " . $tmpCsEid . " [" . $tmpCmpComp . "]"; ?></span>
          </td>
        </tr>
        <?php endif; ?>
      </table>
    </div>


    <!-- APPOINTMENTS -->
    
    <div id="appointmentShow" name="appointmentShow">
      <table align="left" border="0" width="100%">
        <tr>
          <td>
            <table align="left" bgcolor="#000000" border="0" width="100%">
            <?php
              echo printAppointmentHeader($selYear, $selMonth, $selDay, $selWeek);
            ?>
            </table>
          </td>
        </tr>
        <tr>
          <td>  
            <table align="left" bgcolor="#000000" border="0" width="100%">
            <?php
              echo printAppointmentTitle("FFFFFF");
              if ($viewMode == "1") :
                 echo printAppointmentsOfOneDay($selYear, $selMonth, $selDay, $csSpecial);
              elseif ($viewMode == "2") :
                 echo printAppointmentsOfOneWeek($selWeek, $selYear, $selMonth, $selDay, $csSpecial);
              elseif ($viewMode == "3") :
                 echo printAppointmentsOfOneMonth($selYear, $selMonth, $csSpecial);
              elseif ($viewMode == "4") :
                 echo printAppointmentsOfOneYear($selYear, $csSpecial);
              elseif ($viewMode == "9") :
                 echo printAppointmentStatistic($csSpecial);
              else :
                 echo printAppointmentsOfOneDay($selYear, $selMonth, $selDay, $csSpecial);
              endif;
            ?>
            </table>
          </td>
        </tr>
        <tr>
          <td>  
           <br><br>
          </td>
        </tr>
      </table>
    </div>


    <!-- Edit appointment -->
    
    <div id="appointmentEdit" name="appointmentEdit">

      <div <?php echo setStyleHtmlDiv("470px","left","100%"); ?>>

      	<?php echo htmlDivLineSpacer("20px"); ?>
        <?php echo defineButtonType10(getLngt("Neu"), "action_new_ap", "clearAppointmentEditFields();", "100", "left", "3"); ?>
        <?php echo defineButtonType10(getLngt("Speichern"), "action_edit_ap", "insertAppointmentFinishPage();", "100", "", ""); ?>
        <?php echo htmlDivLineSpacer("20px", "", "left"); ?>
        
	      <?php 
          $outDateFrom = "";
          $outDateFrom .= "<select class=\"f8np1\" name=\"f_day\" class=\"f8np1\" onchange=\"fillDateFieldsCheck(0, 'maincontent', 'appointment', 'f_day', 'f_day', 'f_month', 'f_year', '', '', '', 'f_day_to', 'f_month_to', 'f_year_to', '', '', '')\"></select>\n";
          $outDateFrom .= "<select class=\"f8np1\" name=\"f_month\" class=\"f8np1\" onchange=\"fillDateFieldsCheck(0, 'maincontent', 'appointment', 'f_month', 'f_day', 'f_month', 'f_year', '', '', '', 'f_day_to', 'f_month_to', 'f_year_to', '', '', '')\"></select>\n";
          $outDateFrom .= "<select class=\"f8np1\" name=\"f_year\" class=\"f8np1\" onchange=\"fillDateFieldsCheck(0, 'maincontent', 'appointment', 'f_year', 'f_day', 'f_month', 'f_year', '', '', '', 'f_day_to', 'f_month_to', 'f_year_to', '', '', '')\"></select>\n";
          $outDateTo = "";
          $outDateTo .= "<select class=\"f8np1\" name=\"f_day_to\" class=\"f8np1\" onchange=\"fillDateFieldsCheck(0, 'maincontent', 'appointment', 'f_day_to', 'f_day', 'f_month', 'f_year', '', '', '', 'f_day_to', 'f_month_to', 'f_year_to', '', '', '')\"></select>\n";
          $outDateTo .= "<select class=\"f8np1\" name=\"f_month_to\" class=\"f8np1\" onchange=\"fillDateFieldsCheck(0, 'maincontent', 'appointment', 'f_month_to', 'f_day', 'f_month', 'f_year', '', '', '', 'f_day_to', 'f_month_to', 'f_year_to', '', '', '')\"></select>\n";
          $outDateTo .= "<select class=\"f8np1\" name=\"f_year_to\" class=\"f8np1\" onchange=\"fillDateFieldsCheck(0, 'maincontent', 'appointment', 'f_year_to', 'f_day', 'f_month', 'f_year', '', '', '', 'f_day_to', 'f_month_to', 'f_year_to', '', '', '')\"></select>\n";
        ?>

      	<div <?php echo setStyleHtmlDiv("70px","left"); ?>>
      	  <span class="f8bp1">Beginn:</span>
      	</div>
        <div>
	      <?php echo $outDateFrom; ?>&nbsp;&nbsp;
	        <!--
          <select class="f8np1" name="f_day"> <?php echo addOptionsFromRange(1, 31, $selDay, "", 2, "0"); ?> </select>&nbsp;
          <select class="f8np1" name="f_month"> <?php echo addOptionsFromRange(1, 12, $selMonth, "", 2, "0"); ?> </select>&nbsp;
          <select class="f8np1" name="f_year"> <?php echo addOptionsFromRange(2007, (date("Y") + 10), $selYear); ?> </select>&nbsp;&nbsp;&nbsp;
	        -->
          <select class="f8np1" name="f_hour" onChange="checkTimeFields('H');"><?php echo addOptionsFromRange(0, 23, ((date("H") + 1) == "24" ? "00" : (date("H") + 1)), "", 2, "0"); ?> </select>
          <select class="f8np1" name="f_minute" onChange="checkTimeFields('i');"> <?php echo addOptionsFromArray($minuteArray, "", ""); ?> </select>
        </div>
        <?php echo htmlDivLineSpacer("10px"); ?>

      	<div <?php echo setStyleHtmlDiv("70px","left"); ?>>
      	  <span class="f8bp1">Ende:</span>
      	</div>
        <div>
	      <?php echo $outDateTo; ?>&nbsp;&nbsp;
	        <!--
          <select class="f8np1" name="f_day_to"> <?php echo addOptionsFromRange(1, 31, $selDay, "", 2, "0"); ?> </select>&nbsp;
          <select class="f8np1" name="f_month_to"> <?php echo addOptionsFromRange(1, 12, $selMonth, "", 2, "0"); ?> </select>&nbsp;
          <select class="f8np1" name="f_year_to"> <?php echo addOptionsFromRange(2007, (date("Y") + 10), $selYear); ?> </select>&nbsp;&nbsp;&nbsp;
	        -->
          <select class="f8np1" name="f_hour_to" onChange="checkTimeFields('H_to');"> <?php echo addOptionsFromRange(0, 23, ((date("H") + 2) == "24" ? "00" : ((date("H") + 2) == "25" ? "01" : (date("H") + 2))), "1", 2, "0"); ?> </select>
          <select class="f8np1" name="f_minute_to" onChange="checkTimeFields('i_to');"> <?php echo addOptionsFromArray($minuteArray, "", ""); ?> </select>
        </div>
        <?php echo htmlDivLineSpacer("20px"); ?>


        <div><span class="f10bp1"><?php echo getLngt("Kategorien:") ?></span></div>
        <?php echo htmlDivLineSpacer("10px"); ?>
        <div <?php echo setStyleHtmlDiv("100px","left"); ?>>
        	 <span class="f8bp1">Status:</span>
        </div>
        <div>
          <?php echo "<select class=\"f8np1\" name=\"f_ap_cat_1\">" . addOptionsFromTable("metatype","mt_sort","mt_value","mt_sort","mt_type = 'appointment_category_1'",$f_ap_cat_1) . "</select>"; ?>
        </div>
        <?php echo htmlDivLineSpacer("10px"); ?>
        <div <?php echo setStyleHtmlDiv("100px","left"); ?>>
        	 <span class="f8bp1"><?php echo getLngt("Sichtbarkeit:") ?></span>
        </div>
        <div>
          <?php echo "<select class=\"f8np1\" name=\"f_ap_cat_2\">" . addOptionsFromTable("metatype","mt_sort","mt_value","mt_sort","mt_type = 'appointment_category_2'",$f_ap_cat_2) . "</select>"; ?>
        </div>
        <?php echo htmlDivLineSpacer("10px"); ?>
        <div <?php echo setStyleHtmlDiv("100px","left"); ?>>
        	 <span class="f8bp1"><?php echo getLngt("Terminart:") ?></span>
        </div>
        <div>
          <?php echo "<select class=\"f8np1\" name=\"f_ap_cat_3\">" . addOptionsFromTable("metatype","mt_sort","mt_value","mt_value","mt_type = 'appointment_category_3'",$f_ap_cat_3) . "</select>"; ?>
        </div>
        <?php echo htmlDivLineSpacer("10px"); ?>
        <div <?php echo setStyleHtmlDiv("100px","left"); ?>>
        	 <span class="f8bp1"><?php echo getLngt("Kontrolle:") ?></span>
        </div>
        <div>
          <?php echo "<select class=\"f8np1\" name=\"f_ap_cat_4\">" . addOptionsFromTable("metatype","mt_sort","mt_value","mt_sort","mt_type = 'appointment_category_4'",$f_ap_cat_4) . "</select>"; ?>
        </div>
        <?php echo htmlDivLineSpacer("20px"); ?>

        <div><span class="f10bp1"><?php echo getLngt("Verknüpfen mit:") ?></b></div>
        <?php echo htmlDivLineSpacer("10px", "", "left"); ?>
        <div <?php echo setStyleHtmlDiv("130px","left"); ?>><span class="f8bp1"><?php echo getLngt("Kunde/Interessent:") ?></span></div>
        <div style="float:left"><input type="text" name="g_cs_eid" value="" size="10" readonly>&nbsp;&nbsp;</div>
        <?php echo defineButtonType10("...", "action_cs_search", "searchCsCsc();", "40", "left", ""); ?>
        <div style="float:left">&nbsp;<a href="javascript:clearSpecialCustomer();" tabindex="340"><img src="../images/waste.png" border="0" height="15" width="12"></a>&nbsp;&nbsp;</div>
        <?php echo defineButtonType10(getLngt("Statistik"), "action_cal", "openCustomerStatistics('');", "80", "", ""); ?>
        <?php echo htmlDivLineSpacer("20px"); ?>

      	<div>
          <b><?php echo getLngt("Teilnehmer:") ?></b>
        </div>
        <?php echo htmlDivLineSpacer("10px"); ?>
      	<div>
          <?php echo getLngt("Gruppen:") . "&nbsp;&nbsp;<select class=\"f8np1\" name=\"f_grp_id\" onChange=\"selUsersByGroupSelection();\"><option value=\"\">" . getLngt("Auswahl Gruppe") . "</option>" . addOptionsFromTable("groups AS grp, employee AS emp","grp.grp_id","grp.grp_name","grp.grp_name","emp.emp_group like CONCAT('%,',grp.grp_id,',%') AND grp.hq_id IN " . getSQLMandatorArray($f_hq_id),$f_grp_id,"DISTINCT") . "</select>"; ?>
          <?php // echo "<input type=\"button\" name=\"action\" value=\"Alle abwählen\" onClick=\"deactivateAllParticipants();\">" ?>
      	</div>
      	<?php echo htmlDivLineSpacer("5px"); ?>
      	<?php echo defineButtonType10(getLngt("Alle anwählen"), "action_activate_all_participants", "activateAllParticipants();", "120", "left", "2"); ?>
      	<?php echo defineButtonType10(getLngt("Alle abwählen"), "action_deactivate_all_participants", "deactivateAllParticipants();", "120", "", ""); ?>
        <?php echo htmlDivLineSpacer("10px"); ?>
      	<div>
          <?php // echo addCheckboxesFromTable("f_usr_id","user","usr_id","CONCAT(usr_name,', ',usr_firstname)","usr_name","usr_type = '1' AND hq_id IN " . getSQLMandatorArray($f_hq_id) ,"", "<br>"); ?>
          <?php echo addCheckboxesFromTable("f_usr_id","user AS usr, headquarters AS hq","usr.usr_id","CONCAT(usr_name,', ',usr_firstname,' [',hq_mnemonic,']')","usr.usr_name","usr.usr_type = '1' AND usr.hq_id = hq.hq_id AND usr.hq_id IN " . getSQLMandatorArray($f_hq_id) ,"", "<br>"); ?>
      	</div>
      	<?php echo htmlDivLineSpacer("20px"); ?>      	
      </div>

      <!-- Content -->
      <div>
      	<?php echo htmlDivLineSpacer("30px"); ?>
        <div>
          <b><?php echo getLngt("Text:") ?></b>
        </div>
        <?php echo htmlDivLineSpacer("10px"); ?>
        <div>
          <textarea name="f_text" cols="70" rows="10"></textarea>
        </div>
        <?php echo htmlDivLineSpacer("30px"); ?>
        
        <div><span class="f10bp1"><?php echo getLngt("Emailversand:") ?></span></div>
        <?php echo htmlDivLineSpacer("10px"); ?>
        <div><?php echo getLngt("Benachrichtigung der Teilnehmer") ?>&nbsp;<input type="checkbox" name="f_sendmail[]" value="1"></div>
        <?php echo htmlDivLineSpacer("10px"); ?>
        <div><?php echo getLngt("Auch an folgende Mailadresse(n) versenden") ?>&nbsp;<input type="checkbox" name="f_sendmail_cs[]" value="1"></div>
        <?php echo htmlDivLineSpacer("10px"); ?>
        <div><input type="text" name="f_emailAdrCs" value="" size="40" maxlength="200"></div>
        <?php echo htmlDivLineSpacer("20px"); ?>
                        
        <div <?php echo setStyleHtmlDiv("100px","left"); ?>><span class="f8bp1"><?php echo getLngt("Anrede:") ?></span></div>
        <div><input type="text" name="f_mail_salutation" value="" size="70" maxlength="150"></div>
        <?php echo htmlDivLineSpacer("10px"); ?>
        <div <?php echo setStyleHtmlDiv("100px","left"); ?>><span class="f8bp1"><?php echo getLngt("Grußformel:") ?></span></div>
        <div><input type="text" name="f_mail_greetings" value="" size="70" maxlength="150"></div>
        <?php echo $f_cs_eid_out ?>
      </div>

      <?php echo htmlDivLineSpacer("5px", "", "left"); ?>
    </div>

    <div id="contacts" name="contacts">

    	<?php 
    	  $includeMode = "1";
    	  $viewItemsMode = "1";
    	  include_once ("../admin/metafield_list.php");
    	?>

    </div>

  <?php endif; ?>
</div>

</form>
</div>
</body>
</html>
