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


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


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

$autoMode = false;
if (!isset($argv[1]) || $argv[1] == "") :
   $isCron = false;
   include_once ("../include/auth.inc.php");

   getSecHttpVars("1",array("f_act", "title", "hqId", "sendToClientInlineDisplay", "sendToClientFileDownload", "fileTargetType", "pdfPageSize", "specialPath",
                            "mailToAddresses", "mailAttachedFileName", "mailSubject", "mailText", "mailAttachedFileType", "mailCcAddresses", "mailBccAddresses", 
                            "mailSenderAddress", "parKeyForLogFile", "objId", "cascadingObjType",
                            "functionName", "par_01", "par_02", "par_03", "par_04", "par_05", "par_06", "par_07", "par_08", "par_09", "par_10",
                            "customerId", "cscIdRoot", "cscIdActual"));
   $autoMode = true;
   $usrAccessArray["hq"] = "1";
   $usrAccessArray["cs"] = "1";
   $usrAccessArray["cr"] = "1";
   authCheckForAccess($hq_id, $usr_id, $emp_id, "1", $customerId, $cscIdRoot, $cscIdActual);
else :
   // Init parameters
   $f_act = ""; $title = ""; $hqId = ""; $sendToClientInlineDisplay = ""; $sendToClientFileDownload = ""; $fileTargetType = ""; $pdfPageSize = ""; $specialPath = ""; 
   $functionName = ""; $par_01 = ""; $par_02 = ""; $par_03 = ""; $par_04 = ""; $par_05 = ""; $par_06 = ""; $par_07 = ""; $par_08 = ""; $par_09 = ""; $par_10 = "";
   $mailToAddresses = ""; $mailAttachedFileName = ""; $mailSubject = ""; $mailText = ""; $mailAttachedFileType = ""; $mailCcAddresses = ""; $mailBccAddresses = "";
   $mailSenderAddress = ""; $parKeyForLogFile = ""; $objId = ""; $cascadingObjType = "";
   
   $isCron = true;
   if ($argv[1] == "acapella7890") : $autoMode = true; endif;
   if ($autoMode) :
      if (isset($argv[2]) && $argv[2] != "")   : $log_group                 = $argv[2]; endif;
      if (isset($argv[3]) && $argv[3] != "")   : $f_act                     = $argv[3]; endif;
      if (isset($argv[4]) && $argv[4] != "")   : $title                     = $argv[4]; endif;
      if (isset($argv[5]) && $argv[5] != "")   : $hqId                      = $argv[5]; endif;
      if (isset($argv[6]) && $argv[6] != "")   : $sendToClientInlineDisplay = $argv[6]; endif;
      if (isset($argv[7]) && $argv[7] != "")   : $sendToClientFileDownload  = $argv[7]; endif;
      if (isset($argv[8]) && $argv[8] != "")   : $fileTargetType            = $argv[8]; endif;
      if (isset($argv[9]) && $argv[9] != "")   : $pdfPageSize               = $argv[9]; endif;
      if (isset($argv[10]) && $argv[10] != "") : $specialPath               = $argv[10]; endif;
      if (isset($argv[11]) && $argv[11] != "") : $functionName              = $argv[11]; endif;
      if (isset($argv[12]) && $argv[12] != "") : $par_01                    = $argv[12]; endif;
      if (isset($argv[13]) && $argv[13] != "") : $par_02                    = $argv[13]; endif;
      if (isset($argv[14]) && $argv[14] != "") : $par_03                    = $argv[14]; endif;
      if (isset($argv[15]) && $argv[15] != "") : $par_04                    = $argv[15]; endif;
      if (isset($argv[16]) && $argv[16] != "") : $par_05                    = $argv[16]; endif;
      if (isset($argv[17]) && $argv[17] != "") : $par_06                    = $argv[17]; endif;
      if (isset($argv[18]) && $argv[18] != "") : $par_07                    = $argv[18]; endif;
      if (isset($argv[19]) && $argv[19] != "") : $par_08                    = $argv[19]; endif;
      if (isset($argv[20]) && $argv[20] != "") : $par_09                    = $argv[20]; endif;
      if (isset($argv[21]) && $argv[21] != "") : $par_10                    = $argv[21]; endif;
      if (isset($argv[22]) && $argv[22] != "") : $mailToAddresses           = $argv[22]; endif;
      if (isset($argv[23]) && $argv[23] != "") : $mailAttachedFileName      = $argv[23]; endif;
      if (isset($argv[24]) && $argv[24] != "") : $mailSubject               = $argv[24]; endif;
      if (isset($argv[25]) && $argv[25] != "") : $mailText                  = $argv[25]; endif;
      if (isset($argv[26]) && $argv[26] != "") : $mailAttachedFileType      = $argv[26]; endif;
      if (isset($argv[27]) && $argv[27] != "") : $mailCcAddresses           = $argv[27]; endif;
      if (isset($argv[28]) && $argv[28] != "") : $mailBccAddresses          = $argv[28]; endif;
      if (isset($argv[29]) && $argv[29] != "") : $mailSenderAddress         = $argv[29]; endif;
      if (isset($argv[30]) && $argv[30] != "") : $parKeyForLogFile          = $argv[30]; endif;
      if (isset($argv[31]) && $argv[31] != "") : $objId                     = $argv[31]; endif;
      if (isset($argv[32]) && $argv[32] != "") : $cascadingObjType          = $argv[32]; endif;
   endif;
endif;


// Write LOG for CRON only
function cronWriteToFile ($logFile, $text) {
	global $isCron, $log_group;
  if ($isCron) :
     writeToFile($logFile, $log_group . " :: " . $text);
  endif;
}



if ($hqId == "") : $hqId = $hq_id; endif;


$logFile = getParameterValue("0", "AUTOMAILER_CARTAGE_NOTE_LOGFILE", "0");
if ($logFile == "") : $logFile = "../log/automailer_cartage_note.log"; endif;
cronWriteToFile($logFile, "LOG=START|");

if (true) :
   cronWriteToFile($logFile, "f_act=" . $f_act . "|");
   cronWriteToFile($logFile, "title=" . $title . "|");
   cronWriteToFile($logFile, "hqId=" . $hqId . "|");
   cronWriteToFile($logFile, "sendToClientInlineDisplay=" . $sendToClientInlineDisplay . "|");
   cronWriteToFile($logFile, "sendToClientFileDownload=" . $sendToClientFileDownload . "|");
   cronWriteToFile($logFile, "fileTargetType=" . $fileTargetType . "|");
   cronWriteToFile($logFile, "pdfPageSize=" . $pdfPageSize . "|");
   cronWriteToFile($logFile, "specialPath=" . $specialPath . "|");
   cronWriteToFile($logFile, "functionName=" . $functionName . "|");
   cronWriteToFile($logFile, "par_01=" . $par_01 . "|");
   cronWriteToFile($logFile, "par_02=" . $par_02 . "|");
   cronWriteToFile($logFile, "par_03=" . $par_03 . "|");
   cronWriteToFile($logFile, "par_04=" . $par_04 . "|");
   cronWriteToFile($logFile, "par_05=" . $par_05 . "|");
   cronWriteToFile($logFile, "par_06=" . $par_06 . "|");
   cronWriteToFile($logFile, "par_07=" . $par_07 . "|");
   cronWriteToFile($logFile, "par_08=" . $par_08 . "|");
   cronWriteToFile($logFile, "par_09=" . $par_09 . "|");
   cronWriteToFile($logFile, "par_10=" . $par_10 . "|");
   cronWriteToFile($logFile, "mailToAddresses=" . $mailToAddresses . "|");
   cronWriteToFile($logFile, "mailAttachedFileName=" . $mailAttachedFileName . "|");
   cronWriteToFile($logFile, "mailSubject=" . $mailSubject . "|");
   cronWriteToFile($logFile, "mailText=" . $mailText . "|");
   cronWriteToFile($logFile, "mailAttachedFileType=" . $mailAttachedFileType . "|");
   cronWriteToFile($logFile, "mailCcAddresses=" . $mailCcAddresses . "|");
   cronWriteToFile($logFile, "mailBccAddresses=" . $mailBccAddresses . "|");
   cronWriteToFile($logFile, "mailSenderAddress=" . $mailSenderAddress . "|");
endif;


// Check access
if ($autoMode) :

   include_once ("../include/html.inc.php");
   include_once ("../include/inc_html2pdf.inc.php");

   // INIT
   if ($f_act == "") : $f_act = "calculatePDF"; endif;
   if ($sendToClientInlineDisplay == "") : $sendToClientInlineDisplay = "0"; endif;
   if ($sendToClientFileDownload == "") : $sendToClientFileDownload = "1"; endif;
   if ($mailAttachedFileType == "") : $mailAttachedFileType = "pdf"; endif;
   if ($title != "" && $mailSubject == "") : $mailSubject = $title; endif;
   if ($parKeyForLogFile == "") : $parKeyForLogFile = "AUTOMAILER_CARTAGE_NOTE_LOGFILE"; endif;


   // Init for include file "inc_calendar"
   $selDay = getDateTime($mode = "day"); 
   $selMonth = getDateTime($mode = "month"); 
   $selYear = getDateTime($mode = "year"); 

   // Relevant include files to find functions
   $includeArray = array("ftp", "image", "inc_calendar", "inc_customer", "inc_file", "inc_filters", "inc_group", "inc_job", "inc_parseXML", "inc_services", "inc_pnpoly", "inc_stock", "inc_vehicle");

      // NOT in array: "inc_article"
   $includeArrayLen = count($includeArray);
   for ($i = 0; $i < $includeArrayLen; $i++) :
       include_once ("../include/" . $includeArray[$i] . ".inc.php");
   endfor;


   // *************************************************************************************************************************************
   // * BEGIN : Special functions for output ONLY !!!! *

   // Gets the cartage note with all jobs for a specified vehicle and day
   // Needed for special output of the data (e.g. HTML) ONLY
   function getCartageNote ($crvhId, $currDay, $jbStatus, $mode) {
   	global $jobData;
   	$retOutput = "";
   
   	if ($crvhId != "" && is_numeric($crvhId) && $currDay != "") :
   	   if ($jbStatus == "") : $jbStatus = ""; endif;
   	   if ($mode == "") : $mode = ""; endif;
   	   $crvhSid = getFieldValueFromId("couriervehicle", "crvh_id", $crvhId, "crvh_sid");
   
   	   if ($jbStatus == "9") :
   	      // Get job data from all jobs defined in table "vehicledisposition"
   	      $jbArray = getVehicleJobList($crvhId, $currDay, "");
   	   elseif ($jbStatus == "1") :
   	      $jbArray = getVehicleJobList ($crvhId, $currDay, "", "1");
   	   else :
   	      // Get job data from all jobs having the same "cr_id" in job and "jb_status = 1"
   	      $jbArray_01 = getVehicleJobList($crvhId, $currDay, "", "0", " jb.jb_status IN ('9','0') AND jb.jb_offer = '0' AND ");
   	      $jbArray_02 = getVehicleJobList ($crvhId, $currDay, "", "1");
   	      $jbArray = array_merge($jbArray_01, $jbArray_02);
   	   endif;
   	   $jbArrayLen = count($jbArray);

   	   if ($jbArrayLen > 0) :
           $tdStyle = " style=\"width:110px; vertical-align:top\"";
           $retOutput .= "<table border=\"0\" style=\"font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 12pt; font-weight: normal; padding: 1px\">";
           $retOutput .= "<tr>";
           $retOutput .= "  <td colspan=\"5\"><h2>" . getLngt("Fahrzeug") . "&nbsp;&nbsp;" . $crvhSid . "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" . formatOutput($currDay,"datetime","4") . "</h2></td>";
           $retOutput .= "</tr>";
           $retOutput .= "<tr>";
           $retOutput .= "  <td colspan=\"5\">____________________________________________________________________________________________________<br><br></td>";
           $retOutput .= "</tr>";
   
           $taxFactor = 1.19;
           
           $lfdCustomer = 0;
           $lfdRemCompareString = "";
   
       	   for ($i = 0; $i < $jbArrayLen; $i++) :
   
               $jobData["tourarticle"] = array();  // Init because of iteration
       	       $jbId = $jbArray[$i]["jb_id"];
       	       $jbIdParent = $jbArray[$i]["jb_id_parent"];
       	       getDBData("tourarticle", $jbId);
       	       $jbTratArray = $jobData["tourarticle"][2];
       	       $jbTratArrayLen = count($jbTratArray);
   
                // Check for displaying price
       	       $jbPayedPrice = getOneStmt("SELECT SUM(jbp_price) AS price FROM jobpayment WHERE jb_id = '" . $jbId . "'", "price");  // Net price
       	       if ($jbPayedPrice == "") : $jbPayedPrice = 0; endif;
       	       $jbPayedPrice *= $taxFactor;
       	       $jbTotalprice = getFieldValueFromId("job", "jb_id", $jbId, "jb_totalprice");  // Net price
       	       if ($jbTotalprice == "") : $jbTotalprice = 0; endif;
       	       $jbTotalprice *= $taxFactor;  // Gross price
       	       $jbPriceDiff = 0;
       	       if (is_numeric($jbTotalprice) && is_numeric($jbPayedPrice)) :
       	          $jbPriceDiff = ($jbTotalprice - $jbPayedPrice);
       	       endif;

               // Display clock time from day time interval the ordertime is in (e.g. $ecoDayClockTimes[<daytime = 0>] = array("08:00:00", "11:59:59"))

               $parDaytimesComputationMode = getParameterValue("0", "MASK_DISPOSITION_DAYTIMES_COMPUTATION_MODE", "0");
               if ($parDaytimesComputationMode == "1") :
                  $jbDayTimeMtMappedValue = getDaytimeTimeInterval($jbArray[$i]["jb_ordertime"], $jbArray[$i]["cs_id"]);
               elseif ($parDaytimesComputationMode == "2") :
                  $jbDayTimeMtMappedValue = getFieldValueFromClause("phoenix.genericdatacontainer","gdc_content","gdc_obj_type = 'jb' AND gdc_obj_id = '" . $jbId . "' AND gdc_gen_fieldname = 'timewindow_name'");
               else :
                  $intervalArray = getComputedTimeInterval($jbArray[$i]["jb_ordertime"], $jbArray[$i]["cs_id"]);
                  if (count($intervalArray) > 0) :
                     $jbDayTimeMtMappedValue = $intervalArray[0] . " - "  . $intervalArray[1];
                  else :
                     $jbDayTimeMtMappedValue = getDaytimeTimeInterval($jbArray[$i]["jb_ordertime"], $jbArray[$i]["cs_id"]);
                  endif;
               endif;

               // Define computed time interval
               /*
               if ($jbOrderTime != "") :
                  // Compute time interval to be sent to the end customer
                  $intervalArray = getComputedTimeInterval($jbOrderTime, $csId);
                  if (count($intervalArray) > 0) :
                     $jbDayTimeMtMappedValue = substr($jbFreetext1,0,10) . " [" . $intervalArray[0] . " - "  . $intervalArray[1] . "]";
                  endif;
               endif;
               */
   
       	       $jbIdOut = $jbId . "/1";
       	       if ($jbIdParent != "" && is_numeric($jbIdParent) && $jbIdParent > 0):
       	          $jbIdOut = $jbIdParent . "/2";
       	       endif;

               // Check for "Lfd" of the customer
               $lfdCompareString = strtolower($jbArray[$i]["tr2_comp"] . eregPhoneNo($jbArray[$i]["tr2_phone"]));
               if ($lfdRemCompareString != $lfdCompareString) :
                  $lfdRemCompareString = $lfdCompareString;
                  $lfdCustomer++;
               endif;

       	       $retOutput .= "<tr>";
       	       $retOutput .= "  <td" . $tdStyle . "><b>" . getLngt("Auftrag") . "</b></td>";
       	       // $retOutput .= "  <td><b>" . $jbId . "</b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;[" . getLngt("Plantermin") . ":&nbsp;" . substr(formatOutput($jbArray[$i]["jb_ordertime"],"datetime","13"), 0, 5) . "&nbsp;" . getLngt("Uhr") . "]</td>";
       	       $retOutput .= "  <td><b>" . $jbIdOut . "</b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;[" . getLngt("Zeitraum") . ":&nbsp;" . $jbDayTimeMtMappedValue . "]</td>";
       	       $retOutput .= "</tr>";

       	       $retOutput .= "<tr>";
       	       $retOutput .= "  <td" . $tdStyle . "><b>" . getLngt("Kunde") . "&nbsp;[#" . $lfdCustomer . "]</b></td>";
       	       $retOutput .= "  <td><b>" . $jbArray[$i]["tr2_comp"] . "</b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;[" . getLngt("Telefon") . ":&nbsp;" . $jbArray[$i]["tr2_phone"] . "]</b></td>";
       	       $retOutput .= "</tr>";

       	       $retOutput .= "<tr>";
       	       $retOutput .= "  <td" . $tdStyle . "><b>" . getLngt("Adresse") . "</b></td>";
       	       $retOutput .= "  <td>" . $jbArray[$i]["ad2_street"] . "&nbsp;" . $jbArray[$i]["tr2_hsno"] . (trim($jbArray[$i]["tr2_floor"]) != "" ? "&nbsp;&nbsp;&nbsp;[" . getLngt("Etage") . ":&nbsp;" . $jbArray[$i]["tr2_floor"] : "") . "]&nbsp;" . "" . "</td>";
       	       $retOutput .= "</tr>";
       	       $retOutput .= "<tr>";
       	       $retOutput .= "  <td" . $tdStyle . ">&nbsp;</td>";
       	       $retOutput .= "  <td>" . $jbArray[$i]["ad2_zipcode"] . "</b>&nbsp;" . $jbArray[$i]["ad2_city"] . "</td>";
       	       $retOutput .= "</tr>";

               // Get Remark (tr2_remark)
               $tr2Remark = getFieldValueFromClause("tour","tr_remark","jb_id = '" . $jbId . "' AND tr_sort = '2'");
               $tr2Remark = nl2br($tr2Remark);
       	       $retOutput .= "<tr>";
       	       $retOutput .= "  <td" . $tdStyle . "><b>" . getLngt("Service") . "</b></td>";
       	       // $retOutput .= "  <td>" . splitText($tr2Remark, "1", 70) . "</td>";

               // Get requested services
               $jbServices = getColVectorFromDB2ArrayByClause("metatype", "mt_sort", "mt_type = 'service' AND mt_sort >= '2'", "", "mt_sort", "");
               $jbServiceNames = getColVectorFromDB2ArrayByClause("metatype", "mt_value", "mt_type = 'service' AND mt_sort >= '2'", "mt_sort", "mt_sort", "");
               $jbServicesLen = count($jbServices);
               // Iterate array
               $jbServiceText = "";
               for ($j = 0; $j < $jbServicesLen; $j++) :
                   (int)$jbServiceMode = pow(2,$jbServices[$j]);
                   if (($jbArray[$i]["jb_service"] & $jbServiceMode) == $jbServiceMode) :
                      if ($jbServiceText != "") : $jbServiceText .= ", "; endif;
                      $jbServiceText .= "<b>" . getLngt($jbServiceNames[$jbServices[$j]]) . "</b>";
                   endif;
               endfor;
               if ($jbServiceText == "") :
       	          if (($jbArray[$i]["jb_service"] & 1) == 1) :
       	             $jbServiceText = "<b>" . getLngt("Lieferung") . "</b>";
       	             if ($tr2Remark != "") : 
       	                $tr2Remark = "<b>" . $jbServiceText . "<br>" . $tr2Remark;
       	             else :
       	                $tr2Remark = $jbServiceText;
       	             endif;
       	          endif;
       	          if (($jbArray[$i]["jb_service"] & 2) == 2) :
       	             $jbServiceText = "<b>" . getLngt("Montage") . "</b>";
       	             if ($tr2Remark != "") : 
       	                $tr2Remark = $jbServiceText . "<br>" . $tr2Remark;
       	             else :
       	                $tr2Remark = $jbServiceText;
       	             endif;
       	          endif;
       	       else :
       	          if ($tr2Remark != "") : 
       	             $tr2Remark = $jbServiceText . "<br>" . $tr2Remark;
       	          else :
       	             $tr2Remark = $jbServiceText;
       	          endif;
       	       endif;

       	       $retOutput .= "  <td>" . $tr2Remark . "</td>";
       	       $retOutput .= "</tr>";
   
       	       $retOutput .= "<tr>";
       	       $retOutput .= "  <td" . $tdStyle . "><b>" . getLngt("Ware") . "</b></td>";
       	       $retOutput .= "  <td>";


               $retOutput .= "    <table border=\"0\" style=\"font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 12pt; font-weight: normal; padding: 1px\">";
               $retOutput .= "      <tr><td style=\"width:350px;\">" . getLngt("Beschreibung") . "&nbsp;</td><td style=\"width:120px;\">" . getLngt("Artikel") . "&nbsp;</td><td>" . getLngt("Menge") . "&nbsp;</td><td>" . getLngt("Packstücke") . "&nbsp;</td></tr>";  // <td>" . getLngt("Preis") . "&nbsp;</td>

   	           if ($jbTratArrayLen > 0) :
   	              $sumOfTratPackingPieces = 0;
       	          for ($j = 0; $j < $jbTratArrayLen; $j++) :
       	              $retOutput .= "      <tr>";
// !!!! ATTENTION trat_serialno => trat_name, trat_remark => trat_description !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
       	              // $retOutput .= "        <td>" . substr($jbTratArray[$j]["trat_description"], 0, 50) . "</td>";
       	              $retOutput .= "        <td>" . substr($jbTratArray[$j]["trat_remark"], 0, 50) . "</td>";
       	              // $retOutput .= "        <td>" . $jbTratArray[$j]["trat_name"] . "</td>";
       	              $retOutput .= "        <td>" . $jbTratArray[$j]["trat_serialno"] . "</td>";
       	              $retOutput .= "        <td align=\"center\">" . $jbTratArray[$j]["trat_quantity"] . "</td>";
       	              $retOutput .= "        <td align=\"center\">" . $jbTratArray[$j]["trat_packingpieces"] . "</td>";
       	              // $retOutput .= "        <td align=\"right\">" . $jbTratArray[$j]["trat_price"] . "</td>";
       	              $retOutput .= "      </tr>";
       	              
       	              $sumOfTratPackingPieces += $jbTratArray[$j]["trat_packingpieces"];
       	          endfor;
       	          $retOutput .= "      <tr><td colspan=\"4\"><b>" . getLngt("Gesamtanzahl Packstücke") . "&nbsp;:&nbsp;" . $sumOfTratPackingPieces . "</b></td></tr>";
       	       endif;

               // Check for additional article info in GDC
               $gdcContentJbAddedInfo = getFieldValueFromClause("genericdatacontainer", "gdc_content", "gdc_obj_type = 'jb' AND gdc_obj_id = '" . $jbId . "' AND gdc_gen_fieldname = 'jb_addinfo'");
               if ($gdcContentJbAddedInfo) :
                  $retOutput .= "      <tr>";
                  $retOutput .= "        <td colspan=\"4\"><br><b>" . $gdcContentJbAddedInfo . "</b></td>";
                  $retOutput .= "      </tr>";
               endif;
   
       	       // Display price if not have been payed
               if (is_numeric($jbPriceDiff) && $jbPriceDiff > 0) :
                  $retOutput .= "      <tr><td colspan=\"4\"><b>" . getLngt("Inkasso kassieren") . "&nbsp;:&nbsp;€&nbsp;" . number_format(round($jbPriceDiff, 2), 2, ",", ".") . "</b></td></tr>";
       	       endif;
   
       	       // Customer sign
       	       $retOutput .= "      <tr><td colspan=\"4\"><br><br><br></td></tr>";
               $retOutput .= "      <tr><td colspan=\"4\" style=\"text-align:right\">_________________________________________</td></tr>";
               $retOutput .= "      <tr><td colspan=\"4\" style=\"font-size: 8pt; text-align:right\">" . getLngt("Kundenunterschrift") . "</td></tr>";
               $retOutput .= "  ";
   
       	       $retOutput .= "    </table>";

       	       $retOutput .= "  </td>";
       	       $retOutput .= "</tr>";
   
       	       $retOutput .= "<tr>";
       	       $retOutput .= "  <td colspan=\"5\">____________________________________________________________________________________________________<br><br></td>";
       	       $retOutput .= "</tr>";
       	   endfor;
       	   $retOutput .= "</table>";
        endif;
   	endif;
   	return $retOutput;
   }

   // Gets the cartage note with all jobs for a specified vehicle and day
   // Needed for special output of the data (e.g. HTML) ONLY
   function getServiceCartageNote ($crvhId, $currDay, $jbStatus, $mode) {
   	global $jobData;
   	$retOutput = "";
   
   	if ($crvhId != "" && is_numeric($crvhId) && $currDay != "") :
   	   if ($jbStatus == "") : $jbStatus = ""; endif;
   	   if ($mode == "") : $mode = ""; endif;
   	   $crvhSid = getFieldValueFromId("couriervehicle", "crvh_id", $crvhId, "crvh_sid");
   
   	   if ($jbStatus == "9") :
   	      // Get job data from all jobs defined in table "vehicledisposition"
   	      $jbArray = getVehicleJobList($crvhId, $currDay, "");
   	   elseif ($jbStatus == "1") :
   	      $jbArray = getVehicleJobList ($crvhId, $currDay, "", "1");
   	   else :
   	      // Get job data from all jobs having the same "cr_id" in job and "jb_status = 1"
   	      $jbArray_01 = getVehicleJobList($crvhId, $currDay, "", "0", " jb.jb_status IN ('9','0') AND jb.jb_offer = '0' AND ");
   	      $jbArray_02 = getVehicleJobList ($crvhId, $currDay, "", "1");
   	      $jbArray = array_merge($jbArray_01, $jbArray_02);
   	   endif;
   	   $jbArrayLen = count($jbArray);

   	   if ($jbArrayLen > 0) :
           // $tdStyle = " style=\"width:110px; vertical-align:top;\"";
           $tdStyle = "width:110px; vertical-align:top;";
           $retOutput .= "<table border=\"0\" style=\"font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 12pt; font-weight: normal; padding: 1px\">";
           $retOutput .= "<tr>";
           $retOutput .= "  <td colspan=\"5\"><h2>" . getLngt("Fahrzeug") . "&nbsp;&nbsp;" . $crvhSid . "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" . formatOutput($currDay,"datetime","4") . "</h2></td>";
           $retOutput .= "</tr>";
           $retOutput .= "<tr>";
           $retOutput .= "  <td colspan=\"5\">____________________________________________________________________________________________________<br><br></td>";
           $retOutput .= "</tr>";
   
           $taxFactor = 1.19;
           
           $lfdCustomer = 0;
           $lfdRemCompareString = "";
   
       	   for ($i = 0; $i < $jbArrayLen; $i++) :
   
               $jobData["tourarticle"] = array();  // Init because of iteration
       	       $jbId = $jbArray[$i]["jb_id"];
       	       $jbIdParent = $jbArray[$i]["jb_id_parent"];

       	       // Internal remark from GDC
       	       $jbIdInternalRemark = getFieldValueFromClause("genericdatacontainer","gdc_content","gdc_obj_type = 'jb' AND gdc_gen_fieldname = 'internal_remark' AND gdc_obj_id = '" . $jbId . "'");

               // Get stock name
               $stkId = getFieldValueFromId("articleitem", "ati_serialno", $jbArray[$i]["tr2_comp"], "stk_id");
               $stkName = getFieldValueFromId("stock", "stk_id", $stkId, "stk_name");

       	       getDBData("tourarticle", $jbId);
       	       $jbTratArray = $jobData["tourarticle"][2];
       	       $jbTratArrayLen = count($jbTratArray);
   
                // Check for displaying price
       	       $jbPayedPrice = getOneStmt("SELECT SUM(jbp_price) AS price FROM jobpayment WHERE jb_id = '" . $jbId . "'", "price");  // Net price
       	       if ($jbPayedPrice == "") : $jbPayedPrice = 0; endif;
       	       $jbPayedPrice *= $taxFactor;
       	       $jbTotalprice = getFieldValueFromId("job", "jb_id", $jbId, "jb_totalprice");  // Net price
       	       if ($jbTotalprice == "") : $jbTotalprice = 0; endif;
       	       $jbTotalprice *= $taxFactor;  // Gross price
       	       $jbPriceDiff = 0;
       	       if (is_numeric($jbTotalprice) && is_numeric($jbPayedPrice)) :
       	          $jbPriceDiff = ($jbTotalprice - $jbPayedPrice);
       	       endif;

               // Display clock time from day time interval the ordertime is in (e.g. $ecoDayClockTimes[<daytime = 0>] = array("08:00:00", "11:59:59"))

               $parDaytimesComputationMode = getParameterValue("0", "MASK_DISPOSITION_DAYTIMES_COMPUTATION_MODE", "0");
               if ($parDaytimesComputationMode == "1") :
                  $jbDayTimeMtMappedValue = getDaytimeTimeInterval($jbArray[$i]["jb_ordertime"], $jbArray[$i]["cs_id"]);
               elseif ($parDaytimesComputationMode == "2") :
                  $jbDayTimeMtMappedValue = getFieldValueFromClause("phoenix.genericdatacontainer","gdc_content","gdc_obj_type = 'jb' AND gdc_obj_id = '" . $jbId . "' AND gdc_gen_fieldname = 'timewindow_name'");
               else :
                  $intervalArray = getComputedTimeInterval($jbArray[$i]["jb_ordertime"], $jbArray[$i]["cs_id"]);
                  if (count($intervalArray) > 0) :
                     $jbDayTimeMtMappedValue = $intervalArray[0] . " - "  . $intervalArray[1];
                  else :
                     $jbDayTimeMtMappedValue = getDaytimeTimeInterval($jbArray[$i]["jb_ordertime"], $jbArray[$i]["cs_id"]);
                  endif;
               endif;

               // Define computed time interval
               /*
               if ($jbOrderTime != "") :
                  // Compute time interval to be sent to the end customer
                  $intervalArray = getComputedTimeInterval($jbOrderTime, $csId);
                  if (count($intervalArray) > 0) :
                     $jbDayTimeMtMappedValue = substr($jbFreetext1,0,10) . " [" . $intervalArray[0] . " - "  . $intervalArray[1] . "]";
                  endif;
               endif;
   
       	       $jbIdOut = $jbId . "/1";
       	       if ($jbIdParent != "" && is_numeric($jbIdParent) && $jbIdParent > 0):
       	          $jbIdOut = $jbIdParent . "/2";
       	       endif;
               */
               $jbIdOut = $jbId;

               // Check for "Lfd" of the customer
               $lfdCompareString = strtolower($jbArray[$i]["tr2_comp"] . eregPhoneNo($jbArray[$i]["tr2_phone"]));
               if ($lfdRemCompareString != $lfdCompareString) :
                  $lfdRemCompareString = $lfdCompareString;
                  $lfdCustomer++;
               endif;

       	       // $retOutput .= "<tr>";
       	       // $retOutput .= "  <td style=\"" . $tdStyle . "\">" . getLngt("Auftrag") . "</td>";
       	       // $retOutput .= "  <td><b>" . $jbIdOut . "</b></td>";
       	       // $retOutput .= "</tr>";

       	       $retOutput .= "<tr>";
       	       $retOutput .= "  <td style=\"" . $tdStyle . "\">" . getLngt("Servicestelle") . "&nbsp;</td>";
       	       $retOutput .= "  <td style=\"color:green;font-size: 14pt;\"><b>" . $jbArray[$i]["tr2_comp"] . "</b>" . "&nbsp;-&nbsp;" . $stkName . "&nbsp;&nbsp;(" . $jbArray[$i]["tr2_comp2"] . ")</td>";  //  . "&nbsp;&nbsp;&nbsp;<b>[#&nbsp;" . $jbIdOut . "]</b>"
       	       $retOutput .= "</tr>";

       	       // $retOutput .= "<tr>";
       	       // $retOutput .= "  <td style=\"" . $tdStyle . "\">" . getLngt("Adresse") . "</td>";
       	       // $retOutput .= "  <td>" . $jbArray[$i]["ad2_street"] . "&nbsp;" . $jbArray[$i]["tr2_hsno"] . ", " . $jbArray[$i]["ad2_zipcode"] . "</b>&nbsp;" . $jbArray[$i]["ad2_city"] . "</td>";
       	       // $retOutput .= "</tr>";

               $tr2Person = $jbArray[$i]["tr2_person"];
               $tr2PersonArray = getKeyValueArrayFromString($tr2Person);
               $tr2PersonKeyArray = array_keys($tr2PersonArray);
               $tr2PersonKeyArrayLen = count($tr2PersonKeyArray);
               // Because of different names....!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!  :-/
               // $tmpMappingHopperNames = array("BEK" => "BEK", "MEK" => "MEK", "H02" => "H1", "H05" => "H3", "H10" => "H2", "H1" => "H02", "H2" => "H10", "H3" => "H05");
               $tmpMappingHopperNames = array("H02" => "H1", "H05" => "H3", "H10" => "H2");
               for ($k = 0; $k < $tr2PersonKeyArrayLen; $k++) :
                   if ($tmpMappingHopperNames[$tr2PersonKeyArray[$k]] != "") :
                      $tr2PersonArray[$tmpMappingHopperNames[$tr2PersonKeyArray[$k]]] = $tr2PersonArray[$tr2PersonKeyArray[$k]];
                      unset($tr2PersonArray[$tr2PersonKeyArray[$k]]);
                   endif;                   
               endfor;
               $tr2PersonKeyArray = array_keys($tr2PersonArray);
               $tr2Person = implode(",", $tr2PersonKeyArray);

               // Get Remark (tr2_remark)
               $tr2Remark = getFieldValueFromClause("tour","tr_remark","jb_id = '" . $jbId . "' AND tr_sort = '2'");
               // $tr2Remark = nl2br($tr2Remark);

               // Check für remark contains 
               if (substr($tr2Remark, 0, 6) == "[TEXT]") : 
                  $tr2Remark = "<span style=\"color:red;font-size: 14pt;\">" . substr($tr2Remark, 6) . "</span>";
               else :               
                  $tr2RemarkArray = getKeyValueArrayFromString($tr2Remark,"|",":");
                  $tr2RemarkKeyArray = array_keys($tr2RemarkArray);
                  $tr2RemarkKeyArrayLen = count($tr2RemarkKeyArray);
                  $tr2Remark = "";  // Init
                  $tmpCrLfArray = array(2,5,6,7,8,9,10);
                  for ($k = 0; $k < $tr2RemarkKeyArrayLen; $k++) :
                       $tmpKey = $tr2RemarkKeyArray[$k];
                       $tmpValue = trim($tr2RemarkArray[$tr2RemarkKeyArray[$k]]);
                       if ($tmpValue != "") :
                          $tmpInArr1 = in_array($k, $tmpCrLfArray);  // Line feed?
                          $tmpInArr2 = in_array($tmpKey, $tr2PersonKeyArray);  // Mark critical object computed by system
                          $tr2Remark .= ($tr2Remark != "" ? ($tmpInArr1 ? "<br>" : "&nbsp;|&nbsp;") : "") . ($tmpInArr2 ? "<b>" : "") . $tmpKey . ":&nbsp;" . $tmpValue . ($tmpInArr2 ? "</b>" : "");
                       endif;
                  endfor;
               endif;

               // Get critical objects by service unit messages
               $tr2CsFreetext = getFieldValueFromClause("tour","tr_cs_freetext","jb_id = '" . $jbId . "' AND tr_sort = '2'");

               // $tr2Remark = str_replace("|", "</br>", trim($tr2Remark));
       	       $retOutput .= "<tr>";
       	       $retOutput .= "  <td style=\"" . $tdStyle . "\">" . getLngt("Service") . "</td>";

               // Get requested services
               $jbServices = getColVectorFromDB2ArrayByClause("metatype", "mt_sort", "mt_type = 'service' AND mt_sort >= '2'", "", "mt_sort", "");
               $jbServiceNames = getColVectorFromDB2ArrayByClause("metatype", "mt_value", "mt_type = 'service' AND mt_sort >= '2'", "mt_sort", "mt_sort", "");
               $jbServicesLen = count($jbServices);
               // Iterate array
               $jbServiceText = "";
               for ($j = 0; $j < $jbServicesLen; $j++) :
                   (int)$jbServiceMode = pow(2,$jbServices[$j]);
                   if (($jbArray[$i]["jb_service"] & $jbServiceMode) == $jbServiceMode) :
                      if ($jbServiceText != "") : $jbServiceText .= ", "; endif;
                      $jbServiceText .= "<b>" . getLngt($jbServiceNames[$jbServices[$j]]) . "</b>";
                   endif;
               endfor;
               if ($jbServiceText == "") :
       	          if (($jbArray[$i]["jb_service"] & 1) == 1 && $tr2Person != "") :
       	             $jbServiceText .= "<b>" . getLngt("Austausch") . "</b>" . "&nbsp;<b><span style=\"color:red\">" . $tr2Person . "</span></b><br>";
       	          endif;
       	          if (($jbArray[$i]["jb_service"] & 2) == 2 && $tr2CsFreetext != "") :
       	             $jbServiceText .= "<b>" . getLngt("Wartung") . "</b>" . "&nbsp;<b><span style=\"color:red\">" . $tr2CsFreetext . "</span></b><br>";
       	          endif;
       	          if ($tr2Remark != "") : 
       	             $tr2Remark = $jbServiceText . $tr2Remark;
       	          else :
       	             $tr2Remark = $jbServiceText;
       	          endif;
       	       else :
       	          if ($tr2Remark != "") : 
       	             $tr2Remark = $jbServiceText . "&nbsp;<b>" . $tr2Person . "</b><br>" . $tr2Remark;
       	          else :
       	             $tr2Remark = $jbServiceText;
       	          endif;
       	       endif;

       	       $retOutput .= "  <td>" . $tr2Remark . "</td>";
       	       $retOutput .= "</tr>";
/*
       	       $retOutput .= "<tr>";
       	       $retOutput .= "  <td style=\"" . $tdStyle . "\">" . getLngt("Posten") . "</td>";
       	       $retOutput .= "  <td>";


               $retOutput .= "    <table border=\"0\" style=\"font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 12pt; font-weight: normal; padding: 1px\">";
               $retOutput .= "      <tr><td style=\"width:350px;\">" . getLngt("Beschreibung") . "&nbsp;</td><td style=\"width:120px;\">" . getLngt("Artikel") . "&nbsp;</td><td>" . getLngt("Menge") . "&nbsp;</td><td>" . getLngt("Packstücke") . "&nbsp;</td></tr>";  // <td>" . getLngt("Preis") . "&nbsp;</td>

   	           if ($jbTratArrayLen > 0) :
   	              $sumOfTratPackingPieces = 0;
       	          for ($j = 0; $j < $jbTratArrayLen; $j++) :
       	              $retOutput .= "      <tr>";
// !!!! ATTENTION trat_serialno => trat_name, trat_remark => trat_description !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
       	              // $retOutput .= "        <td>" . substr($jbTratArray[$j]["trat_description"], 0, 50) . "</td>";
       	              $retOutput .= "        <td>" . substr($jbTratArray[$j]["trat_remark"], 0, 50) . "</td>";
       	              // $retOutput .= "        <td>" . $jbTratArray[$j]["trat_name"] . "</td>";
       	              $retOutput .= "        <td>" . $jbTratArray[$j]["trat_serialno"] . "</td>";
       	              $retOutput .= "        <td align=\"center\">" . $jbTratArray[$j]["trat_quantity"] . "</td>";
       	              $retOutput .= "        <td align=\"center\">" . $jbTratArray[$j]["trat_packingpieces"] . "</td>";
       	              // $retOutput .= "        <td align=\"right\">" . $jbTratArray[$j]["trat_price"] . "</td>";
       	              $retOutput .= "      </tr>";
       	              
       	              $sumOfTratPackingPieces += $jbTratArray[$j]["trat_packingpieces"];
       	          endfor;
       	          $retOutput .= "      <tr><td colspan=\"4\"><b>" . getLngt("Gesamtanzahl Packstücke") . "&nbsp;:&nbsp;" . $sumOfTratPackingPieces . "</b></td></tr>";
       	       endif;

               // Check for additional article info in GDC
               $gdcContentJbAddedInfo = getFieldValueFromClause("genericdatacontainer", "gdc_content", "gdc_obj_type = 'jb' AND gdc_obj_id = '" . $jbId . "' AND gdc_gen_fieldname = 'jb_addinfo'");
               if ($gdcContentJbAddedInfo) :
                  $retOutput .= "      <tr>";
                  $retOutput .= "        <td colspan=\"4\"><br><b>" . $gdcContentJbAddedInfo . "</b></td>";
                  $retOutput .= "      </tr>";
               endif;
   
       	       // Display price if not have been payed
               if (is_numeric($jbPriceDiff) && $jbPriceDiff > 0) :
                  $retOutput .= "      <tr><td colspan=\"4\"><b>" . getLngt("Inkasso kassieren") . "&nbsp;:&nbsp;€&nbsp;" . number_format(round($jbPriceDiff, 2), 2, ",", ".") . "</b></td></tr>";
       	       endif;

       	       $retOutput .= "      <tr><td colspan=\"4\"><br><br><br></td></tr>";
               $retOutput .= "      <tr><td colspan=\"4\" style=\"text-align:right\">_________________________________________</td></tr>";
               $retOutput .= "      <tr><td colspan=\"4\" style=\"font-size: 8pt; text-align:right\">" . getLngt("Wartungsnotiz") . "</td></tr>";
               $retOutput .= "  ";
   
       	       $retOutput .= "    </table>";

       	       $retOutput .= "  </td>";
       	       $retOutput .= "</tr>";
*/   
       	       $retOutput .= "<tr>";
       	       $retOutput .= "  <td style=\"" . $tdStyle . "\">" . getLngt("Notizen") . "</td>";
       	       $retOutput .= "  <td style=\"color:red;\">" . $jbIdInternalRemark . "<br></td>";
       	       $retOutput .= "</tr>";

       	       $retOutput .= "<tr>";
       	       $retOutput .= "  <td colspan=\"5\">____________________________________________________________________________________________________<br><br></td>";
       	       $retOutput .= "</tr>";
       	   endfor;
       	   $retOutput .= "</table>";
        endif;
   	endif;
   	return $retOutput;
   }
   
   // Gets the delivery statistic for a specified vehicle and day
   function getDeliveryStatistic ($crvhId, $currDay, $mode = "") {
   	global $db, $PHP_SELF, $hq_id;
   	$retOutput = "";
   
   	if ($crvhId != "" && is_numeric($crvhId)) :
   
       $crvhSid = getFieldValueFromId("couriervehicle", "crvh_id", $crvhId, "crvh_sid");
   	   if ($jbStatus == "") : $jbStatus = "2"; endif;
   	   $serviceValue = "1";
   
       $count = 0;
       $timeArray = array();
   
       if ($mode == "1") :
          // Each single job
          $sqlquery = "SELECT jb.jb_id, jb.jb_timeunits, (UNIX_TIMESTAMP(tr.tr_finishtime)-UNIX_TIMESTAMP(jb.jb_ordertime)) AS time"
                       . " FROM couriervehicle AS crvh, job AS jb, tour AS tr"
                       . " WHERE crvh.crvh_id = '" . $crvhId . "' AND"
                       . "       jb.cr_sid = crvh.crvh_sid AND"
                       . "       jb.jb_status = '" . $jbStatus . "' AND"
                       . "       (isnull(jb.jb_storno) OR jb.jb_storno = '0' OR jb.jb_storno = '1' OR jb.jb_storno = '3') AND"
                       . "       tr.jb_id = jb.jb_id AND"
                       . "       tr.tr_sort = '2' AND"
                       . "       ((NOT ISNULL(jb.jb_ordertime)) AND jb.jb_ordertime != '0000-00-00 00:00:00') AND"
                       . "       ((NOT ISNULL(tr.tr_finishtime)) AND tr.tr_finishtime != '0000-00-00 00:00:00') AND"
                       . "       (jb.jb_service & " . $serviceValue . " = " . $serviceValue . ")"
                       . " GOUP BY LEFT(jb.jb_ordertime,7)"
                       . " ORDER BY jb.jb_ordertime";

          $result = $db->query($sqlquery);
          while ($row = $result->fetch_assoc()):
                $timeArray[$count]["val1"] = $row["jb_id"];
                $timeArray[$count]["val2"] = $row["jb_timeunits"];
                $timeArray[$count]["val3"] = secondsToDate($row["time"], "%h " . getLngt("Std.") . ", %i " . getLngt("Min.") . " %s " . getLngt("Sek."));
                $timeArray[$count]["val4"] = "";
                if ($row["time"] > 0 && $row["timeunits"] > 0) :
                   $timeUnitsInSeconds = ($row["timeunits"] * 600);  // A single time unit equals 10 minutes, one minute has 60 seconds => Factor = 10 * 60 = 600
                   $timeArray[$count]["val4"] = round(($row["time"] / $timeUnitsInSeconds), 2);
                endif;
                $count++;
          endwhile;
          $result->free();
   
          $outTextStatistic = getLngt("Auslieferstatistik pro Auftrag");
          $outTextColspan = "4";
          $outTextColumn_1 = getLngt("Auftrag");        $outWidthColumn_1 = " width=\"100\" ";  $outAlignColumn_1 = " align=\"center\" ";
          $outTextColumn_2 = getLngt("Zeiteinheiten");  $outWidthColumn_2 = " width=\"150\" ";  $outAlignColumn_2 = " align=\"center\" ";
          $outTextColumn_3 = getLngt("Benötigte Zeit"); $outWidthColumn_3 = " width=\"250\" ";  $outAlignColumn_3 = " align=\"center\" ";
          $outTextColumn_4 = getLngt("Verhältnis");     $outWidthColumn_4 = " width=\"100\" ";  $outAlignColumn_4 = " align=\"center\" ";
       else :

          // Summation per month
          // $sqlquery = "SELECT LEFT(jb.jb_ordertime,7) AS month, SUM(jb.jb_timeunits) AS timeunits, SUM(UNIX_TIMESTAMP(tr.tr_finishtime)-UNIX_TIMESTAMP(jb.jb_ordertime)) AS time"
          // $sqlquery = "SELECT LEFT(jb.jb_ordertime,7) AS month, SUM(jb.jb_timeunits) AS timeunits, SUM(UNIX_TIMESTAMP(tr.tr_finishtime)-UNIX_TIMESTAMP(STR_TO_DATE(LEFT(gdc_arr_tour.gdc_content,14),'%Y%m%d%h%i%s'))) AS time"
$sqlquery = "SELECT LEFT(jb.jb_ordertime,7) AS month, SUM(jb.jb_timeunits) AS timeunits, SUM(UNIX_TIMESTAMP(tr.tr_modify)-UNIX_TIMESTAMP(STR_TO_DATE(LEFT(gdc_arr_tour.gdc_content,14),'%Y%m%d%h%i%s'))) AS time"
                       . " FROM couriervehicle AS crvh, job AS jb, tour AS tr LEFT JOIN genericdatacontainer AS gdc_arr_tour ON gdc_arr_tour.gdc_obj_id = tr.tr_id AND gdc_arr_tour.gdc_obj_type = 'tr' AND gdc_arr_tour.gdc_gen_fieldname = 'arr_tour'"
                       . " WHERE crvh.crvh_id = '" . $crvhId . "' AND"
                       . "       jb.cr_sid = crvh.crvh_sid AND"
                       . "       jb.jb_status = '" . $jbStatus . "' AND"
                       . "       (isnull(jb.jb_storno) OR jb.jb_storno = '0' OR jb.jb_storno = '1' OR jb.jb_storno = '3') AND"
                       . "       tr.jb_id = jb.jb_id AND"
                       . "       tr.tr_sort = '2' AND"
                       . "       (NOT ISNULL(tr.tr_sign)) AND"
                       . "       ((NOT ISNULL(jb.jb_ordertime)) AND jb.jb_ordertime != '0000-00-00 00:00:00') AND"
                       . "       ((NOT ISNULL(tr.tr_finishtime)) AND tr.tr_finishtime != '0000-00-00 00:00:00') AND"
                       . "       gdc_arr_tour.gdc_content != '' AND"
                       . "       (jb.jb_service & " . $serviceValue . " = " . $serviceValue . ")"
                       . " GROUP BY LEFT(jb.jb_ordertime,7)"
                       . " ORDER BY LEFT(jb.jb_ordertime,7)";
// echo $sqlquery; die();
          $result = $db->query($sqlquery);
          while ($row = $result->fetch_assoc()):
                $timeArray[$count]["val1"] = $row["month"];
                $timeArray[$count]["val2"] = $row["timeunits"];
                $timeArray[$count]["val3"] = secondsToDate($row["time"], "%a " . getLngt("Tage") . ", %h " . getLngt("Std.") . ", %i " . getLngt("Min.") . " %s " . getLngt("Sek."));
                $timeArray[$count]["val4"] = "";
                if ($row["time"] > 0 && $row["timeunits"] > 0) :
                   $timeUnitsInSeconds = ($row["timeunits"] * 600);  // A single time unit equals 10 minutes, one minute has 60 seconds => Factor = 10 * 60 = 600
                   $timeArray[$count]["val4"] = round(($row["time"] / $timeUnitsInSeconds), 2);
                endif;
                $count++;
          endwhile;
          $result->free();
   
          $outTextStatistic = getLngt("Auslieferstatistik pro Monat");
          $outTextColspan = "3";
          $outTextColumn_1 = getLngt("Monat");                 $outWidthColumn_1 = " width=\"100\" ";  $outAlignColumn_1 = " align=\"center\" ";
          $outTextColumn_2 = getLngt("Summe Zeiteinheiten");   $outWidthColumn_2 = " width=\"150\" ";  $outAlignColumn_2 = " align=\"center\" ";
          $outTextColumn_3 = getLngt("Summe benötigter Zeit"); $outWidthColumn_3 = " width=\"250\" ";  $outAlignColumn_3 = " align=\"center\" ";
          $outTextColumn_4 = getLngt("Verhältnis");            $outWidthColumn_4 = " width=\"100\" ";  $outAlignColumn_4 = " align=\"center\" ";
       endif;

       $timeArrayLen = count($timeArray);
       if ($timeArrayLen > 0) :
   
          $tdStyle = " style=\"width:100px; vertical-align:top\"";
          $retOutput .= "<table border=\"0\" style=\"font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 12pt; font-weight: normal; padding: 1px\">";
   
          $retOutput .= "<tr>";
          $retOutput .= "  <td colspan=\"" . $outTextColspan . "\"><h2>" . getLngt("Fahrzeug") . "&nbsp;&nbsp;" . $crvhSid . "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" . $outTextStatistic . "</h2></td>";
          $retOutput .= "</tr>";
          $retOutput .= "<tr>";
          $retOutput .= "  <td colspan=\"" . $outTextColspan . "\">____________________________________________________________________________________________________<br><br></td>";
          $retOutput .= "</tr>";
   
          $retOutput .= "<tr>";
          $retOutput .= "  <td" . $outWidthColumn_1 . $outAlignColumn_1 . "><b>" . $outTextColumn_1 . "</b></td>";
          $retOutput .= "  <td" . $outWidthColumn_2 . $outAlignColumn_2 . "><b>" . $outTextColumn_2 . "</b></td>";
          $retOutput .= "  <td" . $outWidthColumn_3 . $outAlignColumn_3 . "><b>" . $outTextColumn_3 . "</b></td>";
          $retOutput .= "  <td" . $outWidthColumn_4 . $outAlignColumn_4 . "><b>" . $outTextColumn_4 . "</b></td>";
          $retOutput .= "</tr>";
   
          for ($i = 0; $i < $timeArrayLen; $i++) :
              $retOutput .= "<tr>";
              $retOutput .= "  <td" . $outWidthColumn_1 . $outAlignColumn_1 . ">" . $timeArray[$i]["val1"] . "</td>";
              $retOutput .= "  <td" . $outWidthColumn_2 . $outAlignColumn_2 . ">" . $timeArray[$i]["val2"] . "</td>";
              $retOutput .= "  <td" . $outWidthColumn_3 . $outAlignColumn_3 . ">" . $timeArray[$i]["val3"] . "</td>";
              $retOutput .= "  <td" . $outWidthColumn_4 . $outAlignColumn_4 . ">" . $timeArray[$i]["val4"] . "</td>";
              $retOutput .= "</tr>";
          endfor;
          $retOutput .= "</table>";
       endif;
   	endif;
   	return $retOutput;
   }

   // Get the station output
   function getStationData ($jbId, $trSort) {
   	global $jobData, $hq_id, $usr_id, $emp_id;

   	$retOutput = "";

   	getDBData("job", $jbId);
   	getDBData("tour", $jbId);
   	getDBData("tourarticle", $jbId);
   	getDBData("gdc_jb", $jbId);
   	getDBData("gdc_jb_tr", $jbId);
// print_r($jobData); die();

   	if (is_array($jobData)) :
   
        $absoluteSystemPath = getAbsoluteSystemPath();

        // Get invoice address of the current customer
        $csInvAddress = array();
        if ($csId != "" && is_numeric($csId) && $csId > 0) :
           $csId = getFieldValueFromId("costcenter", "csc_id", $jobData["job"]["csc_id_payer"], "cs_id");
           $csInvAddress = getAddress($csId, "costcenteraddress", "2");
        endif;
   
        // Scan event messages
        // $scanMessage = $jobData["gdc_jb"]["gdc_tr_finished_content"][$tmpFieldName];
   
        // Generate sign image
        if ($jobData["tour"][$trSort]["tr_sign"] != "") :
           $rawCoord = splitRawCoordinates($jobData["tour"][$trSort]["tr_sign"]);
           $maxCoord = checkMaxCoordinates($rawCoord);
           $tmpSignPath = "/temp/signs/";
           $imgFilename = "tr_sign_" . $jbId . "_" . $trSort . ".png";
           $im = createSignImage($rawCoord);
           if (!file_exists(".." . $tmpSignPath . $imgFilename)) :
              imagepng($im, ".." . $tmpSignPath . $imgFilename);
           endif;
        endif;
   
        $tdStyle = " style=\"vertical-align:top\"";
        $retOutput .= "<table border=\"0\" style=\"font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 12pt; font-weight: normal; padding: 1px;\">";

        // TOP
        $logoExtName = "";
        $logoExtHeight = "";
        $logoExtWidth = "";
        if ($hq_id != "" && is_numeric($hq_id) && $hq_id > 0) :
           $cmpId = getFieldValueFromId("headquarters", "hq_id", $hq_id, "cmp_id");
           if ($cmpId != "" && is_numeric($cmpId) && $cmpId > 0) :
              $logoExtName = getFieldValueFromId("company", "cmp_id", $cmpId, "cmp_logo");
              $logoExtHeight = getFieldValueFromId("company", "cmp_id", $cmpId, "cmp_logo_height");
              $logoExtWidth = getFieldValueFromId("company", "cmp_id", $cmpId, "cmp_logo_width");
           endif;
        endif;
        $retOutput .= "<tr>";
        $retOutput .= "  <td><br><br><br><br><h2>" . getLngt("Abliefernachweis") . "</h2></td>";
        $retOutput .= "  <td align=\"right\" vertical-align=\"middle\"><img src=\"" . $absoluteSystemPath . "/images/external/" . $logoExtName . "\" border=\"0\" height=\"49\" width=\"200\"></td>";
        $retOutput .= "</tr>";
        $retOutput .= "<tr>";
        $retOutput .= "  <td colspan=\"2\">____________________________________________________________________________________________________<br><br></td>";
        $retOutput .= "</tr>";
        $retOutput .= "<tr>";
        $retOutput .= "  <td colspan=\"2\"><h3>" . getLngt("Auftrag") . "</h3><br></td>";
        $retOutput .= "</tr>";
        
        $retOutput .= "<tr>";
   
        // LINKE SEITE
        $retOutput .= "  <td width=\"70%\">";
        $retOutput .= "    <table border=\"0\">";
        // Empfänger
        $retOutput .= "      <tr>";
        $retOutput .= "        <td" . $tdStyle . ">";
        $retOutput .=            getLngt("Empfänger") . ":";
        $retOutput .= "        </td>";
        $retOutput .= "        <td" . $tdStyle . ">";
        $retOutput .=            $jobData["tour"][$trSort]["tr_comp"] . "<br>" . ($jobData["tour"][$trSort]["tr_cs_freetext"] != "" ? $jobData["tour"][$trSort]["tr_cs_freetext"] : "") . "<br>" . ($jobData["tour"][$trSort]["tr_comp2"] != "" ? $jobData["tour"][$trSort]["tr_comp2"] : "") . "<br>" . ($jobData["tour"][$trSort]["tr_phone"] != "" ? $jobData["tour"][$trSort]["tr_phone"] : "") . "<br>";
        $retOutput .=            $jobData["tour"][$trSort]["ad_street"] . "&nbsp;" . $jobData["tour"][$trSort]["tr_hsno"] . "<br>" . $jobData["tour"][$trSort]["ad_zipcode"] . "&nbsp;" . $jobData["tour"][$trSort]["ad_city"] . "<br><br>";
        $retOutput .= "        </td>";
        $retOutput .= "      </tr>";
        // Anspechpartner
        $retOutput .= "      <tr>";
        $retOutput .= "        <td" . $tdStyle . ">";
        $retOutput .=            getLngt("Anspechpartner") . ":&nbsp;&nbsp;";
        $retOutput .= "        </td>";
        $retOutput .= "        <td" . $tdStyle . ">";
        $retOutput .=            $jobData["tour"][$trSort]["tr_person"] . "<br><br>";
        $retOutput .= "        </td>";
        $retOutput .= "      </tr>";
        // Absender
        $retOutput .= "      <tr>";
        $retOutput .= "        <td" . $tdStyle . ">";
        $retOutput .=            getLngt("Absender") . ":";
        $retOutput .= "        </td>";
        $retOutput .= "        <td" . $tdStyle . ">";
        if (count($csInvAddress) > 0) :
           // Rechnungsadresse
           $retOutput .=         $csInvAddress["comp"] . "<br>" . $csInvAddress["street"] . "&nbsp;" . $csInvAddress["hsno"] . "<br>" . $csInvAddress["zipcode"] . "&nbsp;" . $csInvAddress["city"] . "<br><br>";
        else :
           // Abhol-/Lieferadresse
           $retOutput .=         $jobData["tour"]["1"]["tr_comp"] . "<br>" . $jobData["tour"]["1"][$jbId]["ad_street"] . "&nbsp;" . $jobData["tour"]["1"][$jbId]["tr_hsno"] . "<br>" . $jobData["tour"]["1"][$jbId]["ad_zipcode"] . "&nbsp;" . $jobData["tour"]["1"][$jbId]["ad_city"] . "<br><br>";
        endif;
        $retOutput .= "        </td>";
        $retOutput .= "      </tr>";
        $retOutput .= "    </table>";
        $retOutput .= "  </td>";
   
        // RECHTE SEITE
        $retOutput .= "  <td width=\"30%\">";
        $retOutput .= "    <table border=\"0\">";
        // Ladedatum
        $retOutput .= "      <tr>";
        $retOutput .= "        <td" . $tdStyle . ">";
        $retOutput .=            getLngt("Datum") . ":";
        $retOutput .= "        </td>";
        $retOutput .= "        <td" . $tdStyle . ">";
        $retOutput .=            substr($jobData["job"]["jb_ordertime"],8,2) . "." . substr($jobData["job"]["jb_ordertime"],5,2) . "." . substr($jobData["job"]["jb_ordertime"],0,4) . "<br><br>";
        $retOutput .= "        </td>";
        $retOutput .= "      </tr>";
        // Lieferscheinnr.
        $retOutput .= "      <tr>";
        $retOutput .= "        <td" . $tdStyle . ">";
        $retOutput .=            getLngt("Lieferscheinnr.") . ":&nbsp;&nbsp;";
        $retOutput .= "        </td>";
        $retOutput .= "        <td" . $tdStyle . ">";
        if ($jobData["gdc"]["jb"][$jbId][$trSort . "_info_2"]["gdc_content"] != "") :
           $retOutput .=         $jobData["gdc"]["jb"][$jbId][$trSort . "_info_2"]["gdc_content"] . "<br><br>";
        else :
           $retOutput .=         $jobData["tour"][$trSort]["tr_commission_no"] . "<br><br>";
        endif;
        $retOutput .= "        </td>";
        $retOutput .= "      </tr>";
        // Auftragsnr.
        $retOutput .= "      <tr>";
        $retOutput .= "        <td" . $tdStyle . ">";
        $retOutput .=            getLngt("Auftragsnr.") . ":";
        $retOutput .= "        </td>";
        $retOutput .= "        <td" . $tdStyle . ">";
        if ($jobData["gdc"]["jb"][$jbId][$trSort . "_info_0"]["gdc_content"] != "") :
           $retOutput .=         $jobData["gdc"]["jb"][$jbId][$trSort . "_info_0"]["gdc_content"] . "<br>";
        else :
           $retOutput .=         $jobData["job"]["jb_id"] . "<br>";
        endif;
        $retOutput .= "        </td>";
        $retOutput .= "      </tr>";
        // Kundennrnr.
        if ($jobData["gdc"]["jb"][$jbId][$trSort . "_info_1"]["gdc_content"] != "") :
           $retOutput .= "      <tr>";
           $retOutput .= "        <td" . $tdStyle . ">";
           $retOutput .=            getLngt("Kundennr.") . ":";
           $retOutput .= "        </td>";
           $retOutput .= "        <td" . $tdStyle . ">";
           $retOutput .=            $jobData["gdc"]["jb"][$jbId][$trSort . "_info_1"]["gdc_content"] . "<br><br><br>";
           $retOutput .= "        </td>";
           $retOutput .= "      </tr>";
        endif;
/*
        // Pakete
        $retOutput .= "      <tr>";
        $retOutput .= "        <td" . $tdStyle . ">";
        $retOutput .=            getLngt("Pakete") . ":";
        $retOutput .= "        </td>";
        $retOutput .= "        <td" . $tdStyle . ">";
        $retOutput .=            $jobData["tourarticle"][$trSort]["trat_packingpieces"] . "<br>";
        $retOutput .= "        </td>";
        $retOutput .= "      </tr>";
        // Paletten
        $retOutput .= "      <tr>";
        $retOutput .= "        <td" . $tdStyle . ">";
        $retOutput .=            getLngt("Paletten") . ":";
        $retOutput .= "        </td>";
        $retOutput .= "        <td" . $tdStyle . ">";
        $retOutput .=            $jobData["tour"][$trSort]["trat_remark"] . "<br>";
        $retOutput .= "        </td>";
        $retOutput .= "      </tr>";
        // Gewicht
        $retOutput .= "      <tr>";
        $retOutput .= "        <td" . $tdStyle . ">";
        $retOutput .=            getLngt("Gewicht") . ":";
        $retOutput .= "        </td>";
        $retOutput .= "        <td" . $tdStyle . ">";
        $retOutput .=            number_format(round($jobData["tour"][$trSort]["trat_weight"],2), 2, ",", ".") . " kg<br>";
        $retOutput .= "        </td>";
        $retOutput .= "      </tr>";
        // Scan-Event
        $retOutput .= "      <tr>";
        $retOutput .= "        <td" . $tdStyle . ">";
        $retOutput .=            getLngt("Scan-Event") . ":";
        $retOutput .= "        </td>";
        $retOutput .= "        <td" . $tdStyle . ">";
        $retOutput .=            $scanMessage . "<br><br>";
        $retOutput .= "        </td>";
        $retOutput .= "      </tr>";
*/
        $retOutput .= "    </table>";
        $retOutput .= "  </td>";
        $retOutput .= "</tr>";

        // BOTTOM
        $retOutput .= "<tr>";
        $retOutput .= "  <td colspan=\"2\"><h2>" . getLngt("Auslieferung") . "</h2><br><br></td>";
        $retOutput .= "</tr>";
        $retOutput .= "<tr>";
        $retOutput .= "  <td>";
        $retOutput .= "    <table border=\"0\">";
        // Sendungsstatus
        $retOutput .= "      <tr>";
        $retOutput .= "        <td" . $tdStyle . ">";
        $retOutput .=            getLngt("Sendungsstatus") . ":&nbsp;&nbsp;";
        $retOutput .= "        </td>";
        $retOutput .= "        <td" . $tdStyle . ">";
        $retOutput .=            getLngt("Komplette Auslieferung") . "<br><br>";
        $retOutput .= "        </td>";
        $retOutput .= "      </tr>";
        // Auslieferdatum
        $retOutput .= "      <tr>";
        $retOutput .= "        <td" . $tdStyle . ">";
        $retOutput .=            getLngt("Erfolgte am") . ":";
        $retOutput .= "        </td>";
        $retOutput .= "        <td" . $tdStyle . ">";
        if ($jobData["tour"][$trSort]["tr_finishtime"] != "") :
           $retOutput .=            substr($jobData["tour"][$trSort]["tr_finishtime"],8,2) . "." . substr($jobData["tour"][$trSort]["tr_finishtime"],5,2) . "." . substr($jobData["tour"][$trSort]["tr_finishtime"],0,4) . "&nbsp;" . substr($jobData["tour"][$trSort]["tr_finishtime"],11,2) . ":" . substr($jobData["tour"][$trSort]["tr_finishtime"],14,2);
        endif;
        $retOutput .=            "<br><br>";
        $retOutput .= "        </td>";
        $retOutput .= "      </tr>";
        // Empfänger
        $retOutput .= "      <tr>";
        $retOutput .= "        <td" . $tdStyle . ">";
        $retOutput .=            getLngt("Empfänger") . ":";
        $retOutput .= "        </td>";
        $retOutput .= "        <td" . $tdStyle . ">";
        $retOutput .=            ($jobData["tour"][$trSort]["tr_signname"] != "" ? $jobData["tour"][$trSort]["tr_signname"] : getLngt("Keine Klartextangabe")) . "<br><br>";
        $retOutput .= "        </td>";
        $retOutput .= "      </tr>";
        $retOutput .= "    </table>";
        $retOutput .= "  </td>";
        $retOutput .= "</tr>";
        $retOutput .= "<tr>";
        
        // BOTTOM
        // $retOutput .= "<tr>";
        // $retOutput .= "  <td colspan=\"2\"><br><br></td>";
        // $retOutput .= "</tr>";
        // Sign
        $retOutput .= "<tr>";
        $retOutput .= "  <td" . $tdStyle . " height=\"290\" width=\"320\" colspan=\"2\" align=\"right\">";
        $retOutput .= "    <h3>Unterschriftsfeld&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</h3>";
        $retOutput .= "    <table style=\"height: 270px; width: 320px; border:1px solid #000000; padding:10px;\">";
        $retOutput .= "      <tr>";
        $retOutput .= "        <td>";
        $retOutput .= "          <img src=\"" . $absoluteSystemPath . $tmpSignPath . $imgFilename . "\" border=\"0\" height=\"250\" width=\"300\">";
        $retOutput .= "        </td>";
        $retOutput .= "      </tr>";
        $retOutput .= "    </table>";
        $retOutput .= "  </td>";
        $retOutput .= "</tr>";
        
        $retOutput .= "</table>";
   	endif;
   
   	return $retOutput;
   }

   // * END : Special functions for output ONLY !!!! *
   // *************************************************************************************************************************************
   
   
   $output = "";
   if ($functionName != "") :
      if (function_exists($functionName)) :
   
         cronWriteToFile($logFile, "CALLED_FUNC_EXIST=YES|");
   
         // Get number of arguments of requested function
         $fct = new ReflectionFunction($functionName);
         $numOfFunctionArguments = $fct->getNumberOfRequiredParameters();
         $argumentArray = array();
         for ($i = 1; $i <= $numOfFunctionArguments; $i++) :
             array_push($argumentArray, ${("par_" . pad($i, 2))});
         endfor;
   
         // Call function ang get HTML output
         $output = call_user_func_array($functionName, $argumentArray);
      else :
         cronWriteToFile($logFile, "CALLED_FUNC_EXIST=NO|");
      endif;
   endif;

   // Generate and send mail if requested
   if (($f_act == "calculatePDF" || $f_act == "calculateAndSendMailPDF") && $output != "") :
   
      cronWriteToFile($logFile, "PDF_OP_START=YES|");

      // Generate PDF document
      $fileNameTarget = generatePDF($output, $title, "0", "1", "", "", "");

      // Send mail with attached (generated) PDF document
      if ($f_act == "calculateAndSendMailPDF") :
        
         cronWriteToFile($logFile, "MAIL_OP_START=YES|");

         $mailSent = sendPDFMail($hqId, $output, $title, $mailToAddresses, $fileNameTarget, $mailSubject, $mailText, $mailAttachedFileType, $mailCcAddresses, $mailBccAddresses, $mailSenderAddress, $parKeyForLogFile, $objId, $cascadingObjType);

         if ($mailSent) :
            $statusMessage = "Die Mail wurde generiert!";
            cronWriteToFile($logFile, "MAIL_GENERATED=YES|");
            if ($isCron) : $system_result = "MAIL_SENT"; endif;
         else :
            $statusMessage = "ACHTUNG: Die Mail wurde NICHT generiert!";
            cronWriteToFile($logFile, "MAIL_GENERATED=NO|");
            if ($isCron) : $system_result = "MAIL_NOT_SENT"; endif;
         endif;
      else :
         cronWriteToFile($logFile, "MAIL_OP_START=NO|");
      endif;
   else :
      cronWriteToFile($logFile, "PDF_OP_START=NO|");
   endif;
endif;  // $automode

cronWriteToFile($logFile, "LOG=END|");
?>