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


if (!isset($automailer) || $automailer != "1") :
   include_once ("../include/services_func.inc.php");
   include_once ("../include/mcglobal.inc.php");
   $noExecGlobDefs = "1";
   include_once ("../include/auth.inc.php");
   include_once ("../include/image.inc.php");
   // include_once ("../include/email.inc.php");
   $automailer = "0";
   $currentHqId = $hq_id;
   
   // Check for authentication access and granted rights
   $usrAccessArray["hq"] = "1";
   authCheckForAccess($currentHqId, $usr_id, $emp_id, "1", $customerId, $cscIdRoot, $cscIdActual);
else :
   $hq_id = HQ_ID_DEFAULT;
   if ($hq_id == "") : $hq_id = "1"; endif;
   $automailer = "1";
endif;
if ($currentHqId == "" || !is_numeric($currentHqId)) : die ("$PHP_SELF: Headquarter fails!"); endif;

// Define global parameters
defineGlobalParameters($currentHqId);

// Check HTTP-Parameters
if ($automailer == "0") :
   getSecHttpVars("1",array("f_act", "customerId", "cscIdRoot", "cscIdActual", "empIdMaster", "job_id", "dbhistory",
                            "f_email", "f_crvh_sid_book", "f_crvh_sid_order", "f_crvh_sid_order_permanent", 
                            "f_tourname", "f_jb_incomplete", "f_jb_finishtime4booking", "f_jb_freetext_3_new",
                            "useRemoteDB"));
   
   // Check global setting for default bookjob date
   if ($f_jb_finishtime4booking == "") :
      $constFinishtime4booking = getParameterValue("0", "MASK_JOBDETAILS_BOOKJOB_DATE", $hqId);
      if ($constFinishtime4booking == "1") :
         $f_jb_finishtime4booking = "1";
      else :
         $f_jb_finishtime4booking = "0";
      endif;
   endif;
endif;

// Decision to use the job archive or normal tables
getDBNames($dbhistory);

// Get usr_id of the current employee (session)
$currentSessionUsrId = getFieldValueFromId("employee", "emp_id", $emp_id, "usr_id");

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

// ******************************************************
// Very special treatment for access to remote database
include_once ("../include/bwv.inc.php");
$remoteDBisActive = false;
if (BWV2_checkEmpRemoteDBAccess($useRemoteDB, $emp_id)) :
   $remoteDBisActive = BWV2_setRemoteDBAccessParameter();
endif;
$constLonghaulActive = "";
if ($remoteDBisActive) :   
   if ($f_hq_id == "") : $f_hq_id = array(); endif;
   if (count($f_hq_id) == 0) : array_push($f_hq_id, getMinOfField("headquarters", "hq_id", "")); endif;
   $constLonghaulActive = getParameterValue("0", "LONGHAUL_ACTIVE_REMOTE_DB", "0");
endif;
// ******************************************************

   // --- TEMPLATE ----------------
   
   if ($automailer == "0") :
      // Initiate template-object
      if ($f_act == "printjob") :
         $tpl = new IntegratedTemplate(); 
         $tpl->loadTemplatefile("../longhaul/jb_detail_print.tpl.htm", true, true);
      else :
         $tpl = new IntegratedTemplate(); 
         $tpl->loadTemplatefile("../longhaul/jb_detail.tpl.htm", true, true);
      endif;
      
      // Identification-parameters
      $tpl->setCurrentBlock("dbhistory"); $tpl->setVariable("_dbhistory_", $dbhistory); $tpl->parseCurrentBlock("dbhistory");
      $tpl->setCurrentBlock("jobId"); $tpl->setVariable("_jobId_", ec($job_id)); $tpl->parseCurrentBlock("jobId");
      $tpl->setCurrentBlock("customerId"); $tpl->setVariable("_customerId_", ec($customerId)); $tpl->parseCurrentBlock("customerId");
      $tpl->setCurrentBlock("cscIdRoot"); $tpl->setVariable("_cscIdRoot_", ec($cscIdRoot)); $tpl->parseCurrentBlock("cscIdRoot");
      $tpl->setCurrentBlock("cscIdActual"); $tpl->setVariable("_cscIdActual_", ec($cscIdActual)); $tpl->parseCurrentBlock("cscIdActual");
      $tpl->setCurrentBlock("empIdMaster"); $tpl->setVariable("_empIdMaster_", ec($empIdMaster)); $tpl->parseCurrentBlock("empIdMaster");
      $tpl->setCurrentBlock("useRemoteDB"); $tpl->setVariable("_useRemoteDB_", $useRemoteDB); $tpl->parseCurrentBlock("useRemoteDB");
   endif;


   // --- JOB -------------------
   
   // Initialize
   if ($f_act == "mailsend" || $f_act == "printjob") :
      $titles = "Nr.,Fahrzeug,Auftragszeit,Annahme,Erledigung";
      $fields = "jb_id,vht_value,jb_ordertime,jb_taketime,jb_finishtime";
   else :
      $titles = "Nr.,Tourenname,Kostenstelle,Fahrzeug,Auslage,Gewicht,Auftragszeit,Reservierung,Dauerauftrag,Anforderung,Permanente Anford.,Storno,Spät.Annahmez.,Annahme,Erledigung,Filter,Opt. Filter,Dispo-Info";
      $fields = "jb_id,jb_tourname,csc_name,vht_value,jb_outlay,jb_weight,jb_ordertime,jb_reserv,jb_permanent,cr_sid,cr_id_permanent,jb_storno,jb_latesttaketime,jb_taketime,jb_finishtime,jb_cr_filter,jb_cr_filter_opt,jb_dispoinfo";
   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("jobstatus") . "," . getDBFields("jb_latesttaketime");
   $fieldClause .= ", srvpt.srvpt_traveltime ";

   // Check for existing costcenter
   if ($job_csc_id != "0") : $fieldClause .= "," . getDBFields("costcenter"); endif;
   
   $fromClause = $dbh_jb . " AS jb, metatype AS vht, metatype AS jbs ";
   if ($job_csc_id != "0") : $fromClause .= ", costcenter AS csc "; endif;
   
   // Additional joins e.g. for traveltime to startaddress
   $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 ";

   // $whereClause = "jb.hq_id = " . $currentHqId . " AND ";
   $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 = "";             
   
   $sqlqueryJob = generateStatement($fieldClause,$fromClause,$whereClause,$orderByClause);

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

   // Job-data
   $jobentry = "";
   $jobCourierId = "";
   $job_usr_id = "";
   $job_status = "";
   $job_cr_sid = "";
   $job_longhaul = "";
   while ($row = $result->fetch_assoc()):
         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 (trim($titlesArray[$i]) == "") : $titlesArray[$i] = "&nbsp;"; endif;
             $jobentry .= "<tr>";
             $jobentry .= "<td bgcolor=\"" . $cellColor2 ."\" align=\"left\">" . $titlesArray[$i] . "</td>";
             $tmpVarName = $fieldsArray[$i];
             ${$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];

             // Get the current courier-ID of the job
             // if ($tmpVarName == "cr_id") : $jobCourierId = $row[cr_id]; endif;
             $jobCourierId = $row[cr_id];
             
             // 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;
                          
             if ($showCol) :
                $out = formatOutput(${$tmpVarName},$outputFormatField[$tmpVarName]);
                
                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 = "St.m.K.";
                      elseif (${$tmpVarName} == "2") :
                         $out = "St.o.K.";
                      endif;
                   endif;
                endif;                
             
                if ($tmpVarName == "csc_name" && $job_csc_id == "0") :
                   $out = "Zentrale";
                endif;                                    
                
                $jobentry .= "<td bgcolor=\"" . $cellColor ."\" align=\"left\">" . $out . "</td>";
             endif;
             $jobentry .= "</tr>";
         endfor;         

         // Link to copy the job and link to history
         /*
         if ($f_act != "mailsend" && $f_act != "printjob") :
            $jobentry .= "<tr><td><br>";
            $jobentry .= "<a href=\"../jobs/job_edit.php?jb_id=" . ec($job_id) . "&jb_copy=true&dbhistory=" . ec($dbhistory) . "\" target=\"_blank\">Auftrag kopieren</a><br><br>";
            $jobentry .= "<a href=\"../longhaul/jb_history.php?history_mode=" . ec(2) . "&job_id=" . ec($job_id) . "&op=0&dbhistory=" . ec($dbhistory) . "\" target=\"_blank\">Auftragshistorie</a>";
            // $jobentry .= "<a href=\"javascript:popupWindow('../longhaul/jb_history.php?history_mode=" . ec(2) . "&job_id=" . ec($job_id) . "&op=0&dbhistory=" . ec($dbhistory) . "','Auftrag','scrollbars=yes,width=950,height=700');\">Auftragshistorie</a>";
            $jobentry .= "</td></tr>";
         endif;
         */
   endwhile;
   $result->free();

   if ($automailer == "0") :
      $tpl->setCurrentBlock("jobentry");
      $tpl->setVariable("_jobentry_", $jobentry);
      $tpl->parseCurrentBlock("jobentry");	 
   endif;


   // --- TOUR ------------------
   
   // initialize
   if ($f_act == "mailsend" || $f_act == "printjob") :
      $titles = "Firma,,Person,Straße + Hausnr.,PLZ + Ort,EID,Kostenstelle,Tel.,Kommissionsnummer,Erledigungszeit,Klartext,Unterschrift";
      $fields = "tr_comp,tr_comp2,tr_person,ad_street_hsno,ad_zipcode_city,cs_eid,csc_name,tr_phone,tr_commission_no,tr_finishtime,tr_signname,tr_sign";
   else :
      $titles = "Firma,,Person,Straße + Hausnr.,PLZ + Ort,Tel. (Kunde),Email (Kunde),EID,Kostenstelle,Tel.,Bemerk,Kommissionsnummer,Erledigungszeit,Status,Klartext,Unterschrift";
      $fields = "tr_comp,tr_comp2,tr_person,ad_street_hsno,ad_zipcode_city,usr_phone,usr_email,cs_eid,csc_name,tr_phone,tr_remark,tr_commission_no,tr_finishtime,tr_status,tr_signname,tr_sign";
   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 ";
   $fromClause = $dbh_tr . " AS tr, 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 ";


   $sqlqueryTour = generateStatement($fieldClause,$fromClause,$whereClause,$orderByClause);

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

   // Tour-data
   $tourentry = "";
   $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 (trim($titlesArray[$i]) == "") : $titlesArray[$i] = "&nbsp;"; endif;
             $tourentry .= "<tr>";
             if ($rowCounter == 1) :
                $tourentry .= "<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 = $fieldsArray[$i];
             ${$tmpVarName} = $row[$tmpVarName];
             $out = formatOutput(${$tmpVarName},$outputFormatField[$tmpVarName]);

             // Customer-sign
             if ($tmpVarName == "tr_sign") :
                if ($row[tr_sign] != "") :
                   $rawCoord = splitRawCoordinates ($row[tr_sign]);
                   $maxCoord = checkMaxCoordinates($rawCoord);
                   
                   if ($f_act == "mailsend") :
                      $tmpSignPath = "../temp/signs/";
                      if (SIGNS_PATH != "") : $tmpSignPath = SIGNS_PATH; endif;                   
                      $imgFilename = $tmpSignPath . $job_id . "_" . $row[tr_sort] . ".png";
                      $imgFilenames[] = $imgFilename;
                      $im = createSignImage($rawCoord);
                      imagepng ($im, $imgFilename);
                      
                      $out = "<img src=\"" . $imgFilename . "\" border=\"0\" height=\"" . $maxCoord[1] . "\" width=\"" . $maxCoord[0] . "\">";
                   else :
                      $out = "<a href=\"../admin/jb_detail_sign.php?jb_id=" . ec($job_id) . "&tr_sort=" . ec($row[tr_sort]) . "&dbhistory=" . ec($dbhistory) . "\" target=\"_blank\">"
                              . "<img src=\"../admin/jb_detail_sign2.php?tr_sign=" . $row[tr_sign] . "\" border=\"0\" height=\"" . $maxCoord[1] . "\" width=\"" . $maxCoord[0] . "\">"
                              . "</a>";
                   endif;
                endif;
             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 = "offen"; break;
                   case "1" : $out = "erledigt"; break;
                };
             endif;         
             
             // Finishtime of the stop
             if ($tmpVarName == "tr_finishtime") :
                if (substr($tr_finishtime,0,4) == "1970") :
                   $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;             

             $tourentry .= "<td bgcolor=\"" . $cellColor ."\" align=\"left\">" . $out . "</td>";
             $tourentry .= "</tr>";             
         endfor;         
         $tourentry .= "</table></td>";         
   endwhile;
   $result->free();

   // Output of the whole tour
   if ($automailer == "0") :
      // if ($rowCounter > 1) :
          $tpl->setCurrentBlock("tourentry");
          $tpl->setVariable("_tourentry_", $tourentry);
          $tpl->parseCurrentBlock("tourentry");	 
      // endif;
   endif;   

   
   // --- COURIER ------------------
   
   // Initialize for template-output
   $courierentry = "";
 
   if ($jobCourierId != "") :
      // initialize
      if ($f_act == "mailsend" || $f_act == "printjob") :
         $titles = "Name,Vorname,SID";
         $fields = "usr_name,usr_firstname,cr_sid";
      else :
         $titles = "Firma,,Name,Vorname,Tel.,Tel.2,SID,ExtID,Kennz.,Online,Nutzlast,L x B x H,Fahrzeugfilter";
         $fields = "cmp_comp,cmp_comp2,usr_name,usr_firstname,usr_phone,usr_phone2,cr_sid,cr_eid" . ($job_cr_sid != "" ? ",crvh_vh_sign" : "") . ",cr_available" . ($job_cr_sid != "" ? ",crvh_payload" : "") . ($job_cr_sid != "" ? ",crvh_measures" : "")  . ($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) 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);

      // 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 (trim($titlesArray[$i]) == "") : $titlesArray[$i] = "&nbsp;"; endif;
                $courierentry .= "<tr>";
                $courierentry .= "<td bgcolor=\"" . $cellColor2 ."\" align=\"left\">" . $titlesArray[$i] . "</td>";             
                $tmpVarName = $fieldsArray[$i];
                ${$tmpVarName} = $row[$tmpVarName];
                $out = formatOutput(${$tmpVarName},$outputFormatField[$tmpVarName]);

                // 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 = "nicht online"; break;
                      case "1" : $out = "online"; break;
                   };
                endif;             
		
		if ($tmpVarName == "crvh_filter") :
                      $tmpFilterStr = $out;
                      $out = substr($out, 1, -1);
                      $out = my_str_replace ($out, ",", "<br>", "5");
                      // $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 .= "<br><a href=\"../admin/filter.php?f_crvh_filter_str=" . $tmpFilterStr . "&actionMode=0&deactivateMenu=1&readonly=1\" target=\"_blank\">" . getLngt("Filterübersicht") . "</a>";
                endif;

             
                $courierentry .= "<td bgcolor=\"" . $cellColor ."\" align=\"left\">" . $out . "</td>";
                $courierentry .= "</tr>";             
            endfor;
            
            // Link to copy the job and link to history
            /*
            if ($f_act != "mailsend" && $f_act != "printjob") :
               $courierentry .= "<tr><td><br>";
               $courierentry .= "<a href=\"../longhaul/cr_history.php?cr_id=" . ec($jobCourierId) . "&op=0\" target=\"_blank\">Kurierhistorie</a>";
               $courierentry .= "</td></tr>";
            endif;
            // $courierentry .= "</table></td>";         
            */
      endwhile;
      $result->free();   
   endif;
   
   // Check for global mediation
   if ($f_act != "mailsend" && $f_act != "printjob") :
      if ($job_longhaul == "1" && !authCheckEmployeeRights($emp_id, "10")) :
         $courierentry = "<tr><td class=\"f8np1_red\">FERNTOUR</td></tr>";
      endif;
   endif;
   
   // Output of the courier-data
   if ($automailer == "0") :
      $tpl->setCurrentBlock("courierentry");
      $tpl->setVariable("_courierentry_", $courierentry);
      $tpl->parseCurrentBlock("courierentry");
   endif;



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

   // Initialize for template-output
   $employeeentry = "";

   // 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 = "Name,Vorname,Telefon,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);

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

         // Courier-data      
         $employeeentry .= "<tr><td>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 (trim($titlesArray[$i]) == "") : $titlesArray[$i] = "&nbsp;"; endif;
                   $employeeentry .= "<tr>";
                   $employeeentry .= "<td bgcolor=\"" . $cellColor2 ."\" align=\"left\">" . $titlesArray[$i] . "</td>";             
                   $tmpVarName = $fieldsArray[$i];
                   ${$tmpVarName} = $row[$tmpVarName];
                   $out = formatOutput(${$tmpVarName},$outputFormatField[$tmpVarName]);

                   $employeeentry .= "<td bgcolor=\"" . $cellColor ."\" align=\"left\">" . $out . "</td>";
                   $employeeentry .= "</tr>";             
               endfor;         
               // $employeeentry .= "</table></td>";         
         endwhile;
         $result->free();   
      endif;

   else :   // Display history of employees

      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 logo.logo_id IN (1,2,5,10,13,14,15,16,17,18,19,20,21,22,23,25,26,32)";
         $orderByClause = "log.log_createtime";      
      endif;

      $sqlqueryUser = generateStatement($fieldClause,$fromClause,$whereClause,$orderByClause);

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

      // Generate list with header
      $titleArray = array("Vorgang&nbsp;","Zeitpunkt&nbsp;","Name&nbsp;","Vorname&nbsp;","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\">MITARBEITER:</td></tr>";
      $employeeentry .= $tableHeader . $tableBody;

      $result->free();
   endif;
   
   // Output of the courier-data
   if ($automailer == "0") :
      $tpl->setCurrentBlock("employeeentry");
      $tpl->setVariable("_employeeentry_", $employeeentry);
      $tpl->parseCurrentBlock("employeeentry");
   endif;

      
   // --- JOB-COSTS ------------------
   /*
   $jobcosts = "<tr><td>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>";
   */

   
   // Get the persistent tourservice data 
   $fieldString = getDBFields("tourservice");
   /*
   $sqlqueryCosts = "SELECT " . $fieldString . ",csc.csc_name, (trs.trs_price * ((100 - trs.trs_discount) / 100)) AS business_volume"
                  . " 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";
   */
   $sqlqueryCosts = "SELECT " . $fieldString . ",csc.csc_name, cscad.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"
                  . " 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"
                  . " WHERE trs.jb_id = '" . $job_id . "'"
                  . " ORDER BY trs.csc_id, trs.tr_sort";

   $result = $db->query($sqlqueryCosts);
   if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage() . ": " . $sqlqueryCosts);
   
   // Generate list with header
   $titleArray = array("Kostenstelle&nbsp;","Tel.&nbsp;","EID&nbsp;","Kunde","Leistung&nbsp;","Betrag");
   $fieldArray = array("csc_name","cscad_phone","cs_eid","cmp_comp","trs_srv_name","business_volume");
   $aligns = "l,l,l,l,l,r";
   
   $alignArray = spliti(",",$aligns);
   $alignTitles = "left";
   $widths = "150,120,50,150,0";
   $widthArray = spliti(",",$widths);
   $summationField = "business_volume";
   $mode = "1";             // Output from DB-RESULT
   $sortDBField = "";       // Used in following include-file for sorting per column;
   include ("../include/inc_list_defineoutput.inc.php");
   // $jobcosts = "<tr><td colspan=\"" . (count($fieldArray)) . "\">KOSTEN:</td></tr>\n";
   $jobcosts .= $tableHeader . $tableBody;
   $jobcosts .= "<tr><td class=\"f8np1_red\" colspan=\"" . (count($fieldArray) - 1) . "\">GESAMTSUMME:</td><td class=\"f8np1_red\" align=\"center\">" . number_format(round($sumOfSummationField,2), 2, ",", ".") . "</td></tr>\n";


   // Output of the job-costs
   if ($automailer == "0") :
      $tpl->setCurrentBlock("jobcosts");
      $tpl->setVariable("_jobcosts_", $jobcosts);
      $tpl->parseCurrentBlock("jobcosts");
   endif;
   

   // --- FAVOURED COURIERS OF THE CUSTOMER (ONLY PAYER !!!) ASSOCIATED TO THE JOB ---------------
   $jobFavouredCouriers = "";   
   if ($job_id != "") :
      
      // Get vehicle type of the job
      $jbVhtId = getFieldValueFromId($dbh_jb, "jb_id", $job_id, "vht_id");

      // Check first job is a cashpayer one
      $cscIdPayer = getFieldValueFromId($dbh_jb, "jb_id", $job_id, "csc_id_payer");

      if (($cscIdPayer != "") && ($cscIdPayer == CSC_ID_PAYER_CASH || $cscIdPayer == "-1" )) :
         // Job is cashpayer one => Get id of the cashpayer
         $tmpSqlquery = "SELECT DISTINCT cscr.cr_id, cr.cr_sid, cr.vht_id"
                        . " FROM " . $dbh_jb . " AS jb, costcenter AS csc, customercourier AS cscr, courier AS cr"
                        . " WHERE jb.jb_id = '" . $job_id . "'        AND"
                        . "       jb.csc_id_payer_cash = csc.csc_id   AND"
                        . "       csc.cs_id = cscr.cs_id              AND"
                        . "       cscr.cr_id = cr.cr_id               AND"
                        . "       cscr.cscr_relation = '1'"
                        . " ORDER BY cscr.cscr_sort";
                        // . "       cr.vht_id >= '" . $jbVhtId . "'  AND"
      else :
         // Job is an invoice one
         $tmpSqlquery = "SELECT DISTINCT cscr.cr_id, cr.cr_sid, cr.vht_id"
                        . " FROM " . $dbh_trs . " AS trs, costcenter AS csc, customercourier AS cscr, courier AS cr"
                        . " WHERE trs.jb_id = '" . $job_id . "'   AND"
                        . "       trs.csc_id = csc.csc_id         AND"
                        . "       csc.cs_id = cscr.cs_id          AND"
                        . "       cscr.cr_id = cr.cr_id           AND"
                        . "       cscr.cscr_relation = '1'"
                        . " ORDER BY cscr.cscr_sort";
                        // . "       cr.vht_id >= '" . $jbVhtId . "' AND"
      endif;

      $result = $db->query($tmpSqlquery);
      if (DB::isError($result)) die ("$PHP_SELF 5: {$tmpSqlquery} " . $result->getMessage() . ": " . $tmpSqlquery);
      $jobFavouredCouriersMatchingVehicle = "";
      $jobFavouredCouriersNotMatchingVehicle = "";
      while ($row = $result->fetch_assoc()):
            if ($row["vht_id"] >= $jbVhtId) :
               $jobFavouredCouriersMatchingVehicle .= $row["cr_sid"] . "&nbsp;&nbsp;&nbsp;";
            else :
               $jobFavouredCouriersNotMatchingVehicle .= $row["cr_sid"] . "&nbsp;&nbsp;&nbsp;";
            endif;
      endwhile;
      $result->free();
   endif;
   
   $jobFavouredCouriers = "<tr><td colspan=\"2\">EINGETRAGENE BEVORZUGTE KURIERE:</td></tr>\n" .
                          "<tr><td>Mit passenden Fahrzeugen: </td><td>&nbsp;&nbsp;" . $jobFavouredCouriersMatchingVehicle . "</td></tr>\n" .
                          "<tr><td>Restliche: </td><td>&nbsp;&nbsp;" . $jobFavouredCouriersNotMatchingVehicle . "</td></tr>\n";
   
   // Output of the favoured couriers
   if ($automailer == "0") :
      $tpl->setCurrentBlock("jobFavouredCouriers");
      $tpl->setVariable("_jobFavouredCouriers_", $jobFavouredCouriers);
      $tpl->parseCurrentBlock("jobFavouredCouriers");
   endif;


   // --- SEND MAIL ---------------
   if ($job_status == "2" || $mailTextJobStatus != "") :

      $mailsend = "";
      $mailsendStatus = "&nbsp;&nbsp;&nbsp;";
   
      if ($f_act == "mailsend") :
      
         if (checkEmailFormat($f_email)) :
      
            if ($automailer == "0") :   
               include_once ('../include/email/htmlMimeMail.php');
            endif;
            $mailObj = new htmlMimeMail();

            $mailtext  = "<html><head><meta text/html>";
            $mailtext .= "<style type=\"text/css\">";
            $mailtext .= ".f8np1 { font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 8pt; font-weight: normal; padding: 1px}";
            $mailtext .= ".f8bp1 { font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 8pt; font-weight: bold; padding: 1px}";
            $mailtext .= ".f8np1_red { font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 8pt; font-weight: normal; padding: 1px; color: #FF0000;}";
            $mailtext .= "</style>";
            $mailtext .= "</head><body><h4>";
            
            $mailtext .= "<div class=\"f8bp1\">Sehr geehrte Damen und Herren,</div><br>";
            if ($mailTextJobStatus == "1") :
               $mailtext .= "<div class=\"f8bp1\">Die Abholung der Ware erfolgte.</div>";
            elseif ($mailTextJobStatus == "8" || $mailTextJobStatus == "9") :
               $mailtext .= "<div class=\"f8bp1\">Ihr Transportauftrag befindet sich in der Vermittlung.</div>";
            else :
               $mailtext .= "<div class=\"f8bp1\">Ihr Transportauftrag wurde ausgeführt.</div>";
            endif;
            $mailtext .= "<div class=\"f8bp1\">Anbei übersenden wir Ihnen die Auftragsdaten.</div><br>";
            $mailtext .= "<div class=\"f8bp1\">Mit freundlichem Gruß,</div>";
            $mailSalutationText = getParameterValue("0", "MAIL_SALUTATION_TEXT", $currentHqId);
            $mailtext .= "<div class=\"f8bp1\">" . $mailSalutationText . "</div><br>";

            // LOGO
            $logoName = getParameterValue("0", "IMG_LOGO_NAME", $currentHqId);
            $logoHeight = getParameterValue("0", "IMG_LOGO_HEIGHT", $currentHqId);
            $logoWidth = getParameterValue("0", "IMG_LOGO_WIDTH", $currentHqId);
            if ($logoName != "" && $logoHeight != "" && $logoWidth != "") :
               $mailtext .= "<br><div><img src=\"../images/external/" . $logoName . "\" border=\"0\" height=\"" . $logoHeight . "\" width=\"" . $logoWidth . "\"></div><br><br>";
            endif;
            
            // Current date
            $mailtext .= "<div class=\"f10bp1\">Transportdatum: " . getDateTime(5) . "</div><br><br>";

            $mailtext .= "<table><tr><td valign=\"top\">";
            $mailtext .= "<span class=\"f8bp1\">AUFTRAG:</span><br>";
            $mailtext .= "<table class=\"f8np1\">" . $jobentry . "</table><br>";
            $mailtext .= "</td><td>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td><td valign=\"top\">";
            if ($courierentry != "" && $mailTextJobStatus != "0" && $mailTextJobStatus != "8" && $mailTextJobStatus != "9") :
               $mailtext .= "<span class=\"f8bp1\">TRANSPORTEUR:</span><br>";
               $mailtext .= "<table class=\"f8np1\">" . $courierentry . "</table><br>";
            endif;
            $mailtext .= "</td></tr></table>";
            if ($tourentry != "") :
               $mailtext .= "<span class=\"f8bp1\">TOUR:</span><br>";
               $mailtext .= "<table class=\"f8np1\">" . $tourentry . "</table><br>";
            endif;
            if ($jobcosts != "") :
               $mailtext .= "<span class=\"f8bp1\">KOSTEN:</span><br>";
               $mailtext .= "<table class=\"f8np1\">" . $jobcosts . "</table><br>";
            endif;
            $mailtext .= "</body></html>";

            $mailObj->setHtml($mailtext, null, "./");
            // $mailObj->setHtml($mailtext);

            // Set From address
            $mailObj->setFrom(MAIL_SENDER_ADDRESS);

            // Set Cc address
            $mailCcAddress = getParameterValue("0", "MAIL_CC_ADDRESS", $currentHqId);
            if ($mailCcAddress == "" || !checkEmailFormat($mailCcAddress)) :
               $mailCcAddress = MAIL_CC_ADDRESS;
            endif;                        
            if ($mailCcAddress != "" && checkEmailFormat($mailCcAddress)) :
               $mailObj->setCc($mailCcAddress);
            endif;
            
            // Set Bcc address
            $mailBccAddress = getParameterValue("0", "MAIL_BCC_ADDRESS", $currentHqId);
            if ($mailBccAddress == "" || !checkEmailFormat($mailBccAddress)) :
               $mailBccAddress = MAIL_BCC_ADDRESS;
            endif;                        
            if ($mailBccAddress != "" && checkEmailFormat($mailBccAddress)) :
               $mailObj->setBcc($mailBccAddress);
            endif;            
            
            if ($mailTextJobStatus == "1") :
               $mailObj->setSubject("Transportauftrag " . $job_id . " : Die Abholung erfolgte!");
            elseif ($mailTextJobStatus == "8" || $mailTextJobStatus == "9") :
               $mailObj->setSubject("Transportauftrag " . $job_id . " ist in der Vermittlung!");
            else :
               $mailObj->setSubject("Transportauftrag " . $job_id . " ist erledigt!");
            endif;
            
            
            $mailResult = $mailObj->send(array($f_email), 'smtp');

            // Using PEAR alternative
            // $conf = prepareSendMailPear("smtp.1und1.com","m34847762-7","%CdGm%",$f_email,"Transportauftrag " . $job_id . " erledigt!","Assecutor","support@assecutor.de",$mailtext,"html");
            // $mail_object =& Mail::factory("smtp", $conf[0]);
            // if ($mail_object->send($conf[1], $conf[2], $conf[3])) :
            if ($mailResult) :
               $mailsendStatus = "Die Nachricht wurde versandt!";
               
               // Write logdata into log database
               writeToLogDB("22",$currentHqId,$job_id,$currentSessionUsrId,"","","",$f_email);
            else :
               $mailsendStatus = "Die Nachricht konnte nicht gesendet werden!";
               
               // Write logdata into log database
               writeToLogDB("23",$currentHqId,$job_id,$currentSessionUsrId,"","","",$f_email);
            endif;
            
            // $mailObj->free();
            $mailObj = NULL;

            // Remove stored temporary images on the filesystem
            $tmpSignPath = "../temp/signs/";
            $imgFilenamesLen = count($imgFilenames);
            if (SIGNS_PATH != "") : $tmpSignPath = SIGNS_PATH; endif;
            for ($im = 0; $im < $imgFilenamesLen; $im++) :
                if (file_exists($tmpSignPath . $imgFilenames[$im])) :
                   unlink($tmpSignPath . $imgFilenames[$im]);
                endif;
            endfor;
         else :
            $mailsendStatus = "Die eingegebene Emailadresse ist syntaktisch nicht korrekt!";
         endif;
      endif;

      if ($automailer == "0") :
         $mailsend .= "<br><br>\n";
         $mailsend .= "Mailadresse:&nbsp;&nbsp;";
         $mailsend .= "<input type=\"text\" name=\"f_email\" value=\"\">&nbsp;&nbsp;&nbsp;";
         $mailsend .= "<input type=\"button\" value=\"Erledigungsmail senden\" onClick=\"javascript:mailsend();\">";
         $mailsend .= "<br><br><span class=\"f8np1_red\">" . $mailsendStatus . "</span>";

         // Output of the mail ONLY if job done
         $tpl->setCurrentBlock("mailsend");
         $tpl->setVariable("_mailsend_", $mailsend);
         $tpl->parseCurrentBlock("mailsend");
      endif;
   endif;


   // --- BOOK JOB (Finalize) ---------------
   // --- CHANGE COURIER (If job is finished and not exported) ---------------
   if ($job_id != "") :
      $bookjob = "";
      $bookjobStatus = "&nbsp;&nbsp;&nbsp;";
   
      if ($f_act == "bookjob") :   
   
         if ($f_crvh_sid_book != "") :
            
            // Get cr_id from SID
            $cr_id_book = getFieldValueFromId("couriervehicle", "crvh_sid", $f_crvh_sid_book, "cr_id");

            // Set the current timestamp to store the data
            $currentTime = getDateTime("0");
            
            if ($cr_id_book != "") :
               
               $bookJobTime = $currentTime;
               
               // Get ordertime of the job if requested to store the value into jb_finishtime
               if ($f_jb_finishtime4booking == "1") :
                  $bookJobTime = getFieldValueFromId($dbh_jb, "jb_id", $job_id, "jb_ordertime");
                  if ($bookJobTime == "") : $bookJobTime = $currentTime; endif; 
               endif;

               if ($job_status != "2") :

                  // Update and finalize job
                  updateStmt($dbh_jb, "jb_id", $job_id, array("cr_id", $cr_id_book, "jb_status", "2", "cr_sid", $f_crvh_sid_book, "jb_finishtime", $bookJobTime, "jb_booktime", $currentTime), "(hq_id = '" . $currentHqId . "')");

                  $bookjobStatus = "Der Auftrag wurde abgeschlossen!";
                  
                  // Write logdata into log database
                  writeToLogDB("5",$currentHqId,$job_id,$currentSessionUsrId,$cr_id_book,$f_crvh_sid_book,"","");
               else :
                  if ($job_export_time == "" || $job_export_time == "0000-00-00 00:00:00") :
                     
                     // Activate this ONLY for changing the vehicle of the current courier of the job to avoid booking of other couriers!
                     // if ($jobCourierId == $cr_id_book) :
                                        
                        // Update finalized (not exported) job only with vehicle number
                     // updateStmt($dbh_jb, "jb_id", $job_id, array("cr_sid", $f_crvh_sid_book), "(hq_id = '" . $currentHqId . "')");
                        updateStmt($dbh_jb, "jb_id", $job_id, array("cr_id", $cr_id_book, "cr_sid", $f_crvh_sid_book), "(hq_id = '" . $currentHqId . "')");
                        
                        $bookjobStatus = "Die Fahrzeugnummer wurde geändert!";
                        
                        // Write logdata into log database
                        writeToLogDB("21",$currentHqId,$job_id,$currentSessionUsrId,$cr_id_book,$f_crvh_sid_book,"","");
                        
                     // else :
                     //   $bookjobStatus = "Achtung! Das eingegebene Fahrzeug stammt nicht von dem Transporteur der Tour!";
                     // endif;
                  else:
                     $bookjobStatus = "Der Auftrag wurde schon exportiert! Eine Änderung ist daher nicht möglich!";
                  endif;
               endif;
            else :
               $bookjobStatus = "Die gewählte Fahrzeugnummer konnte keinem Kurier zugeordnet werden!";
            endif;
         else:
            $bookjobStatus = "Der Auftrag konnte nicht verbucht werden! Geben Sie bitte einen Transporteur an!";
         endif;
      endif;
     
      // ONLY show if job is not exported
      /*
      if ($job_export_time == "" || $job_export_time == "0000-00-00 00:00:00") :
      
         $bookjobButtonText = "Auftrag abschließen";
         if ($job_status == "2") : $bookjobButtonText = "Fahrzeug ändern"; endif;
      
         $bookjob .= "<br><br>\n";
         $bookjob .= "<select name=\"f_crvh_sid_book\">\n";
         $bookjob .= "<option value=\"\" selected>&nbsp;</option>\n";
         
         // Activate this ONLY for changing the vehicle of the current courier of the job to avoid booking of other couriers!
         // if ($job_status != "2"):
            // $bookjob .= addOptionsFromTable("couriervehicle", "crvh_sid", "crvh_sid", "crvh_sid", "", "");
            $bookjob .= addOptionsFromTable("couriervehicle AS crvh, courier AS cr", "crvh_sid", "crvh_sid", "crvh_sid", "crvh.cr_id = cr.cr_id AND cr.hq_id = '" . $currentHqId . "'", "");
         // else :
         //    $bookjob .= addOptionsFromTable("couriervehicle", "crvh_sid", "crvh_sid", "crvh_sid", " cr_id = '" . $jobCourierId . "' ", $job_cr_sid);
         // endif;
                  
         $bookjob .= "</select>\n";
         $bookjob .= "<input type=\"button\" value=\"" . $bookjobButtonText . "\" onClick=\"javascript:bookjob();\">";
         
         // Select "current time" (default) or "finish time" to finalize the job
         if ($job_status != "2") :
            $bookjob .= "<br><br>";
            $bookjob .= "<input type=\"radio\" name=\"f_jb_finishtime4booking\" value=\"0\"" . ($f_jb_finishtime4booking == "" || $f_jb_finishtime4booking == "0" ? "checked" : "") . "> Akt. Tagesdatum";
            $bookjob .= "<input type=\"radio\" name=\"f_jb_finishtime4booking\" value=\"1\"" . ($f_jb_finishtime4booking == "1" ? "checked" : "") . "> Auftragsdatum";
         endif;
         
         $bookjob .= "<br><br><span class=\"f8np1_red\">" . $bookjobStatus . "</span>";
      endif;
      
      // Output
      if ($automailer == "0") :      
         $tpl->setCurrentBlock("bookjob");
         $tpl->setVariable("_bookjob_", $bookjob);
         $tpl->parseCurrentBlock("bookjob");
      endif;
      */
   endif;
   
   
   // --- CHANGE COURIER ONLY FOR RESERVATIONS ---------------
   /*
   if ($job_id != "" && $job_status == "8" && $job_reserv == "1") :
      $changeCourier = "";
      $changeCourierStatus = "&nbsp;&nbsp;&nbsp;";
   
      if ($f_act == "changeCourierOrder") :   
   
         if ($f_crvh_sid_order != "") :
            
            // Get cr_id from SID
            $cr_id_order = getFieldValueFromId("couriervehicle", "crvh_sid", $f_crvh_sid_order, "cr_id");
            
            // Set the current timestamp to store the data
            $currentTime = getDateTime("0");
            
            if ($cr_id_order != "") :            

               // Check if courier has to be set permanent for future jobs               
               if ($f_crvh_sid_order_permanent == "1") :
                  updateStmt($dbh_jb, "jb_id", $job_id, array("cr_id_order", $cr_id_order, "cr_sid", $f_crvh_sid_order, "cr_id_permanent", $f_crvh_sid_order), "(hq_id = '" . $currentHqId . "')");
                  
                  // Write logdata into log database
                  writeToLogDB("18",$currentHqId,$job_id,$currentSessionUsrId,$cr_id_order,$f_crvh_sid_order,"",$f_crvh_sid_order);
               else :
                  updateStmt($dbh_jb, "jb_id", $job_id, array("cr_id_order", $cr_id_order, "cr_sid", $f_crvh_sid_order), "(hq_id = '" . $currentHqId . "')");
                  
                  // Write logdata into log database
                  writeToLogDB("17",$currentHqId,$job_id,$currentSessionUsrId,$cr_id_order,$f_crvh_sid_order,"",$f_crvh_sid_order);
               endif;

               $changeCourierStatus = "Die Anforderung wurde geändert!";
            else :
               // Remove courier
               if ($f_crvh_sid_order == "0") :
                  
                  // Check if courier has to be set permanent for future jobs               
                  if ($f_crvh_sid_order_permanent == "1") :
                     updateStmt($dbh_jb, "jb_id", $job_id, array("cr_id_order", "", "cr_sid", "", "cr_id_permanent", ""), "(hq_id = '" . $currentHqId . "')");

                     // Write logdata into log database
                     writeToLogDB("20",$currentHqId,$job_id,$currentSessionUsrId,"","","","");
                  else :
                     updateStmt($dbh_jb, "jb_id", $job_id, array("cr_id_order", "", "cr_sid", ""), "(hq_id = '" . $currentHqId . "')");
                     
                     // Write logdata into log database
                     writeToLogDB("19",$currentHqId,$job_id,$currentSessionUsrId,"","","","");
                  endif;                  
               else :
                  $changeCourierStatus = "Die gewählte Fahrzeugnummer konnte keinem Kurier zugeordnet werden!";
               endif;
            endif;
         else:
            $changeCourierStatus = "Die Anforderung konnte nicht zugeteilt werden! Geben Sie bitte ein Fahrzeug an!";
         endif;
      endif;
     
      $changeCourier .= "<br><br>\n";
      $changeCourier .= "<select name=\"f_crvh_sid_order\">\n";
      $changeCourier .= "<option value=\"\" selected>&nbsp;</option>\n";
      $changeCourier .= "<option value=\"0\">Keine Anford.</option>\n";
      // $changeCourier .= addOptionsFromTable("couriervehicle", "crvh_sid", "crvh_sid", "crvh_sid", "", "");      
      $changeCourier .= addOptionsFromTable("couriervehicle AS crvh, courier AS cr", "crvh_sid", "crvh_sid", "crvh_sid", "crvh.cr_id = cr.cr_id AND cr.hq_id = '" . $currentHqId . "'", "");      
      $changeCourier .= "</select>\n";
      $changeCourier .= "<input type=\"button\" value=\"Anforderung ändern\" onClick=\"javascript:changeCourierOrder();\">";
      $changeCourier .= "<br>";
      $changeCourier .= "<input type=\"checkbox\" name=\"f_crvh_sid_order_permanent\" value=\"1\"> Permanente Anforderung\n";
      $changeCourier .= "<br><br><span class=\"f8np1_red\">" . $changeCourierStatus . "</span>";      
      
      // Output
      if ($automailer == "0") :
         $tpl->setCurrentBlock("changeCourier");
         $tpl->setVariable("_changeCourier_", $changeCourier);
         $tpl->parseCurrentBlock("changeCourier");
      endif;
   endif;
   */


   // --- MODIFY/REMOVE TOURNAME ---------------
   /*
   if ($job_id != "") :
      $modifyTourname = "";
      $modifyTournameStatus = "&nbsp;&nbsp;&nbsp;";
      $f_tourname = trim($f_tourname);
   
      if ($f_act == "modifyTourname") :            
   
         if ($f_tourname != "") :
               
            if (!existsEntry($dbh_jb, array("jb_tourname",$f_tourname,"hq_id",$currentHqId))) :
                        
               // Update job with new tourname
               updateStmt($dbh_jb, "jb_id", $job_id, array("jb_tourname", $f_tourname), "(hq_id = '" . $currentHqId . "')");

               $modifyTournameStatus = "Der Tourname wurde geändert!";
               
               // Write logdata into log database
               writeToLogDB("15",$currentHqId,$job_id,$currentSessionUsrId,"","","",$f_tourname);
            else :
               $modifyTournameStatus = "Der Tourname existiert schon! Bitte wählen Sie einen anderen!";
            endif;
         else :         
            // Remove tourname from job
            updateStmt($dbh_jb, "jb_id", $job_id, array("jb_tourname", ""), "(hq_id = '" . $currentHqId . "')");
            
            $modifyTournameStatus = "Der Tourname wurde gelöscht!";
            
            // Write logdata into log database
            writeToLogDB("16",$currentHqId,$job_id,$currentSessionUsrId,"","","","");
         endif;
         
         $job_tourname = $f_tourname;
      endif;
     
      $modifyTourname .= "<br><br>\n";
      $modifyTourname .= "Tourname:&nbsp;&nbsp;";
      $modifyTourname .= "<input type=\"text\" name=\"f_tourname\" value=\"" . $job_tourname . "\" size=\"50\" maxlength=\"50\">&nbsp;&nbsp;&nbsp;";
      $modifyTourname .= "<input type=\"button\" value=\"Tourname modifizieren\" onClick=\"javascript:changeTourname();\">";
      $modifyTourname .= "<br><br><span class=\"f8np1_red\">" . $modifyTournameStatus . "</span>";
      
      // Output
      if ($automailer == "0") :
         $tpl->setCurrentBlock("modifyTourname");
         $tpl->setVariable("_modifyTourname_", $modifyTourname);
         $tpl->parseCurrentBlock("modifyTourname");
      endif;
   endif;   
   */


   // --- SWITCH JOB "COMPLETE" <=> "INCOMPLETE" IF JOB IS NOT EXPORTED ---------------
   /*
   if ($job_id != "" && ($job_export_time == "" || $job_export_time == "0000-00-00 00:00:00")) :
      $completeJob = "";
      $completeJobStatus = "";

      if ($f_act == "completeJob") :   

         if ($f_jb_incomplete != "" && ($f_jb_incomplete == "0" || $f_jb_incomplete == "1")) :

            // Update job with new status jb_incomplete
            updateStmt($dbh_jb, "jb_id", $job_id, array("jb_incomplete", $f_jb_incomplete), "(hq_id = '" . $currentHqId . "' AND (ISNULL(jb_export_time)) OR jb_export_time = '0000-00-00 00:00:00')");
            
            $job_incomplete = $f_jb_incomplete;

            // Write logdata into log database
            writeToLogDB(($f_jb_incomplete == "1" ? "14" : "13"),$currentHqId,$job_id,$currentSessionUsrId,"","","","");
         endif;                  
      endif;
      
      if ($job_incomplete == "1") :
         $completeJobStatus .= "<span class=\"f8np1_red\"><b>UNFERTIG!</b></span>";
      else :
         $completeJobStatus .= "<span class=\"f8np1_green\"><b>OK!</b></span>";
      endif;      

      $completeJob .= "<br><br>\n";
      $completeJob .= "<input type=\"hidden\" name=\"f_jb_incomplete\" value=\"" . ($job_incomplete == "1" ? "0" : "1") . "\">";
      $completeJob .= "<br><br><br>Buchhaltungsstatus des Auftrags: " . $completeJobStatus . "&nbsp;&nbsp;&nbsp;\n";
      $completeJob .= "<input type=\"button\" value=\"Auf " . ($job_incomplete == "1" ? "ok" : "unfertig") . " setzen\" onClick=\"javascript:changeComplete();\">\n";

      // Output
      if ($automailer == "0") :
         $tpl->setCurrentBlock("completeJob");
         $tpl->setVariable("_completeJob_", $completeJob);
         $tpl->parseCurrentBlock("completeJob");
      endif;
   endif;   
   */


   // --- INVOICE TEXT ---------------
   /*
   $f_jb_invtext = getFieldValueFromId($dbh_jb, "jb_id", $job_id, "jb_invtext");
   
   $jobinvoicetext = "<br><br>(Vorläufiger) Rechnungstext:<br>";
   $jobinvoicetext .= "<textarea name=\"f_jb_invtext_new\" cols=\"70\" rows=\"15\" readonly>" . $f_jb_invtext . "</textarea><br>\n";
   // $jobinvoicetext .= "<input type=\"button\" value=\"Rechnungstext speichern\" onClick=\"javascript:changeInvoiceText();\">\n";
   
   if ($automailer == "0") :
      $tpl->setCurrentBlock("jobinvoicetext");
      $tpl->setVariable("_jobinvoicetext_", $jobinvoicetext);
      $tpl->parseCurrentBlock("jobinvoicetext");	 
   endif;
   */


   // --- INTERNAL REMARK ---------------
   if ($job_id != "") :
      if ($f_act == "changeInternalRemark") :

         updateStmt($dbh_jb, "jb_id", $job_id, array("jb_freetext_3", $f_jb_freetext_3_new), "(hq_id = '" . $currentHqId . "')");
      endif;
   endif;
   $f_jb_freetext_3 = getFieldValueFromId($dbh_jb, "jb_id", $job_id, "jb_freetext_3");
   
   $jobinternalremark = "<br><br>Interne Bemerkung:<br>";
   $jobinternalremark .= "<textarea name=\"f_jb_freetext_3_new\" cols=\"50\" rows=\"10\" readonly>" . $f_jb_freetext_3 . "</textarea><br>\n";
   // $jobinternalremark .= "<input type=\"button\" value=\"Interne Bemerkung speichern\" onClick=\"javascript:changeInternalRemark();\">\n";
   
   if ($automailer == "0") :
      $tpl->setCurrentBlock("jobinternalremark");
      $tpl->setVariable("_jobinternalremark_", $jobinternalremark);
      $tpl->parseCurrentBlock("jobinternalremark");	 
   endif;
   
   
   // --- COURIER REMARK ---------------
   $f_jb_cr_remark = getFieldValueFromId($dbh_jb, "jb_id", $job_id, "jb_cr_remark");
   
   $jobcourierremark = "<br><br>Anmerkungen Transporteur:<br>";
   $jobcourierremark .= "<textarea name=\"f_jb_cr_remark\" cols=\"70\" rows=\"4\" readonly>" . $f_jb_cr_remark . "</textarea><br>\n";
   
   if ($automailer == "0") :
      $tpl->setCurrentBlock("jobcourierremark");
      $tpl->setVariable("_jobcourierremark_", $jobcourierremark);
      $tpl->parseCurrentBlock("jobcourierremark");
   endif;
   
   
   // --- SUB-JOBS ---------------
   
   if ($job_id != "") :

      $listOfSubjobs = "";
      if (getCountOfTable($dbh_jb, "jb_id_parent = '" . $job_id . "'") > 0) :

         // $tmpSqlquery = "SELECT jb.jb_id AS jb_id_sub"
         //                . " FROM " . $dbh_jb . " AS jb"
         //                . " WHERE jb.jb_id_parent = '" . $job_id . "'"
         //                . " ORDER BY jb.jb_id";
                        
         $tmpSqlquery = "SELECT jb.jb_id AS jb_id_sub, jb.jb_totalprice AS business_volume, cr.cr_eid, usr.usr_name"
                        . " FROM " . $dbh_jb . " AS jb LEFT JOIN courier AS cr ON jb.cr_id = cr.cr_id"
                        . "                            LEFT JOIN user AS usr ON cr.usr_id = usr.usr_id"
                        . " WHERE jb.jb_id_parent = '" . $job_id . "'"
                        . " ORDER BY jb.jb_id";                        
   
         $result = $db->query($tmpSqlquery);
         if (DB::isError($result)) die ("$PHP_SELF 5: {$tmpSqlquery} " . $result->getMessage() . ": " . $sqlquery);
        
         // Generate list with header
         $titleArray = array("Auftrag&nbsp;","Preis&nbsp;", "ExtID&nbsp;", "Name");
         $fieldArray = array("jb_id_sub", "business_volume", "cr_eid", "usr_name");
         
         $aligns = "l,r,l,l";
         $alignArray = spliti(",",$aligns);
         $alignTitles = "left";
         $widths = "30";
         $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");
         $listOfSubjobs .= "<tr><td colspan=\"2\">UNTERAUFTRÄGE:</td></tr>\n";
         $listOfSubjobs .= $tableHeader . $tableBody;
         
         $result->free();
      endif;
      
      if ($automailer == "0") :
         $tpl->setCurrentBlock("listOfSubjobs");
         $tpl->setVariable("_listOfSubjobs_", $listOfSubjobs);
         $tpl->parseCurrentBlock("listOfSubjobs");	 
      endif;      
   endif;
      

   if ($automailer == "0") :
      $tpl->show();
   endif;
?>
   
