<?php
/*=======================================================================
 *
 * jb_detail_history.inc.php
 *
 * Autor: Marc Vollmann
 *
 =======================================================================*/

include_once ("../include/image.inc.php");
include_once ("../include/inc_job.inc.php");
include_once ("../include/inc_filters.inc.php");
if ($automailer == "0") :
   include ("../locating/showInGoogleMaps.inc.php");
endif;

// Get the array for formatting the database-values for the output according to the defined type
$outputFormatField = defineOutputFormats();


function getJobSnapshot($job_id, $retMode = "", $execSQLStmts = "1") {
   global $db, $hq_id, $currentHqId, $emp_id, $usr_id, $userTypeName, $outputFormatField, $f_act, $automailer;
	 global $dbhistory, $dbh_jb, $dbh_tr, $dbh_trs, $dbh_cdt, $dbh_jbc;
	 global $jobentry, $tourentry, $jobcosts, $courierentry, $employeeentry, $tourentryArray, $tourDisplayClassicMode;
	 global $sqlqueryJob, $sqlqueryTour, $sqlqueryCourier, $sqlqueryUser, $sqlqueryCosts;
	 global $job_status, $job_tourname, $job_export_time, $job_reserv, $job_incomplete;
	 global $job_cr_sid, $job_longhaul, $job_orderer, $job_id_parent, $job_subtotalprice;
	 global $job_markup, $job_ordertime, $jobCourierId, $cscIdPayer, $csIdPayer, $cscIdRelated;
	 global $jobCourierId, $job_cr_sid, $taxFactor, $globalParUseRelatedCustomer, $jobIsAllowedToBeModified, $jobIsNotExported;
	 global $jbMailEmbeddedImages, $maskJobInternalRemarkItems, $mtIntRemItem, $mtIntRemItemLen, $currentCashPayerId;
	 global $jbAccessModeArr;

   if ($currentHqId == "" || !is_numeric($currentHqId)) : $currentHqId = $hq_id; endif;
   if ($taxFactor == "") : $taxFactor = 1.19; endif;
   mcIsSet($specialOutputFormat);

   // --- JOB -------------------

   // Show values for KM and CO2
   $parMaskJobKmCO2 = getParameterValue("0", "MASK_JOBDETAILS_KM_CO2", $hq_id);
   if ($parMaskJobKmCO2 == "") : $parMaskJobKmCO2 = getParameterValue("0", "MASK_JOBDETAILS_KM_CO2", "0"); endif;

   // Initialize
   if ($f_act == "mailsend" || $f_act == "printjob" || $f_act == "export") :
      $titles = getLngt("Nr.") . "," . getLngt("Fahrzeug") . "," . getLngt("Auftragszeit") . "," . getLngt("Annahme") . "," . getLngt("Erledigung");
      $fields = "jb_id,vht_value,jb_ordertime,jb_taketime,jb_finishtime";
   elseif ($userTypeName == "cs") :
      $titles = getLngt("Nr.") . "," . getLngt("Kostenstelle") . "," . getLngt("Fahrzeug") . "," . getLngt("Auslage") . "," . getLngt("Gewicht") . "," . getLngt("Auftragszeit") . "," . getLngt("Reservierung") . "," . getLngt("Storno") . "," . getLngt("Annahme");
      $fields = "jb_id,csc_name,vht_value,jb_outlay,jb_weight,jb_ordertime,jb_reserv,jb_storno,jb_taketime";
   else :
      $titles = getLngt("Nr.") . "," . getLngt("Zusatzinfo") . "," . getLngt("Tourenname") . "," . getLngt("Besteller") . "," . getLngt("Kostenstelle") . "," . getLngt("Fahrzeug&nbsp;angefordert&nbsp;") . "," . getLngt("Fahrzeug gefahren") . "," . getLngt("Auslage") . "," . getLngt("Gewicht") . "," . getLngt("Auftragszeit") . "," . getLngt("Reservierung") . "," . getLngt("Dauerauftrag") . "," . getLngt("Anforderung") . "," . getLngt("Permanente Anford.") . "," . getLngt("Storno") . "," . getLngt("Spät. Annahmezeit") . "," . getLngt("Annahme") . "," . getLngt("Erledigung") . "," . getLngt("Abrechnungsexport") . "," . getLngt("Filter") . "," . getLngt("Opt. Filter") . "," . getLngt("L x B x H x S") . "," . getLngt("Dispo-Info");
      $fields = "jb_id,gdc_jb_search,jb_tourname,jb_orderer,csc_name,vht_value,vht_value_real,jb_outlay,jb_weight,jb_ordertime,jb_reserv,jb_permanent,cr_sid,cr_id_permanent,jb_storno,jb_latesttaketime,jb_taketime,jb_finishtime,jb_export_time,jb_cr_filter,jb_cr_filter_opt,jb_crvh_measures,jb_dispoinfo";
      if ($parMaskJobKmCO2 == 1) :
         $titles .=  "," . getLngt("KM") . "," . getLngt("CO2e/kg");
         $fields .= ",jbprc_km,jbprc_co2";
      endif;
      if ($globalParUseRelatedCustomer == 1) :
         $titles .= "," . getLngt("Man. Service-Nr.");
         $fields .= ",gdc_jb_man_service_no";
      endif;
   endif;
   $titlesArray = spliti(",",$titles);
   $titlesLength = count($titlesArray);
   $fieldsArray = spliti(",",$fields);
   $fieldsLength = count($fieldsArray);

   // Get csc_id of the current job (job entered by customer [csc_id > 0] or headquarter [csc_id = 0])
   $job_csc_id = getFieldValueFromId($dbh_jb, "jb_id", $job_id, "csc_id");
   if ($job_csc_id == "") : $job_csc_id = "0"; endif;
   $fieldClause = getDBFields("job") . "," . getDBFields("vehicletype") . "," . getDBFields("vehicletype_real") . "," . getDBFields("jobstatus") . "," . getDBFields("jb_latesttaketime");
   $fieldClause .= ", jbprc_11.jbprc_price AS jbprc_km, jbprc_12.jbprc_price AS jbprc_co2";
   $fieldClause .= ", CONCAT(jb.jb_crvh_length,' x ',jb.jb_crvh_width,' x ',jb.jb_crvh_height,' x ',jb.jb_crvh_position) AS jb_crvh_measures";
   $fieldClause .= ", srvpt.srvpt_traveltime, gdc_jb_search.gdc_content AS gdc_jb_search ";
   if ($globalParUseRelatedCustomer == 1) :
      $fieldClause .= ", gdc_jb_man_service_no.gdc_content AS gdc_jb_man_service_no ";
   endif;

   // Check for existing costcenter
   if ($job_csc_id != "0") : $fieldClause .= "," . getDBFields("costcenter"); endif;
   
   // $fromClause = $dbh_jb . " AS jb, metatype AS vht, metatype AS jbs ";
   $fromClause = "metatype AS vht, metatype AS jbs ";
   if ($job_csc_id != "0") : $fromClause .= ", costcenter AS csc "; endif;
   $fromClause .= ", " . $dbh_jb . " AS jb ";

   // Additional joins e.g. for traveltime to startaddress, GDC values, etc.
   $fromClause .= " LEFT JOIN genericdatacontainer AS gdc_jb_search ON gdc_jb_search.gdc_obj_id = jb.jb_id AND gdc_jb_search.gdc_obj_type = 'jb' AND gdc_jb_search.gdc_gen_fieldname = 'jb_search' ";
   if ($globalParUseRelatedCustomer == 1) :
      $fromClause .= " LEFT JOIN genericdatacontainer AS gdc_jb_man_service_no ON gdc_jb_man_service_no.gdc_obj_id = jb.jb_id AND gdc_jb_man_service_no.gdc_obj_type = 'jb' AND gdc_jb_man_service_no.gdc_gen_fieldname = 'man_sams' ";
   endif;
   $fromClause .= " LEFT JOIN jobprice AS jbprc_11 ON jbprc_11.jb_id = jb.jb_id AND jbprc_11.mt_sort = '11' ";
   $fromClause .= " LEFT JOIN jobprice AS jbprc_12 ON jbprc_12.jb_id = jb.jb_id AND jbprc_12.mt_sort = '12' ";
   $fromClause .= " LEFT JOIN " . $dbh_tr . " AS tr ON jb.jb_id = tr.jb_id AND tr.tr_sort = '1' ";
   $fromClause .= " LEFT JOIN address AS ad ON tr.ad_id = ad.ad_id ";
   $fromClause .= " LEFT JOIN serviceplz AS srvp ON ad.ad_zipcode = srvp.srvp_plz ";
   $fromClause .= " LEFT JOIN serviceplztraveltime AS srvpt ON srvp.srvp_id = srvpt.srvp_id AND srvpt.hq_id = jb.hq_id ";
   $fromClause .= " LEFT JOIN metatype AS vht_real ON jb.vht_id_real = vht_real.mt_sort AND vht_real.mt_type = 'vehicletype' ";

   $whereClause = "jb.jb_id = " . $job_id . " AND ";
   if ($job_csc_id != "0") : $whereClause .= "(jb.csc_id = csc.csc_id) AND "; endif;   
   $whereClause .= "(jb.vht_id = vht.mt_sort AND vht.mt_type = 'vehicletype') AND ";   
   
   $whereClause .= "(jb.jb_status = jbs.mt_sort AND jbs.mt_type = 'job_status') ";   
   // Changes only because of jb_status='9' within the SAME list as jb_status='0'! Look in "jb_list.php"
   // $whereClause .= "((jb.jb_status = jbs.mt_sort OR jb.jb_status-9 = jbs.mt_sort) AND jbs.mt_type = 'job_status') ";

   $orderByClause = "";

   if ($userTypeName == "cs") :
      $fieldClause = getDBFields("job") . "," . getDBFields("vehicletype") . "," . getDBFields("jobstatus") . "," . getDBFields("costcenter") . "," . getDBFields("jb_latesttaketime");
      
      $fromClause = $dbh_jb . " AS jb, costcenter AS csc, metatype AS vht, metatype AS jbs ";
      
      $whereClause = "jb.hq_id = " . $currentHqId . " AND ";
      $whereClause .= "jb.jb_id = " . $job_id . " AND ";
      $whereClause .= "(jb.csc_id_payer = csc.csc_id) AND ";
      $whereClause .= "(jb.vht_id = vht.mt_sort AND vht.mt_type = 'vehicletype') AND ";
      
      $whereClause .= "(jb.jb_status = jbs.mt_sort AND jbs.mt_type = 'job_status') ";   
      // Changes only because of jb_status='9' within the SAME list as jb_status='0'! Look in "jb_list.php"
      // $whereClause .= "((jb.jb_status = jbs.mt_sort OR jb.jb_status-9 = jbs.mt_sort) AND jbs.mt_type = 'job_status') ";
      
      $orderByClause = "";
   endif;

   // Excludes filters for output only
   $constMaskExcludedFilterStr = getParameterValue("0", "MASK_MANDATORY_FILTERS", $currentHqId);
   $constMaskExcludedFilterArr = explode(",", $constMaskExcludedFilterStr);
   $constMaskExcludedFilterArrLen = count($constMaskExcludedFilterArr);

   $sqlqueryJob = generateStatement($fieldClause,$fromClause,$whereClause,$orderByClause);
   // echo $sqlqueryJob . "<br><br>";

   // The JOB statement has to be executed every time because of some global parameters used for following statements
   if (true || $execSQLStmts == "1") :

      // Send request to database
      $result = $db->query($sqlqueryJob);
      if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage() . ": " . $sqlqueryJob);

      // Handling of type "datetime" output of the current day (today) => "H:i (d.m)" or only "H:i" (default)
      $constMaskJbDatetimeTodayFormat = getParameterValue("0", "MASK_JB_DATETIME_TODAY_FORMAT", $currentHqId);

      // Job-data
      $jobentry = "";
      $rawJobData = "";  // (= "[JOB]");
      $jobCourierId = "";
      $job_usr_id = "";
      $job_status = "";
      $job_cr_sid = "";
      $job_longhaul = "";
      $job_orderer = "";
      mcIsSet($jbprc_km);
      mcIsSet($jbprc_co2);
      $rowCounter = 0;
      while ($row = $result->fetch_assoc()):
            $rowCounter++;
            for ($i = 0; $i < $fieldsLength; $i++) :
                $showCol = true;
                if ($i % 2 == 0) : $cellColor = "#BBBBFF"; $cellColor2 = "#DDDDDD"; endif;
                if ($i % 2 == 1) : $cellColor = "#CCCCFF"; $cellColor2 = "#EEEEEE"; endif;

                if (mcArrTrim($titlesArray, $i) == "") : $titlesArray[$i] = "&nbsp;"; endif;
                $jobentry .= "<tr>";
                $jobentry .= "<td bgcolor=\"" . $cellColor2 ."\" align=\"left\">" . $titlesArray[$i] . "</td>";
                $tmpVarName = mcArrIsSet($fieldsArray, $i);
                $row[$tmpVarName] = mcArrIsSet($row, $tmpVarName);
                ${$tmpVarName} = $row[$tmpVarName];

                // Some parameters (e.g. for mail, booking, changing tourname, etc.)
                $job_status = $row["jb_status"];
                $job_tourname = $row["jb_tourname"];
                $job_export_time = $row["jb_export_time"];
                $job_reserv = $row["jb_reserv"];
                $job_incomplete = $row["jb_incomplete"];
                $job_cr_sid = $row["cr_sid"];
                $job_longhaul = $row["jb_longhaul"];
                $job_orderer = $row["jb_orderer"];
                $job_id_parent = $row["jb_id_parent"];
                $job_subtotalprice = $row["jb_subtotalprice"];
                $job_markup = $row["jb_markup"];
                $jbprc_markup = $db->getOne("SELECT jbprc_price FROM jobprice WHERE jb_id = " . $job_id . " AND mt_sort = 8");
                if ($jbprc_markup != "") :
                  $job_markup = sprintf("%01.2f", $jbprc_markup);
                endif;
                if ($jbprc_km != "") :                  
                  $jbprc_km = str_replace(".", ",", $jbprc_km);
                endif;
                if ($jbprc_co2 != "") :
                  $jbprc_co2 = str_replace(".", ",", $jbprc_co2);
                endif;
                if ($userTypeName == "hq" && $f_act != "mailsend" && $f_act != "printjob" && $f_act != "export") :
                   if ($tmpVarName == "jbprc_km") :
                      $jbprc_km  = '<span id="km_span">' . $jbprc_km . '</span>&nbsp;&nbsp;'
                                 . '<input type="hidden" id="kmValOld" name="kmValOld" value="' . $jbprc_km . '">'
                                 . '<input type="button" style="width: 10px; height: 10px; vertical-align: middle;" name="km_button" name="km_button" value="" onClick="containerAction(\'kmEdit\', \'show\');">'
                                 . '<div id="kmEdit" style="width:180px; height:50px; background-color:#AAAACC; border:grey 3px solid; box-shadow: 10px 20px 30px grey;">'
                                 . defineButtonType08("Speichern", "action_km_save", "saveKM(" . $job_id . ", document.forms[0].kmValNew); containerAction('kmEdit', 'hide');", "90", "left", "0")
                                 . defineButtonType08("Schließen", "action_km_close", "containerAction('kmEdit', 'hide');", "90", "", "")
                                 . '<div style="width: 180px; height: 50px; vertical-align: middle; text-align: center;"><input type="text" style="width: 80px; height: 20px;" id="kmValNew" name="kmValNew" value="' . $jbprc_km . '"></div>'
                                 . '</div>';
                   endif;
                   if ($tmpVarName == "jbprc_co2") :
                      $jbprc_co2  = '<span id="co2_span">' . $jbprc_co2 . '</span>&nbsp;&nbsp;'
                                  . '<input type="hidden" id="co2ValOld" name="co2ValOld" value="' . $jbprc_co2 . '">'
                                  . '<input type="button" style="width: 10px; height: 10px; vertical-align: middle;" name="co2_button" name="co2_button" value="" onClick="containerAction(\'co2Edit\', \'show\');">'
                                  . '<div id="co2Edit" style="width:180px; height:50px; background-color:#AAAACC; border:grey 3px solid; box-shadow: 10px 20px 30px grey;">'
                                  . defineButtonType08("Speichern", "action_co2_save", "saveCO2(" . $job_id . ", document.forms[0].co2ValNew); containerAction('co2Edit', 'hide');", "90", "left", "0")
                                  . defineButtonType08("Schließen", "action_co2_close", "containerAction('co2Edit', 'hide');", "90", "", "")
                                  . '<div style="width: 180px; height: 50px; vertical-align: middle; text-align: center;"><input type="text" style="width: 80px; height: 20px;" id="co2ValNew" name="co2ValNew" value="' . $jbprc_co2 . '"></div>'
                                  . '</div>';
                   endif;
                endif;

                $job_ordertime = $row["jb_ordertime"];
                // Get the current courier-ID of the job
                // if ($tmpVarName == "cr_id") : $jobCourierId = $row["cr_id"]; endif;
                $jobCourierId = $row["cr_id"];
      
                // Get the payer of the job
                $cscIdPayer = getFieldValueFromId($dbh_jb, "jb_id", $job_id, "csc_id_payer");
                $csIdPayer = getFieldValueFromId("costcenter", "csc_id", $cscIdPayer, "cs_id");

                // Get the related customer of the job
                $cscIdRelated = getFieldValueFromId($dbh_jb, "jb_id", $job_id, "csc_id_related");
      
                // If automailer is running check job for having subjobs to change
                // courier data to courier data of the subjob to get the real driver
                if ($automailer == "1" || $f_act == "mailsend" || $f_act == "export") :
                   if ($job_id_parent == "-1") :
                      // $tmpJobIdParent = getFieldValueFromId($dbh_jb,"jb_id_parent",$job_id,"jb_id");
                      $tmpJobIdParent = getFieldValueFromClause($dbh_jb,"jb_id"," jb_id_parent = '" . $job_id . "' ORDER BY jb_id DESC ");
                      $jobCourierId = getFieldValueFromId($dbh_jb,"jb_id",$tmpJobIdParent,"cr_id");
                      $job_cr_sid = getFieldValueFromId($dbh_jb,"jb_id",$tmpJobIdParent,"cr_sid");
                   endif;
                endif;
      
                // Get the current employee (user-id !!!) of the job
                // HAS TO BE IN THE field-list TO GET HERE !!!!!!!!!!
                // if ($tmpVarName == "emp_id") : $job_usr_id = $row["emp_id"]; endif;
      
                // Special job-data
                if ($tmpVarName == "jb_latesttaketime") :
                   if ($row["jb_waittime"] != "") :
                      ${$tmpVarName} = $row["jb_waittime"];
                   else :
                      $tmp = ${$tmpVarName};
                      if ($row["jb_reserv"] == 1) :      
                          // mktime(hour,minute,second,month,day,year)
                          $latestTakeTime = LATEST_TAKETIME_IN_MINUTES;
                          if (is_numeric($row["srvpt_traveltime"]) && $row["srvpt_traveltime"] > 0) :
                             $latestTakeTime = $row["srvpt_traveltime"];
                          endif;                       
                          ${$tmpVarName} = date("Y-m-d H:i:s", mktime(substr($tmp,11,2),substr($tmp,14,2)-($latestTakeTime),substr($tmp,17,2),substr($tmp,5,2),substr($tmp,8,2),substr($tmp,2,2)));
                      else :
                          ${$tmpVarName} = date("Y-m-d H:i:s", mktime(substr($tmp,11,2),substr($tmp,14,2)+5,substr($tmp,17,2),substr($tmp,5,2),substr($tmp,8,2),substr($tmp,2,2)));
                      endif;             
                   endif;
                   if ((date("Y-m-d H:i:s") > ${$tmpVarName}) && ($row["jb_status"] == 0)) :
                       if ($i % 2 == 0) : $cellColor = "#FF2222"; $cellColor2 = "#FF4444"; endif;
                       if ($i % 2 == 1) : $cellColor = "#FF3333"; $cellColor2 = "#FF5555"; endif;
                   endif;
                endif;

                // Do not show excluded filters, remove them by parameter for output only
                if ($tmpVarName == "jb_cr_filter" && ${$tmpVarName} != "" && $constMaskExcludedFilterStr != "") :
                   ${$tmpVarName} = removeItemsFromString(${$tmpVarName}, $constMaskExcludedFilterStr);
                endif;

                if ($showCol) :
                   mcArrIsSet($outputFormatField, $tmpVarName);
                   if ($outputFormatField[$tmpVarName] == "datetime" && ($constMaskJbDatetimeTodayFormat == "1" || $tmpVarName == "jb_export_time")) :
                      $out = formatOutput(${$tmpVarName},$outputFormatField[$tmpVarName],"13");  // "H:i (d.m)"
                   else :
                      $out = formatOutput(${$tmpVarName},$outputFormatField[$tmpVarName]);
                   endif;

                   if ($tmpVarName == "jb_storno") :
                      if (${$tmpVarName} != "0" && ${$tmpVarName} != "") :
                         if ($rowCounter % 2 == 0 && $i % 2 == 0) : $cellColor = "#FF2222"; endif;
                         if ($rowCounter % 2 == 0 && $i % 2 == 1) : $cellColor = "#FF3333"; endif;
                         if ($rowCounter % 2 == 1 && $i % 2 == 0) : $cellColor = "#FF4444"; endif;
                         if ($rowCounter % 2 == 1 && $i % 2 == 1) : $cellColor = "#FF5555"; endif;                   
                      
                         if (${$tmpVarName} == "1") :
                            $out = getLngt("St.m.K.");
                         elseif (${$tmpVarName} == "2") :
                            $out = getLngt("St.o.K.");
                         endif;
                      endif;
                   endif;                
                
                   if ($tmpVarName == "csc_name" && $job_csc_id == "0") :
                      $out = getLngt("Zentrale");
                   endif;                                    
                   
                   $jobentry .= "<td bgcolor=\"" . $cellColor ."\" align=\"left\">" . $out . "</td>";
      
                   if ($tmpVarName == "jb_reserv") :
                      $rawJobData .= "jb_" . $tmpVarName . "=" . $row["jb_reserv"] . "|";
                   // elseif ($tmpVarName == "jb_permanent") :
                   //   $rawJobData .= "jb_" . $tmpVarName . "=" . $row["jb_permanent"] . "|";
                   else :
                      if ($out == "&nbsp;") : $out = ""; endif;
                      $rawJobData .= "jb_" . $tmpVarName . "=" . $out . "|";
                   endif;
                endif;
                $jobentry .= "</tr>";
            endfor;         
      
            // Link to copy the job and link to history
            if ($f_act != "mailsend" && $f_act != "printjob" && $f_act != "export") :

               // Check for access to map view
               $mapViewLink = "";

               $showMapView = false;
               if ($userTypeName == "hq" && authCheckEmployeeRights($emp_id, "19")) :
                  $showMapView = true;
               endif;
               if ($userTypeName == "cs") :
                   $constCsShowMapView = getParameterValue("0", "MASK_JB_MAP_VIEW_ENABLED_" . $csIdPayer, "0");
                   if ($constCsShowMapView == "1") :
                      $showMapView = true;
                   endif;
               endif;
               if ($showMapView && (($jobIsAllowedToBeModified && $jobIsNotExported) || $userTypeName == "cs")) :
                  $mapViewLink = "<br><br><a href=\"../locating/map.php?jb_id=" . $job_id . "" . "\" target=\"_blank\">" . getLngt("Kartendarstellung") . "</a><br>";
               endif;

               if ($userTypeName == "cs") :
                  $jobentry .= "<tr><td><br>";
                  $jobentry .= $mapViewLink;  // Defined above
                  $jobentry .= "</td></tr>";
               else :
                  // Get some informations for the following links            
                  $tmpCmpIdPayer = getFieldValueFromId("customer", "cs_id", $csIdPayer, "cmp_id");
                  $tmpCmpPayerFields = getFieldsValueFromId("company", "cmp_id", $tmpCmpIdPayer, array("cmp_authenticated","cmp_visible"));

                  $jobentry .= "<tr><td><br>";

                  if ($jbAccessModeArr["1"]) :
                     if ($globalParUseRelatedCustomer == 1) :
                        if ($jobIsAllowedToBeModified && $jobIsNotExported) :
                           $jobentry .= "<a href=\"../admin/disposition_appointments.php?jbId=" . $job_id . "\" target=\"_blank\">" . getLngt("Termin vergeben") . "</a><br>";
                        endif;
                     else :
                        $jobentry .= "<a href=\"../jobs/job_edit.php?jb_id=" . $job_id . "&jb_copy=true&dbhistory=" . $dbhistory . "\" target=\"_blank\">" . getLngt("Auftrag kopieren") . "</a><br>";
                     endif;
                  endif;

                  if ($tmpCmpPayerFields[0] == "0" || $tmpCmpPayerFields[1] == "0") : 
                     $jobentry .= "(" . getLngt("ACHTUNG") . ": " . getLngt("Der Bezahler ist") . " ";
                     if ($tmpCmpPayerFields[0] == "0") : $jobentry .= getLngt("gesperrt"); endif;
                     if ($tmpCmpPayerFields[0] == "0" && $tmpCmpPayerFields[1] == "0") : $jobentry .= getLngt(" und "); endif;
                     if ($tmpCmpPayerFields[1] == "0") : $jobentry .= getLngt("ausgeblendet"); endif;
                     $jobentry .= "!)<br>";
                  endif;
                  
                  $jobentry .= "<br><a href=\"../admin/history.php?history_mode=2&job_id=" . $job_id . "&op=0&dbhistory=" . $dbhistory . "\" target=\"_blank\">" . getLngt("Auftragshistorie") . "</a>";
                  // $jobentry .= "<a href=\"javascript:popupWindow('../admin/jb_history.php?job_id=" . $job_id . "&op=0&dbhistory=" . $dbhistory . "','Auftrag','scrollbars=yes,width=950,height=700');\">" . getLngt("Auftragshistorie") . "</a>";

                  // $jobentry .= "<br><br><a href=\"../locating/map.php?jb_id=" . $job_id . "" . "\" target=\"_blank\">" . getLngt("Kartendarstellung") . "</a>";
                  $jobentry .= $mapViewLink;  // Defined above

                  $jobentry .= "</td></tr>";
               endif;

            endif;            
      endwhile;
      $result->free();
   endif;


   // --- TOUR ------------------

   // Parameter for displaying station number
   $constMaskStationsStationNumber = getObjectBasedParameterValue("JOBDETAILS_STATIONS_STATION_NUMBER", $csIdPayer, $currentHqId);

   // Parameter for displaying photos
   $jbMailEmbeddedImages = array();
   $constMaskStationsPodPhoto = getParameterValue("0", "MASK_JOBDETAILS_STATIONS_POD_PHOTOS", $hq_id);
   if ($constMaskStationsPodPhoto == "") : $constMaskStationsPodPhoto = getParameterValue("0", "MASK_JOBDETAILS_STATIONS_POD_PHOTOS", "0"); endif;
   // Check for overriding parameter for station photo(s) by job configuration
   $trPhotos = array();
   if ($constMaskStationsPodPhoto != "1") :      
      $jbTrIds = getColVectorFromDB2ArrayByClause("tour", "tr_id", "jb_id = '" . $job_id . "'", "", "", "");
      if (count($jbTrIds) > 0) :
         // Get required photo configuration for each station of the job into associative array
         // ($trPhotos[$trId] = "min|max" [e.g. $trPhotos[1234567] = "1|2" <=> at least 1 an max. 2 photos for station 1234567])
         $trPhotos = getColVectorFromDB2ArrayByClause("genericdatacontainer", "gdc_content", "gdc_obj_type = 'tr' AND gdc_obj_id IN (" . implode(",", $jbTrIds) . ") AND gdc_gen_fieldname = 'tr_photo'", "gdc_obj_id", "", "");
      endif;
      // if (count($trPhotos) > 0) :  // Disabled because of optional photo is possible
         $constMaskStationsPodPhoto = "1";
      // endif;
   endif;

   // Parameter for displaying scan events
   $constMaskStationsPodScanEvents = getParameterValue("0", "MASK_JOBDETAILS_STATIONS_POD_SCAN_EVENTS", $hq_id);
   if ($constMaskStationsPodScanEvents == "") : $constMaskStationsPodScanEvents = getParameterValue("0", "MASK_JOBDETAILS_STATIONS_POD_SCAN_EVENTS", "0"); endif;
 
   // Parameter for displaying number of scanned packages
   $constMaskStationsPodNumOfScannedPackages = getObjectBasedParameterValue("MASK_JOBDETAILS_STATIONS_POD_NUM_SCANNED_PACKAGES", $csIdPayer, $currentHqId);

   // Parameter for displaying delivery codes with names
   $deliveryCodeArray = array("Ok","1 NA,nicht angetroffen","2 NA,Betriebsferien,Streik","3 AV,Ware gefällt nicht","4 Kd Verursacher,sonst.Gründe",
                              "5 Adressklärung,Anl.nicht möglich","6 AV,Bestelldaten sind falsch","7 AV,Auftrag doppelt erfasst","8 Sonstige Gründe",
                              "9 FP,Fehlpaket","10 AV,Richtiger Artikel auf LS","11 Paket im Lager beschädigt","12 Verspätete Abf.Nachtsprung LKW",
                              "13 Pakete im falschen RDC gelandet","14 Nachtspr.LKW verspätet im RDC","15 Besch.Pak.durch Nachtsprung","16 Pakete im RDC vertauscht",
                              "17 Aus Zeitgründen nicht ausgel.","18 Besch.Pak.durch Fahrer/RDC","19 Sonstiges,Fehler Versandteam","20 Autobahnvollsp.,höh.Gewalt","21 Sonstiges");
   $deliveryCodes = getObjectBasedParameterValue("JOBDETAILS_STATIONS_DELIVERY_CODES", $csIdPayer, $currentHqId);
   if ($deliveryCodes != "") :
      // $deliveryCodes = str_replace("|", "-,-", $deliveryCodes);
      // $deliveryCodeArray = spliti("-,-", $deliveryCodes);
      $deliveryCodeArray = getKeyValueArrayFromString($deliveryCodes);
   endif;
   $deliveryCodeArrayLen = count($deliveryCodeArray);

   // Parameter for displaying survey
   $constMaskStationsSurvey = getParameterValue("0", "MASK_JOBDETAILS_STATIONS_SURVEY", $hq_id);
   if ($constMaskStationsSurvey == "") : $constMaskStationsSurvey = getParameterValue("0", "MASK_JOBDETAILS_STATIONS_SURVEY", "0"); endif;

   // Parameter for NOT displaying costcenters in mails
   $parTrCostcenterDisabled = getObjectBasedParameterValue("JOB_MAIL_STATION_COSTCENTER_DISABLED", $csIdPayer, $currentHqId);
   // Check for displaying the arrival time in mails
   $trCostcenterField = "csc_name,"; 
   $trCostcenterText = getLngt("Kostenstelle") . ",";
   if ($parTrCostcenterDisabled == "1") : 
      $trCostcenterField = "";
      $trCostcenterText = "";
   endif;

   // Check for displaying the arrival time in mails or customer login
   $parTrArrivalTime = getObjectBasedParameterValue("JOB_MAIL_STATION_ARRIVAL_TIME", $csIdPayer, $currentHqId);
   // Check for displaying the arrival time in mails
   $trArrivalTimeField = ""; 
   $trArrivalText = "";
   if ($parTrArrivalTime == "1") : 
      $trArrivalTimeField = "gdc_arr_tour_content,";
      $trArrivalText = getLngt("Ankunftszeit") . ",";
   endif;
   
   // Check for tracking being enabled for the customer
   $csTracking = getFieldValueFromId("customer","cs_id",$csIdPayer,"cs_tracking");


   // Initialize
   if ($f_act == "mailsend" || $f_act == "printjob" || $f_act == "export") :
   
      // Parameter for displaying field "tr_remark"
      $constMaskStationsPrintRemarkEnabled = "";
      if ($f_act == "printjob") :
         $constMaskStationsPrintRemarkEnabled = getParameterValue("0", "MASK_JOBDETAILS_STATIONS_PRINT_REMARK_ENABLED", $hq_id);
         if ($constMaskStationsPrintRemarkEnabled == "") : $constMaskStationsPrintRemarkEnabled = getParameterValue("0", "MASK_JOBDETAILS_STATIONS_PRINT_REMARK_ENABLED", "0"); endif;
      endif;

      $tmpTitlePart = "";
      $tmpFieldPart = "";
      $csJbstatusmailFields = getFieldValueFromId("customer","cs_id",$csIdPayer,"cs_jbstatusmail_fields");
      if (substr($csJbstatusmailFields, 0, 1) == "1" || $constMaskStationsPrintRemarkEnabled == "1") :
         $tmpTitlePart = getLngt("Bemerkung") . ",";
         $tmpFieldPart = "tr_remark,";
      endif;
      // Define fields and titles      
      $titles = ($constMaskStationsStationNumber == "1" ? getLngt("Station") . "," : "") . getLngt("Firma") . "," . "" . "," . getLngt("Person") . "," . getLngt("Straße + Hausnr.") . "," . getLngt("PLZ + Ort") . "," . getLngt("EID") . "," . $trCostcenterText . getLngt("Tel.") . "," . $tmpTitlePart . getLngt("Kommissionsnummer") . "," . $trArrivalText . getLngt("Erledigungszeit") . "," . getLngt("Quittungsgeber") . "," . getLngt("Unterschrift");
      $fields = ($constMaskStationsStationNumber == "1" ? "tr_sort," : "") . "tr_comp,tr_comp2,tr_person,ad_street_hsno,ad_zipcode_city,cs_eid," . $trCostcenterField . "tr_phone," . $tmpFieldPart . "tr_commission_no," . $trArrivalTimeField . "tr_finishtime,tr_signname,tr_sign";
      // Check for overriding parameter for station photo(s) by customer configuration for this job
      /*
      if ($constMaskStationsPodPhoto != "1" && substr($csJbstatusmailFields, 5, 1) == "1") :
         $constMaskStationsPodPhoto = "1";
         $titles .=  "," . getLngt("Abliefernachweis Foto");
         $fields .= ",tr_pod_photo";
      endif;
      */
      if ($constMaskStationsPodPhoto == "1") :
         $titles .=  "," . getLngt("Abliefernachweis Foto");
         $fields .= ",tr_pod_photo";
      endif;
      if ($constMaskStationsPodScanEvents == "1" && substr($csJbstatusmailFields, 8, 1) == "1") : 
         $titles .=  "," . getLngt("Bemerkung Kurier") . "&nbsp;";
         $fields .= ",tr_pod_scan_events";
      endif;
      if ($maskJobInternalRemarkItems == "1" && substr($csJbstatusmailFields, 9, 1) == "1") : 
         $titles .=  "," . getLngt("Bemerkung Innendienst") . "&nbsp;";
         $fields .= ",tr_id_int_rem";
      endif;
      if (false) :  // TEST ONLY
         $titles .=  "," . getLngt("TEST ONLY :: Auftrag-Fertig-Zeit");
         $fields .= ",gdc_tr_fin_work_content";
      endif;
   elseif ($userTypeName == "cs") :
      $tmpTitlePart = "";
      $tmpFieldPart = "";
      $csJbstatusmailFields = getFieldValueFromId("customer","cs_id",$csIdPayer,"cs_jbstatusmail_fields");
      // Display station remark if job is a cash payer job and job had been created by customer
      // if (substr($csJbstatusmailFields, 0, 1) == "1" || ($currentCashPayerId == $cscIdPayer && $job_csc_id != "0")) :
      if (false) :
         $tmpTitlePart = getLngt("Bemerkung") . ",";
         $tmpFieldPart = "tr_remark,";
      endif;
      $titles = ($constMaskStationsStationNumber == "1" ? getLngt("Station") . "," : "") . getLngt("Firma") . "," . "" . "," . getLngt("Person") . "," . getLngt("Straße + Hausnr.") . "," . getLngt("PLZ + Ort") . "," . getLngt("Email (Endkunde)") . "," . getLngt("EID") . "," . $trCostcenterText . getLngt("Tel.") . "," . $tmpTitlePart . getLngt("Kommissionsnummer") . "," . $trArrivalText . getLngt("Erledigungszeit") . "," . getLngt("Quittungsgeber") . "," . getLngt("Unterschrift");
      $fields = ($constMaskStationsStationNumber == "1" ? "tr_sort," : "") . "tr_comp,tr_comp2,tr_person,ad_street_hsno,ad_zipcode_city,gdc_tracking_content,cs_eid," . $trCostcenterField . "tr_phone," . $tmpFieldPart . "tr_commission_no," . $trArrivalTimeField . "tr_finishtime,tr_signname,tr_sign";
      if ($constMaskStationsPodPhoto == "1") :
         $titles .=  "," . getLngt("Abliefernachweis Foto");
         $fields .= ",tr_pod_photo";
      endif;
      if ($constMaskStationsPodScanEvents == "1") : 
         $titles .=  "," . getLngt("Bemerkung Kundenmail Kurier") . "&nbsp";
         $fields .= ",tr_pod_scan_events";
      endif;
      if ($constMaskStationsPodNumOfScannedPackages == "1") : 
         $titles .=  "," . getLngt("Anzahl gescannter Pakete");
         $fields .= ",tr_pod_num_scanned_packages";
      endif;
      if (false) :  // TEST ONLY
         $titles .=  "," . getLngt("TEST ONLY :: Auftrag-Fertig-Zeit");
         $fields .= ",gdc_tr_fin_work_content";
      endif;
   else :
      $titles = ($constMaskStationsStationNumber == "1" ? getLngt("Station") . "," : "") . getLngt("Firma") . "," . "" . "," . getLngt("Person") . "," . getLngt("Straße + Hausnr.") . "," . getLngt("PLZ + Ort") . "," . getLngt("Tel. (Kunde)") . "," . getLngt("Email (Kunde)") . "," . getLngt("Email (Endkunde)") . "," . getLngt("EID") . "," . getLngt("Kostenstelle") . "," . getLngt("Tel.") . "," . getLngt("Abholung/Anlieferung") . "," . getLngt("Bemerkung") . "," . getLngt("Kommissionsnummer") . "," . getLngt("Ankunftszeit") . "," . getLngt("Arbeitsbeendigungszeit") . "," . getLngt("Erledigungszeit") . "," . getLngt("Status") . "," . getLngt("Quittungsgeber") . "," . getLngt("Unterschrift");
      $fields = ($constMaskStationsStationNumber == "1" ? "tr_sort," : "") . "tr_comp,tr_comp2,tr_person,ad_street_hsno,ad_zipcode_city,usr_phone,usr_email,gdc_tracking_content,cs_eid,csc_name,tr_phone,tr_ware_from_to,tr_remark,tr_commission_no,gdc_arr_tour_content,gdc_fin_work_content,tr_finishtime,tr_status,tr_signname,tr_sign";
      if ($constMaskStationsPodPhoto == "1") :
         $titles .=  "," . getLngt("Abliefernachweis Foto");
         $fields .= ",tr_pod_photo";
      endif;
      if ($constMaskStationsPodScanEvents == "1") : 
         $titles .=  "," . getLngt("Bemerkung Kundenmail Kurier") . "&nbsp";
         $fields .= ",tr_pod_scan_events";
      endif;
      if ($constMaskStationsPodNumOfScannedPackages == "1") : 
         $titles .=  "," . getLngt("Anzahl gescannter Pakete");
         $fields .= ",tr_pod_num_scanned_packages";
      endif;
      if ($constMaskStationsSurvey == "1") : 
         $titles .=  "," . getLngt("Kundenbewertung");
         $fields .= ",gdc_survey_1_content";
      endif;
      if ($maskJobInternalRemarkItems == "1") : 
         $titles .=  "," . getLngt("Bemerkung Kundenmail Innendienst");
         $fields .= ",tr_id_int_rem";
      endif;
      if (false) :  // TEST ONLY
         $titles .=  "," . getLngt("TEST ONLY :: Auftrag-Fertig-Zeit");
         $fields .= ",gdc_tr_fin_work_content";
      endif;
   endif;
   $titlesArray = spliti(",",$titles);
   $titlesLength = count($titlesArray);
   $fieldsArray = spliti(",",$fields);
   $fieldsLength = count($fieldsArray);   

   $fieldClause = getDBFields("tour") . "," . getDBFields("address") . "," . getDBFields("costcenter");
   $fieldClause .= ", CONCAT(ad_street,' ',tr_hsno) AS ad_street_hsno, CONCAT(ad_zipcode,' ',ad_city) AS ad_zipcode_city ";
   if (true) :  // Check for customer display the photos
      $fieldClause .= ", '' AS tr_pod_photo, '' AS tr_pod_scan_events";  // Proof of delivery photo
   endif;
   if ($maskJobInternalRemarkItems == "1") :       
      $fieldClause .= ", tr_id AS tr_id_int_rem";
   endif;
   if ($userTypeName == "hq") :
      $fieldClause .= ", gdc_arr_tour.gdc_content AS gdc_arr_tour_content";  // Arrival timestamp and coordinates
      $fieldClause .= ", gdc_fin_work.gdc_content AS gdc_fin_work_content";  // Finish work timestamp and coordinates
   else :
      $fieldClause .= ", LEFT(gdc_arr_tour.gdc_content,14) AS gdc_arr_tour_content";  // Arrival timestamp of the courier per station
   endif;
   $fieldClause .= ", gdc_tracking.gdc_content AS gdc_tracking_content, gdc_tracking.gdc_context AS gdc_tracking_context";  // End customer data for tracking
   $fieldClause .= ", gdc_survey_1.gdc_content AS gdc_survey_1_content";  // Customer survey
   $fromClause = $dbh_tr . " AS tr ";
   $fromClause .= "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' ";
   if ($userTypeName == "hq") :
      $fromClause .= "LEFT JOIN genericdatacontainer AS gdc_fin_work ON gdc_fin_work.gdc_obj_id = tr.tr_id AND gdc_fin_work.gdc_obj_type = 'tr' AND gdc_fin_work.gdc_gen_fieldname = 'fin_work' ";
   endif;
   $fromClause .= "LEFT JOIN genericdatacontainer AS gdc_tracking ON gdc_tracking.gdc_obj_id = tr.tr_id AND gdc_tracking.gdc_obj_type = 'tr' AND gdc_tracking.gdc_gen_fieldname = 'tr_tracking' ";
   $fromClause .= "LEFT JOIN genericdatacontainer AS gdc_survey_1 ON gdc_survey_1.gdc_obj_id = tr.tr_id AND gdc_survey_1.gdc_obj_type = 'tr' AND gdc_survey_1.gdc_gen_fieldname = 'survey' AND gdc_survey_1.gdc_context = '1' ";
   $fromClause .= ", address AS ad, costcenter AS csc ";   
   $whereClause = "tr.jb_id = " . $job_id . " AND tr.ad_id = ad.ad_id AND tr.csc_id = csc.csc_id";   
   $orderByClause = "tr.tr_sort";

   // Additional customer informations (phone, name, ...)
   $fieldClause .= " , cs.cs_eid, usr.usr_phone, usr.usr_email ";
   $fromClause .= " LEFT JOIN customer AS cs ON cs.cs_id = csc.cs_id ";
   $fromClause .= " LEFT JOIN employee AS emp ON emp.emp_id = cs.cs_admin ";
   $fromClause .= " LEFT JOIN user AS usr ON usr.usr_id = emp.usr_id ";

   if ($userTypeName == "cs") :
      $fieldClause = getDBFields("tour") . "," . getDBFields("address") . "," . getDBFields("costcenter") . " ";
      $fieldClause .= ", CONCAT(ad_street,' ',tr_hsno) AS ad_street_hsno, CONCAT(ad_zipcode,' ',ad_city) AS ad_zipcode_city ";
      $fieldClause .= ", LEFT(gdc_arr_tour.gdc_content,14) AS gdc_arr_tour_content";  // Arrival timestamp of the courier per station

      $fromClause = $dbh_tr . " AS tr ";
      $fromClause .= "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' ";
      $fromClause .= ", address AS ad, costcenter AS csc ";

      $whereClause = "tr.jb_id = " . $job_id . " AND tr.ad_id = ad.ad_id AND tr.csc_id = csc.csc_id";

      $orderByClause = "tr.tr_sort";
   endif;

   $sqlqueryTour = generateStatement($fieldClause,$fromClause,$whereClause,$orderByClause);
   // echo $sqlqueryTour . "<br><br>";

   if ($execSQLStmts == "1") :

      // Send request to database
      $result = $db->query($sqlqueryTour);
      if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage() . ": " . $sqlqueryTour);
      
      // Get path for proof of delivery photo
      $parPodPath = getParameterValue("0", "JOB_DETAILS_PATH_POD_PHOTO", $currentHqId);
      if ($parPodPath == "") : $parPodPath = getParameterValue("0", "JOB_DETAILS_PATH_POD_PHOTO", "0"); endif;
      
      // Tour-data
      $tourentryArray = array();
      $tourentry = "";
      // $rawJobData .= "[TOUR]";
      $rowCounter = 0;
      $imgFilenames = array();
      while ($row = $result->fetch_assoc()):
            $rowCounter++;
            $tourentry .= "<td valign=\"top\"><table class=\"f8np1\">";
      
            for ($i = 0; $i < $fieldsLength; $i++) :
      
                if ($i % 2 == 0) : $cellColor = "#BBBBFF"; $cellColor2 = "#DDDDDD"; endif;
                if ($i % 2 == 1) : $cellColor = "#CCCCFF"; $cellColor2 = "#EEEEEE"; endif;
                
                if (mcArrTrim($titlesArray, $i) == "") : $titlesArray[$i] = "&nbsp;"; endif;
                $tourentry .= "<tr>";
                if ($rowCounter == 1) :
                   $tourentry .= "<td bgcolor=\"" . $cellColor2 ."\" align=\"left\">" . $titlesArray[$i] . "</td>";
                   $tourentryArray[$i][0] = "<td bgcolor=\"" . $cellColor2 ."\" align=\"left\">" . $titlesArray[$i] . "</td>";
                // elseif ($i == floor($fieldsLength / 2)) :
                elseif ($i == 0) :
                   $tourentry .= "<td valign=\"top\"><img src=\"../images/arrow_right.jpg\" border=\"0\" height=\"10\" width=\"25\"></td>";
                else :
                   $tourentry .= "<td>&nbsp;</td>";
                endif;
                $tmpVarName = mcArrIsSet($fieldsArray, $i);
                ${$tmpVarName} = $row[$tmpVarName];
                mcArrIsSet($outputFormatField, $tmpVarName);
                if ($outputFormatField[$tmpVarName] == "datetime") :
                   $out = formatOutput(${$tmpVarName},$outputFormatField[$tmpVarName],"13");  // "H:i (d.m)"
                elseif ($outputFormatField[$tmpVarName] == "timestamp_classic") :
                   $out = formatOutput(${$tmpVarName},$outputFormatField[$tmpVarName],"2");  // "H:i (d.m)"
                else :
                   $out = formatOutput(${$tmpVarName},$outputFormatField[$tmpVarName],$specialOutputFormat);
                endif;

                if ($tmpVarName == "gdc_arr_tour_content") :
                   // Arrival time
                   $tmpArrivalTime = substr(${$tmpVarName}, 0, 13);
                   $out = formatOutput($tmpArrivalTime,$outputFormatField[$tmpVarName],"2");  // "H:i (d.m)"
                   // Coordinates
                   $tmpCoords = trim(substr(${$tmpVarName}, 15));
                   if ($tmpCoords != "") :
                      $tmpArrCoords = explode("|", $tmpCoords);
                      $tmpCoords = "/" . $tmpArrCoords[1] . "," . $tmpArrCoords[0];
                      $tmpCoordsTxt = "(" . $tmpArrCoords[1] . ", " . $tmpArrCoords[0] . ")";
                      $out .= "<br><a href=\"https://www.google.de/maps/dir" . $tmpCoords . "/" . "\" target=\"_blank\">" . $tmpCoordsTxt . "</a>";
                   endif;
                endif;

                // For HQ only (!!!!)
                if ($tmpVarName == "gdc_fin_work_content" && $userTypeName == "hq") :
                   // Finish work time
                   $tmpFinishWorkTime = substr(${$tmpVarName}, 0, 13);
                   $out = formatOutput($tmpFinishWorkTime,$outputFormatField[$tmpVarName],"2");  // "H:i (d.m)"
                   // Coordinates
                   $tmpCoords = trim(substr(${$tmpVarName}, 15));
                   if ($tmpCoords != "") :
                      $tmpArrCoords = explode("|", $tmpCoords);
                      $tmpCoords = "/" . $tmpArrCoords[1] . "," . $tmpArrCoords[0];
                      $tmpCoordsTxt = "(" . $tmpArrCoords[1] . ", " . $tmpArrCoords[0] . ")";
                      $out .= "<br><a href=\"https://www.google.de/maps/dir" . $tmpCoords . "/" . "\" target=\"_blank\">" . $tmpCoordsTxt . "</a>";
                   endif;
                endif;

                // Customer-sign
                if ($tmpVarName == "tr_sign") :
                   if ($row["tr_sign"] != "") :
                      $rawCoord = splitRawCoordinates ($row["tr_sign"]);
                      $maxCoord = checkMaxCoordinates($rawCoord);
                      
                      if ($f_act == "mailsend" || $f_act == "export") :
                         $tmpSignPath = "../temp/signs/";
                         if (SIGNS_PATH != "") : $tmpSignPath = SIGNS_PATH; endif;                   
                         $imgFilename = $tmpSignPath . $job_id . "_" . $row["tr_sort"] . ".png";
                         $imgFilenames[] = $imgFilename;
                         if ($f_act == "mailsend") :
                            $im = createSignImage($rawCoord);
                            imagepng ($im, $imgFilename);
                         endif;

                         $out = "<img src=\"" . $imgFilename . "\" border=\"0\" height=\"" . round($maxCoord[1] / 2) . "\" width=\"" . round($maxCoord[0] / 2) . "\">";
                      else :
                         $out = "<a href=\"../admin/jb_detail_sign.php?jb_id=" . $job_id . "&tr_sort=" . $row["tr_sort"] . "&dbhistory=" . $dbhistory . "\" target=\"_blank\">"
                                 . "<img src=\"../admin/jb_detail_sign2.php?tr_sign=" . $row["tr_sign"] . "\" border=\"0\" height=\"" . round($maxCoord[1] / 2) . "\" width=\"" . round($maxCoord[0] / 2) . "\">"
                                 . "</a>";
                      endif;
                   endif;
                endif;

                // Proof of delivery by photo
                if ($tmpVarName == "tr_pod_photo") :
                   if ($constMaskStationsPodPhoto == "1") :
                      // Number of required photos
                      mcArrIsSet($trPhotos, $row["tr_id"]);
                      $numOfRequiredPhotos = substr($trPhotos[$row["tr_id"]], 0, strrpos($trPhotos[$row["tr_id"]],"|"));                      
                      $numOfMaxPhotos = substr($trPhotos[$row["tr_id"]], strrpos($trPhotos[$row["tr_id"]],"|") + 1);                      
                      if (trim($numOfRequiredPhotos) == "") : $numOfRequiredPhotos = "0"; endif;
                      if (trim($numOfMaxPhotos) == "") : $numOfMaxPhotos = "1"; endif;
                      $tmpColorOut = "black";
                      if ($job_status != "2" && $numOfRequiredPhotos > "0") : $tmpColorOut = "red"; endif;
                      $out = "";
                      if ($f_act != "mailsend") :
                         if ($numOfRequiredPhotos == "0" && $numOfMaxPhotos == "1"):
                            $out = "<span style=\"color:" . $tmpColorOut . "\">" . getLngt("Anzahl") . ":&nbsp;" . getLngt("Ein optionales Foto") . "</span><br>";
                         else :
                            $out = "<span style=\"color:" . $tmpColorOut . "\">" . getLngt("Anzahl") . ":&nbsp;" . getLngt("Mindestens") . "&nbsp;" . $numOfRequiredPhotos .  "&nbsp;|&nbsp;" . getLngt("Maximal") . "&nbsp;" . $numOfMaxPhotos . "</span><br>";
                         endif;                         
                      endif;
                      // Photo output
                      if ($parPodPath != "") :
                         if ($f_act != "export") :
                            global $jbMailAttachements;
                            if (!isset($jbMailAttachements) || !is_array($jbMailAttachements)) :
                               $jbMailAttachements = array();
                            endif;
                            $jbMailAttachementsLen = count($jbMailAttachements);
                            // Check existence of the photo in filesystem
                            // $podPhotoFilename = $job_id . "_" . $row["tr_sort"] . "_pod.JPG";
                            /*
                            $podPhotoFilename = getImageFromB2bObjects($row["tr_id"], $parPodPath);
                            if ($podPhotoFilename != "") :
                               if (file_exists($parPodPath . $podPhotoFilename)) :
                                  $out .= "<a href=\"javascript:openImageViewer('" . $podPhotoFilename . "','800','600','" . $parPodPath . "');\"><img src=\"" . $parPodPath . $podPhotoFilename . "\" border=\"" . "0" . "\" height=\"100\" width=\"100\"></a>";
                               endif;
                            endif;
                            */
                            // Check existence in "pic"
                            $podPhotoFilenames = getImagesFromPic($row["tr_id"], $parPodPath);
                            $podPhotoFilenamesLen = count($podPhotoFilenames);
                            if ($podPhotoFilenamesLen == 0) :
                               // Check existence in "b2b_objects"
                               $podPhotoFilenames = getImagesFromB2bObjects($row["tr_id"], $parPodPath);
                               $podPhotoFilenamesLen = count($podPhotoFilenames);
                            endif;
                            for ($p = 0; $p < $podPhotoFilenamesLen; $p++) :
                                if ($podPhotoFilenames[$p] != "") :
                                   if (file_exists($parPodPath . $podPhotoFilenames[$p])) :
                                      if ($f_act == "mailsend") :
                                         // $out .= "<img src=\"" . $parPodPath . $podPhotoFilenames[$p] . "\" border=\"0\" height=\"100\" width=\"100\">&nbsp;";
                                         if (file_exists($parPodPath . "pht_" . $podPhotoFilenames[$p])) :
                                            unlink($parPodPath . "pht_" . $podPhotoFilenames[$p]);
                                         endif;
                                         $im = imagecreatefromjpeg($parPodPath . $podPhotoFilenames[$p]);
                                         if ($im) :
                                            if (imagejpeg($im, $parPodPath . "pht_" . $podPhotoFilenames[$p])) :
                                               $out .= "<img src=\"" . $parPodPath . "pht_" . $podPhotoFilenames[$p] . "\" border=\"0\" height=\"100\" width=\"100\">&nbsp;";
                                            endif;
                                         endif;
                                         /*
                                         $jbMailEmbeddedImages[$p][0] = $parPodPath . $podPhotoFilenames[$p];
                                         $jbMailEmbeddedImages[$p][1] = $podPhotoFilenames[$p];
                                         $out .= "<img src=\"" . $podPhotoFilenames[$p] . "\" border=\"0\" height=\"100\" width=\"100\">&nbsp;";
                                         */
                                         // Attach each photo to the mail (!!!!)
                                         $jbMailAttachements[($p + $jbMailAttachementsLen)][0] = $parPodPath . $podPhotoFilenames[$p];
                                         $jbMailAttachements[($p + $jbMailAttachementsLen)][1] = $podPhotoFilenames[$p];
                                      else :
                                         $out .= "<a href=\"javascript:openImageViewer('" . $podPhotoFilenames[$p] . "','800','600','" . "EMC2" . substr($parPodPath, 2) . "');\"><img src=\"" . $parPodPath . $podPhotoFilenames[$p] . "\" border=\"" . "0" . "\" height=\"100\" width=\"100\"></a>&nbsp;";
                                      endif;
                                   endif;
                                endif;
                            endfor;
                         endif;
                      endif;
                   endif;
                endif;

                // Proof of delivery by scan events
                if ($constMaskStationsPodScanEvents == "1") :
                   if ($tmpVarName == "tr_pod_scan_events") :
                      // if ($f_act != "mailsend" || $f_act != "export") :
                         // Get scan event state
                         $tmpOut = "";
                         // Get state (del_code)
                         $tmpEventState = getFieldValueFromClause("genericdatacontainer", "gdc_content", "gdc_obj_type = 'tr' AND gdc_obj_id = '" . $row["tr_id"] . "' AND gdc_gen_fieldname = 'del_code'");
                         if ($tmpEventState != "" && is_numeric($tmpEventState)) :
                            // $tmpOut .= getLngt("Status") . ":<br>" . $deliveryCodeArray[$tmpEventState] . "<br><br>";
                            if ($tmpEventState == "1") :
                               if ($row["tr_ware_from_to"] == "1") :
                                  $tmpOut .= "<b>" . getLngt("Status") . "</b>: " . getLngt("Abgeholt") . "<br><br>";
                               elseif ($row["tr_ware_from_to"] == "2" || $row["tr_ware_from_to"] == "3") :
                                  $tmpOut .= "<b>" . getLngt("Status") . "</b>: " . getLngt("Abgeliefert") . "<br><br>";
                               endif;
                            else :
                               $tmpOut .= "<b>" . getLngt("Status") . "</b>:<br>" . $deliveryCodeArray[$tmpEventState] . "<br><br>";
                            endif;
                         endif;
                         // Get state reason (del_rem)
                         $tmpEventRemark = getFieldValueFromClause("genericdatacontainer", "gdc_content", "gdc_obj_type = 'tr' AND gdc_obj_id = '" . $row["tr_id"] . "' AND gdc_gen_fieldname = 'del_rem'");
                         if ($tmpEventRemark != "") :
                            $tmpOut .= "<b>" . getLngt("Statusgrund") . "</b>:<br>" . $tmpEventRemark . "<br><br>";
                         endif;
                         // Get state reason (tr_hint)
                         if ($userTypeName == "hq") :
                            $tmpStationRemark = getFieldValueFromClause("genericdatacontainer", "gdc_content", "gdc_obj_type = 'tr' AND gdc_obj_id = '" . $row["tr_id"] . "' AND gdc_gen_fieldname = 'tr_hint'");
                            if ($tmpStationRemark != "") :
                               $tmpOut .= "<b>" . getLngt("Notiz des Transporteurs zur Station") . "</b>:<br>" . $tmpStationRemark . "<br><br>";
                            endif;
                         endif;
                         
                         // Output scan barcodes
                         $out = $tmpOut . getOutputJobTratArticleData($job_id, "1", "", "1", "1", $row["tr_sort"]);
                      // endif;
                   endif;
                endif;

                // Number of scanned packages (SPECIAL CUSTOMER SOLUTION !!!!)
                if ($constMaskStationsPodNumOfScannedPackages == "1") :
                   if ($tmpVarName == "tr_pod_num_scanned_packages") :
                      if ($f_act != "mailsend" || $f_act != "export") :
                         // Get number of scanned packages
                         $tmpOut = "";
                         $tmpTratId = getFieldValueFromId("tourarticle","tr_id",$row["tr_id"],"trat_id");
                         if ($tmpTratId != "" && is_numeric($tmpTratId)) :
                            $tmpNumOfScannedPackages = getFieldValueFromClause("tourarticleprocess", "tratp_remark", "trat_id = '" . $tmpTratId . "' AND tratp_remark LIKE 'cnt=%'");
                            if ($tmpNumOfScannedPackages == "") :
                               $tmpNumOfScannedPackages = "0";
                            else :
                               $tmpNumOfScannedPackages = substr($tmpNumOfScannedPackages,4);
                            endif;
                            $tmpOut .= $tmpNumOfScannedPackages;
                            $tmpTratPackingpieces = getFieldValueFromId("tourarticle","trat_id",$tmpTratId,"trat_packingpieces");
                            if ($tmpTratPackingpieces != "") :
                               $tmpOut .= " / " . $tmpTratPackingpieces;
                            endif;
                         endif;
                         
                         // Output scan barcodes
                         if ($tmpOut != "") :
                            $out = $tmpOut;
                         endif;
                      endif;
                   endif;
                endif;

                // End customer tracking
                if ($csTracking == "1") :
                   if ($tmpVarName == "gdc_tracking_content") :
                      if ($f_act != "mailsend" || $f_act != "export") :
                         $tmpGdcTrackingArr = explode("|", $row["gdc_tracking_content"]);
                         $tmpGdcTrackingEndCustomerEmail = $tmpGdcTrackingArr[0];
                         $tmpTrackingColor = "black";
                         if ($row["gdc_tracking_context"] != "") :
                            if ($row["gdc_tracking_context"] == "SENT_OK") :
                               $tmpTrackingColor = "green";
                            elseif ($row["gdc_tracking_context"] == "SENT_NOK") :
                               $tmpTrackingColor = "red";
                            elseif (is_numeric($row["gdc_tracking_context"])) :
                                $tmpTrackingColor = "blue";
                            endif;
                         endif;
                         $out = "<span style=\"color:" . $tmpTrackingColor . "\">" . $tmpGdcTrackingEndCustomerEmail . "</span>";
                      endif;
                   endif;
                endif;

                // Survey
                if ($constMaskStationsSurvey == "1") :
                   if ($tmpVarName == "gdc_survey_1_content") :
                      if ($f_act != "mailsend" || $f_act != "export") :
                         switch($out) {
                            case "0" : $out = getLngt("Keine Angabe"); break;
                            case "1" : $out = "<span style=\"color:red\">" . getLngt("Unzufrieden") . "</span>"; break;
                            case "2" : $out = "<span style=\"color:yellow\">" . getLngt("Neutral") . "</span>"; break;
                            case "3" : $out = "<span style=\"color:green\">" . getLngt("Zufrieden") . "</span>"; break;
                         };
                      endif;
                   endif;
                endif;

                // Iternal remark items
                if ($maskJobInternalRemarkItems == "1") :
                   if ($tmpVarName == "tr_id_int_rem") :
                      if ($f_act != "mailsend" || $f_act != "export") :
                         if ($f_act != "mailsend" && ($job_export_time == "" || $job_export_time == "0000-00-00 00:00:00")) :
                             $out = "&nbsp;&nbsp;<input type=\"button\" style=\"width: 15px; height: 15px;\" name=\"int_rem_items_" . $row["tr_id_int_rem"] . "\" value=\"\" onClick=\"openActionContainer(" . $row["tr_id_int_rem"] . ", " . $row["tr_sort"] . ");\">";
                             $out .= "<span id=\"out_tr_int_rem_" . pad($row["tr_id"],2) . "\">";
                             $out .= getJobInternalRemarkItems($job_id, "2", $row["tr_id"]);
                             $out .= "</span>";
                         else :
                             $out = getJobInternalRemarkItems($job_id, "2", $row["tr_id"]);
                         endif;
                      endif;
                   endif;
                endif;

                if ($tmpVarName == "tr_ware_from_to") :
                    $tmpColorOut = "black";
                    if ($job_status != "2") : $tmpColorOut = "red"; endif;
                    switch($out) {
                       case "0" : $out = getLngt("Keine Angabe"); break;
                       case "1" : $out = "<span style=\"color:" . $tmpColorOut . "\">" . getLngt("Abholung") . "</span>"; break;
                       case "2" : $out = "<span style=\"color:" . $tmpColorOut . "\">" . getLngt("Anlieferung") . "</span>"; break;
                       case "3" : $out = "<span style=\"color:" . $tmpColorOut . "\">" . getLngt("Abholung und Anlieferung") . "</span>"; break;
                    };
                endif;

                if ($tmpVarName == "tr_remark") :
                   // Remove some internal annotations fron station remark
                   if ($userTypeName == "cs" || $f_act == "mailsend") :
                      if (!(strpos($out, "[[") === false)) :
                         $jb_cr_priceStr = strstr($out, "[[");
                         if ($jb_cr_priceStr != "" && !(strpos($jb_cr_priceStr, "]]") === false)) :
                            $jb_cr_priceStr = substr($jb_cr_priceStr, 0, strpos($jb_cr_priceStr, "]]", 2) + 2);
                            $out = str_replace($jb_cr_priceStr, "", $out);
                         endif;
                      endif;
                   endif;
                   $out = nl2br($out);
                endif;

                // Email
                if ($tmpVarName == "usr_email") :
                   if ($job_status == "2") :
                      $out = "<a href=\"#\" onClick=\"javascript:document.jb_detail.f_email.value = '" . $out . "';\">" . $out . "</a>";
                   endif;
                endif;             

                // Special formatting for tour-fields
                if ($tmpVarName == "tr_status") :
                   switch($out) {
                      case "0" : $out = getLngt("offen"); break;
                      case "1" : $out = getLngt("erledigt"); break;
                   };
                endif;

                // Finishtime of the station
                if ($tmpVarName == "tr_finishtime") :
                   if (substr($tr_finishtime,0,4) == "1970") :
                      $out = "";
                   endif;
                endif;
      
                // wrap finishtime (ONLY for corrupted data)
                if ($userTypeName == "cs") :
                   if ($tmpVarName == "tr_finishtime" && ($row["tr_finishtime"] == "" || $row["tr_finishtime"] < "2004-10-01 00:00:00")) :
                      $out = "";
                   endif;
                endif;
      
                // Do not show customer data if external costcenter
                if ($tmpVarName == "usr_phone" || $tmpVarName == "usr_email" || $tmpVarName == "cs_eid") :
                   if (!(strpos(strtoupper($row["csc_path"]), "//EXTERN//") === FALSE)) :
                      $out = "";
                   endif;
                endif;

                // Station number
                if ($tmpVarName == "tr_sort") :
                   $out = "<b>[&nbsp;#&nbsp;" . $out . "&nbsp;]</b>";
                   $out = "<a href=\"javascript:openJobStation(" . $job_id . "," . $row["tr_sort"] . ");\">" . $out . "</a>";
                endif;

                $tourentry .= "<td bgcolor=\"" . $cellColor ."\" align=\"left\">" . $out . "</td>";
                $tourentry .= "</tr>";

                $cellColorMatrix = getListColorGeneric($i, $rowCounter, "#AAAAFF", "#BBBBFF", "#CCCCFF", "#DDDDFF");
                $tourentryArray[$i][$rowCounter] = "<td style=\"padding: 3px; vertical-align:top; background-color: " . $cellColorMatrix .";\">" . $out . "</td>";
      
                if ($tmpVarName == "usr_email") :
                   $rawJobData .= "tr_" . $row["tr_sort"] . "_" . $tmpVarName . "=" . $row["usr_email"] . "|";
                elseif ($tmpVarName == "tr_sign") :
                   $rawJobData .= "tr_" . $row["tr_sort"] . "_" . $tmpVarName . "=" . $row["tr_sign"] . "|";
                else :
                   if ($out == "&nbsp;") : $out = ""; endif;
                   $rawJobData .= "tr_" . $row["tr_sort"] . "_" . $tmpVarName . "=" . $out . "|";
                endif;

            endfor;
            $tourentry .= "</table></td>";
            
            if ($f_act == "printjob") :
               $constNumOfStationsPerLineToPrint = getParameterValue("0", "MASK_JB_STATIONS_PRINT_FORMAT", $currentHqId);
               if ($constNumOfStationsPerLineToPrint == "" || !is_numeric($constNumOfStationsPerLineToPrint)) : $constNumOfStationsPerLineToPrint = 5; endif;
               if (($rowCounter % $constNumOfStationsPerLineToPrint) == 0) :
                  $tourentry .= "</tr></table><table class=\"f8np1\"><tr><td valign=\"top\"><table class=\"f8np1\">";
               endif;
            endif;
      endwhile;
      $result->free();
      $tr_numberofstations = $rowCounter;
      
      // Overwrite with new structure
      if ($tourDisplayClassicMode != "1") :
         $tourentry = convertMatrixToTable($tourentryArray, "1");
      endif;
   endif;


   // --- COURIER ------------------
   
   // Initialize for template-output
   $courierentry = "";
   // $rawJobData .= "[COURIER]";
 
   if ($jobCourierId != "") :
      // initialize
      if ($f_act == "mailsend" || $f_act == "printjob" || $f_act == "export") :
         $tmpTitlePart = "";
         $tmpFieldPart = "";
         $csJbstatusmailFields = getFieldValueFromId("customer","cs_id",$csIdPayer,"cs_jbstatusmail_fields");
         if (substr($csJbstatusmailFields, 1, 1) == "1") :
            $tmpTitlePart .= "," . getLngt("Mobil-Nr.");
            $tmpFieldPart .= ",usr_phone";
         endif;
         if (substr($csJbstatusmailFields, 6, 1) == "1" && $job_cr_sid != "") :
            $tmpTitlePart .= "," . getLngt("Kennzeichen");
            $tmpFieldPart .= ",crvh_vh_sign";
         endif;
         // $titles = getLngt("Name") . "," . getLngt("Vorname") . "," . getLngt("SID") . $tmpTitlePart;
         // $fields = "usr_name,usr_firstname,cr_sid" . $tmpFieldPart;
         $titles = getLngt("SID") . $tmpTitlePart;
         $fields = "cr_sid" . $tmpFieldPart;
      else :
         $titles = getLngt("Firma") . "," . "" . "," . getLngt("Name") . "," . getLngt("Vorname") . "," . getLngt("Tel.") . "," . getLngt("Tel.2") . "," . getLngt("Tel.PDA/VPA") . "," . getLngt("SID") . "," . getLngt("ExtID") . "," . getLngt("Kennz.") . "," . getLngt("Online") . "," . getLngt("Nutzlast") . "," . getLngt("L x B x H x S") . "," . getLngt("Transporteursfilter") . "," . getLngt("Fahrzeugfilter");
         $fields = "cmp_comp,cmp_comp2,usr_name,usr_firstname,usr_phone,usr_phone2,cr_mobile_pda,cr_sid,cr_eid" . ($job_cr_sid != "" ? ",crvh_vh_sign" : "") . ",cr_available" . ($job_cr_sid != "" ? ",crvh_payload" : "") . ($job_cr_sid != "" ? ",crvh_measures" : "") . ",cr_filter" . ($job_cr_sid != "" ? ",crvh_filter" : "");
      endif;
      $titlesArray = spliti(",",$titles);
      $titlesLength = count($titlesArray);
      $fieldsArray = spliti(",",$fields);
      $fieldsLength = count($fieldsArray);

      $fieldClause = getDBFields("courier") . "," . getDBFields("company") . "," . getDBFields("user") . " ";

      $fromClause = "courier AS cr, company AS cmp, user AS usr ";
      $whereClause = "cr.cr_id = " . $jobCourierId . " AND cmp.cmp_id = cr.cmp_id AND usr.usr_id = cr.usr_id";
      $orderByClause = "";      

      if ($job_cr_sid != "") :
         $fieldClause .= ", crvh.crvh_id, crvh.crvh_vh_sign, crvh.crvh_payload, CONCAT(crvh.crvh_length,' x ',crvh.crvh_width,' x ',crvh.crvh_height,' x ',crvh.crvh_position) AS crvh_measures, crvh.crvh_filter ";
         // $fromClause = "courier AS cr LEFT JOIN couriervehicle AS crvh ON cr.cr_id = crvh.cr_id AND crvh.crvh_sid = '" . $job_cr_sid . "', company AS cmp, user AS usr ";
         $fromClause = "courier AS cr LEFT JOIN couriervehicle AS crvh ON crvh.crvh_sid = '" . $job_cr_sid . "', company AS cmp, user AS usr ";
      endif;

      $orderByClause = "";

      $sqlqueryCourier = generateStatement($fieldClause,$fromClause,$whereClause,$orderByClause);
      // echo $sqlqueryCourier . "<br><br>";

      if ($execSQLStmts == "1") :

         // Send request to database
         $result = $db->query($sqlqueryCourier);
         if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage() . ": " . $sqlqueryCourier);
         
         // Courier-data
         while ($row = $result->fetch_assoc()):
               // $courierentry .= "<td><table>";
               for ($i = 0; $i < $fieldsLength; $i++) :             
                   if ($i % 2 == 0) : $cellColor = "#BBBBFF"; $cellColor2 = "#DDDDDD"; endif;
                   if ($i % 2 == 1) : $cellColor = "#CCCCFF"; $cellColor2 = "#EEEEEE"; endif;

                   if (mcArrTrim($titlesArray, $i) == "") : $titlesArray[$i] = "&nbsp;"; endif;
                   $courierentry .= "<tr>";
                   $courierentry .= "<td bgcolor=\"" . $cellColor2 ."\" align=\"left\">" . $titlesArray[$i] . "</td>";             
                   $tmpVarName = mcArrIsSet($fieldsArray, $i);
                   ${$tmpVarName} = $row[$tmpVarName];
                   mcArrIsSet($outputFormatField, $tmpVarName);

                   // Do not show excluded filters, remove them by parameter for output only
                   if (($tmpVarName == "cr_filter" || $tmpVarName == "crvh_filter") && ${$tmpVarName} != "" && $constMaskExcludedFilterStr != "") :
                      for ($e = 0; $e < $constMaskExcludedFilterArrLen; $e++) :
                          ${$tmpVarName} = removeItemFromFilterstringWithCommata(${$tmpVarName}, $constMaskExcludedFilterArr[$e]);
                      endfor;
                   endif;

                   $out = formatOutput(${$tmpVarName},$outputFormatField[$tmpVarName],$specialOutputFormat);

                   // Take cr_sid from job because (1:n)-relation "courier:vehicle"
                   if ($tmpVarName == "cr_sid") :
                      $out = $job_cr_sid;
                   endif;

                   // special formatting for tour-fields
                   if ($tmpVarName == "cr_available") :
                      switch($out) {
                         case "0" : $out = getLngt("nicht online"); break;
                         case "1" : $out = getLngt("online"); break;
                      };
                   endif;

                   if ($tmpVarName == "cr_filter") :
                      $tmpFilterStr = $out;
                      if ($out == "&nbsp;") :
                         $out = "";
                      else :
                         $out = substr($out, 1, -1);
                         $out = my_str_replace ($out, ",", "<br>", "5");
                         $out .= "<br>";
                      endif;
                      // $out .= "<br><a href=\"../admin/courier_vehicle.php?courierId=" . $jobCourierId . "&f_crvh_id=" . $row["crvh_id"] . "&f_act=\" target=\"_blank\">" . $job_cr_sid . "</a>";
                      $out .= "<a href=\"../admin/filter.php?f_crvh_filter_str=" . $tmpFilterStr . "&filterType=1&actionMode=0&deactivateMenu=1&readonly=1\" target=\"_blank\">" . getLngt("Übersicht") . "</a>";
                   endif;

                   if ($tmpVarName == "crvh_filter") :
                      $tmpFilterStr = $out;
                      if ($out == "&nbsp;") :
                         $out = "";
                      else :
                         $out = substr($out, 1, -1);
                         $out = my_str_replace ($out, ",", "<br>", "5");
                         $out .= "<br>";
                      endif;
                      // $out .= "<br><a href=\"../admin/courier_vehicle.php?courierId=" . $jobCourierId . "&f_crvh_id=" . $row["crvh_id"] . "&f_act=\" target=\"_blank\">" . $job_cr_sid . "</a>";
                      $out .= "<a href=\"../admin/filter.php?f_crvh_filter_str=" . $tmpFilterStr . "&filterType=0&actionMode=0&deactivateMenu=1&readonly=1\" target=\"_blank\">" . getLngt("Übersicht") . "</a>";
                   endif;

                   $courierentry .= "<td bgcolor=\"" . $cellColor ."\" align=\"left\">" . $out . "</td>";
                   $courierentry .= "</tr>";

                   if ($out == "&nbsp;") : $out = ""; endif;
                   $rawJobData .= "cr_" . $tmpVarName . "=" . $out . "|";
               endfor;

               // Link to copy the job and link to history
               if ($f_act != "mailsend" && $f_act != "printjob" && $f_act != "export") :
                  $courierentry .= "<tr><td><br>";
                  $courierentry .= "<a href=\"../admin/history.php?history_mode=1&cr_id=" . $jobCourierId . "&op=0\" target=\"_blank\">" . getLngt("Kurierhistorie") . "</a>";
                  $courierentry .= "</td></tr>";
               endif;
               // $courierentry .= "</table></td>";
         endwhile;
         $result->free();
      endif;
   endif;
   
   // Check for global mediation
   if ($f_act != "mailsend" && $f_act != "printjob" && $f_act != "export") :
      if ($job_longhaul == "1" && !authCheckEmployeeRights($emp_id, "10")) :
         $courierentry = "<tr><td class=\"f8np1_red\">" . getLngt("FERNTOUR") . "</td></tr>";
      endif;
   endif;

   // ATTENTION: Overwrite all courier data in $courierentry if it is a customer call !!!
   if ($userTypeName == "cs") :
      // Get "cr_sid" from table "job"
      $courierentry = "<tr><td>" . getLngt("KURIER") . ":</td></tr>";
      if ($jobCourierId != "") :
         $parMaskCsShowUserData = getParameterValue("0", "CUSTOMER_MASK_SHOW_USER_DATA", $currentHqId);
         if ($parMaskCsShowUserData == "") :
            $parMaskCsShowUserData = getParameterValue("0", "CUSTOMER_MASK_SHOW_USER_DATA", "0");
         endif;
         if ($parMaskCsShowUserData == "1") :
            $tmpUsrId = getFieldValueFromId("courier", "cr_id", $jobCourierId, "usr_id");
            if ($tmpUsrId != "") :
               $courierentry .= "<tr><td>" . getLngt("Name") . ":&nbsp;" . getFieldValueFromId("user", "usr_id", $tmpUsrId, "usr_name") . "</td></tr>";
               $courierentry .= "<tr><td>" . getLngt("Vorname") . ":&nbsp;" . getFieldValueFromId("user", "usr_id", $tmpUsrId, "usr_firstname") . "</td></tr>";
            endif;
         endif;
      endif;
      $courierentry .= "<tr><td>" . getLngt("Fahrzeug") . ":&nbsp;" . getFieldValueFromId($dbh_jb, "jb_id", $job_id, "cr_sid") . "</td></tr>";
   endif;



   // --- USER (EMPLOYEE) ------------------

   // Initialize for template-output
   $employeeentry = "";
   // $rawJobData .= "[EMPLOYEE]";

   // Display only the creator of the job or display the history of employees
   if (MASK_JOBDETAILS_USER_HISTORY == "" || MASK_JOBDETAILS_USER_HISTORY == "0") :
   
      // Get the user (employee) of the current job
      $job_usr_id = getFieldValueFromId($dbh_jb,"jb_id",$job_id,"emp_id");

      if ($job_usr_id != "") :
         // initialize
         $titles = getLngt("Name") . "," . getLngt("Vorname") . "," . getLngt("Telefon") . "," . getLngt("E-Mail");
         $titlesArray = spliti(",",$titles);
         $titlesLength = count($titlesArray);
         $fields = "usr_name,usr_firstname,usr_phone,usr_email";
         $fieldsArray = spliti(",",$fields);
         $fieldsLength = count($fieldsArray);   

         $fieldClause = getDBFields("user") . " ";
         $fromClause = "user AS usr ";
         $whereClause = "usr.usr_id = " . $job_usr_id;
         $orderByClause = "";

         $sqlqueryUser = generateStatement($fieldClause,$fromClause,$whereClause,$orderByClause);
         // echo $sqlqueryUser . "<br><br>";

         if ($execSQLStmts == "1") :

            // Send request to database
            $result = $db->query($sqlqueryUser);
            if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage() . ": " . $sqlqueryUser);
            
            // Employee-data      
            $employeeentry .= "<tr><td>" . getLngt("MITARBEITER:") . "</td></tr>";
            while ($row = $result->fetch_assoc()):
                  // $employeeentry .= "<td><table>";
                  for ($i = 0; $i < $fieldsLength; $i++) :             
                      if ($i % 2 == 0) : $cellColor = "#BBBBFF"; $cellColor2 = "#DDDDDD"; endif;
                      if ($i % 2 == 1) : $cellColor = "#CCCCFF"; $cellColor2 = "#EEEEEE"; endif;

                      if (mcArrTrim($titlesArray, $i) == "") : $titlesArray[$i] = "&nbsp;"; endif;
                      $employeeentry .= "<tr>";
                      $employeeentry .= "<td bgcolor=\"" . $cellColor2 ."\" align=\"left\">" . $titlesArray[$i] . "</td>";             
                      $tmpVarName = mcArrIsSet($fieldsArray, $i);
                      ${$tmpVarName} = $row[$tmpVarName];
                      mcArrIsSet($outputFormatField, $tmpVarName);
                      $out = formatOutput(${$tmpVarName},$outputFormatField[$tmpVarName],$specialOutputFormat);
            
                      $employeeentry .= "<td bgcolor=\"" . $cellColor ."\" align=\"left\">" . $out . "</td>";
                      $employeeentry .= "</tr>";
            
                      if ($out == "&nbsp;") : $out = ""; endif;
                      $rawJobData .= "emp_" . $tmpVarName . "=" . $out . "|";
                  endfor;         
                  // $employeeentry .= "</table></td>";         
            endwhile;
            $result->free();
         endif;
      endif;

   else :   // Display history of employees

      if ($job_id != "" && is_numeric($job_id) && $job_id > "0") :

         if (FALSE) :
            // From table "jobemployee"
            $fieldClause = getDBFields("jobemployee") . "," . getDBFields("user") . " ";
            $fromClause = "jobemployee AS jbemp, user AS usr ";
            $whereClause = "jbemp.jb_id = '" . $job_id . "' AND jbemp.usr_id = usr.usr_id";
            $orderByClause = "jbemp.jbemp_modifytime";
         else :
            // From table "log"
            $fieldClause = getDBFields("logoperation") . "," . getDBFields("log") . "," . getDBFields("user") . " ";
            $fromClause = " phoenix_log.logoperation AS logo, phoenix_log.log AS log "
                        . " LEFT JOIN phoenix.user AS usr ON log.usr_id = usr.usr_id ";
            $whereClause = " log.jb_id = '" . $job_id . "' AND log.logo_id = logo.logo_id AND ";
            if ($userTypeName == "cs") :
               $whereClause .= "logo.logo_id IN (1,10)";
            else :
               $whereClause .= "logo.logo_id IN (1,2,5,10,13,14,15,16,17,18,19,20,21,22,23,25,26,32,102,149,161,162,163)";
            endif;
            
            $orderByClause = "log.log_createtime";      
         endif;
         
         $sqlqueryUser = generateStatement($fieldClause,$fromClause,$whereClause,$orderByClause);

         if ($execSQLStmts == "1") :

            // Send request to database
            $result = $db->query($sqlqueryUser);
            if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage() . ": " . $sqlqueryUser);
            
            // Generate list with header
            $titleArray = array(getLngt("Vorgang&nbsp;"),getLngt("Zeitpunkt&nbsp;"),getLngt("Name&nbsp;"),getLngt("Vorname&nbsp;"),getLngt("Telefon&nbsp;"));
            if (FALSE) :
               // From table "jobemployee"
               $fieldArray = array("jbemp_description","jbemp_modifytime","usr_name","usr_firstname","usr_phone");
            else :
               // From table "log"
               $fieldArray = array("logo_op_shortname","log_createtime","usr_name","usr_firstname","usr_phone");
            endif;
            $aligns = "l,l,l,l,l,l";
            $alignArray = spliti(",",$aligns);
            $alignTitles = "left";
            $widths = "50,150,50,50,50";
            $widthArray = spliti(",",$widths);
            $summationField = "";
            $mode = "1";             // Output from DB-RESULT
            $sortDBField = "";       // Used in following include-file for sorting per column;
            include ("../include/inc_list_defineoutput.inc.php");
            // $employeeentry .= "<tr><td colspan=\"6\">" . getLngt("MITARBEITER:") . "</td></tr>";
            $employeeentry .= $tableHeader . $tableBody;

             if ($automailer == "0" && $job_status == 1) {
               $employeeentry .=
                 "<tr><td colspan=\"6\">&nbsp;<br><br></td></tr><tr>" .
                 "<tr><td colspan=\"6\">Aktuelle Route in Google Maps:</td></tr><tr>" .
                 "<tr><td colspan=\"6\">" . showInGoogleMaps($job_id) . "</td></tr><tr>";
             }
            
            $result->free();
         endif;
      endif;
   endif;

   // OLD: Overwrite all employee data in $employeeentry if it is a customer call
   // Since 2018-11-19 :: Activate output for customers but for some log operations only !!!!
   if ($userTypeName == "cs") :
      // $employeeentry = "";
   endif;


   // --- JOB-COSTS ------------------
   $jobcosts = "";
   /*
   $jobcosts = "<tr><td>" . getLngt("KOSTEN") . ":</td></tr>";
   $jobcosts .= "<tr><td bgcolor=\"#BBBBFF\">";
   $jobCostArr = getJobCostsByID($job_id);

   foreach ($jobCostArr as $costArr) {
     $jobcosts .= "Zahler: " . $costArr[0] . "<br>";
     for ($j = 0; $j < (count($costArr[1]) - 1); $j++):  
       $jobcosts .=  $costArr[1][$j][0] . ": " . number_format($costArr[1][$j][1], 2, ',', '.') . "<br>";
     endfor;
     $jobcosts .=  "<span style=\"color:red\"><i>" . $costArr[1][$j][0] . "</i></span>: ";
     $jobcosts .=  "<span style=\"color:red\"><i>" . number_format($costArr[1][$j][1], 2, ',', '.') . "</i></span>" . "<br>";
   }
   $jobcosts .= "</td></tr>";
   */

   
   // $rawJobData .= "[COSTS]";
   
   // Get the persistent tourservice data 
   $fieldString = getDBFields("tourservice");

   $whereClauseCosts = "";
   if ($automailer == "1" || $f_act == "mailsend" || $userTypeName == "cs") :
      $whereClauseCosts = " AND NOT (trs_srvt_name = 'z' AND trs_price = '0') ";
   endif;

   $sqlqueryCosts = "SELECT " . $fieldString . ",csc.csc_name, CONCAT(cscad.cscad_phone,'</br>',usr.usr_email) AS cscad_phone, cs.cs_eid,"
                  . "       CONCAT(cmp.cmp_comp,'<br>',cmp.cmp_comp2) AS cmp_comp, (trs.trs_price * ((100 - trs.trs_discount) / 100)) AS business_volume,"
                  . "       ((trs.trs_price * ((100 - trs.trs_discount) / 100)) * " . $taxFactor . ") AS business_volume_gross"
                  . " FROM " . $dbh_trs . " AS trs LEFT JOIN costcenter AS csc ON trs.csc_id = csc.csc_id"
                  . "                              LEFT JOIN costcenteraddress AS cscad ON csc.csc_id = cscad.csc_id AND cscad.adt_id = '4'"
                  . "                              LEFT JOIN customer AS cs ON csc.cs_id = cs.cs_id"
                  . "                              LEFT JOIN company AS cmp ON cs.cmp_id = cmp.cmp_id"
                  . "                              LEFT JOIN employee AS emp ON cs.cs_admin = emp.emp_id"
                  . "                              LEFT JOIN user AS usr ON emp.usr_id = usr.usr_id"
                  . " WHERE trs.jb_id = '" . $job_id . "'" . $whereClauseCosts
                  . " ORDER BY trs.csc_id, trs.tr_sort";

   if ($userTypeName == "cs") :
      $sqlquery = "SELECT " . $fieldString . ",csc.csc_name, (trs.trs_price * ((100 - trs.trs_discount) / 100)) AS business_volume, ((trs.trs_price * ((100 - trs.trs_discount) / 100)) * " . $taxFactor . ") AS business_volume_gross"
                . " FROM " . $dbh_trs . " AS trs LEFT JOIN costcenter AS csc ON trs.csc_id = csc.csc_id"
                . " WHERE trs.jb_id = '" . $job_id . "'"
                . " ORDER BY trs.csc_id, trs.tr_sort";
   endif;
   // echo $sqlqueryCosts . "<br><br>";

   if ($execSQLStmts == "1") :

      $result = $db->query($sqlqueryCosts);
      if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage() . ": " . $sqlqueryCosts);
      
      // Generate list with header
      $titleArray = array(getLngt("Kostenstelle&nbsp;"),getLngt("Tel.&nbsp;/&nbsp;Email"),getLngt("EID&nbsp;"),getLngt("Kunde"),getLngt("Leistung&nbsp;"),getLngt("Betrag"));
      $businessVolumeField = "business_volume";
      if ($globalParUseRelatedCustomer == 1) :
         $businessVolumeField = "business_volume_gross";
      endif;
      $fieldArray = array("csc_name","cscad_phone","cs_eid","cmp_comp","trs_srv_name",$businessVolumeField);
      $aligns = "l,l,l,l,l,r";
      $widths = "150,120,50,150,150,70";

      if ($userTypeName == "cs") :
         $titleArray = array(getLngt("Kostenstelle&nbsp;"),getLngt("Leistung&nbsp;"),getLngt("Betrag"));
         $fieldArray = array("csc_name","trs_srv_name",$businessVolumeField);
         $aligns = "l,l,r";
         $widths = "150,150,0";
      endif;

      $alignArray = spliti(",",$aligns);
      $alignTitles = "left";   
      $widthArray = spliti(",",$widths);
      $summationField = $businessVolumeField;
      $mode = "1";             // Output from DB-RESULT
      $sortDBField = "";       // Used in following include-file for sorting per column;
      include ("../include/inc_list_defineoutput.inc.php");

      // Add toll if does exist
      $jbToll = getFieldValueFromClause("genericdatacontainer","gdc_content","gdc_obj_type = 'jb' AND gdc_gen_fieldname = 'jb_toll' AND gdc_obj_id = '" . $job_id . "'");
      $jbToll = trim($jbToll);
      $jobCostsToll = "";
      $outSummationText = getLngt("KUNDENPREIS");
      $jbTotalSumWithToll = $sumOfSummationField;  // Init
      if ($jbToll != "") :
         $outSummationText = getLngt("ZWISCHENSUMME");
         $jbTotalSumWithToll = $sumOfSummationField + $jbToll;
      endif;

      if ($userTypeName != "cs") :   // ONLY headquarters and automailer
         // $jobcosts = "<tr><td colspan=\"" . (count($fieldArray)) . "\">" . getLngt("KOSTEN:") . "</td></tr>\n";
         $jobcosts .= $tableHeader . $tableBody;
         // $jobcosts .= $jobCostsToll;  // Toll
         $jobcosts .= "<tr><td class=\"f8np1_red\" colspan=\"" . (count($fieldArray) - 1) . "\">" . $outSummationText . ":</td><td class=\"f8np1_red\" align=\"right\">" . number_format(round($sumOfSummationField,2), 2, ",", ".") . "&nbsp;&nbsp;</td></tr>\n";

         $rawJobData .= "costs_" . "sum=" . number_format(round($sumOfSummationField,2), 2, ",", ".") . "|";

         $self_service_discount = $db->getOne("SELECT jbprc_price FROM jobprice WHERE jb_id = " . $job_id . " AND mt_sort = 13");
         if ($self_service_discount == "") $self_service_discount = 0;
         if ($self_service_discount != 0) :
            $gross_price = $db->getOne("SELECT jbprc_remark FROM jobprice WHERE jb_id = " . $job_id . " AND mt_sort = 13");
            if ($gross_price == "") : $gross_price = 0; endif;
            $jobcosts .= "<tr><td class=\"f8np1\" colspan=\"" . (count($fieldArray) - 1) . "\">[" . getLngt("Selbsterfasserrabatt") . " (" . sprintf("%01.2f", $self_service_discount) . "% auf " . number_format(round($gross_price,2), 2, ",", ".") . "):</td><td class=\"f8np1\" align=\"right\">" . number_format($gross_price - round($gross_price * ((100-$self_service_discount)/100), 2), 2, ",", ".") . "]</td></tr>\n";
         endif;

         if ($job_markup != 0) :
            // $jobcosts .= "<tr><td>&nbsp;</td><td>&nbsp;</td></tr>";
            $jobcosts .= "<tr><td class=\"f8np1\" colspan=\"" . (count($fieldArray) - 1) . "\">[" . getLngt("Ohne Aufschlag") . " (" . $job_markup . "%):</td><td class=\"f8np1\" align=\"right\">" . number_format(round($job_subtotalprice,2), 2, ",", ".") . "]</td></tr>\n";
      
            $rawJobData .= "costs_" . "sum_withoutmarkup=" . number_format(round($job_subtotalprice,2), 2, ",", ".") . "|";
         endif;

         if (($automailer == "1" || $f_act == "mailsend") && $job_status == "2") :
            $csJbstatusmailFields = getFieldValueFromId("customer","cs_id",$csIdPayer,"cs_jbstatusmail_fields");
            if (substr($csJbstatusmailFields, 2, 1) == "1") :
               // Show invoice text in mail
               $jbInvoiceText = getFieldValueFromId("job", "jb_id", $job_id, "jb_invtext");
               $jbInvoiceText = nl2br(trim($jbInvoiceText));
               $jobcosts .= "<tr><td></td></tr>";
               $jobcosts .= "<tr><td valign=\"top\" bgcolor=\"#DDDDDD\">" . getLngt("Rechnungstext:") . "</td><td bgcolor=\"#EEEEEE\" colspan=\"" . (count($fieldArray) - 2) . "\">" . $jbInvoiceText  . "</td></tr>\n";
            endif;
         endif;
      else : 
         $jobcosts = "<tr><td colspan=\"3\">" . getLngt("KOSTEN") . ":</td></tr>";
         $jobcosts .= $tableHeader . $tableBody;
         $jobcosts .= "<tr><td class=\"f8np1_red\">" . $outSummationText . ":</td><td>&nbsp;</td><td class=\"f8np1_red\" align=\"right\">" . number_format(round($sumOfSummationField,2), 2, ",", ".") . "&nbsp;&nbsp;</td></tr>";
      endif;

      if ($jbToll != "") :
         $rawJobData .= "costs_" . "toll=" . $jbToll . "|";

         $rowArray = array();
         $rowArray[0]["col1"] = ""; $rowArray[0]["col2"] = ""; $rowArray[0]["col3"] = ""; $rowArray[0]["col4"] = "";
         $rowArray[0]["jb_toll_text"] = getLngt("Maut&nbsp;");
         $rowArray[0]["jb_toll_value"] = str_replace(".", ",", $jbToll);

         $fieldArray = array("col1","col2","col3","col4","jb_toll_text","jb_toll_value");
         $mode = "2";             // Output from MATRIX
         $sortDBField = "";       // Used in following include-file for sorting per column;
         include ("../include/inc_list_defineoutput.inc.php");
         $jobcosts .= "<tr><td>&nbsp;</td></tr>" . $tableBody;
         $jobcosts .= "<tr><td class=\"f8np1_red\" colspan=\"" . (count($fieldArray) - 1) . "\">" . getLngt("KUNDENPREIS") . ":</td><td class=\"f8np1_red\" align=\"right\">" . number_format(round($jbTotalSumWithToll,2), 2, ",", ".") . "&nbsp;&nbsp;</td></tr>\n";
      endif;

      if ($userTypeName != "cs") :   // ONLY headquarters and automailer
         // Add cartage in headquarters view
         if ($userTypeName == "hq" && $automailer == "0" && $f_act != "mailsend") : 
             // Check for finished jobs only
             $parCrPriceMode = getParameterValue("0", "MASK_CR_PRICE_MODE", $currentHqId);
             if ($parCrPriceMode == "1") :
                $tmpJbFinishtime = getFieldValueFromId("job","jb_id",$job_id,"jb_finishtime");
                $tmpJbVhtId = getFieldValueFromId("job","jb_id",$job_id,"vht_id");
                list($jbCrPrice, $jbCrPriceRate) = getCr_price_global($sumOfSummationField, $currentHqId, $csIdPayer, $tmpJbFinishtime, "", $tmpJbVhtId);
                if ($jbCrPrice == "" || !is_numeric($jbCrPrice)) : $jbCrPrice = 0; endif;
                $jbCrPrice = getFieldValueFromId("job","jb_id",$job_id,"jb_cr_price");
                $jb_cr_serviceprice = $db->getOne("SELECT jbprc_price FROM jobprice WHERE jb_id = " . $job_id . " AND mt_sort = 3");
                if (!is_numeric($jb_cr_serviceprice))
                   $jb_cr_serviceprice = 0;
                $jbCrPrice_without_service = $jbCrPrice;
                if ($jb_cr_serviceprice != ""):
                  $jbCrPrice_without_service = $jbCrPrice - $jb_cr_serviceprice;
                  $jb_cr_serviceprice = sprintf("%01.2f", $jb_cr_serviceprice);
                endif;
                $jbprc_cr_subtotal = $db->getOne("SELECT jbprc_price FROM jobprice WHERE jb_id = " . $job_id . " AND mt_sort = 10");
                if (!is_numeric($jbprc_cr_subtotal))
                   $jbprc_cr_subtotal = 0;
                $jbprc_cr_subtotal_inkl_agio = $jbprc_cr_subtotal - $jb_cr_serviceprice;
                if ($jbprc_cr_subtotal != "")
                  $jbprc_cr_subtotal = sprintf("%01.2f", $jbprc_cr_subtotal);
                $jbCrAgio = $db->getOne("SELECT jbprc_price FROM jobprice WHERE jb_id = " . $job_id . " AND mt_sort = 7");
                $jbCrAgioText = "";
                if ($jbCrAgio != ""):
//                  $jbprc_cr_subtotal_inkl_agio = $jbprc_cr_subtotal * (1 + ($jbCrAgio / 100));
//                  $jbCrAgio = sprintf("%01.2f", $jbCrAgio);
                    $jb_cr_price_rate = $db->getOne("SELECT jbprc_price FROM jobprice WHERE jb_id = " . $jb_id . " AND mt_sort = 5");
                    $jb_cr_price_rate_real = 0;
                    if ($jb_cr_price_rate > 0)
                      $jbCrAgioText = "Der Frachtvergütungsabschlag beträgt " . sprintf("%01.2f", $jb_cr_price_rate) . "% - " . sprintf("%01.2f", $jbCrAgio) . "% = " . sprintf("%01.2f", $jb_cr_price_rate - $jbCrAgio) . "%";
                endif;
                $jbprc_cr_markup = $db->getOne("SELECT jbprc_price FROM jobprice WHERE jb_id = " . $job_id . " AND mt_sort IN (1,9)");
                $jbprc_cr_subtotal_inkl_agio_and_markup = $jbprc_cr_subtotal_inkl_agio;
                if ($jbprc_cr_markup != ""):
                  $jbprc_cr_subtotal_inkl_agio_and_markup = $jbprc_cr_subtotal_inkl_agio * (1 + ($jbprc_cr_markup / 100));
                  $jbprc_cr_markup = sprintf("%01.2f", $jbprc_cr_markup);
                endif;
                $jobcosts .= "<tr><td class=\"f8np1_red\" colspan=\"" . (count($fieldArray) - 1) . "\">" . getLngt("FRACHTVERGÜTUNG") . ":</td><td class=\"f8np1_red\" align=\"right\">" . number_format($jbCrPrice, 2, ",", ".") . "&nbsp;&nbsp;</td></tr>\n";
                if ($jb_cr_serviceprice != "" && $jb_cr_serviceprice > 0):
                  $jobcosts .= "<tr><td class=\"f8np1\" colspan=\"" . (count($fieldArray) - 1) . "\">[" . getLngt("Ohne Service") . " (" . $jb_cr_serviceprice . " EUR):</td><td class=\"f8np1\" align=\"right\">" . number_format(round($jbprc_cr_subtotal_inkl_agio_and_markup,2), 2, ",", ".") . "]</td></tr>\n";
                endif;
                if ($jbprc_cr_markup != "" && $jbprc_cr_markup > 0):
                  $jobcosts .= "<tr><td class=\"f8np1\" colspan=\"" . (count($fieldArray) - 1) . "\">[" . getLngt("Ohne Aufschlag") . " (" . $jbprc_cr_markup . "%):</td><td class=\"f8np1\" align=\"right\">" . number_format(round($jbprc_cr_subtotal_inkl_agio,2), 2, ",", ".") . "]</td></tr>\n";
                endif;
//                if ($jbCrAgio != "" && $jbCrAgio > 0):
//                  $jobcosts .= "<tr><td class=\"f8np1\" colspan=\"" . (count($fieldArray) - 1) . "\">[" . getLngt("Ohne Kundenaufschlag") . " (" . $jbCrAgio . "%):</td><td class=\"f8np1\" align=\"right\">" . number_format($jbprc_cr_subtotal, 2, ",", ".") . "]</td></tr>\n";
                if ($jbCrAgioText != ""):
                  $jobcosts .= "<tr><td class=\"f8np1\" colspan=\"" . (count($fieldArray) - 1) . "\">[" . $jbCrAgioText . "]</td></tr>\n";
                endif;
                if ($db->getOne("SELECT jb_id FROM job AS jb, genericdatacontainer AS gdc WHERE jb_id = " . $jb_id . " AND jb_id = gdc_obj_id AND gdc_obj_type = 'jb' AND gdc_gen_fieldname = 'jb_cr_price_retour' AND gdc_context = ''") == $jb_id):
                  $jb_cr_price_retour = $db->getOne("SELECT gdc_content FROM job AS jb, genericdatacontainer AS gdc WHERE jb_id = " . $jb_id . " AND jb_id = gdc_obj_id AND gdc_obj_type = 'jb' AND gdc_gen_fieldname = 'jb_cr_price_retour' AND gdc_context = ''");
                  $jb_cr_price_retourArr = explode("|", $jb_cr_price_retour);
                  $jobcosts .= "<tr><td class=\"f8np1_red\" colspan=\"" . (count($fieldArray) - 1) . "\">" . getLngt("Frachtvergütung bei BWV-Anschluss") . ":</td><td class=\"f8np1_red\" align=\"right\">" . number_format($jb_cr_price_retourArr[0], 2, ",", ".") . "&nbsp;&nbsp;</td></tr>\n";
                  $jobcosts .= "<tr><td class=\"f8np1\" colspan=\"" . (count($fieldArray) - 1) . "\">[" . getLngt("Ohne Aufschlag") . " (" . $jbprc_cr_markup . "%):</td><td class=\"f8np1\" align=\"right\">" . number_format($jb_cr_price_retourArr[1], 2, ",", ".") . "]</td></tr>\n";
                endif;
                if ($db->getOne("SELECT jb_id FROM tourservice WHERE jb_id = " . $jb_id . " AND trs_srvt_name = 'z'") == $jb_id &&
                    $db->getOne("SELECT jb_id FROM phoenix_log.route WHERE jb_id = " . $jb_id) == $jb_id):
                  $jobcosts .= "<tr><td class=\"f8np1\" colspan=\"" . (count($fieldArray)) . "\"><br><a href=\"../locating/map_pzm.php?jb_id=" . $jb_id . "\" target=\"_blank\">" . getLngt("Route der PZM-Preisberechnung") . "</a></td></tr>\n";
                endif;
             endif;
         endif;
      endif;
   endif;

   // Store number of stations of the tour
   $rawJobData .= "tr_numberofstations=" . mcIsSet($tr_numberofstations, 0);

   
   $jbParState = "job_status=".$job_status."|"."job_tourname=".$job_tourname."|"."job_export_time=".$job_export_time."|"
               . "job_reserv=".$job_reserv."|"."job_incomplete=".$job_incomplete."|"."job_cr_sid=".$job_cr_sid."|"
               . "job_longhaul=".$job_longhaul."|"."job_id_parent=".$job_id_parent."|"."job_subtotalprice=".$job_subtotalprice."|"
               . "job_markup=".$job_markup."|"."job_ordertime=".$job_ordertime."|"."jobCourierId=".$jobCourierId."|"
               . "cscIdPayer=".$cscIdPayer."|"."csIdPayer=".$csIdPayer."|"."jobCourierId=".$jobCourierId."|"
               . "job_cr_sid=".$job_cr_sid;
   
   if ($retMode == "1") :
      $retVal = array($rawJobData, $jbParState);
   else :
      $retVal = $jbParState;
   endif;

	 return $retVal;
}


// If job ($job_id) is exported, then look for existing content in DB field "jb_history_data"
function checkForTakingRealOrHistoricJobData ($mode = "") {
   global $db, $dbhostJob2History, $job_id, $hq_id, $userTypeName, $outputFormatField, $f_act, $automailer;
   global $historicJobParameterState, $jobentry, $tourentry, $jobcosts, $courierentry, $employeeentry;

   $takeRealJobData = true;
   $jbHistoryData = "";
   $jbHistoryRawData = "";
   if (true) :
      $jbExportTime = getFieldValueFromId("job", "jb_id", $job_id, "jb_export_time");      
      if ($jbExportTime != "" && $jbExportTime != "0000-00-00 00:00:00") :

         $db_conn = $db;
         $job2Name = "job2";
         $jbExportTimeYear = substr($jbExportTime, 0, 4);
         $currentYear = getDateTime("year");
         if ($jbExportTimeYear >= "2010" && $jbExportTimeYear < $currentYear) :
            $job2Name = "job2_" . $jbExportTimeYear;
            // Check existence in separate "job2" table of the requested year, otherwise reset name
            // $db_conn = $db;
            if ($dbhostJob2History != "") :
               global $dbname, $dblogin, $dbpassword;
               $db_conn = getDbConnectionSpecial($dbhostJob2History, $dbname, $dblogin, $dbpassword);
               // if ($db_conn == "ERR_DB") : $db_conn = $db; endif;
               if (!is_object($db_conn) || $db_conn == "") : $db_conn = $db; endif;
            endif;
            $jb2Exist = $db_conn->getOne("SELECT jb_id FROM " . $job2Name . " WHERE jb_id = '" . $job_id . "'");
            if ($jb2Exist == "" || $jb2Exist == "NULL") : 
               $job2Name = "job2";
               $db_conn = $db;
            endif;
         endif;

         // Take historic job data
         if ($mode == "0") :
            $jbHistoryRawData = getFieldValueFromId($job2Name, "jb_id", $job_id, "jb2_history_rawdata", $db_conn);
         elseif ($mode == "1") :
            if ($f_act == "mailsend") :
               $jbHistoryData = getFieldValueFromId($job2Name, "jb_id", $job_id, "jb2_history_mail", $db_conn);
            else :
               $jbHistoryData = getFieldValueFromId($job2Name, "jb_id", $job_id, "jb2_history_hq", $db_conn);
            endif;
         elseif ($mode == "2") :
            $jbHistoryData = getFieldValueFromId($job2Name, "jb_id", $job_id, "jb2_history_cs", $db_conn);
         else :
            $jbHistoryData = getFieldValueFromId($job2Name, "jb_id", $job_id, "jb2_history_hq", $db_conn);
         endif;
         // Uncompress historic data
         // $jbHistoryRawData = uncompress($jbHistoryRawData, $uncompressRawFunc);
         // $jbHistoryData    = uncompress($jbHistoryData, $uncompressFunc);
         if ($mode == "0") :
            if (substr(phpversion(), 0, 1) >= "5") :
               // $jbHistoryRawData = gzuncompress($jbHistoryRawData);
               $jbHistoryRawData = gzinflate($jbHistoryRawData);
            else :
               // $jbHistoryRawData = gzuncompress(substr($jbHistoryRawData,4));
               $jbHistoryRawData = getFieldValueFromId($job2Name, "jb_id", $job_id, "UNCOMPRESS(jb2_history_rawdata)", $db_conn);
            endif;            
         else :
            if ($jbHistoryData != "") :
               $jbHistoryData = gzinflate($jbHistoryData);
            endif;
         endif;
         // Get historic html data from the job according to the mode
         if (trim($jbHistoryData) != "") :
            $jbHistoryData = str_replace("SIGNS_PATH", "../temp/signs/", $jbHistoryData);
            $jbHistoryData = str_replace("\'", "'", $jbHistoryData);
            $jbHistoryDataArray = spliti("-;-", $jbHistoryData);
            if (count($jbHistoryDataArray) > 0) :
               $historicJobParameterState = $jbHistoryDataArray[0];
               $jobentry        = $jbHistoryDataArray[1];
               $tourentry       = $jbHistoryDataArray[2];
               $jobcosts        = $jbHistoryDataArray[3];
               $courierentry    = $jbHistoryDataArray[4];
               $employeeentry   = $jbHistoryDataArray[5];
               $takeRealJobData = false;
               $historicJobParameterState = str_replace("|", "-,-", $historicJobParameterState);
               $historicJobParameterArray = spliti("-,-", $historicJobParameterState);
               $historicJobParameterArrayLen = count($historicJobParameterArray);
               for ($l = 0; $l < $historicJobParameterArrayLen; $l++) :
                   $singleJobParameterArray = spliti("=", $historicJobParameterArray[$l]);
                   global ${$singleJobParameterArray[0]};
                   ${$singleJobParameterArray[0]} = trim($singleJobParameterArray[1]);                   
               endfor;
            endif;
         endif;
         // Get historic raw data from the job
         if (trim($jbHistoryRawData) != "") :
            $takeRealJobData = false;
            // Parse raw job data and set all global parameters            
            $jbHistoryRawData = str_replace("|", "-,-", $jbHistoryRawData);
            $jbHistoryRawDataArray = spliti("-,-", $jbHistoryRawData);
            $jbHistoryRawDataArrayLen = count($jbHistoryRawDataArray);
            for ($l = 0; $l < $jbHistoryRawDataArrayLen; $l++) :
                $singleJobParameterArray = spliti("=", $jbHistoryRawDataArray[$l]);
                global ${$singleJobParameterArray[0]};
                ${$singleJobParameterArray[0]} = trim($singleJobParameterArray[1]);
            endfor;
         endif;
      endif;
   endif;

	 return $takeRealJobData;
}
?>
