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

include_once ("../include/mcglobal.inc.php");
include_once ("../include/auth.inc.php");


// Execution-Time for script
set_time_limit(30000);

getSecHttpVars("1",array("f_act", "dbhistory", "day_from", "month_from", "year_from", "day_to", "month_to", "year_to",
                         "hour_from", "minute_from", "hour_to", "minute_to",
                         "f_statistic", "f_sort", "f_direction_sort", "g_cs_eid", "g_cr_eid", "g_crvh_filter",
                         "f_showDateAndTime", "f_hq_id", "f_usr_id", "f_grp_id", "f_numOfIntervals", 
                         "f_filter_01", "f_filter_02", "f_filter_03", "f_filter_04",
                         "cscIdRoot", "customerId", "cscIdActual", 
                         "outputTitle", "outputColumnMode", "specialAligns", "fileOutput", "f_group",
                         "simulator_event", "f_appusr_code"));


$usrAccessArray["hq"] = "1"; $usrAccessArray["cs"] = "1";
authCheckForAccess($hq_id, $usr_id, $emp_id, "1", $customerId, $cscIdRoot, $cscIdActual);
authCheckEmployeeRights($emp_id, "8", "1");


// *******************
// * Initialisations *
// *******************

// Include the modules for 
// - generating the category-dbfields
// - converting result of database search to array
// - defining the SQL-SELECT-statements
// include_once ("../include/inc_category_dbfields.inc.php");
// include_once ("../include/inc_dbfields2array.inc.php");
// include_once ("../include/inc_group.inc.php");
// include_once ("../statistic/statistic_sql.inc.php");
$pageTitel = getLngt("ZEITERFASSUNG");
include_once ("../admin/menu.php");
include_once ("../include/html.inc.php");
include_once ("../include/inc_APP.inc.php");


// Init
$debug = false;
$currentTimestamp = getDateTime("0");
$currentDate = getDateTime("3");
if ($f_statistic == "") : $f_statistic = "10"; endif;                               // Statistic-mode (timetracking overview, ...)
if ($fileOutput == "1") : $fileOutput = true; else : $fileOutput = false; endif;    // Send output to file
$f_appusr_code = trim($f_appusr_code);
$screenOutput = "";
$hours = 23;
$pixelWidthPerMinute = 1;
$timelineHeight = 20;

$delimiter = ";";
$writeHeader = "1";

// Get global unique DB Instance number
$constGlobalDbInstNo = getParameterValue("0", "GLOBAL_UNIQUE_DB_INSTANCE_NO", "0", "0");

// Mandator filter
if ($f_hq_id == "") : $f_hq_id = $hq_id; endif;

// Check ranges of time. All fields have to be set
if ($hour_from == "" || $minute_from == "" || $hour_to == "" || $minute_to == "") :
    $hour_from = "00";
    $minute_from = "00";
    $hour_to = "23";
    $minute_to = "59";
    $f_showDateAndTime = "0";
endif;
$hour_from = pad($hour_from,2);
$minute_from = pad($minute_from,2);
$hour_to = pad($hour_to,2);
$minute_to = pad($minute_to,2);
// Time range
$fromTimeRange = " " . $hour_from . ":" . $minute_from . ":00";
$toTimeRange = " " . $hour_to . ":" . $minute_to . ":59";
if ($f_statistic == "11") :
   $day_from = "1";
endif;
// Check ranges of date. All fields have to be set
if ($day_from == "" || $month_from == "" || $year_from == "") :
   $day_from = getDateTime("day");
   $month_from = getDateTime("month");
   $year_from = getDateTime("year");
endif;
if ($f_statistic == "10") :
   $day_to = $day_from;
   $month_to = $month_from;
   $year_to = $year_from;
endif;
if ($day_to == "" || $month_to == "" || $year_to == "") :
   $day_to = getDateTime("day");
   $month_to = getDateTime("month");
   $year_to = getDateTime("year");
endif;
$fromDateRange = $year_from . "-" . pad($month_from,2) . "-" . pad($day_from,2) . $fromTimeRange;
$toDateRange = $year_to . "-" . pad($month_to,2) . "-" . pad($day_to,2) . $toTimeRange;

$selMonth = $month_from; $selDay = $day_from; $selYear = $year_from;
include_once ("../include/inc_calendar.inc.php");
// include_once ("../groupware/calendar.php");

// Change time interval regarding statistic format
if ($f_statistic == "11") :
   $fromDateRange = $selYear . "-" . pad($selMonth,2) . "-" . "01" . $fromTimeRange;
   $toDateRange = $selYear . "-" . pad($selMonth,2) . "-" . pad($calMonthDays[$selMonth - 1],2) . $toTimeRange;
endif;



function postParseTimeTrackingStatisticDetails ($textToParse) {
	global $f_statistic;
  $textToParse = trim($textToParse);
  if ($textToParse != "") :  
     // Iterate ALL occurrences of "<postparser>...</postparser>"          
     while (!(strpos($textToParse, "<postparser>") === FALSE)) {
        $beginTagPosBegin = strpos($textToParse, "<postparser>");
        $beginTagPosEnd = $beginTagPosBegin + 12;
        $endTagPosBegin = strpos($textToParse, "</postparser>");
        $endTagPosEnd = $endTagPosBegin + 13;
        if ($beginTagPosEnd < $endTagPosBegin) :
           $tagContent = substr($textToParse, $beginTagPosEnd, $endTagPosBegin - $beginTagPosEnd);
           if ($tagContent != "") :
              // $tagContent = "<a href=\"../admin/customer_special.php?companyId=" . ec($tmpCmpId) . "\" target=\"_blank\">" . $tagContent . "</a>";
           endif;
           // Substitute text fragment
           $textToParse = substr_replace($textToParse, $tagContent, $beginTagPosBegin, $endTagPosEnd - $beginTagPosBegin);
        endif;
      }
  endif;
  return $textToParse;  
}

function getDistinctValuesOfTimeInterval ($mode = "days") {
	global $db, $PHP_SELF;
  global $f_hq_id, $f_usr_id, $f_grp_id, $fromDateRange, $toDateRange;
  $retArray = array();
  $whereClause = " AND usr.hq_id = '" . $f_hq_id . "' ";
  if ($f_usr_id != "") :
     $whereClause .= " AND usr.usr_id = '" . $f_usr_id . "' ";    // Filter by user
  endif;
  // $whereClause = "tt.tt_datetime >= '" . $fromDateRange . "' AND tt.tt_datetime <= '" . $toDateRange . "' AND tt.usr_id = usr.usr_id" . $whereClause;
  if ($mode == "days") :
     $whereClause = "tt.tt_datetime >= '" . $fromDateRange . "' AND tt.tt_datetime <= '" . $toDateRange . "'" . $whereClause;
  endif;
  if ($mode == "days") :
     $retArray = getColVectorFromDB2ArrayByClause("phoenix_group.timetracking AS tt, phoenix.user AS usr", "LEFT(tt.tt_datetime,10) AS tt_date", $whereClause, "", "tt_date", "DISTINCT");
  elseif ($mode == "users") :
     // $retArray = getColVectorFromDB2ArrayByClause("phoenix_group.timetracking AS tt, phoenix.user AS usr", "usr.usr_id", $whereClause, "", "usr.usr_id", "DISTINCT");
     $retArray = getColVectorFromDB2ArrayByClause("phoenix.user AS usr, phoenix.courier AS cr", "usr.usr_id", "usr.usr_id = cr.usr_id " . $whereClause, "", "usr.usr_id", "");
  else :
     // Default mode "days"
     $retArray = getColVectorFromDB2ArrayByClause("phoenix_group.timetracking AS tt, phoenix.user AS usr", "LEFT(tt.tt_datetime,10) AS tt_date", $whereClause, "", "tt_date", "DISTINCT");
  endif;
  return $retArray;
}

function getTimeTrackingData ($orderByClause = "") {
	global $db, $PHP_SELF;
  global $f_statistic, $f_hq_id, $f_usr_id, $f_grp_id, $fromDateRange, $toDateRange;
  global $f_filter_01, $f_filter_02, $f_filter_03, $f_filter_04;
// echo $fromDateRange . "<br>" . $toDateRange . "<br>" . $f_statistic . "<br>";
  $retArray = array();
  if ($f_statistic != "" && $f_statistic > "0") :
     $fromClause = "";
     $whereClause = " AND usr.hq_id = '" . $f_hq_id . "' ";
     if ($f_usr_id != "") :
        $whereClause .= " AND usr.usr_id = '" . $f_usr_id . "' ";    // Filter by user
     endif;
     if ($f_grp_id != "") :
        $fromClause .= ", phoenix.courier AS couier";
        $whereClause .= " AND usr.usr_id = cr.usr_id AND cr.group LIKE '%," . $f_grp_id . ",%' ";    // Filter by group
     endif;
     if ($orderByClause == "") :
        $orderByClause = "usr.usr_id, tt.tt_datetime";
     endif;
     $sqlquery = "SELECT tt.tt_datetime, UNIX_TIMESTAMP(tt.tt_datetime) AS tt_unixtime, tt.tt_id, tt.tt_gps_long, tt.tt_gps_lat, tt.tt_description, usr.usr_id"
                    . " FROM phoenix_group.timetracking AS tt, phoenix.user AS usr"
                    . " WHERE tt.tt_datetime >= '" . $fromDateRange . "' AND tt.tt_datetime <= '" . $toDateRange . "' AND tt.usr_id = usr.usr_id" . $whereClause
                    . " ORDER BY " . $orderByClause;
// echo $sqlquery . "<br>";
     $result = $db->query($sqlquery);
     while ($row = $result->fetch_assoc()):
           $retArray[] = $row;
     endwhile;
     $result->free();
  endif;
  return $retArray;
}


// Gets the worktime of all users inside the time interval
function getWorktimePerTimeInterval ($statArray, $days, $users) {
	global $db, $PHP_SELF;
  global $f_statistic, $f_hq_id, $f_usr_id, $f_grp_id, $fromDateRange, $toDateRange;
  global $currentTimestamp, $currentDate, $startEndClockTimeArray;
  global $f_filter_01, $f_filter_02, $f_filter_03, $f_filter_04; 

  $workTimePerUserArray = array();    // Minutes only (e.g. 375 minutes)
  $startEndClockTimeArray = array();  // Start and end time of the user of the day

  if (is_array($statArray)) :

     // Get all days inside the time interval
     if (!is_array($days)) :
        $days = getDistinctValuesOfTimeInterval("days");
     endif;
     $daysLen = count($days);
     
     // Get all users inside the time interval
     if (!is_array($users)) :
        $users = getDistinctValuesOfTimeInterval("users");
     endif;
     $usersLen = count($users);

     // **** Init ****
     $statArrayLen = count($statArray);
     $remUsrId = $statArray[0]["usr_id"];
     $remDateTime = $statArray[0]["tt_datetime"];
     $remLastEventArray = array();
     for ($k = 0; $k < $usersLen; $k++) :
         $remLastEventArray[$users[$k]] = "2";
     endfor;
     $remLastEvent = "2";

     // Init with first time for first user
     $tmpHourMinute = substr($remDateTime,11,5);
     $startEndClockTimeArray[$remUsrId][$days[0]][0] = $tmpHourMinute;
// echo "START : " . $remUsrId . " " . $days[0] . " " . $tmpHourMinute . "<br>";
     $startEndClockTimeArray[$remUsrId][$days[0]][1] = $tmpHourMinute;
// echo "END : " . $remUsrId . " " . $days[0] . " " . $tmpHourMinute . "<br>";

     for ($j = 0; $j < $daysLen; $j++) :

         $currentDayBeginUnixTimestamp = mktime(0, 0, 0, intval(substr($days[$j],5,2)), intval(substr($days[$j],8,2)), intval(substr($days[$j],0,4)));
         if (substr($days[$j],0,10) == $currentDate) :
            $currentDayEndUnixTimestamp = mktime(intval(substr($currentTimestamp,11,2)), intval(substr($currentTimestamp,14,2)), intval(substr($currentTimestamp,17,2)), intval(substr($currentTimestamp,5,2)), intval(substr($currentTimestamp,8,2)), intval(substr($currentTimestamp,0,4)));
         else :         
            $currentDayEndUnixTimestamp = mktime(23, 59, 59, intval(substr($days[$j],5,2)), intval(substr($days[$j],8,2)), intval(substr($days[$j],0,4)));
         endif;

         $lastUnixTimestamp = $currentDayBeginUnixTimestamp;
         if ($remLastEventArray[$statArray[$i]["usr_id"]] != "") :
            $remLastEvent = $remLastEventArray[$statArray[$i]["usr_id"]];    // Init with last event from last day would be possible !!!!
         endif;

         for ($i = 0; $i < $statArrayLen; $i++) :

             if (substr($statArray[$i]["tt_datetime"],0,10) == $days[$j]):

                // Set start time
                if ($remUsrId == $statArray[$i]["usr_id"]) :
                $tmpRemHourMinute = substr($remDateTime,11,5);
                if ($startEndClockTimeArray[$remUsrId][$days[$j]][0] == "") :
                    $startEndClockTimeArray[$remUsrId][$days[$j]][0] = $tmpRemHourMinute;
// echo "START : " . $remUsrId . " " . $days[$j] . " " . $tmpRemHourMinute . "<br>";
                endif;
                // Set end time
                $tmpHourMinute = substr($statArray[$i]["tt_datetime"],11,5);
                if ($startEndClockTimeArray[$remUsrId][$days[$j]][1] == "" || $startEndClockTimeArray[$remUsrId][$days[$j]][1] < $tmpHourMinute) :
                    $startEndClockTimeArray[$remUsrId][$days[$j]][1] = $tmpHourMinute;
// echo "END : " . $remUsrId . " " . $days[$j] . " " . $tmpHourMinute . "<br>";
                endif;
                endif;

                // Check for next user
                if ($remUsrId != $statArray[$i]["usr_id"]) :

                   // Compute difference to end of the selected day
                   if ($currentDayEndUnixTimestamp > $lastUnixTimestamp) :
                      $tmpMinutesBetweenEvents = ($currentDayEndUnixTimestamp - $lastUnixTimestamp) / 60;
// echo "usr_id : " . $remUsrId . "&nbsp;&nbsp;&nbsp;&nbsp;remLastEvent : " . $remLastEvent . "&nbsp;&nbsp;&nbsp;&nbsp;tmpMinutesBetweenEvents : " . $tmpMinutesBetweenEvents . " = (" . $statArray[$i]["tt_unixtime"] . " - " . $lastUnixTimestamp . ") / 60" . "&nbsp;&nbsp;&nbsp;&nbsp;";
                      if (count($workTimePerUserArray[$remUsrId][$days[$j]]) == 0) :
                         $workTimePerUserArray[$remUsrId][$days[$j]] = 0;
                      endif;
                      if ($remLastEvent == "1") :
                         $workTimePerUserArray[$remUsrId][$days[$j]] += round($tmpMinutesBetweenEvents);
                      endif;
// echo "workTimePerUserArray[" . $remUsrId . "][" . $days[$j] . "] = " . $workTimePerUserArray[$remUsrId][$days[$j]] . "<br>";
                   endif;

                   // Set values for the next user !!!!
                   $remUsrId = $statArray[$i]["usr_id"];
                   $remDateTime = $statArray[$i]["tt_datetime"];
                   $remLastEvent = $remLastEvent[$statArray[$i]["usr_id"]];
                   $lastUnixTimestamp = $currentDayBeginUnixTimestamp;
                   $count++;
                endif;

                $tmpMinutesBetweenEvents = ($statArray[$i]["tt_unixtime"] - $lastUnixTimestamp) / 60;
// echo "usr_id : " . $remUsrId . "&nbsp;&nbsp;&nbsp;&nbsp;remLastEvent : " . $remLastEvent . "&nbsp;&nbsp;&nbsp;&nbsp;tmpMinutesBetweenEvents : " . $tmpMinutesBetweenEvents . " = (" . $statArray[$i]["tt_unixtime"] . " - " . $lastUnixTimestamp . ") / 60" . "&nbsp;&nbsp;&nbsp;&nbsp;";
                if (count($workTimePerUserArray[$remUsrId][$days[$j]]) == 0) :
                   $workTimePerUserArray[$remUsrId][$days[$j]] = 0;
                endif;
                if ($remLastEvent == "1") :
                   $workTimePerUserArray[$remUsrId][$days[$j]] += round($tmpMinutesBetweenEvents);
                endif;
                
                $lastUnixTimestamp = $statArray[$i]["tt_unixtime"];
                $remLastEvent[$statArray[$i]["usr_id"]] = $statArray[$i]["tt_id"];
                $remLastEvent = $remLastEvent[$statArray[$i]["usr_id"]];
// echo "workTimePerUserArray[" . $remUsrId . "][" . $days[$j] . "] = " . $workTimePerUserArray[$remUsrId][$days[$j]] . "<br>";
             endif;
         endfor;

         // Compute difference to end of the selected day of the last user displayed
         if ($currentDayEndUnixTimestamp > $lastUnixTimestamp) :
            $tmpMinutesBetweenEvents = ($currentDayEndUnixTimestamp - $lastUnixTimestamp) / 60;
// echo "usr_id : " . $remUsrId . "&nbsp;&nbsp;&nbsp;&nbsp;remLastEvent : " . $remLastEvent . "&nbsp;&nbsp;&nbsp;&nbsp;tmpMinutesBetweenEvents : " . $tmpMinutesBetweenEvents . " = (" . $statArray[$i]["tt_unixtime"] . " - " . $lastUnixTimestamp . ") / 60" . "&nbsp;&nbsp;&nbsp;&nbsp;";
            if (count($workTimePerUserArray[$remUsrId][$days[$j]]) == 0) :
               $workTimePerUserArray[$remUsrId][$days[$j]] = 0;  
            endif;
            if ($remLastEvent == "1") :
               $workTimePerUserArray[$remUsrId][$days[$j]] += round($tmpMinutesBetweenEvents);
            endif;
// echo "workTimePerUserArray[" . $remUsrId . "][" . $days[$j] . "] = " . $workTimePerUserArray[$remUsrId][$days[$j]] . "<br>";
         endif;
// echo "<br><br>";
     endfor;
  endif;
  return $workTimePerUserArray;
}




// ***************************
// * Calculate the statistic *
// ***************************
if ($f_act == "calculate") :

   // **** DAILY OUTPUT: Display timeline of one or more users ****
   if ($f_statistic == "10"):

      // Get statistic array
      $statArray = getTimeTrackingData();  // ORDER BY usr.usr_id, tt.tt_datetime !!!!
      $statArrayLen = count($statArray);
      $outputLinesArray = array();
      $outputMatrixArray = array();  // Number of minutes
      $outputMatrixArray2 = array(); // Start- and endtime of the day
      if ($statArrayLen > 0) :

         // **** Init ****
         $workTimePerUserArray = array();        // Minutes only (e.g. 375 minutes)
         $workTimeHoursPerUserArray = array();   // Hours from $workTimePerUserArray[<USR_ID>] (e.g. 6 hours (eq. 360 minutes))
         $workTimeMinutesPerUserArray = array(); // Minutes remaining from $workTimePerUserArray[<USR_ID>] (e.g. 15 minutes)

         $remUsrId = $statArray[0]["usr_id"];         
         $workTimePerUserArray[$remUsrId] = 0;         
         $currentDayBeginUnixTimestamp = mktime(0, 0, 0, intval(substr($statArray[0]["tt_datetime"],5,2)), intval(substr($statArray[0]["tt_datetime"],8,2)), intval(substr($statArray[0]["tt_datetime"],0,4)));
         if (substr($statArray[0]["tt_datetime"],0,10) == $currentDate) :
            $currentDayEndUnixTimestamp = mktime(intval(substr($currentTimestamp,11,2)), intval(substr($currentTimestamp,14,2)), intval(substr($currentTimestamp,17,2)), intval(substr($currentTimestamp,5,2)), intval(substr($currentTimestamp,8,2)), intval(substr($currentTimestamp,0,4)));
         else :         
            $currentDayEndUnixTimestamp = mktime(23, 59, 59, intval(substr($statArray[0]["tt_datetime"],5,2)), intval(substr($statArray[0]["tt_datetime"],8,2)), intval(substr($statArray[0]["tt_datetime"],0,4)));
         endif;
         $lastUnixTimestamp = $currentDayBeginUnixTimestamp;
         $remLastEvent = "2";  // Init with last event from last day would be possible !!!!
         // $coordLong = $statArray[0]["tt_gps_long"];
         // $coordLat = $statArray[0]["tt_gps_lat"];
         $coordLong = "";
         $coordLat = "";

         // **** Timeline header ****
         $screenOutput .= "<table border=\"0\">\n";
         $screenOutput .= "<tr>\n";
         $screenOutput .= "<td width=\"100\"><b>" . getLngt("Mitarbeiter") . "</b></td><td>\n";
         for ($i = 0; $i <= 23; $i++) :
             // $screenOutput .= "<td width=\"" . round(60 * $pixelWidthPerMinute) . "\"><img src=\"../images/spacer_black.jpg\" border=\"0\" height=\"" . $timelineHeight . "\" width=\"1\">" . pad($i, 2) . "</td>\n";
             $imgFilename = "../images/timetracking_hour_" . pad($i, 2);
             if (!file_exists($imgFilename)) :
                $im = imagecreate(60, $timelineHeight) or die ("Cannot Initialize new GD image stream");
                $background_color = imagecolorallocate ($im, 255, 255, 255);
                $lineCol = imagecolorallocate ($im, 0, 0, 0);
                imagettftext ($im, 8, 0, 5, 10, $lineCol, "../include/arial.ttf", pad($i, 2));
                imagepng ($im, $imgFilename);
                imagedestroy ($im);
             endif;
             $screenOutput .= "<img src=\"../images/spacer_black.jpg\" border=\"0\" height=\"" . $timelineHeight . "\" width=\"1\">";
             $screenOutput .= "<img src=\"" . $imgFilename . "\" border=\"0\" height=\"" . $timelineHeight . "\" width=\"" . (60 - 1) . "\">";
         endfor;
         $screenOutput .= "</td>";
         $screenOutput .= "<td width=\"100\"><b>" . getLngt("Nettoarbeitszeit") . "</b></td><td>\n";
         $screenOutput .= "</tr>\n";
         // $screenOutput .= "</table>\n";

         $outUser = $remUsrId;
         if (!$userAnonymised) :
            $tmpUsrName = getFieldValueFromId("user", "usr_id", $remUsrId, "usr_name");
            $tmpUsrFirstname = getFieldValueFromId("user", "usr_id", $remUsrId, "usr_firstname");
            $outUser = substr($tmpUsrName . ", " . substr($tmpUsrFirstname, 0, 1) . ".", 0, 15);
         endif;

         // **** Timelines ****
         // $screenOutput .= "<table border=\"0\">\n";
         $screenOutput .= "<tr><td width=\"100\">" . $outUser . "&nbsp;&nbsp;&nbsp;&nbsp;</td><td>\n";
         for ($i = 0; $i < $statArrayLen; $i++) :

             // Check for next user
             if ($remUsrId != $statArray[$i]["usr_id"]) :
                // Compute difference to end of the selected day
                if ($currentDayEndUnixTimestamp > $lastUnixTimestamp) :
                   $tmpMinutesBetweenEvents = (($currentDayEndUnixTimestamp - $lastUnixTimestamp) * $pixelWidthPerMinute) / 60;
                   $tmpColorImage = "spacer_red.jpg";
                   if ($remLastEvent == "1") :
                      $workTimePerUserArray[$remUsrId] += round($tmpMinutesBetweenEvents);
                      $tmpColorImage = "spacer_green.jpg";
                   endif;
                   $tmpWidthOfImage = round($tmpMinutesBetweenEvents * $pixelWidthPerMinute);

                   // Hour and minutes
                   $tmpTimeHours = floor(($currentDayEndUnixTimestamp - $lastUnixTimestamp) / 3600);
                   $tmpTimeMinutes = round(((($currentDayEndUnixTimestamp - $lastUnixTimestamp) / 3600) - $tmpTimeHours) * 60);
                   $tmpTimeDiff = pad($tmpTimeHours,2) . "&nbsp;" . getLngt("Std.") . "&nbsp;" . pad($tmpTimeMinutes,2) . "&nbsp;" . getLngt("Min.");

                   $screenOutput .= "<a href=\"../locating/mc_map.php?coordUsrId=" . $remUsrId . "&coordLong=" . $coordLong . "&coordLat=" . $coordLat . "\" target=\"_blank\">";
                   $screenOutput .= "<img src=\"../images/" . $tmpColorImage . "\" border=\"0\" height=\"" . $timelineHeight . "\" width=\"" . $tmpWidthOfImage . "\" title=\"" . $tmpTimeDiff . "\">";
                   $screenOutput .= "</a>";
                endif;

                $workTimeHoursPerUserArray[$remUsrId] = floor(($workTimePerUserArray[$remUsrId]) / 60);
                $workTimeMinutesPerUserArray[$remUsrId] = round((($workTimePerUserArray[$remUsrId] / 60) - $workTimeHoursPerUserArray[$remUsrId]) * 60);
                $screenOutput .= "</td><td align=\"right\">" . pad($workTimeHoursPerUserArray[$remUsrId],2) . "&nbsp;" . getLngt("Std.") . "&nbsp;" . pad($workTimeMinutesPerUserArray[$remUsrId],2) . "&nbsp;" . getLngt("Min.") . "</td></tr>";

                // Set values for the next user !!!!
                $remUsrId = $statArray[$i]["usr_id"];
                $workTimePerUserArray[$remUsrId] = 0;
                $outUser = $remUsrId;
                if (!$userAnonymised) :
                   $tmpUsrName = getFieldValueFromId("user", "usr_id", $remUsrId, "usr_name");
                   $tmpUsrFirstname = getFieldValueFromId("user", "usr_id", $remUsrId, "usr_firstname");
                   $outUser = substr($tmpUsrName . ", " . substr($tmpUsrFirstname, 0, 1) . ".", 0, 15);
                endif;
                $screenOutput .= "<tr><td width=\"100\">" . $outUser . "&nbsp;&nbsp;&nbsp;&nbsp;</td><td>\n";
                $lastUnixTimestamp = $currentDayBeginUnixTimestamp;
                $remBeforeLastEvent = $remLastEvent;  // For the last entry ONLY
                $remLastEvent = "2";  // Init with last event from last day would be possible !!!!
                $count++;
             endif;

             $tmpColorImage = "spacer_red.jpg";
             // if ($statArray[$i]["tt_id"] == "2") : $tmpColorImage = "spacer_green.jpg"; endif;
             if ($remLastEvent == "1") : $tmpColorImage = "spacer_green.jpg"; endif;
             $tmpMinutesBetweenEvents = (($statArray[$i]["tt_unixtime"] - $lastUnixTimestamp) * $pixelWidthPerMinute) / 60;
             if ($remLastEvent == "1") :
                $workTimePerUserArray[$remUsrId] += round($tmpMinutesBetweenEvents);
             endif;
             $tmpWidthOfImage = round($tmpMinutesBetweenEvents * $pixelWidthPerMinute);

             // Hour and minutes
             $tmpTimeHours = floor(($statArray[$i]["tt_unixtime"] - $lastUnixTimestamp) / 3600);
             $tmpTimeMinutes = round(((($statArray[$i]["tt_unixtime"] - $lastUnixTimestamp) / 3600) - $tmpTimeHours) * 60);
             $tmpTimeDiff = pad($tmpTimeHours,2) . "&nbsp;" . getLngt("Std.") . "&nbsp;" . pad($tmpTimeMinutes,2) . "&nbsp;" . getLngt("Min.");

             $screenOutput .= "<a href=\"../locating/mc_map.php?coordUsrId=" . $remUsrId . "&coordLong=" . $coordLong . "&coordLat=" . $coordLat . "\" target=\"_blank\">";
             $screenOutput .= "<img src=\"../images/" . $tmpColorImage . "\" border=\"0\" height=\"" . $timelineHeight . "\" width=\"" . $tmpWidthOfImage . "\" title=\"" . $tmpTimeDiff . "\">";
             $screenOutput .= "</a>";

             // Write working time only into file
             if ($statArray[$i]["tt_id"] == "2") :
                if (!$userAnonymised) :
                   $tmpUsrName = getFieldValueFromId("user", "usr_id", $statArray[$i]["usr_id"], "usr_name");
                   $tmpUsrFirstname = getFieldValueFromId("user", "usr_id", $statArray[$i]["usr_id"], "usr_firstname");
                endif;
                $outputLinesArray[] = substr($statArray[$i]["tt_datetime"], 0, 10) . ";" . (!$userAnonymised ? $tmpUsrName . ";" . $tmpUsrFirstname : $statArray[$i]["usr_id"]) . ";" . date("H:i:s", $lastUnixTimestamp) . ";" . date("H:i:s", $statArray[$i]["tt_unixtime"]) . ";" . $tmpTimeDiff . ";" . $workTimePerUserArray[$statArray[$i]["usr_id"]] . ";";
             endif;

             $lastUnixTimestamp = $statArray[$i]["tt_unixtime"];
             
             $remLastEvent = $statArray[$i]["tt_id"];
             $remBeforeLastEvent = $remLastEvent;  // For the last entry ONLY

             $coordLong = $statArray[$i]["tt_gps_long"];
             $coordLat = $statArray[$i]["tt_gps_lat"];
         endfor;

         // Compute difference to end of the selected day of the last user displayed
         if ($currentDayEndUnixTimestamp > $lastUnixTimestamp) :
            $tmpMinutesBetweenEvents = (($currentDayEndUnixTimestamp - $lastUnixTimestamp) * $pixelWidthPerMinute) / 60;
            $tmpColorImage = "spacer_red.jpg";
            if ($remBeforeLastEvent == "1") :
               $workTimePerUserArray[$remUsrId] += round($tmpMinutesBetweenEvents);
               $tmpColorImage = "spacer_green.jpg";
            endif;
            $tmpWidthOfImage = round($tmpMinutesBetweenEvents * $pixelWidthPerMinute);

            // Hour and minutes
            $tmpTimeHours = floor(($currentDayEndUnixTimestamp - $lastUnixTimestamp) / 3600);
            $tmpTimeMinutes = round(((($currentDayEndUnixTimestamp - $lastUnixTimestamp) / 3600) - $tmpTimeHours) * 60);
            $tmpTimeDiff = pad($tmpTimeHours,2) . "&nbsp;" . getLngt("Std.") . "&nbsp;" . pad($tmpTimeMinutes,2) . "&nbsp;" . getLngt("Min.");

            $screenOutput .= "<a href=\"../locating/mc_map.php?coordUsrId=" . $remUsrId . "&coordLong=" . $coordLong . "&coordLat=" . $coordLat . "\" target=\"_blank\">";
            $screenOutput .= "<img src=\"../images/" . $tmpColorImage . "\" border=\"0\" height=\"" . $timelineHeight . "\" width=\"" . $tmpWidthOfImage . "\" title=\"" . $tmpTimeDiff . "\">";
            $screenOutput .= "</a>";
         endif;

         $workTimeHoursPerUserArray[$remUsrId] = floor(($workTimePerUserArray[$remUsrId]) / 60);
         $workTimeMinutesPerUserArray[$remUsrId] = round((($workTimePerUserArray[$remUsrId] / 60) - $workTimeHoursPerUserArray[$remUsrId]) * 60);
         $screenOutput .= "</td><td align=\"right\">" . pad($workTimeHoursPerUserArray[$remUsrId],2) . "&nbsp;" . getLngt("Std.") . "&nbsp;" . pad($workTimeMinutesPerUserArray[$remUsrId],2) . "&nbsp;" . getLngt("Min.") . "</td></tr>";

         $screenOutput .= "</table>\n";
      endif;
   endif;


   // **** MONTHLY OUTPUT: Display timeline of one or more users ****
   if ($f_statistic == "11"):

      // Get statistic array of raw data
      $statArray = getTimeTrackingData("LEFT(tt.tt_datetime,10), usr.usr_id, tt.tt_datetime");  // ORDER BY usr.usr_id, tt.tt_datetime !!!!

      // Get days (DISTINCT) of raw data
      $users = getDistinctValuesOfTimeInterval("users");
      $usersLen = count($users);

      // Get name, firstname, etc. of the user
      $userData = array();
      if (!$userAnonymised) :
         for ($i = 0; $i < $usersLen; $i++) :
             $tmpUsrName = getFieldValueFromId("user", "usr_id", $users[$i], "usr_name");
             $tmpUsrFirstname = getFieldValueFromId("user", "usr_id", $users[$i], "usr_firstname");
             $userData[$users[$i]] = array($tmpUsrName, $tmpUsrFirstname);
         endfor;
      endif;

      // Get days (DISTINCT) of raw data
      $days = getDistinctValuesOfTimeInterval("days");
      $daysLen = count($days);

      $workTimePerUserArray = getWorktimePerTimeInterval($statArray, $days, $users);

      $colorImageArray = array("spacer_green.jpg", "spacer_purple.jpg", "spacer_blue_menu_01.jpg", "spacer_white.jpg", "spacer_black.jpg", "spacer_red.jpg",
                               "spacer_green.jpg", "spacer_purple.jpg", "spacer_blue_menu_01.jpg", "spacer_white.jpg", "spacer_black.jpg", "spacer_red.jpg",
                               "spacer_green.jpg", "spacer_purple.jpg", "spacer_blue_menu_01.jpg", "spacer_white.jpg", "spacer_black.jpg", "spacer_red.jpg",
                               "spacer_green.jpg", "spacer_purple.jpg", "spacer_blue_menu_01.jpg", "spacer_white.jpg", "spacer_black.jpg", "spacer_red.jpg",
                               "spacer_green.jpg", "spacer_purple.jpg", "spacer_blue_menu_01.jpg", "spacer_white.jpg", "spacer_black.jpg", "spacer_red.jpg",
                               "spacer_green.jpg", "spacer_purple.jpg", "spacer_blue_menu_01.jpg", "spacer_white.jpg", "spacer_black.jpg", "spacer_red.jpg");

      $height = "5";
      $screenOutput = "<table border=\"0\">\n";
      $screenOutput .= "  <tr>\n";
      $screenOutput .= "    <td colspan=\"2\" class=\"f10bp1\">\n";
      $screenOutput .=        $calMonthNames[$selMonth - 1] . "&nbsp;" . $selYear . "<br><br>";
      $screenOutput .= "    </td>\n";
      $screenOutput .= "  </tr>\n";

      $screenOutput .= "  <tr>\n";
      $screenOutput .= "    <td width=\"190\">Anzahl&nbsp;Stunden&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td>\n";
      $screenOutput .= "    <td width=\"1440\" class=\"f10np1\" height=\"" . $height . "\">\n";
      for ($h = 1; $h <= 24; $h++) :
          $screenOutput .= "&nbsp;&nbsp;<span class=\"f8bp1\">" . pad($h,2) . "</span><span class=\"f7bp1\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>";
          // $screenOutput .= "<div class=\"f8bp1\" style=\"float:left; width:60px\" align=\"center\">" . pad($h,2) . "</div>";
      endfor;
      $screenOutput .= "    </td>\n";
      $screenOutput .= "  </tr>\n";

      // File matrix output
      if ($writeHeader == "1") :
         $headline = "";
         for ($i = 0; $i < $usersLen; $i++) :
             $headline .= $delimiter . $userData[$users[$i]][0] . ", " . $userData[$users[$i]][1];
         endfor;
         $outputMatrixArray[] = getLngt("Datum") . $headline;
         $outputMatrixArray2[] = getLngt("Datum") . $headline;
      endif;

      $count = 0;
      $numOfDaysOfTheMonth = $calMonthDays[$selMonth - 1];
      for ($j = 1; $j <= $numOfDaysOfTheMonth; $j++) :

          $tmpDay = $selYear . "-" . pad($selMonth,2) . "-" . pad($j,2);

          // File matrix output
          $bodyLine = $tmpDay;
          $bodyLine2 = $tmpDay;

          $tmpNumOfTheDay = date("w", mktime(0, 0, 0, $selMonth, $j, $selYear));   // 0 = Sunday, 1 = Monday, etc.
          if ($tmpNumOfTheDay == 0) : $tmpNumOfTheDay = "7"; endif;                // Reformat to 1 = Monday, ... , 7 = Sunday

          $screenOutput .= "  <tr>\n";
          $screenOutput .= "    <td colspan=\"2\" height=\"" . $height . "\">\n";
          $screenOutput .=        "<b>" . pad($j,2) . "</b>.&nbsp;&nbsp;";
          if ($tmpNumOfTheDay == "7") :
             $screenOutput .= "<span class=\"f8np1_red\">(" . $calWeekDays[$tmpNumOfTheDay - 1] . ")</span>";
          else :
             $screenOutput .= "<b>(" . $calWeekDays[$tmpNumOfTheDay - 1] . ")</b>";
          endif;
          $screenOutput .= "    </td>\n";
          $screenOutput .= "  </tr>\n";

          $screenOutput .= "  <tr>\n";
          $screenOutput .= "    <td colspan=\"2\" align=\"left\">\n";

          $screenOutput .= "      <table border=\"0\">\n";
          for ($i = 0; $i < $usersLen; $i++) :

              $minutesOfUserOfDay = $workTimePerUserArray[$users[$i]][$tmpDay];
              if ($minutesOfUserOfDay == "") :
                 $minutesOfUserOfDay = 0;
              endif;
              $tmpHours = floor(($minutesOfUserOfDay) / 60);
              $tmpMinutes = round((($minutesOfUserOfDay / 60) - $tmpHours) * 60);

              $outUser = $users[$i];
              if (!$userAnonymised) :
                 $outUser = substr($userData[$users[$i]][0] . ", " . substr($userData[$users[$i]][1], 0, 1) . ".", 0, 15);
              endif;

              $screenOutput .= "  <tr>\n";
              $screenOutput .= "    <td width=\"100\">" . $outUser . "</td>\n";
              $screenOutput .= "    <td width=\"90\">" . pad($tmpHours,2) . "&nbsp;Std.&nbsp;" . pad($tmpMinutes,2) . "&nbsp;Min.</td>\n";
              $screenOutput .= "    <td width=\"1440\" height=\"" . $height . "\" background=\"../images/timeTableBg.png\">\n";
              $screenOutput .= "     <img src=\"../images/" . $colorImageArray[$i] . "\" border=\"0\" height=\"" . $height . "\" width=\"" . $minutesOfUserOfDay . "\">";
              $screenOutput .= "    </td>\n";
              $screenOutput .= "  </tr>\n";
              
              $outputLinesArray[$count] = $users[$i] . ";" . (!$userAnonymised ? $userData[$users[$i]][0] . ";" . $userData[$users[$i]][1] . ";" : "") . $tmpDay . ";" . $minutesOfUserOfDay . ";" . $tmpHours . ";" . $tmpMinutes . ";";
              
              // File matrix output
              $bodyLine .= $delimiter . $minutesOfUserOfDay;
// echo $users[$i] . " => " . $tmpDay . " => " . $startEndClockTimeArray[$users[$i]][$tmpDay][0] . "-" . $startEndClockTimeArray[$users[$i]][$tmpDay][1] . "<br>";
              $bodyLine2 .= $delimiter . $startEndClockTimeArray[$users[$i]][$tmpDay][0] . "-" . $startEndClockTimeArray[$users[$i]][$tmpDay][1];
              
              $count++;
          endfor;
          $screenOutput .= "      </table>\n";

          $screenOutput .= "    </td>\n";
          $screenOutput .= "  </tr>\n";

          // File matrix output
          $outputMatrixArray[] = $bodyLine;
          $outputMatrixArray2[] = $bodyLine2;
      endfor;
      $screenOutput .= "</table>\n";
   endif;
   $outputMatrixArrayLen = count($outputMatrixArray);
   $outputMatrixArray2Len = count($outputMatrixArray2);


   // **** Optional output to file ****
   $f_secretFileName = "";
   if ($fileOutput) :

      // Remove old files
      /*
      foreach (glob("../temp/download/" . "*.tt.csv") as $fileNameToBoRemoved) {
          if ((time() - filemtime($fileNameToBoRemoved)) > 60) :
             if (file_exists($fileNameToBoRemoved)) :
                unlink($fileNameToBoRemoved);
             endif;
          endif;
      }
      */

      $f_fileName = getLngt("ZEITERFASSUNG") . "_" . $selYear . pad($selMonth,2) . pad($selDay,2) . ".csv";
      if ($f_statistic == "11"):
         $outputLinesArray = $outputMatrixArray;  // HARDCODED SWITCH BETWEEN OUTPUT FILE FORMAT VERSION 1 AND 2
         if ($outputMatrixArray2Len > 0) :
            for ($p = $outputMatrixArrayLen; $p < 35; $p++) :
                $outputLinesArray[] = "-------";
            endfor;
            $outputLinesArray = array_merge($outputLinesArray, $outputMatrixArray2);
         endif;
         $f_fileName = getLngt("ZEITERFASSUNG") . "_" . $selYear . pad($selMonth,2) . ".csv";
      endif;

      // Check for using secret filename      
      $f_secretFileName = $f_fileName;
      if (false) :
         $f_secretFileName = md5($f_secretFileName) . ".csv";
      endif;
      // Remove existing file if does exist
      if (file_exists("../temp/download/" . $f_secretFileName)) :
          unlink("../temp/download/" . $f_secretFileName);
      endif;

      // Define output parameters
      // include_once ("../include/inc_list_defineoutput2file.inc.php");
      $outputLinesArrayLen = count($outputLinesArray);
      if ($outputLinesArrayLen > 0) :
         if ($outputHeader != "") :
            writeToFile("../temp/download/" . $f_secretFileName, $outputHeader);   // Write header if requested
         endif;
         for ($i = 0; $i < $outputLinesArrayLen; $i++) : 
             $outputLinesArray[$i] = str_replace("&nbsp;", " ", $outputLinesArray[$i]);
             // echo $i . " => " . $outputLinesArray[$i] . "<br>";
             writeToFile("../temp/download/" . $f_secretFileName, $outputLinesArray[$i]);   // Write timetracking data
         endfor;
      else :
         $statusMessage = "Es wurden keine Daten gefunden! Eine Datei wurde deshalb nicht generiert!";
         $fileOutput = false;
      endif;
   endif;
endif;


// FOR SIMULATION ONLY
if ($f_act == "simulator_start") :
   insertStmt("phoenix_group.timetracking", array("tt_datetime",$currentTimestamp,"tt_id","1","usr_id",$usr_id,"tt_gps_long","","tt_gps_lat","","tt_description",""));
endif;
if ($f_act == "simulator_finish") :
   insertStmt("phoenix_group.timetracking", array("tt_datetime",$currentTimestamp,"tt_id","2","usr_id",$usr_id,"tt_gps_long","","tt_gps_lat","","tt_description",""));
endif;


// * Generate new key *
$generatedKey = "";
if ($f_act == "generateNewAppusrCode") :
   if ($f_usr_id != "") :
      $generatedKey = md5(strval(rand(1000,9999)) . strval($f_usr_id) . strval(rand(1000,9999)));
   endif;
endif;

// * Store registration key *
$outputErrStoringRegisterCodeOfUser = "";
if ($f_act == "storeNewAppusrCode") :
   if (is_numeric($constGlobalDbInstNo)) :
      if ($f_usr_id != "" && $f_appusr_code != "") :
         $regCodeArray = setRegisterCode("1", $constGlobalDbInstNo, $f_usr_id, $f_appusr_code);
         $errCode = $regCodeArray[0];
         $errMsg = $regCodeArray[2];
         if ($errCode != "0") :
            $outputErrStoringRegisterCodeOfUser .= "<span class=\"f10bp1_red\">" . getLngt("Der Registrierungsschlüssel konnte nicht eingetragen werden!") . "</span>";
         else : 
            $outputErrStoringRegisterCodeOfUser .= "<span class=\"f10bp1_red\">" . $errMsg . "</span>";
         endif;
      else :
         $outputErrStoringRegisterCodeOfUser .= "<span class=\"f10bp1_red\">" . getLngt("Der Registrierungsschlüssel ist leer!") . "</span>";
      endif;
   else :
      $outputErrStoringRegisterCodeOfUser .= "<span class=\"f10bp1_red\">" . getLngt("Die globale Zuordnungsnummer der Datenbank-Instanz ist nicht definiert!") . "</span>";
   endif;
endif;

// * Association between selected user and timetracking APP *
$outputRegisterCodeOfUser = "";
if ($f_usr_id != "") :
   $usrName = getFieldValueFromId("user", "usr_id", $f_usr_id, "usr_name");
   $usrFirstname = getFieldValueFromId("user", "usr_id", $f_usr_id, "usr_firstname");

   // Get registration code for current user
   if (is_numeric($constGlobalDbInstNo)) :
      $regCodeArray = getRegisterCode("1", $constGlobalDbInstNo, $f_usr_id);
      $errCode = $regCodeArray[0];
      if ($errCode == "0") :
         $appusrCode = $regCodeArray[1];
         $appusrActivated = $regCodeArray[2];
         if ($generatedKey != "") :
            $appusrCode = $generatedKey;
            $appusrActivated = "0";
         endif;
         $outputRegisterCodeOfUser .= "<input type=\"text\" class=\"f10bp1\" name=\"f_appusr_code\" value=\"" . $appusrCode . "\" maxlength=\"30\" size=\"30\">"  . "&nbsp;&nbsp;&nbsp;&nbsp;" . ($appusrActivated == "1" ? getLngt("Aktiviert") : getLngt("Nicht aktiviert"));
      elseif ($errCode == "301") :
         $outputRegisterCodeOfUser .= "<span class=\"f10bp1_red\">" . getLngt("Derzeit kann nicht auf die Registrierungsstruktur zugegriffen werden! Bitte kontaktieren Sie den Support!") . "</span>";
      elseif ($errCode == "302") :
         $outputRegisterCodeOfUser .= "<input type=\"text\" class=\"f10bp1\" name=\"f_appusr_code\" value=\"" . $generatedKey . "\" maxlength=\"30\" size=\"30\">";
         $outputRegisterCodeOfUser .= "&nbsp;&nbsp;<span class=\"f10bp1\">" . getLngt("Derzeit existiert kein Registrierungsschlüssel für den Mitarbeiter!") . "</span>";
      endif;
   else :
      $outputErrStoringRegisterCodeOfUser .= "<span class=\"f10bp1_red\">" . getLngt("Die globale Zuordnungsnummer der Datenbank-Instanz ist nicht definiert!") . "</span>";
   endif;
endif;
if ($outputErrStoringRegisterCodeOfUser != "") :
   $outputRegisterCodeOfUser .= " " . $outputErrStoringRegisterCodeOfUser;   // Attach error message from storing the register code
endif;


// **** OUTPUT ****

// Javascript-function as template only for categorie depending on date-filter (not status-filter)
$onLoadCall = "";
// $onLoadCall .= "displayStatusMessage();";

$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\",\"statistic\",\"\",\"day_from\",\"month_from\",\"year_from\",\"\",\"\",\"\");\n";
$js_date .= "  setDateTimeFields(\"maincontent\",\"statistic\",".$day_from.",".$month_from.",".$year_from.", \"\", \"\", \"day_from\", \"month_from\", \"year_from\", \"\", \"\", \"\");\n";
$js_date .= "  fillDateFields(1,\"maincontent\",\"statistic\", \"\", \"day_to\", \"month_to\", \"year_to\", \"\", \"\", \"\");\n";
$js_date .= "  setDateTimeFields(\"maincontent\",\"statistic\",".$day_to.",".$month_to.",".$year_to.", \"\", \"\", \"day_to\", \"month_to\", \"year_to\", \"\", \"\", \"\");\n";
$js_date .= "}\n";
$js_date .= "-->\n";
$js_date .= "</script>\n";

if ($fileOutput) :
   $onLoadCall .= "downloadFile();";
endif;
$onLoadCall .= "initForm();";

// Date ranges
if ($f_statistic != "10" && $f_statistic != "11") :
   $statisticDateFilter  = "von:\n";
endif;
if ($f_statistic == "11") :
   $statisticDateFilter .= "<select class=\"f8np1\" name=\"month_from\">";
   $statisticDateFilter .= addOptionsFromRange(1,12,$month_from,"1");
   $statisticDateFilter .= "</select>";
   $statisticDateFilter .= "&nbsp;";
   $statisticDateFilter .= "<select class=\"f8np1\" name=\"year_from\">";
   $statisticDateFilter .= addOptionsFromRange(getDateTime("year")-3,getDateTime("year"),$year_from,"1");
   $statisticDateFilter .= "</select>";
   // $statisticDateFilter .= getLngt("(Monat/Jahr)");
else :
   $statisticDateFilter .= "<select name=\"day_from\" class=\"f8np1\" onchange=\"fillDateFieldsCheck(0, 'maincontent', 'statistic', 'day_from', 'day_from', 'month_from', 'year_from', '', '', '', 'day_to', 'month_to', 'year_to', '', '', '')\"></select>\n";
   $statisticDateFilter .= "<select name=\"month_from\" class=\"f8np1\" onchange=\"fillDateFieldsCheck(0, 'maincontent', 'statistic', 'month_from', 'day_from', 'month_from', 'year_from', '', '', '', 'day_to', 'month_to', 'year_to', '', '', '')\"></select>\n";
   $statisticDateFilter .= "<select name=\"year_from\" class=\"f8np1\" onchange=\"fillDateFieldsCheck(0, 'maincontent', 'statistic', 'year_from', 'day_from', 'month_from', 'year_from', '', '', '', 'day_to', 'month_to', 'year_to', '', '', '')\"></select>\n";      
   if ($f_statistic != "10") :
      $statisticDateFilter .= "&nbsp;&nbsp;bis:\n";     
      $statisticDateFilter .= "<select name=\"day_to\" class=\"f8np1\" onchange=\"fillDateFieldsCheck(0, 'maincontent', 'statistic', 'day_to', 'day_from', 'month_from', 'year_from', '', '', '', 'day_to', 'month_to', 'year_to', '', '', '')\"></select>\n";
      $statisticDateFilter .= "<select name=\"month_to\" class=\"f8np1\" onchange=\"fillDateFieldsCheck(0, 'maincontent', 'statistic', 'month_to', 'day_from', 'month_from', 'year_from', '', '', '', 'day_to', 'month_to', 'year_to', '', '', '')\"></select>\n";
      $statisticDateFilter .= "<select name=\"year_to\" class=\"f8np1\" onchange=\"fillDateFieldsCheck(0, 'maincontent', 'statistic', 'year_to', 'day_from', 'month_from', 'year_from', '', '', '', 'day_to', 'month_to', 'year_to', '', '', '')\"></select>\n";
      $statisticDateFilter .= "&nbsp;";
   endif;
   $statisticDateFilter .= "[" . $calCurrentWeekName . "&nbsp;" . $calCurrentWeekNum . "]&nbsp;";
endif;

// Time ranges
$statisticTimeFilter  = "";
/*
$statisticTimeFilter .= "[";
$statisticTimeFilter .= "Ohne<input class=\"smaller\" type=\"radio\" name=\"f_showDateAndTime\" value=\"0\" " . ($f_showDateAndTime == "0" ? "checked" : "") . ">|";
$statisticTimeFilter .= "Mit<input class=\"smaller\" type=\"radio\" name=\"f_showDateAndTime\" value=\"1\" " . ($f_showDateAndTime == "1" ? "checked" : "") . ">";
$statisticTimeFilter .= "Einschränkung auf Zeitintervall von:\n";
$statisticTimeFilter .= "<select name=\"hour_from\" class=\"f8np1\">" . addOptionsFromRange("0","23",$hour_from,"1") . "</select>\n";
$statisticTimeFilter .= "<select name=\"minute_from\" class=\"f8np1\">" . addOptionsFromRange("0","59",$minute_from,"1") . "</select>\n";
$statisticTimeFilter .= "Uhr&nbsp;&nbsp;bis:\n";      
$statisticTimeFilter .= "<select name=\"hour_to\" class=\"f8np1\">" . addOptionsFromRange("0","23",$hour_to,"1") . "</select>\n";
$statisticTimeFilter .= "<select name=\"minute_to\" class=\"f8np1\">" . addOptionsFromRange("0","59",$minute_to,"1") . "</select>\n";
$statisticTimeFilter .= "Uhr]\n";
*/
?>


<html>

<head>
<title><?php echo $pageTitel ?></title>

<link rel="stylesheet" type="text/css" href="../css/phoenix.css">
<style type="text/css">
  <?php include_once ("../css/navigation.css.php"); ?>
</style>

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

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


function finishPage(f_act_value) {  
  document.forms[0].f_act.value=f_act_value;
  document.forms[0].submit();
};

/*
function searchCourier(mode) {
  var f_act = 'search';

  var widthPopupWin = 850;
  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/courier_list.php?f_act=" + f_act + "&f_mode=" + mode, "","dependent=yes,width=" + widthPopupWin + ",height=" + heightPopupWin +",left=" + leftPopupWin + ",top=" + topPopupWin + ",scrollbars=yes");
};
*/

/*
function clearCourier() {	
  document.forms[0].g_cr_id.value='';
  document.forms[0].g_cr_eid.value='';
};
*/

function downloadFile() {
  var widthPopupWin = 850;
  var heightPopupWin = 600;
  var leftPopupWin = (screen.width / 2) - (widthPopupWin / 2) - 12;
  var topPopupWin = (screen.height / 2) - (heightPopupWin / 2) - 50;
  var popupWin;

  popupWin = window.open("../include/data_download.php?f_path=../temp/download/&f_fileName=<?php echo $f_secretFileName ?>", "","dependent=yes,width=" + widthPopupWin + ",height=" + heightPopupWin +",left=" + leftPopupWin + ",top=" + topPopupWin + ",scrollbars=yes"); 
};

// Shows/Hides the group list
/*
function groupList(displayState) {
  if (displayState == 'on') {
  	 myshow('groupList');
  	 myhide('groupListReduced');
  };
  if (displayState == 'off') {
  	 myshow('groupListReduced');
  	 myhide('groupList');
  };
}
*/

/*
function openCustomerFilters() {
  var widthPopupWin = 900;
  var heightPopupWin = 700;
  var leftPopupWin = (screen.width / 2) - (widthPopupWin / 2) - 12;
  var topPopupWin = (screen.height / 2) - (heightPopupWin / 2) - 50;
  var popupWin;
  var f_crvh_filter_str = document.forms[0].g_crvh_filter.value;
  popupWin = window.open("../admin/filter.php?f_crvh_filter_str=" + f_crvh_filter_str,"","dependent=yes,width=" + widthPopupWin + ",height=" + heightPopupWin +",left=" + leftPopupWin + ",top=" + topPopupWin + ",scrollbars=yes");
};
*/
-->
</script>

<?php echo $js_date ?>


</head>

<body onLoad="<?php echo $phpCurrentNavigationOnLoad ?><?php echo $onLoadCall ?>" >

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

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

<form name="statistic" action="../tools/timetracking.php" method="post">
  <input type="hidden" name="f_act" value="">
  <input type="hidden" name="dbhistory" value="<?php echo $dbhistory ?>">
  <input type="hidden" name="outputTitle" value="<?php echo $outputTitle ?>">
  <?php echo $phpCurrentNavigationInputHidden ?>
  <input type="hidden" name="deactivateMenu" value="<?php echo ec($deactivateMenu) ?>">  
  <input type="hidden" name="f_sort" value="<?php echo $f_sort ?>">
  <input type="hidden" name="outputColumnMode" value="<?php echo $outputColumnMode ?>">
  <input type="hidden" name="specialAligns" value="<?php echo $specialAligns ?>">

  <input type="hidden" name="f_sort" value="">
  <?php echo htmlDivLineSpacer("20px"); ?>

  <!-- Output of the calculated values -->  
  <div>
    <div class="f12bp1_blue">Optionen</div>
  </div>

  <?php echo htmlDivLineSpacer("15px"); ?>

  <div>
  	<table>
  		<tr>
  			<!-- Format options -->
  			<td>
  				<?php echo getLngt("Arbeitszeitenübersicht"); ?>
  			</td>

  			<!-- Headquarters options -->
  			<?php if (authCheckEmployeeRights($emp_id, "10")) : ?>
  			  <td>
  				  <?php echo getLngt("Niederlassung"); ?>
  			  </td>
  			<?php endif; ?>

        <!-- Project options -->
  			<td>
  				<?php echo getLngt("Projekte"); ?>
  			</td>

        <!-- User options -->
  			<td>
  				<?php echo getLngt("Benutzer"); ?>
  			</td>

        <!-- Date filter -->
  			<td>
  				<?php echo getLngt("Datum"); ?>
  			</td>
  		</tr>

  		<tr>
  			<!-- Format options -->
  			<td>
         <select class="f8np1" name="f_statistic" id="f_statistic" onChange="finishPage('');">
           <!-- <option value="0" <?php if ($f_statistic == "0") : echo "selected"; endif; ?>>---</option> -->
           <option value="10" <?php if ($f_statistic == "10") : echo "selected"; endif; ?>>Tagesübersicht</option>
           <option value="11" <?php if ($f_statistic == "11") : echo "selected"; endif; ?>>Monatsübersicht</option>
         </select>
  		  </td>

  			<!-- Headquarters options -->
  			<?php if (authCheckEmployeeRights($emp_id, "10")) : ?>
  			  <td>
            <select class="f8np1" name="f_hq_id" id="f_hq_id" onChange="finishPage('');">
              <?php echo getHeadquartersOptions(array($f_hq_id), $f_hq_id); ?>
            </select>
  			  </td>
  			<?php endif; ?>

        <!-- Project (group) options -->
  			<td>
          <select class="f8np1" name="f_grp_id" id="f_usr_id" onChange="finishPage('');">
          	<option value="" <?php if ($f_grp_id == "") : echo "selected"; endif; ?>><?php echo getLngt("Keine Einschränkung"); ?></option>
            <?php // echo addOptionsFromTable("group AS grp","grp.grp_id","grp.grp_name","grp.grp_name","grp.hq_id IN ('0','" . $f_hq_id . "')", $f_grp_id); ?>
          </select>
  			</td>

        <!-- User options -->
  			<td>
          <select class="f8np1" name="f_usr_id" id="f_usr_id" onChange="finishPage('');">
          	<option value="" <?php if ($f_usr_id == "") : echo "selected"; endif; ?>><?php echo getLngt("Keine Einschränkung"); ?></option>
            <?php echo addOptionsFromTable("user","usr_id","CONCAT(usr_name,', ',usr_firstname)","usr_name, usr_firstname","hq_id = '" . $f_hq_id . "' AND usr_type = '3' AND usr_name != ''", $f_usr_id); ?>
          </select>
  			</td>

        <!-- Date filter -->
  			<td>
  				<?php echo $statisticDateFilter; ?>
  				<?php echo $statisticTimeFilter; ?>
  			</td>
  		</tr>
    </table>
  </div>

  <?php echo htmlDivLineSpacer("20px", "", "left"); ?>


  <!-- Display register code of the selected user values -->
  <?php if ($f_usr_id != "" && $outputRegisterCodeOfUser != "") : ?>
    <div>
      <div class="f12bp1_blue"><?php echo getLngt("Registrierungschlüssel des Mitarbeiters") . "&nbsp;" . $usrFirstname . "&nbsp;" . $usrName ?></div>
    </div>
    <?php echo htmlDivLineSpacer("10px"); ?>   
    <div>
      <?php echo $outputRegisterCodeOfUser ?>
    </div>
    <?php echo htmlDivLineSpacer("10px"); ?>
    <?php echo defineButtonType10(getLngt("Schlüssel generieren"), "action_generate_appusr_code", "finishPage('generateNewAppusrCode');", "200", "left", "3"); ?>
    <?php echo defineButtonType10(getLngt("Schlüssel speichern"), "action_store_appusr_code", "finishPage('storeNewAppusrCode');", "200", "left", "3"); ?>
    <?php echo htmlDivLineSpacer("30px", "", "left"); ?>
  <?php endif; ?>

<!--
  <div>
    <div <?php echo $htmlDivFixedWidth; ?>>Weitere Filter:</div>
    <div>
      <input type="checkbox" name="f_filter_01" value="1" <?php if ($f_filter_01 == "1") : echo "checked"; endif; ?>>&nbsp;Aufteilung nach Niederlassungen
    </div>
    <?php echo htmlDivLineSpacer("5px"); ?>

    <?php if (authCheckEmployeeRights($emp_id, "10")) : ?>
      <div <?php echo $htmlDivFixedWidth; ?>>&nbsp;</div>
      <div>
        <input type="checkbox" name="f_filter_02" value="1" <?php if ($f_filter_02 == "1") : echo "checked"; endif; ?>>&nbsp;Aufteilung nach Benutzern
      </div>
      <?php echo htmlDivLineSpacer("5px"); ?>
    <?php endif; ?>
  </div>
  <?php echo htmlDivLineSpacer("10px"); ?>
-->

  <div>
    <div>
      <?php echo defineButtonType10(getLngt("Auswertung anzeigen"), "action_statistic", "finishPage('calculate');", "200", "left", "3"); ?>
      <?php if (authCheckEmployeeRights($emp_id, "10")) : ?>
         &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
         <input type="checkbox" name="fileOutput" value="1" <?php /* if ($fileOutput) : echo "checked"; endif; */ ?>>&nbsp;Zusätzlicher&nbsp;Download&nbsp;der&nbsp;Daten
      <?php endif; ?>
    </div>
  </div>
  <?php echo htmlDivLineSpacer("30px"); ?>

  <!-- Display calculated values -->
  <div>
    <div class="f12bp1_blue"><?php if ($outputTitle != "") : echo $outputTitle; else : echo "Aufstellung"; endif; ?></div>
  </div>

  <?php echo htmlDivLineSpacer("15px"); ?>

  <div>
    <?php echo $screenOutput; ?>
  </div>

<?php if (false) : ?>
  <!-- FOR GENERATING ENTRIES IN TABLE event ONLY !!!! -->
  <?php echo htmlDivLineSpacer("15px"); ?>
  <div>
    <div <?php echo $htmlDivFixedWidth; ?>>SIMULATOR:</div>
    <div>
      <?php echo defineButton("Aktiv", "action_sim_start", "finishPage('simulator_start');", "left", "", "", "", "100px"); ?>
      <?php echo defineButton("Pause", "action_simulator_finish", "finishPage('simulator_finish');", "left", "", "", "", "100px"); ?>
    </div>
  </div>
  <?php echo htmlDivLineSpacer("30px"); ?>
<?php endif; ?>
</form>

</div>

</body>
</html>     

