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

$userType = "";
$userTypeName = "";

if (!isset($automailer) || $automailer != "1") :
   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 :
   if (isset($currentHqId) && is_numeric($currentHqId)) : $hq_id = $currentHqId; endif;
   if ($hq_id == "") : $hq_id = "1"; endif;
   $automailer = "1";
   $GLOBALS['HTTP_SERVER_VARS']['HTTP_HOST'] = "assecutor.de";
endif;

// Check HTTP-Parameters
if ($automailer == "0") :
   // Define both constants for encryption/decryption WITH HEADQUARTERS OF THE EMPLOEE!!!
   if (!defined('HTTP_VARS_SEC_STATE')) : define ('HTTP_VARS_SEC_STATE', getParameterValue("0", "HTTP_VARS_SEC_STATE", $hqId)); endif;
   if (!defined('HTTP_VARS_SEC_SEQ')) : define ('HTTP_VARS_SEC_SEQ', getParameterValue("0", "HTTP_VARS_SEC_SEQ", $hqId)); endif;

   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_jbp_mode", "f_jbp_price_rest", "f_jbp_csc_id", "f_jbp_tan", "f_jb_gdc_add_mon", "f_jbp_mode_add_mon",
                            "f_tourname", "f_jb_incomplete", "f_jb_finishtime4booking", "f_jb_freetext_3_new", "deactivateMenu"));

   // Check existence of the job in history table space
   $dbhistory = checkHistoryLevel($dbhistory, "jb", $job_id);
   $dbhistory = getDBNames($dbhistory);

   // Check for mandator rights regarding switching the headquarters
   if (authCheckEmployeeRights($emp_id, "10")) :
      // Get headquarters from the job
      if ($job_id != "" && is_numeric($job_id)) :
         $jbHqId = getFieldValueFromId($dbh_jb, "jb_id", $job_id, "hq_id");
         if ($jbHqId != "") :
            $currentHqId = $jbHqId;
         endif;
      endif;
   endif;
endif;

// Access structure
$empHasAccessToLonghaul = false;
if (authCheckEmployeeRights($emp_id, "44")) : $empHasAccessToLonghaul = true; endif;
$jbHqIdArr = getFieldsValueFromId("job", "jb_id", $job_id, array("hq_id","hq_id_dispo","hq_id_exec","hq_id_sales","jb_status"));
$jbAccessModeArr = getAccessHqTypeJbStatus($jbHqIdArr, $jbHqIdArr[4], $empHasAccessToLonghaul, "");  // "Anzeige", "Änderung", "Vermittlung"

// Get the emp_id of the root admin
$empIdRootAdmin = getEmpIdOfRootAdmin($userTypeName);

// Includes
include_once ("../include/inc_file.inc.php");
include_once ("../include/jb_detail_history.inc.php");
include_once ("../include/inc_job.inc.php");
include_once ("../include/inc_scan_events.inc.php");
include_once ("../include/inc_parseXML.inc.php");

if ($currentHqId == "" || !is_numeric($currentHqId)) : die ("$PHP_SELF: Headquarter fails!"); endif;

// Define global parameters
defineGlobalParameters($currentHqId);

getLanguage(__FILE__);

if ($automailer == "0") :

   $deactivateMenuStatic = "1";
   $pageTitel = getLngt("AUFTRAGSDETAILS");
   include_once ("../admin/menu.php");
   include_once ("../include/services_func.inc.php");   // Attention: File includes menu.php !!!

   // Check global setting for default bookjob date
   if ($f_jb_finishtime4booking == "") :
      $constFinishtime4booking = getParameterValue("0", "MASK_JOBDETAILS_BOOKJOB_DATE", $currentHqId);
      if ($constFinishtime4booking == "1") :
         $f_jb_finishtime4booking = "1";
      else :
         $f_jb_finishtime4booking = "0";
      endif;
   endif;
endif;
include_once ("../include/html.inc.php");
getCurrentScript(__FILE__);

// 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();

// Set to "1" for displaying stations in classic mode
$tourDisplayClassicMode = "";

mcIsSet($importPath);
mcIsSet($mailTextJobStatus);
mcIsSet($changeCourier);
mcIsSet($changeGDC_addMon);
mcIsSet($changePayment);

$mailsend = "";

// Check for mode of system usage
$jobService = "";
$jobHasAddedInstallation = false;
$jobAddedInstallationId = "";
$jobAddedInstallationIsExported = false;
$globalParUseRelatedCustomer = getParameterValue("0", "GLOBAL_USE_RELATED_CUSTOMER", "0");
if ($globalParUseRelatedCustomer == 1) :
   $jobService = getFieldValueFromId("job","jb_id",$job_id,"jb_service");
   
   // Check for added installation
   if (existsEntry("genericdatacontainer", array("gdc_obj_type", "jb", "gdc_gen_fieldname", "jb_addmont", "gdc_obj_id", $job_id))) :
      $jobHasAddedInstallation = true;

      // Get job ID of the added installation
      $jobAddedInstallationId = getFieldValueFromClause("genericdatacontainer", "gdc_content", "gdc_obj_type = 'jb' AND gdc_obj_id = '" . $job_id . "' AND gdc_gen_fieldname = 'jb_id_addmont'");
      
      // Get export state of added installation job
      if ($jobAddedInstallationId != "" && is_numeric($jobAddedInstallationId)) :
         $tmpJobAddedInstallationExported = getFieldValueFromId("job","jb_id",$jobAddedInstallationId,"jb_export_time");
         if (!($tmpJobAddedInstallationExported == "" || $tmpJobAddedInstallationExported == "0000-00-00 00:00:00")) :
            $jobAddedInstallationIsExported = true;
         endif;
      endif;
   endif;
endif;

// Check status of the job regarding storno 
$jobStorno = getFieldValueFromId("job","jb_id",$job_id,"jb_storno");
$jobOffer = getFieldValueFromId("job","jb_id",$job_id,"jb_offer");
$job_export_time = getFieldValueFromId("job","jb_id",$job_id,"jb_export_time");
$jobIsNotExported = false;
if ($job_export_time == "" || $job_export_time == "0000-00-00 00:00:00") :
   $jobIsNotExported = true;
endif;
$jobIsAllowedToBeModified = false;
if (($jobStorno == "" || $jobStorno == "0") && $jobOffer == "0") :
   $jobIsAllowedToBeModified = true;
endif;


// Get vector of metatype items regarding internal remark cases
$mtIntRemItem = getColVectorFromDB2ArrayByClause("metatype", "mt_value", "mt_type = 'internal_remark' AND mt_objtype = '' AND mt_objid = '0'", "mt_sort", "mt_sort", "");
$mtIntRemItemLen = count($mtIntRemItem);

// Get tax value associated to the job
$taxFactor = getSalesTaxFactor($job_id);


// Check global usage of the context menu
$maskJobInternalRemarkItems = "";
// if ($jobIsNotExported) :
   $maskJobInternalRemarkItems = getParameterValue("0", "MASK_JOBDETAILS_INTERNAL_REMARK_ITEMS", $currentHqId);
   if ($maskJobInternalRemarkItems != "1") : $maskJobInternalRemarkItems = getParameterValue("0", "MASK_JOBDETAILS_INTERNAL_REMARK_ITEMS", "0"); endif;
// endif;


// If job ($job_id) is exported, then look for existing content in history field in table "job2"
$takeRealJobData = checkForTakingRealOrHistoricJobData("1");

// Get current snapshot of job data (JOB, TOUR, COURIER, COSTS, EMPLOYEES)
if ($takeRealJobData) :
   $currentJobParameterState = getJobSnapshot($job_id);
else :
  if ($userTypeName == "hq" && $automailer == "0" && $f_act != "mailsend") : 
      // Check for finished jobs only
      $parCrPriceMode = getParameterValue("0", "MASK_CR_PRICE_MODE", $currentHqId);
      if ($parCrPriceMode == "1") :
         if ($db->getOne("SELECT jb_id FROM tourservice WHERE jb_id = " . $job_id . " AND trs_srvt_name = 'z'") == $job_id &&
             $db->getOne("SELECT jb_id FROM phoenix_log.route WHERE jb_id = " . $job_id) == $job_id) :
             $jobcosts .= "<tr><td class=\"f8np1\" colspan=\"6\"><br><a href=\"../locating/map_pzm.php?jb_id=" . $job_id . "\" target=\"_blank\">" . getLngt("Route der PZM-Preisberechnung") . "</a></td></tr>\n";
         endif;
      endif;
  endif;
endif;


// Check for documents associated to the job
if ($job_id != "") :
   // Get path for courier documents (type "JB")
   if ($importPath == "") : $importPath = getFieldValueFromId("mandator","md_id",$md_id,"md_doc_path"); endif;
   $importPath = getPathForObjectData($importPath, "JB");
   // Get number of documents for the current customer
   $jbNumOfFiles = getNumOfFilesByFilterInFolder($importPath, $job_id . "_", "1");
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");    // DEFINED ABOVE !!!
   
   // Get parameter 
   $constMaskJobDetailsFavCrShowMode = getParameterValue("0", "MASK_JOBDETAILS_FAVOURED_COURIER_SHOW_MODE", "0");

   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, cr.cr_eid"
                     . " 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"
       $cscIdPayer = getFieldValueFromId($dbh_jb, "jb_id", $job_id, "csc_id_payer_cash");
   else :
      // Job is an invoice one
      $tmpSqlquery = "SELECT DISTINCT cscr.cr_id, cr.cr_sid, cr.vht_id, cr.cr_eid"
                     . " 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 = "";
   $tmpCount1 = 0;
   $tmpCount2 = 0;
   while ($row = $result->fetch_assoc()):
         if ($row["vht_id"] >= $jbVhtId) :               
            if ($constMaskJobDetailsFavCrShowMode == "1") :
               $jobFavouredCouriersMatchingVehicle .= $row["cr_eid"] . "&nbsp;(" . $row["cr_sid"] . ")&nbsp;&nbsp;&nbsp;";
               $tmpCount1++;
               if ($tmpCount1 == "3") :
                  $tmpCount1 = 0;
                  // $jobFavouredCouriersMatchingVehicle .= "<br>&nbsp;&nbsp;&nbsp;";
                  $jobFavouredCouriersMatchingVehicle .= "</td></tr><tr><td>&nbsp;</td><td>\n";
               endif;
            else :
               $jobFavouredCouriersMatchingVehicle .= $row["cr_sid"] . "&nbsp;&nbsp;&nbsp;";
            endif;
         else :
            if ($constMaskJobDetailsFavCrShowMode == "1") :
               $tmpCount2++;
               if ($tmpCount2 == "3") :
                  $tmpCount2 = 0;
                  // $jobFavouredCouriersNotMatchingVehicle .= "<br>&nbsp;&nbsp;&nbsp;";
                  $jobFavouredCouriersNotMatchingVehicle .= "</td></tr><tr><td>&nbsp;</td><td>\n";
               endif;               
               $jobFavouredCouriersNotMatchingVehicle .= $row["cr_eid"] . "&nbsp;(" . $row["cr_sid"] . ")&nbsp;&nbsp;&nbsp;";
            else :
               $jobFavouredCouriersNotMatchingVehicle .= $row["cr_sid"] . "&nbsp;&nbsp;&nbsp;";
            endif;
         endif;
   endwhile;
   $result->free();
endif;

$jobFavouredCouriers = "<tr><td class=\"mc_table-header\" colspan=\"2\">" . getLngt("EINGETRAGENE BEVORZUGTE KURIERE:") . "</td></tr>\n" .
                       "<tr><td>" . getLngt("Mit passenden Fahrzeugen:") . " </td><td>&nbsp;&nbsp;" . $jobFavouredCouriersMatchingVehicle . "</td></tr>\n" .
                       "<tr><td>" . "Restliche:" . " </td><td>&nbsp;&nbsp;" . $jobFavouredCouriersNotMatchingVehicle . "</td></tr>\n";


// --- SEND MAIL ---------------
// Allow sending mail regarding jb_status = 1
if ($automailer == "0" && $mailTextJobStatus == "") :    // Pay attention
   if ($job_status == "1") :
      $maskExtendJbStatusPickup = getParameterValue("0", "MASK_MAIL_JOB_STATE_PICKUP", $currentHqId);
      if ($maskExtendJbStatusPickup == "1") :
         $mailTextJobStatus = "1";
      endif;
   endif;
   if ($job_status == "9") :
      $maskExtendJbStatusPickup = getParameterValue("0", "MASK_MAIL_JOB_STATE_DISPOSITION", $currentHqId);
      if ($maskExtendJbStatusPickup == "1") :
         $mailTextJobStatus = "9";
      endif;
   endif;
endif;

if ($job_status == "2" || $mailTextJobStatus != "") :

   $mailsend = "";
   $mailsendStatus = "&nbsp;&nbsp;&nbsp;";

   if ($f_act == "mailsend") :

      if (checkEmailFormat($f_email)) :

         // Check language by customer parameter
         $csLanguageMail = getParameterValue("0", "JOBDETAILS_EMAIL_LANGUAGE_" . $csIdPayer, "0");
         if ($csLanguageMail == "") :
            $csLanguageMail = "0";
         endif;
         $remLanguageSelected = "";
         if ($takeRealJobData && $csLanguageMail != "" && $languageSelected != $csLanguageMail) :
            $remLanguageSelected = $languageSelected;
            $languageSelected = $csLanguageMail;
            getLanguage(__FILE__);
            $currentJobParameterState = getJobSnapshot($job_id);
         endif;

         // It is necessary to (re)create sign images if mail is based on historic data
         $imgFilenames = array();
         if (!$takeRealJobData) :

            $tmpSqlquery = "SELECT tr.tr_sign, tr.tr_sort"
                           . " FROM " . $dbh_tr . " AS tr"
                           . " WHERE tr.jb_id = '" . $job_id . "'"
                           . " ORDER BY tr.tr_sort";

            $result = $db->query($tmpSqlquery);
            if (DB::isError($result)) die ("$PHP_SELF 5: {$tmpSqlquery} " . $result->getMessage() . ": " . $tmpSqlquery);
            
            $tmpSignPath = "../temp/signs/";
            if (SIGNS_PATH != "") : $tmpSignPath = SIGNS_PATH; endif;
            while ($row = $result->fetch_assoc()):
               $rawCoord = splitRawCoordinates ($row["tr_sign"]);
               $maxCoord = checkMaxCoordinates($rawCoord);            

               $imgFilename = $tmpSignPath . $job_id . "_" . $row["tr_sort"] . ".png";
               $imgFilenames[] = $imgFilename;
               $im = createSignImage($rawCoord);
               imagepng ($im, $imgFilename);
            endwhile;
            $result->free();
         endif;

         if ($automailer == "0") :   
            include_once ('../include/email/htmlMimeMail.php');
         endif;
         $mailObj = new htmlMimeMail();

         $mailCssFontType = getParameterValue("0", "MAIL_CSS_FONT_TYPE", $currentHqId);
         if ($mailCssFontType == "") : $mailCssFontType = "Verdana, Arial, Helvetica, sans-serif"; endif;

         $mailtext  = "<html><head><meta text/html>";
         $mailtext .= "<style type=\"text/css\">";
         $mailtext .= ".f8np1 { font-family: " . $mailCssFontType . "; font-size: 8pt; font-weight: normal; padding: 1px}";
         $mailtext .= ".f8bp1 { font-family: " . $mailCssFontType . "; font-size: 8pt; font-weight: bold; padding: 1px}";
         $mailtext .= ".f10np1 { font-family: " . $mailCssFontType . "; font-size: 10pt; font-weight: normal; padding: 1px}";
         $mailtext .= ".f10bp1 { font-family: " . $mailCssFontType . "; font-size: 10pt; font-weight: bold; padding: 1px}";
         $mailtext .= ".f8np1_red { font-family: " . $mailCssFontType . "; font-size: 8pt; font-weight: normal; padding: 1px; color: #FF0000;}";
         $mailtext .= "</style>";
         $mailtext .= "</head><body><h4>";
         
         // BEGIN Job data
         $jobtext = "";
         
         // Definition of the output place of the job data
         $mailJobData = getParameterValue("0", "MAIL_JOBDATA", "0");
         if ($mailJobData == "") : $mailJobData = "0"; endif;

         // Transport date or current date
         $mailJobDate = getParameterValue("0", "MAIL_JOBDATE", "0");

         if ($mailJobDate == "1") :
            $jobtext .= "<div class=\"f10bp1\">" . getLngt("Transportdatum:") . " " . formatOutput($job_ordertime, "datetime", 4) . "</div>";
         else :
            $jobtext .= "<div class=\"f10bp1\">" . getLngt("Transportdatum:") . " " . getDateTime(5) . "</div>";
         endif;
         $jobtext .= "<div style=\"width:100%; height:10px;\"> </div>";
         
         $jobtext .= "<table><tr><td valign=\"top\">";
         $jobtext .= "<span class=\"f8bp1\">" . getLngt("AUFTRAG:") . "</span><br>";
         $jobtext .= "<table class=\"f8np1\">" . $jobentry . "</table><br>";
         $jobtext .= "</td><td>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td><td valign=\"top\">";
         if ($courierentry != "" && $mailTextJobStatus != "0" && $mailTextJobStatus != "8" && $mailTextJobStatus != "9") :
            $jobtext .= "<span class=\"f8bp1\">" . getLngt("TRANSPORTEUR:") . "</span><br>";
            $jobtext .= "<table class=\"f8np1\">" . $courierentry . "</table><br>";
         endif;
         $jobtext .= "</td></tr></table>";
         if ($tourentry != "") :
            $jobtext .= "<span class=\"f8bp1\">" . getLngt("TOUR:") . "</span><br>";
            // Insert existing photos for EXPORTED JOBS ONLY
            // ATTENTION: Dirty code for keepimg compatibility !!!!
            //            The special <tr> of $tourentry with the photos will be removed and added again with generated photos
            // Start photos
            // Get position of text for the photos
            $jbExportTime = getFieldValueFromId($dbh_jb, "jb_id", $job_id, "jb_export_time");
            if ($jbExportTime != "" && $jbExportTime != "NULL" && $jbExportTime != "0000-00-00 00:00:00" && $jbExportTime != "9999-12-31 23:59:59") :
               $tmpPos = strpos($tourentry, "Abliefernachweis Foto");
               if (!($tmpPos === FALSE)) :
                  // Get positions of the last "<tr>" before and the first "</tr>" after the text for photos
                  // Tag before the text
                  $tmpStrBefore = substr($tourentry,0,$tmpPos);
                  $tmpPosBefore = strrpos($tmpStrBefore, "<tr>");  // !!!!
                  // Tag after the text
                  $tmpStrAfter = substr($tourentry,$tmpPos);
                  $tmpPosAfter  = strrpos($tmpStrAfter, "</tr>");  // !!!!
                  $tmpPosAfter += $tmpPos;  // !!!!
                  // Substring to be replaced
                  $strToBeReplaced = substr($tourentry,$tmpPosBefore, $tmpPosAfter);
                  // Generate photos
                  // Get parameter to check photos are activated or not
                  $constMaskStationsPodPhoto = getParameterValue("0", "MASK_JOBDETAILS_STATIONS_POD_PHOTOS", $currentHqId);
                  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") :
                     // Check for mandatory photos
                     $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) :
                        $constMaskStationsPodPhoto = "1";
                     // endif;
                  endif;
                  if ($constMaskStationsPodPhoto == "1") :
                     // Replace all occurrences of tag content with special content
                     $tmpStrTd = "|&nbsp;|";
                     $strToBeReplaced = str_replace("&nbsp;",$tmpStrTd,$strToBeReplaced);
                     // Iterate all stations
                     $numOfStations = count($jbTrIds);
                     for ($s = 0; $s < $numOfStations; $s++) :
                         $tagPhoto = getStationPhotos($jbTrIds[$s], "mailsend");
                         $tmpPos = strpos($strToBeReplaced, $tmpStrTd);
                         $strToBeReplaced = substr($strToBeReplaced,0,$tmpPos) . $tagPhoto . substr($strToBeReplaced,$tmpPos + strlen($tmpStrTd));
                     endfor;
                     // Finally replace $strToBeReplaced in $tourentry
                     $tourentry = substr($tourentry,0,$tmpPosBefore) . $strToBeReplaced . substr($tourentry,$tmpPosAfter);
                  endif;
               endif;
            endif;
            // End photos
            $jobtext .= "<table class=\"f8np1\">" . $tourentry . "</table><br>";
         endif;
         if ($jobcosts != "") :
            $csJbstatusmailPrice = getFieldValueFromId("customer","cs_id",$csIdPayer,"cs_jbstatusmail_price");
            if ($csJbstatusmailPrice == "1") :
               $jobtext .= "<span class=\"f8bp1\">" . getLngt("KOSTEN:") . "</span><br>";
               if ($job_orderer != "") :
                  $jobtext .= "<span class=\"f8bp1\">" . getLngt("Besteller:") . "&nbsp;" . $job_orderer . "</span><br>";
               endif;
               $jobtext .= "<table class=\"f8np1\">" . $jobcosts . "</table><br>";
            endif;
         endif;
         // END Job data

         $mailCssFontClass = getParameterValue("0", "MAIL_CSS_FONT_CLASS", $currentHqId);
         if ($mailCssFontClass == "") : $mailCssFontClass = "f8bp1"; endif;

         $mailPreSalutationText = getParameterValue("0", "MAIL_PRE_SALUTATION_TEXT", $currentHqId);
         if ($mailPreSalutationText == "") : $mailPreSalutationText = getLngt("Sehr geehrte Damen und Herren,"); endif;         
         if ($mailTextJobStatus == "OFFER") :
            // $mailPreSalutationText = getParameterValue("0", "MAIL_PRE_SALUTATION_TEXT_OFFER", $currentHqId);
            // if ($mailPreSalutationText == "") : $mailPreSalutationText = getParameterValue("0", "MAIL_PRE_SALUTATION_TEXT_OFFER", "0"); endif;
            // if ($mailPreSalutationText == "") :
               $tmpJbOrderer = getFieldValueFromId("job","jb_id",$job_id,"jb_orderer");
               if ($tmpJbOrderer != "") :
                  $mailPreSalutationText = getLngt("Sehr geehrte/r") . " " . $tmpJbOrderer . ",";
               endif;
               $mailPreSalutationText .= "</br>" 
                                      . getLngt("vielen Dank für Ihre Anfrage und das damit entgegengebrachte Vertrauen.") . "</br>"
                                      . getLngt("Gerne bieten wir Ihnen auf Basis der von Ihnen übermittelten Informationen, folgendes an:");
            // endif;
         elseif ($mailTextJobStatus == "OFFER_CHANGE") :
            // $mailPreSalutationText = getParameterValue("0", "MAIL_PRE_SALUTATION_TEXT_OFFER_CHANGE", $currentHqId);
            // if ($mailPreSalutationText == "") : $mailPreSalutationText = getParameterValue("0", "MAIL_PRE_SALUTATION_TEXT_OFFER_CHANGE", "0"); endif;
            // if ($mailPreSalutationText == "") :
               $tmpJbOrderer = getFieldValueFromId("job","jb_id",$job_id,"jb_orderer");
               if ($tmpJbOrderer != "") :
                  $mailPreSalutationText = getLngt("Sehr geehrte/r") . " " . $tmpJbOrderer . ",";
               endif;
               $mailPreSalutationText .= "</br>" 
                                      . getLngt("vielen Dank für Ihre Anfrage und das damit entgegengebrachte Vertrauen.") . "</br>"
                                      . getLngt("Gerne bieten wir Ihnen auf Basis der von Ihnen übermittelten Informationen, folgendes an:");
            // endif;
         endif;
         $mailtext .= "<div class=\"" . $mailCssFontClass . "\">" . $mailPreSalutationText . "</div>";
         $mailtext .= "<div style=\"width:100%; height:10px;\"> </div>";

         if ($mailTextJobStatus == "1") :
            $mailTextPickup = getParameterValue("0", "MAIL_TEXT_PICKUP", $currentHqId);
            if ($mailTextPickup == "") : $mailTextPickup = getLngt("Die Abholung der Ware erfolgte."); endif;
            $mailtext .= "<div class=\"" . $mailCssFontClass . "\">" . $mailTextPickup . "</div>";
         elseif ($mailTextJobStatus == "8" || $mailTextJobStatus == "9") :
            $mailTextDisposition = getParameterValue("0", "MAIL_TEXT_DISPOSITION", $currentHqId);
            if ($mailTextDisposition == "") : $mailTextDisposition = getLngt("Ihr Transportauftrag befindet sich in der Vermittlung."); endif;
            $mailtext .= "<div class=\"" . $mailCssFontClass . "\">" . $mailTextDisposition . "</div>";
         elseif ($mailTextJobStatus == "ALL") :
            $mailTextDisposition = getParameterValue("0", "MAIL_TEXT_ALL_STATIONS", $currentHqId);
            if ($mailTextDisposition == "") : $mailTextDisposition = getLngt("Die") . " " . $tour_sort . ". " . getLngt("Station Ihres Auftrags wurde erledigt."); endif;
            $mailtext .= "<div class=\"" . $mailCssFontClass . "\">" . $mailTextDisposition . "</div>";
         elseif ($mailTextJobStatus == "CHANGE") :
            $mailTextDisposition = getParameterValue("0", "MAIL_TEXT_CHANGE", $currentHqId);
            if ($mailTextDisposition == "") : $mailTextDisposition = "Ihr Transportauftrag wurde geändert."; endif;
            $mailtext .= "<div class=\"" . $mailCssFontClass . "\">" . getLngt($mailTextDisposition) . "</div>";
         elseif ($mailTextJobStatus == "OFFER") :
            $mailTextDisposition = getParameterValue("0", "MAIL_TEXT_OFFER", $currentHqId);
            if ($mailTextDisposition == "") : $mailTextDisposition = "Ihr Angebot."; endif;
            $mailtext .= "<div class=\"" . $mailCssFontClass . "\">" . getLngt($mailTextDisposition) . "</div>";
         elseif ($mailTextJobStatus == "OFFER_CHANGE") :
            $mailTextDisposition = getParameterValue("0", "MAIL_TEXT_OFFER_CHANGE", $currentHqId);
            if ($mailTextDisposition == "") : $mailTextDisposition = "Ihr Angebot wurde geändert."; endif;
            $mailtext .= "<div class=\"" . $mailCssFontClass . "\">" . getLngt($mailTextDisposition) . "</div>";
         else :
            $mailTextCompletion = getParameterValue("0", "MAIL_TEXT_COMPLETION", $currentHqId);
            if ($mailTextCompletion == "") : $mailTextCompletion = "Ihr Transportauftrag wurde ausgeführt."; endif;
            $mailtext .= "<div class=\"" . $mailCssFontClass . "\">" . getLngt($mailTextCompletion) . "</div>";
            // Extended text
            $mailTextCompletion2 = getParameterValue("0", "MAIL_TEXT_COMPLETION_2", $currentHqId);
            if ($mailTextCompletion2 != "") : 
               $mailtext .= "<div style=\"width:100%; height:10px;\"> </div>";
               $mailtext .= "<div class=\"" . $mailCssFontClass . "\">" . getLngt($mailTextCompletion2) . "</div>";
               $mailTextCompletion3 = getParameterValue("0", "MAIL_TEXT_COMPLETION_3", $currentHqId);
               if ($mailTextCompletion3 != "") : 
                  $mailtext .= "<div class=\"" . $mailCssFontClass . "\">" . getLngt($mailTextCompletion3) . "</div>"; 
                  $mailTextCompletion4 = getParameterValue("0", "MAIL_TEXT_COMPLETION_4", $currentHqId);
                  if ($mailTextCompletion4 != "") : 
                     $mailtext .= "<div class=\"" . $mailCssFontClass . "\">" . getLngt($mailTextCompletion4) . "</div>";
                     $mailTextCompletion5 = getParameterValue("0", "MAIL_TEXT_COMPLETION_5", $currentHqId);
                     if ($mailTextCompletion5 != "") : 
                        $mailtext .= "<div class=\"" . $mailCssFontClass . "\">" . getLngt($mailTextCompletion5) . "</div>";
                     endif;
                  endif;
               endif;
               $mailtext .= "<div style=\"width:100%; height:10px;\"> </div>";
            endif;
         endif;
         // $mailtext .= "<div style=\"width:100%; height:10px;\"> </div>";

         $mailTextJobdata = getParameterValue("0", "MAIL_TEXT_JOBDATA", $currentHqId);
         if ($mailTextJobdata == "") : $mailTextJobdata = getLngt("Anbei übersenden wir Ihnen die Auftragsdaten."); endif;
         $mailtext .= "<div class=\"" . $mailCssFontClass . "\">" . $mailTextJobdata . "</div>";
         $mailtext .= "<div style=\"width:100%; height:10px;\"> </div>";

         // Special usage for requesting state of the customer service
         $mailDisplayModeEmployeeData = getParameterValue("0", "MAIL_DISPLAY_MODE_EMPLOYEE_DATA", $currentHqId);
         if ($mailDisplayModeEmployeeData == "") : $mailDisplayModeEmployeeData = "0"; endif;
         if ($job_status == "2") :
            $mailSuccessRequest = getParameterValue("0", "MAIL_SUCCESS_REQUEST", $currentHqId);
            if ($mailSuccessRequest != "") :
               // Only if a mail success request does exist in the database (line above) then check if it is enabled for the payer of the job
               $csJbstatusmailEmp = getFieldValueFromId("customer","cs_id",$csIdPayer,"cs_jbstatusmail_emp");
               if ($csJbstatusmailEmp == "1") :
                  // Get the user data of the current employee of the job
                  $job_usr_id = getFieldValueFromId($dbh_jb,"jb_id",$job_id,"emp_id");
                  if ($job_usr_id != "") :
                     // Check user type. Display following data for headquarters users only!
                     $job_usr_type = getFieldValueFromId("user","usr_id",$job_usr_id,"usr_type");
                     if ($job_usr_type == "1") :
                        $mailEmployeeData = getFieldsValueFromId("user", "usr_id", $job_usr_id, array("usr_firstname","usr_name","usr_phone","usr_email","usr_fax"));
                        if ($mailEmployeeData[0] == "" || $mailEmployeeData[1] == "" || $mailEmployeeData[2] == "" || $mailEmployeeData[3] == "") :
                           $mailDisplayModeEmployeeData = "";
                        endif;
                        if ($mailDisplayModeEmployeeData == "0") :
                           $mailtext .= "<div class=\"" . $mailCssFontClass . "\">" . getLngt($mailSuccessRequest) . "</div>";
                           $mailtext .= "<div class=\"" . $mailCssFontClass . "\">" . $mailEmployeeData[0] . " " . $mailEmployeeData[1] . "</div>";
                           $mailtext .= "<div class=\"" . $mailCssFontClass . "\">" . getLngt("Telefon") . ": " . $mailEmployeeData[2] . "</div>";
                           // $mailtext .= "<div class=\"" . $mailCssFontClass . "\">" . getLngt("Fax") . ": " . $mailEmployeeData[4] . "</div>";
                           $mailtext .= "<div class=\"" . $mailCssFontClass . "\">" . getLngt("Email") . ": " . $mailEmployeeData[3] . "</div>";
                           $mailtext .= "<div style=\"width:100%; height:10px;\"> </div>";
                        endif;
                     endif;
                  endif;
               endif;
            endif;
         else :
            $mailDisplayModeEmployeeData = "";
         endif;

         // Recension (Google, etc.)
         if ($job_status == "2") :
            $mailTextRecension = getParameterValue("0", "MAIL_TEXT_RECENSION", $currentHqId);
            if ($mailTextRecension == "") : $mailTextRecension = getParameterValue("0", "MAIL_TEXT_RECENSION", "0"); endif;
            if ($mailTextRecension != "") :
               $mailtext .= "<div class=\"" . $mailCssFontClass . "\">" . $mailTextRecension . "</div>";
               $mailtext .= "<div style=\"width:100%; height:10px;\"> </div>";
            endif;
         endif;

         if ($mailJobData == "1") :
            $mailtext .= "<div style=\"width:100%; height:30px;\"> </div>";
            $mailtext .= $jobtext;
            $mailtext .= "<div style=\"width:100%; height:20px;\"> </div>";
         endif;
         
         if ($mailDisplayModeEmployeeData == "1") :
            $mailtext .= "<div class=\"" . $mailCssFontClass . "\">" . $mailSuccessRequest . "</div>";
            $mailtext .= "<div style=\"width:100%; height:10px;\"> </div>";
         endif;

         // Survey
         if ($job_status == "2") :
            $mailSurvey = getParameterValue("0", "MAIL_SURVEY", $currentHqId);
            if ($mailSurvey == "" || !is_numeric($mailSurvey)) : $mailSurvey = getParameterValue("0", "MAIL_SURVEY", "0"); endif;
            if ($mailSurvey != "" && is_numeric($mailSurvey)) :
               // Send survey link in mail if random number equals "1" only
               if (rand(1, $mailSurvey) == 1) :
                  if (checkJobForSurvey($job_id, "15", "0")) :
                     $mailTextSurvey = getParameterValue("0", "MAIL_TEXT_SURVEY", $currentHqId);
                     if ($mailTextSurvey == "") : $mailTextSurvey = getLngt("Bitte machen Sie uns eine Freude und bewerten Sie uns"); endif;
                     $mailTextSurvey2 = getParameterValue("0", "MAIL_TEXT_SURVEY2", $currentHqId);
                     if ($mailTextSurvey2 == "") : $mailTextSurvey2 = getLngt("HIER"); endif;
                     $mailTextSurvey3 = getParameterValue("0", "MAIL_TEXT_SURVEY3", $currentHqId);
                     // if ($mailTextSurvey3 == "") : $mailTextSurvey3 = getLngt(""); endif;
                     $mailLinkSurvey = getParameterValue("0", "MAIL_LINK_SURVEY", $currentHqId);
                     if ($mailLinkSurvey == "") : $mailLinkSurvey = getParameterValue("0", "MAIL_LINK_SURVEY", "0"); endif;
                     if ($mailLinkSurvey != "") : 
                        $jbCrypt = (((((((($job_id + $eca[0]) * 2) + $eca[1]) * 2) + $eca[2]) * 2) + $eca[3]) * 2) + $eca[4];
                        $mailTextSurvey = $mailTextSurvey . " " . "<a href=\"" . $mailLinkSurvey . "survey.php?jb=__" . $jbCrypt . "__&op=<postparser>HASH</postparser>\">" . getLngt($mailTextSurvey2) . "</a>" . " " . getLngt($mailTextSurvey3);
                        $mailTextSurvey = postParseMailtext($mailTextSurvey, "cs", $csIdPayer);
                        $mailtext .= "<div class=\"" . $mailCssFontClass . "\">" . getLngt($mailTextSurvey) . "</div>";
                        $mailtext .= "<div style=\"width:100%; height:10px;\"> </div>";
                     endif;
                  endif;
               endif;
            endif;
         endif;

         // Conditions
         if ($mailTextJobStatus == "OFFER") :
            // $mailConditionText = getParameterValue("0", "MAIL_CONDITION_TEXT_OFFER", $currentHqId);
            // if ($mailConditionText == "") : $mailConditionText = getParameterValue("0", "MAIL_CONDITION_TEXT_OFFER", "0"); endif;
            // if ($mailConditionText == "") :
               $mailConditionText = getLngt("Unsere Preise verstehen sich zzgl. 19% MwSt. - exkl. kostenpflichtiger Servicezeit.") . "</br>"
                                  . getLngt("Zur Erfüllung der rechtlichen Verpflichtung werden die Anfragen, Angebote, Mails datenschutzkonform gelöscht.") . "</br>"
                                  . getLngt("Wenn Sie Änderungswünsche haben, oder ihre Bestellung auslösen möchten, melden Sie sich gerne per Antwort auf diese Mail") . "</br>"
                                  . getLngt("oder rufen Sie uns einfach unter Nennung der Angebotsnummer an.");
            // endif;
            $mailtext .= "<div class=\"" . $mailCssFontClass . "\">" . $mailConditionText . "</div>";
            $mailtext .= "<div style=\"width:100%; height:10px;\"> </div>";
         elseif ($mailTextJobStatus == "OFFER_CHANGE") :
            // $mailConditionText = getParameterValue("0", "MAIL_CONDITION_TEXT_OFFER_CHANGE", $currentHqId);
            // if ($mailConditionText == "") : $mailConditionText = getParameterValue("0", "MAIL_CONDITION_TEXT_OFFER_CHANGE", "0"); endif;
            // if ($mailConditionText == "") :
               $mailConditionText = getLngt("Unsere Preise verstehen sich zzgl. 19% MwSt. - exkl. kostenpflichtiger Servicezeit.") . "</br>"
                                  . getLngt("Zur Erfüllung der rechtlichen Verpflichtung werden die Anfragen, Angebote, Mails datenschutzkonform gelöscht.") . "</br>"
                                  . getLngt("Wenn Sie Änderungswünsche haben, oder ihre Bestellung auslösen möchten, melden Sie sich gerne per Antwort auf diese Mail") . "</br>"
                                  . getLngt("oder rufen Sie uns einfach unter Nennung der Angebotsnummer an.");
            // endif;
            $mailtext .= "<div class=\"" . $mailCssFontClass . "\">" . $mailConditionText . "</div>";
            $mailtext .= "<div style=\"width:100%; height:10px;\"> </div>";
         endif;

         // Current informations to customer
         $mailTextInfoByHq = "";
         // Check for avoiding footer
         $csEmailNoFooter = getParameterValue("0", "JOBDETAILS_EMAIL_NO_FOOTER_" . $csIdPayer, "0");
         if ($csEmailNoFooter != "1") : 
            if (existsEntry("genericdatacontainer",array("gdc_obj_type","hq2cs","gdc_obj_id",$hq_id,"gdc_gen_fieldname","global_cs_email_info"))) :
               $mailTextInfoByHq = getFieldValueFromClause("genericdatacontainer","gdc_content","gdc_obj_type = 'hq2cs' AND gdc_obj_id = '" . $currentHqId . "' AND gdc_gen_fieldname = 'global_cs_email_info'");
               $mailTextInfoByHq = trim($mailTextInfoByHq);
               if ($mailTextInfoByHq != "") :
                   $mailTextInfoByHq = nl2br($mailTextInfoByHq);
                   $mailtext .= "<div class=\"" . $mailCssFontClass . "\">" . $mailTextInfoByHq . "</div>";
                   $mailtext .= "<div style=\"width:100%; height:10px;\"> </div>";
               endif;
            endif;
         endif;

         // Signature
         $mailTextRegards = getParameterValue("0", "MAIL_TEXT_REGARDS", $currentHqId);
         if ($mailTextRegards == "") : $mailTextRegards = getLngt("Mit freundlichem Gruß,"); endif;
         $mailtext .= "<div class=\"" . $mailCssFontClass . "\">" . $mailTextRegards . "</div>";
         if ($mailDisplayModeEmployeeData == "1" && $mailEmployeeData[0] != "" && $mailEmployeeData[1] != "") :
            $mailtext .= "<div style=\"width:100%; height:10px;\"> </div>";
            $mailtext .= "<div class=\"" . $mailCssFontClass . "\">" . $mailEmployeeData[0] . " " . $mailEmployeeData[1] . "</div>";
         else :
            $mailSalutationText = getParameterValue("0", "MAIL_SALUTATION_TEXT", $currentHqId);
            $mailtext .= "<div class=\"" . $mailCssFontClass . "\">" . getLngt($mailSalutationText) . "</div>";
         endif;
         $mailtext .= "<div style=\"width:100%; height:10px;\"> </div>";

         // HOMEPAGE
         $mailFooterWebPage = getParameterValue("0", "MAIL_FOOTER_WEB_PAGE", $currentHqId);

         // 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 .= "<div style=\"width:100%; height:10px;\"> </div>";
            if ($mailFooterWebPage != "") : 
               $mailtext .= "<div><a href=\"http://" . $mailFooterWebPage . "\"><img src=\"../images/external/" . $logoName . "\" border=\"0\" height=\"" . $logoHeight . "\" width=\"" . $logoWidth . "\"></a></div>";
            else :
               $mailtext .= "<div><img src=\"../images/external/" . $logoName . "\" border=\"0\" height=\"" . $logoHeight . "\" width=\"" . $logoWidth . "\"></div>";
            endif;
            $mailtext .= "<div style=\"width:100%; height:10px;\"> </div>";
         endif;

         
         $mailFooterEnabled = getParameterValue("0", "MAIL_FOOTER_ENABLED", $currentHqId);
         if ($mailFooterEnabled == "1") :
            $mailFooterAddress = getParameterValue("0", "MAIL_FOOTER_ADDRESS", $currentHqId);
            if ($mailFooterAddress != "") :
               $mailtext .= "<table style=\"font-family: Arial; font-size: 10pt; font-weight: normal; padding: 1px; color: #000000;\">";
               $mailtext .= $mailFooterAddress;
               $mailtext .= "</table>";
               $mailtext .= "<div style=\"width:100%; height:10px;\"> </div>";
            endif;
            $mailFooterContact = getParameterValue("0", "MAIL_FOOTER_CONTACT", $currentHqId);
            if ($mailFooterContact != "") :                  
               if ($mailDisplayModeEmployeeData == "1" && ($mailEmployeeData[2] != "" || $mailEmployeeData[3] != "" || $mailEmployeeData[4] != "")) :
                  $mailtext .= "<table>";
                  if ($mailEmployeeData[2] != "") : 
                     $mailtext .= "<tr><td><span class=\"" . $mailCssFontClass . "\">" . getLngt("Telefon") . ": " . $mailEmployeeData[2] . "</span></td></tr>";
                  endif;
                  if ($mailEmployeeData[4] != "") : 
                     $mailtext .= "<tr><td><span class=\"" . $mailCssFontClass . "\">" . getLngt("Fax") . ": " . $mailEmployeeData[4] . "</span></td></tr>";
                  endif;
                  if ($mailEmployeeData[3] != "") : 
                     $mailtext .= "<tr><td><span class=\"" . $mailCssFontClass . "\">" . getLngt("Email") . ": " . $mailEmployeeData[3] . "</span></td></tr>";
                  endif;
                  // $mailFooterWebPage = getParameterValue("0", "MAIL_FOOTER_WEB_PAGE", $currentHqId);
                  if ($mailFooterWebPage != "") : 
                     // $mailtext .= "<tr><td><span class=\"" . $mailCssFontClass . "\">" . $mailFooterWebPage . "</span></td></tr>";
                     $mailtext .= "<tr><td><span class=\"" . $mailCssFontClass . "\"><a href=\"http://" . $mailFooterWebPage . "\">" . $mailFooterWebPage . "</a></span></td></tr>";
                  endif;
                  $mailtext .= "</table>";
               else :
                  $mailtext .= "<table style=\"font-family: Arial; font-size: 10pt; font-weight: normal; padding: 1px; color: #000000;\">";
                  $mailtext .= $mailFooterContact;
                  $mailtext .= "</table>";
               endif;                  
               $mailtext .= "<div style=\"width:100%; height:10px;\"> </div>";
            endif;
            $mailFooterImpressum = getParameterValue("0", "MAIL_FOOTER_IMPRESSUM", $currentHqId);
            if ($mailFooterImpressum != "") :
               $mailtext .= "<table style=\"font-family: Arial; font-size: 7pt; font-weight: normal; padding: 1px; color: #000000;\">";
               $mailtext .= $mailFooterImpressum;
               $mailtext .= "</table>";
               $mailtext .= "<div style=\"width:100%; height:10px;\"> </div>";
            endif;
            $mailFooterResponsibility = getParameterValue("0", "MAIL_FOOTER_RESPONSIBILITY", $currentHqId);
            if ($mailFooterResponsibility == "") : $mailFooterResponsibility = getParameterValue("0", "MAIL_FOOTER_RESPONSIBILITY", "0"); endif;
            if ($mailFooterResponsibility != "") : 
               $mailtext .= "<div style=\"font-family: Arial; font-size: 7pt; font-weight: normal; padding: 1px; color: #000000;\">" . $mailFooterResponsibility . "</div>";
               // Extended text
               $mailFooterResponsibility2 = getParameterValue("0", "MAIL_FOOTER_RESPONSIBILITY_2", $currentHqId);
               if ($mailFooterResponsibility2 == "") : $mailFooterResponsibility2 = getParameterValue("0", "MAIL_FOOTER_RESPONSIBILITY_2", "0"); endif;
               if ($mailFooterResponsibility2 != "") : 
                  $mailtext .= "<div style=\"font-family: Arial; font-size: 7pt; font-weight: normal; padding: 1px; color: #000000;\">" . $mailFooterResponsibility2 . "</div>";
                  $mailFooterResponsibility3 = getParameterValue("0", "MAIL_FOOTER_RESPONSIBILITY_3", $currentHqId);
                  if ($mailFooterResponsibility3 == "") : $mailFooterResponsibility3 = getParameterValue("0", "MAIL_FOOTER_RESPONSIBILITY_3", "0"); endif;
                  if ($mailFooterResponsibility3 != "") : 
                     $mailtext .= "<div style=\"font-family: Arial; font-size: 7pt; font-weight: normal; padding: 1px; color: #000000;\">" . $mailFooterResponsibility3 . "</div>"; 
                     $mailFooterResponsibility4 = getParameterValue("0", "MAIL_FOOTER_RESPONSIBILITY_4", $currentHqId);
                     if ($mailFooterResponsibility4 == "") : $mailFooterResponsibility4 = getParameterValue("0", "MAIL_FOOTER_RESPONSIBILITY_4", "0"); endif;
                     if ($mailFooterResponsibility4 != "") : 
                        $mailtext .= "<div style=\"font-family: Arial; font-size: 7pt; font-weight: normal; padding: 1px; color: #000000;\">" . $mailFooterResponsibility4 . "</div>";
                        $mailFooterResponsibility5 = getParameterValue("0", "MAIL_FOOTER_RESPONSIBILITY_5", $currentHqId);
                        if ($mailFooterResponsibility5 == "") : $mailFooterResponsibility5 = getParameterValue("0", "MAIL_FOOTER_RESPONSIBILITY_5", "0"); endif;
                        if ($mailFooterResponsibility5 != "") : 
                           $mailtext .= "<div class=\"" . $mailFooterImpressum . "\">" . $mailFooterResponsibility5 . "</div>";
                        endif;
                     endif;
                  endif;
                  $mailtext .= "<div style=\"width:100%; height:10px;\"> </div>";
               endif;
            endif;
            $mailFooterThinkGreen = getParameterValue("0", "MAIL_FOOTER_THINK_GREEN", $currentHqId);
            if ($mailFooterThinkGreen != "") :
               $mailtext .= $mailFooterThinkGreen;
               $mailtext .= "<div style=\"width:100%; height:10px;\"> </div>";
            endif;
            $mailtext .= "<div style=\"width:100%; height:30px;\"> </div>";               
         endif;

         // Mandatory email footer
         $mailFooterMandatory = getParameterValue("0", "MAIL_FOOTER_MANDATORY", $currentHqId);
         if ($mailFooterMandatory == "") : $mailFooterMandatory = getParameterValue("0", "MAIL_FOOTER_MANDATORY", "0"); endif;
         if ($mailFooterMandatory != "") :
            $mailtext .= "<div class=\"" . $mailCssFontClass . "\" style=\"width: 100%; text-align: left;\">";
            $mailtext .= "  <div style=\"max-width: 600px; margin: 0; line-height: 1.5; color: #333333;\">";
            $mailtext .= "    <table role=\"presentation\" width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">";
            $mailtext .= "      <tr><td style=\"padding: 10px 0; text-align: left; word-wrap: break-word;\">" . $mailFooterMandatory . "</td></tr>";
            $mailtext .= "    </table>";
            $mailtext .= "  </div>";
            $mailtext .= "</div>";
            $mailtext .= "<div style=\"width:100%; height:10px;\"> </div>";
         endif;

         if ($mailJobData == "0") :
            $mailtext .= $jobtext;
         endif;

         $mailtext .= "</body></html>";

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

         // Set From address
         $mailFromAddress = getParameterValue("0", "MAIL_SENDER_ADDRESS", $currentHqId);
         if ($mailFromAddress == "") :
            $mailFromAddress = MAIL_SENDER_ADDRESS;
         endif;
         $mailObj->setFrom($mailFromAddress);

         // 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(getLngt("Transportauftrag") . " " . $job_id . " : " . getLngt("Die Abholung erfolgte!"));
         elseif ($mailTextJobStatus == "8" || $mailTextJobStatus == "9") :
            $mailObj->setSubject(getLngt("Transportauftrag") . " " . $job_id . " " . getLngt("ist in der Vermittlung!"));
         elseif ($mailTextJobStatus == "ALL") :
            $mailObj->setSubject(getLngt("Transportauftrag") . " " . $job_id . " : " . getLngt("Die") . " " . $tour_sort . ". " . getLngt("Station Ihres Auftrags wurde erledigt."));
         elseif ($mailTextJobStatus == "CHANGE") :
            $mailObj->setSubject(getLngt("Transportauftrag") . " " . $job_id . " " . getLngt("wurde geändert!"));
         elseif ($mailTextJobStatus == "OFFER") :
            $mailObj->setSubject(getLngt("Ihre Transportanfrage / unser Angebot") . " " . $job_id);
         elseif ($mailTextJobStatus == "OFFER_CHANGE") :
            $mailObj->setSubject(getLngt("Ihre Transportanfrage / unser Angebot") . " " . $job_id . " " . getLngt("wurde geändert!"));
         else :
            $mailObj->setSubject(getLngt("Transportauftrag") . " " . $job_id . " " . getLngt("ist erledigt!"));
         endif;

         // Generate PDF if enabled for customer            
         $tmpPdfPath = "../temp/pdf/";
         $pdfFile = "Auftrag_" . $job_id . ".pdf";
         $csJbstatusmailPdf = getFieldValueFromId("customer","cs_id",$csIdPayer,"cs_jbstatusmail_pdf");
         if ($csJbstatusmailPdf == "1" && $job_status == "2") :
            $remAutomailer = $automailer;  // Remember state            
            $includePDFGeneric = "1";
            $f_act = "generatePDFJob";
            $storeAsFile = "1";
            $jbId = $job_id;            
            // include_once ("../admin/pdf_generic.php");
            include ("../admin/pdf_generic.php");

            if (file_exists($tmpPdfPath . $pdfFile)) :
               $attachment = $mailObj->getFile($tmpPdfPath . $pdfFile);
               $mailObj->addAttachment($attachment, $pdfFile, 'application/pdf');
            endif;
            $automailer = $remAutomailer;
         endif;

         // Check for existence of more attachements
         if (isset($jbMailAttachements) && is_array($jbMailAttachements)) :
            $jbMailAttachementslen = count($jbMailAttachements);
            $tmpAttachement = array();
            for ($at = 0; $at < $jbMailAttachementslen; $at++) :
                if ($jbMailAttachements[$at] != "") :
                   $tmpAttachement[$at] = $mailObj->getFile($jbMailAttachements[$at][0]);
                   $mailObj->addAttachment($tmpAttachement[$at], $jbMailAttachements[$at][1], 'application/pdf');
                endif;
            endfor;
         endif;

         // Check for existence of embedded images
         /*
         if (isset($jbMailEmbeddedImages) && is_array($jbMailEmbeddedImages)) :
            $jbMailEmbeddedImageslen = count($jbMailEmbeddedImages);
            $tmpEmbeddedImages = array();
            for ($ei = 0; $ei < $jbMailEmbeddedImageslen; $ei++) :
                if ($jbMailEmbeddedImages[$ei] != "") :
                   $tmpEmbeddedImages[$ei] = $mailObj->getFile($jbMailEmbeddedImages[$ei][0]);
                   $mailObj->addHtmlImage($tmpEmbeddedImages[$ei], $jbMailEmbeddedImages[$ei][1], 'image/jpeg');
                endif;
            endfor;
         endif;
         */

         $mailResult = false;
         $semaphorMailSent = true;
         $semaphorInsertedForMailSent = false;
         $jbMailAttachements = array();  // Reset attachement array (!!!!)
         /*
         if (isset($semaphorNewFunctionality) && $semaphorNewFunctionality == "1") :  // ATTENTION: For compatibility regarding semaphore only !!!!!!!!!!!! **** REMOVE **** !!!!!!!!!!!
            if ($automailer == "1" && $semaphorKey != "") :
               
               $semaphorMailSent = false;
               $currentTime = getDateTime("0");
            
               // Set semaphore to be LOCKED               
               $res = updateStmt("phoenix_log.semaphor", "sp_obj_id", $job_id, array("sp_content", "LOCKED", "sp_createtime", $currentTime), "sp_obj_type = 'jb' AND sp_fieldname = '" . $semaphorKey . "' AND sp_content = ''");
               if ($res > 0) :
                  $semaphorMailSent = true;
                  $semaphorInsertedForMailSent = true;
               endif;
            endif;
         endif;
         */
         if ($semaphorMailSent) :
            // Send email
            $mailResult = $mailObj->send(array($f_email), 'smtp');

            // Using PEAR alternative
            // $conf = prepareSendMailPear("smtp.1und1.com","m34847762-7","%CdGm%",$f_email,"Transportauftrag " . $job_id . " erledigt!","votian","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 = getLngt("Die Nachricht wurde versandt!");
               
               // Write logdata into log database
               writeToLogDB("22",$currentHqId,$job_id,$currentSessionUsrId,"","","","MAIL_STATE=SENT|MAIL_TO=" . $f_email);
            else :
               // In case of failure this process only, which successfully inserted the semaphore, is able to remove the semaphore for the next trial sending the mail for a new process
               /*
               if ($semaphorInsertedForMailSent) :
                  $currentTime = getDateTime("0");
                  $res = updateStmt("phoenix_log.semaphor", "sp_obj_id", $job_id, array("sp_content", "", "sp_createtime", $currentTime), "sp_obj_type = 'jb' AND sp_fieldname = '" . $semaphorKey . "' AND sp_content = 'LOCKED'");
               endif;
               */
            
               $mailsendStatus = getLngt("Die Nachricht konnte nicht gesendet werden!");
               
               // Write logdata into log database
               writeToLogDB("23",$currentHqId,$job_id,$currentSessionUsrId,"","","","MAIL_STATE=NOT SENT|MAIL_TO=" . $f_email);
            endif;
         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;

         // Remove stored temporary pdf documents on the filesystem
         if (file_exists($tmpPdfPath . $pdfFile)) :
            unlink($tmpPdfPath . $pdfFile);
         endif;

         if ($remLanguageSelected != "") :
            $languageSelected = $remLanguageSelected;  // Reset language of the customer
            getLanguage(__FILE__);
            $currentJobParameterState = getJobSnapshot($job_id);
         endif;
      else :
         $mailsendStatus = getLngt("Die eingegebene Emailadresse ist syntaktisch nicht korrekt!");
      endif;
   endif;

   if ($automailer == "0" && $jobIsAllowedToBeModified) :
      $mailsend .= "<div style=\"float:left\">\n";
      $mailsend .= getLngt("Mailadresse:") . "&nbsp;&nbsp;";
      $mailsend .= "<input type=\"text\" name=\"f_email\" value=\"\">&nbsp;&nbsp;&nbsp;";
      $mailsend .= "</div>";
      // $mailsend .= "<input type=\"button\" value=\"" . getLngt("Auftragsmail senden") . "\" onClick=\"javascript:mailsend();\">";
      $mailsend .= defineButtonType10(getLngt("Auftragsmail senden"), "action_sendmail", "mailsend();", "150");
      $mailsend .= "<div><br><span class=\"f8np1_red\">" . $mailsendStatus . "</span></div>";
   endif;
endif;


// --- BOOK JOB (Finalize) ---------------
// --- CHANGE COURIER (If job is finished and not exported) ---------------
if ($automailer == "0" && $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");
         
         // Get real vht_id to store in job in contrast to requested vht_id
         $vht_id_book = getFieldValueFromId("couriervehicle", "crvh_sid", $f_crvh_sid_book, "vht_id");

         // Set the current timestamp to store the data
         $currentTime = getDateTime("0");

         if ($cr_id_book != "") :

            $bookJobTime = $currentTime;
            $cr_hq_id_book = getFieldValueFromId("courier", "cr_id", $cr_id_book, "hq_id");

            // 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;

            // Get "third country" state of the job regarding flag "jb_incomplete"
            // $jobThirdCountry = getFieldValueFromClause("genericdatacontainer", "gdc_content", "gdc_obj_type = 'jb' AND gdc_obj_id = '" . $job_id . "' AND gdc_gen_fieldname = 'jb_third_country'");

            if ($globalParUseRelatedCustomer == "1" || $job_id_parent == "" || $job_id_parent == "0") :   // Either special mode of system usage OR only jobs not having sub-jobs

               if ($job_status != "2") :

                  // Check current state of job is "taken"
                  if ($job_status == "1") :
                     $jbCrIdCurr = getFieldValueFromId("job", "jb_id", $job_id, "cr_id");
                     if (is_numeric($jbCrIdCurr) && $jbCrIdCurr > "0") :
                        // Send command
                        insertPDACommand($currentHqId, $jbCrIdCurr, "3", "1", $job_id, $currentTime, "");
                     endif;
                  endif;

                  // Update and finalize job
                  updateStmt($dbh_jb, "jb_id", $job_id, array("cr_id", $cr_id_book, "hq_id_exec", $cr_hq_id_book, "jb_status", "2", "cr_sid", $f_crvh_sid_book, "vht_id_real", $vht_id_book, "jb_finishtime", $bookJobTime, "jb_booktime", $currentTime), "(hq_id = '" . $currentHqId . "')");
                  /*
                  if ($jobThirdCountry == "1") :
                     $job_incomplete = "1";
                     $f_jb_incomplete = "";
                     updateStmt($dbh_jb, "jb_id", $job_id, array("jb_incomplete", $job_incomplete), "(hq_id = '" . $currentHqId . "')");
                  endif;
                  */

                  $bookjobStatus = getLngt("Der Auftrag wurde abgeschlossen!");

                  // Update available time according to finishing by PDA
                  if ($jobCourierId == $cr_id_book && substr($job_ordertime, 0, 10) == substr($currentTime, 0, 10)) :

                     updateStmt("courier", "cr_id", $cr_id_book, array("cr_availabletime", $currentTime), "(hq_id = '" . $currentHqId . "')");

                     $bookjobStatus .= " " . getLngt("Der Transporteur verlor seine Rankingposition!");
                  endif;

                  // Update "vehicledisposition" and remove job
                  updateStmt("vehicledisposition", "jb_id", $job_id, array("jb_id", "0"));

                  // Write logdata into log database
                  writeToLogDB("5",$currentHqId,$job_id,$currentSessionUsrId,$cr_id_book,$f_crvh_sid_book,"","");

                  // check whether there is something to do with jb_cr_price
                  check_cr_agio($job_id);
               else :               
                  if ($job_export_time == "" || $job_export_time == "0000-00-00 00:00:00" || $job_export_time == "9999-12-31 23:59:59") :

                     // 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) :

                        // Not used here because job state is "finished" and not "taken" (!!!!)
                        // if (is_numeric($jbCrIdCurr) && $jbCrIdCurr > "0") :
                           // Send command
                           // insertPDACommand($hq_id, $jbCrIdCurr, "3", "1", $job_id, $currentTime, "");
                           // insertPDACommand($hq_id, $jbCrIdCurr, "8", "1", $job_id, $currentTime, "");
                        // endif;

                        // 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, "hq_id_exec", $cr_hq_id_book, "cr_sid", $f_crvh_sid_book, "vht_id_real", $vht_id_book), "(hq_id = '" . $currentHqId . "')");
                        /*
                        if ($jobThirdCountry == "1") :
                           $job_incomplete = "1";
                           $f_jb_incomplete = "";
                           updateStmt($dbh_jb, "jb_id", $job_id, array("jb_incomplete", $job_incomplete), "(hq_id = '" . $currentHqId . "')");
                        endif;
                        */
                        
                        $bookjobStatus = getLngt("Die Fahrzeugnummer wurde geändert!");
                        
                        // Write logdata into log database
                        writeToLogDB("21",$currentHqId,$job_id,$currentSessionUsrId,$cr_id_book,$f_crvh_sid_book,"","");

                        // check whether there is something to do with jb_cr_price
                        check_cr_agio($job_id);

                     // else :
                     //   $bookjobStatus = getLngt("Achtung! Das eingegebene Fahrzeug stammt nicht von dem Transporteur der Tour!");
                     // endif;
                  else:
                     $bookjobStatus = getLngt("Der Auftrag wurde schon exportiert! Eine Änderung ist daher nicht möglich!");
                  endif;
               endif;
            else:
               $bookjobStatus = getLngt("Der Auftrag hat Unteraufträge! Eine Änderung ist daher nicht möglich!");
            endif;
         else :
            $bookjobStatus = getLngt("Die gewählte Fahrzeugnummer konnte keinem Kurier zugeordnet werden!");
         endif;
      else:
         $bookjobStatus = getLngt("Der Auftrag konnte nicht verbucht werden! Geben Sie bitte einen Transporteur an!");
      endif;
   endif;
  
   // ONLY show if job is not exported
   if ($automailer == "0" && ($job_export_time == "" || $job_export_time == "0000-00-00 00:00:00" || $job_export_time == "9999-12-31 23:59:59") && $takeRealJobData) :
 
      if ($jbAccessModeArr["1"]) :
 
         $bookjobButtonText = getLngt("Auftrag&nbsp;abschließen");
         if ($job_status == "2") : $bookjobButtonText = getLngt("Fahrzeug&nbsp;ändern"); endif;
         
         $bookjob .= "<div style=\"float:left\">\n";
         $bookjob .= "<select id=\"f_crvh_sid_book\" 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 . "'", "");
            $bookjob .= addOptionsFromTable("couriervehicle AS crvh, courier AS cr, headquarters AS hq", "crvh_sid", "crvh_sid", "crvh_sid", "crvh.cr_id = cr.cr_id AND cr.hq_id = hq.hq_id AND hq.hq_disabled = '0'", "");
         // else :
         //    $bookjob .= addOptionsFromTable("couriervehicle", "crvh_sid", "crvh_sid", "crvh_sid", " cr_id = '" . $jobCourierId . "' ", $job_cr_sid);
         // endif;
         
         $bookjob .= "</select>\n";
         $bookjob .= "&nbsp;&nbsp;\n";
         $bookjob .= "<input id=\"crSearchInput\" onkeyup=\"filterOptions('crSearchInput', 'f_crvh_sid_book')\" type=\"text\" placeholder=\"" . getLngt("Suche SID") . "\" size=\"10\">";
         $bookjob .= "&nbsp;&nbsp;</div>\n";
         $bookjob .= defineButtonType10($bookjobButtonText, "action_book", "bookjob();", "150", "left", "3");
         $bookjob .= "<div style\"float_left\">\n";
         
         // Select "current time" (default) or "finish time" to finalize the job
         if ($job_status != "2") :
            $bookjob .= "<input type=\"radio\" name=\"f_jb_finishtime4booking\" value=\"0\"" . ($f_jb_finishtime4booking == "" || $f_jb_finishtime4booking == "0" ? "checked" : "") . "> " . getLngt("Akt. Tagesdatum");
            $bookjob .= "<input type=\"radio\" name=\"f_jb_finishtime4booking\" value=\"1\"" . ($f_jb_finishtime4booking == "1" ? "checked" : "") . "> " . getLngt("Auftragsdatum");
         endif;
         
         $bookjob .= "<br><br><span class=\"f8np1_red\">" . $bookjobStatus . "</span>";
         $bookjob .= "</div>\n";
      endif;
   endif;
endif;


// --- CHANGE COURIER ONLY FOR RESERVATIONS ---------------
if ($automailer == "0" && ($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");
         
         // Get real vht_id to store in job in contrast to requested vht_id
         $vht_id_order = getFieldValueFromId("couriervehicle", "crvh_sid", $f_crvh_sid_order, "vht_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, "vht_id_real", $vht_id_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, "vht_id_real", $vht_id_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 = getLngt("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", "", "vht_id_real", "0"), "(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", "", "vht_id_real", "0"), "(hq_id = '" . $currentHqId . "')");
                  
                  // Write logdata into log database
                  writeToLogDB("19",$currentHqId,$job_id,$currentSessionUsrId,"","","","");
               endif;                  
            else :
               $changeCourierStatus = getLngt("Die gewählte Fahrzeugnummer konnte keinem Kurier zugeordnet werden!");
            endif;
         endif;
      else:
         $changeCourierStatus = getLngt("Die Anforderung konnte nicht zugeteilt werden! Geben Sie bitte ein Fahrzeug an!");
      endif;
   endif;
  
   $changeCourier .= "<select name=\"f_crvh_sid_order\">\n";
   $changeCourier .= "<option value=\"\" selected>&nbsp;</option>\n";
   $changeCourier .= "<option value=\"0\">" . getLngt("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=\"" . getLngt("Anforderung ändern") . "\" onClick=\"javascript:changeCourierOrder();\">";
   $changeCourier .= "<br>";
   $changeCourier .= "<input type=\"checkbox\" name=\"f_crvh_sid_order_permanent\" value=\"1\"> " . getLngt("Permanente Anforderung") . "\n";
   $changeCourier .= "<br><br><span class=\"f8np1_red\">" . $changeCourierStatus . "</span>";
endif;   


// --- MODIFY/REMOVE TOURNAME ---------------
if ($automailer == "0" && $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, "csc_id_payer", $cscIdPayer)) ||
                existsEntry($dbh_jb, array("jb_tourname", $f_tourname, "csc_id_payer_cash", $cscIdPayer)))):
              
            // Update job with new tourname
            updateStmt($dbh_jb, "jb_id", $job_id, array("jb_tourname", $f_tourname), "(hq_id = '" . $currentHqId . "')");

            $modifyTournameStatus = getLngt("Der Tourname wurde geändert!");
            
            // Write logdata into log database
            writeToLogDB("15",$currentHqId,$job_id,$currentSessionUsrId,"","","",$f_tourname);
         else :
            $modifyTournameStatus = getLngt("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 = getLngt("Der Tourname wurde gelöscht!");
         
         // Write logdata into log database
         writeToLogDB("16",$currentHqId,$job_id,$currentSessionUsrId,"","","","");
      endif;
      
      $job_tourname = $f_tourname;
   endif;

   if ($jobIsAllowedToBeModified || $globalParUseRelatedCustomer != 1) :
      $modifyTourname .= "<div style=\"float:left\">" . getLngt("Tourname") . ":&nbsp;&nbsp;";
      $modifyTourname .= "<input type=\"text\" name=\"f_tourname\" value=\"" . $job_tourname . "\" size=\"50\" maxlength=\"50\">&nbsp;&nbsp;&nbsp;</div>";
      if ($jbAccessModeArr["1"]) :
         $modifyTourname .= defineButtonType10(getLngt("Tourname&nbsp;modifizieren"), "action_tourname", "changeTourname();", "180", "left", "3");
      endif;
      $modifyTourname .= "<div><br><br><span class=\"f8np1_red\">" . $modifyTournameStatus . "</span></div>";
   endif;
endif;   


// Change added installation value
if ($f_act == "changeGDC_addMon") :
   if ($globalParUseRelatedCustomer == "1" && $jobHasAddedInstallation && $automailer == "0" && $job_id != "" && ($jobService & 2) == 2) :

      $f_jb_gdc_add_mon = trim($f_jb_gdc_add_mon);
      $f_jb_gdc_add_mon = str_replace (",", ".", $f_jb_gdc_add_mon);
      if ($f_jb_gdc_add_mon != "" && is_numeric($f_jb_gdc_add_mon) && $f_jbp_mode_add_mon != "" && is_numeric($f_jbp_mode_add_mon)) :

         // Update value in GDC
         // ATTENTION: Presently the row has to exist and a new row cannot be inserted !!!!
         updateStmt("genericdatacontainer", "gdc_obj_id", $job_id, array("gdc_content", $f_jb_gdc_add_mon), "gdc_obj_type = 'jb' AND gdc_gen_fieldname = 'jb_addmont'");
         addmontEdit($job_id, $f_jbp_mode_add_mon);
      endif;
   endif;
endif;


// --- DISPLAY SCAN EVENTS ---------------
$scanEventsHtml = "";
if ($globalParUseRelatedCustomer == 1 && $automailer == "0" && $job_id != "") :
   $scanEventsHtml = getScanEventsHtml($job_id);
endif;

// --- DISPLAY MANUAL EVENTS ---------------
$manualEventsHtml = "";
if ($globalParUseRelatedCustomer == 1 && $automailer == "0" && $job_id != "") :
   $manualEventsHtml = getManualEventsHtml($job_id);
endif;

// --- DISPLAY TOURARTICLES ---------------
// Display articles
$outputTourarticle = "";
if ($globalParUseRelatedCustomer == "1" && $automailer == "0" && $job_id != "") :
   $outputTourarticle = getOutputJobTratArticleData($job_id);
endif;


// --- DISPLAY JOBCALCULATOR ENTRIES ---------------
$outputJobcalculator = "";
if ($globalParUseRelatedCustomer == "1" && $automailer == "0" && $job_id != "") :
   $outputJobcalculator = getOutputJobCalculatorData($job_id);
endif;


// --- DISPLAY JOBPRICE ENTRIES ---------------
$outputJobprice = "";
if ($globalParUseRelatedCustomer == "1" && $automailer == "0" && $job_id != "") :
   $outputJobprice = getOutputJobPriceData($job_id);
endif;


// Get possible payment methodes for customer or group
if ($globalParUseRelatedCustomer == "1") :

   // Check job being a special service job
   $jobIsSpecialServiceJob = "";
   if ($db->getOne("SELECT gdc_content FROM genericdatacontainer WHERE gdc_obj_type = 'jb' AND gdc_obj_id = '" . $job_id . "' AND gdc_gen_fieldname = 'jb_service_job'") == 1):
      $jobIsSpecialServiceJob = "1";
   endif;

   // Check job being a special job payed by the carrier
   $jobIsPayedByCarrier = "";
   if ($db->getOne("SELECT gdc_content FROM genericdatacontainer WHERE gdc_obj_type = 'jb' AND gdc_obj_id = '" . $job_id . "' AND gdc_gen_fieldname = 'jb_no_payment_job'") == 1):
      $jobIsPayedByCarrier = "1";
   endif;

   // Get related customer and group
   $jbpCscId = getFieldValueFromId("job", "jb_id", $job_id, "csc_id_related");
   $jbpCsId = getFieldValueFromId("costcenter", "csc_id", $jbpCscId, "cs_id");
   $tmpJbpCsGrpId = getFieldValueFromId("customer","cs_id",$jbpCsId,"cs_group");
   $jbpCsGrpIdArray = spliti(",", $tmpJbpCsGrpId);
   $jbpCsGrpIdArrayLen = count($jbpCsGrpIdArray);
   if ($jbpCsGrpIdArrayLen > 0) :
      $jbpCsGrpId = $jbpCsGrpIdArray[1];  // .... because of leading comma sign
   endif;
   if ($jbpCsId != "") :
      // Get payment types using cascading structure
      $mtPaymentTypes = getColVectorFromDB2ArrayByClause("metatype", "mt_value", "mt_type = 'payment_type' AND mt_objtype = 'cs' AND mt_objid = '" . $jbpCsId . "'", "mt_sort", "mt_sort", "");
      if (count($mtPaymentTypes) == 0 && $jbpCsGrpId != "") :
         $mtPaymentTypes = getColVectorFromDB2ArrayByClause("metatype", "mt_value", "mt_type = 'payment_type' AND mt_objtype = 'grp' AND mt_objid = '" . $jbpCsGrpId . "'", "mt_sort", "mt_sort", "");
      endif;
      if (count($mtPaymentTypes) == 0) :
         $mtPaymentTypes = getColVectorFromDB2ArrayByClause("metatype", "mt_value", "mt_type = 'payment_type' AND mt_objtype = '' AND mt_objid = '0'", "mt_sort", "mt_sort", "");
      endif;
      // Get state of job being a service job and then get payment types for istallation booking
      
      if ($jobIsSpecialServiceJob == "1"):
         $paymentTypesRequested = getObjectBasedParameterValue("JOB_DETAILS_CAT_09_SERVICEJOB_JBPMODES_CS", $jbpCsId, $currentHqId);
         if ($paymentTypesRequested == "" && $jbpCsGrpId != "") :
            $paymentTypesRequested = getObjectBasedParameterValue("JOB_DETAILS_CAT_09_SERVICEJOB_JBPMODES_GRP", $jbpCsGrpId, $currentHqId);
         endif;
      else :
         $paymentTypesRequested = getObjectBasedParameterValue("JOB_DETAILS_CAT_09_JBPMODES_CS", $jbpCsId, $currentHqId);
         if ($paymentTypesRequested == "" && $jbpCsGrpId != "") :
            $paymentTypesRequested = getObjectBasedParameterValue("JOB_DETAILS_CAT_09_JBPMODES_GRP", $jbpCsGrpId, $currentHqId);
         endif;
      endif;
   endif;
   $paymentTypesRequested = spliti(",", $paymentTypesRequested);
endif;


// --- CHANGE ADDED INSTALLATION TIME IN GDC ---------------
if ($globalParUseRelatedCustomer == "1" && $automailer == "0" && $job_id != "" && ($jobService & 2) == 2) :

   if ($jobHasAddedInstallation) :

      $changeGDC_addMon = "<div class=\"f10bp1\">" . getLngt("Zusätzliche Montagezeit") . "</div>";

      // Try to get content from "gdc_content"
      $gdcContextAddMon = getFieldValueFromClause("genericdatacontainer", "gdc_content", "gdc_obj_type = 'jb' AND gdc_gen_fieldname = 'jb_addmont' AND gdc_obj_id = '" . $job_id . "'");
      $gdcContextAddMon = trim($gdcContextAddMon);
      if ($gdcContextAddMon == "") :
         // If "gdc_content" is empty, try to get content from "gdc_context"
         $gdcContextAddMon = getFieldValueFromClause("genericdatacontainer", "gdc_context", "gdc_obj_type = 'jb' AND gdc_gen_fieldname = 'jb_addmont' AND gdc_obj_id = '" . $job_id . "'");
         $gdcContextAddMon = trim($gdcContextAddMon);
      endif;
      if ($jobIsAllowedToBeModified && $jobIsPayedByCarrier == "" && !$jobAddedInstallationIsExported) :
         $changeGDC_addMon .= "<div style=\"float:left\"><input type=\"text\" name=\"f_jb_gdc_add_mon\" value=\"" . $gdcContextAddMon . "\"  size=\"5\">&nbsp;&nbsp;&nbsp;</div>";
         $changeGDC_addMon .= "<div style=\"float:left\"><select name=\"f_jbp_mode_add_mon\">\n";
         // Check for being special service job
         if ($jobIsSpecialServiceJob == ""):
            $changeGDC_addMon .= "<option value=\"\" selected>&nbsp;</option>\n";
         endif;
         $paymentTypesRequestedLen = count($paymentTypesRequested);
         for ($i = 0; $i < $paymentTypesRequestedLen; $i++) :
             $changeGDC_addMon .= "<option value=\"" . $paymentTypesRequested[$i] . "\">" . $mtPaymentTypes[$paymentTypesRequested[$i]] . "</option>\n";
         endfor;
         $changeGDC_addMon .= "</select></div>\n";
         if ($job_status == "2" && $jobCourierId != "" && $jobCourierId != "0") :
            $changeGDC_addMon .= defineButtonType10(getLngt("Service-Zeit ändern"), "action_gdc_add_mon", "changeGDC_addMon();", "200", "", "");
         endif;
         $changeGDC_addMon .= "<br>";
      endif;

      // ******************************************
      // Get all payment rows associated to the added installation job
      if ($jobAddedInstallationId != "" && is_numeric($jobAddedInstallationId)) :

         $jbPaymentAddedInstallationArray = getPaymentsReceived($jobAddedInstallationId);
         $jbPaymentAddedInstallationArrayLen = count($jbPaymentAddedInstallationArray);

         // Display existing rows
         if ($jbPaymentAddedInstallationArrayLen > 0) :
            $changeGDC_addMon .= "<div>\n";
            $changeGDC_addMon .= "<table>\n";
            $changeGDC_addMon .= "<tr><td class=\"f10np1\" colspan=\"5\">" . getLngt("Zahlungseingänge der Zusatzmontage") . "<br></td></tr>\n";
            $changeGDC_addMon .= "<tr><td>" . getLngt("Zahlart") . "</td><td>" . getLngt("Umsatz") . "</td><td>" . getLngt("Eingangszeitpunkt") . "</td><td>" . getLngt("Exportzeitpunkt") . "</td><td>" . getLngt("Auftrag") . "</td></tr>";

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

                // Get gross value from the stores net value
                $jobAddedInstallationJbpPriceGross = $jbPaymentAddedInstallationArray[$i][3] * $taxFactor;
// **** START ************************
// PROPRIETÄR FÜR IKEA !!!!!!!!
                // True payment type in "jbp_tan"
                $jbpTanOut = "";
                // if ($outJbpcId == "") :
                   if ($jbpCsGrpId == "1" || $jbpCsGrpId == "11") :
                      if (existsEntry("genericdatacontainer",array("gdc_obj_type","jb","gdc_gen_fieldname","acquisitiontime","gdc_obj_id",$job_id))) :
                         if ($jbPaymentAddedInstallationArray[$i][2] == "18" || $jbPaymentAddedInstallationArray[$i][2] == "19") :
                            if ($jbPaymentAddedInstallationArray[$i][10] != "" && is_numeric($jbPaymentAddedInstallationArray[$i][10])) :
                               $jbpTanOut = "&nbsp;" . $mtPaymentTypes[$jbPaymentAddedInstallationArray[$i][10]];
                            endif;
                         endif;
                      endif;
                   endif;
                // endif;
// **** END ************************
                $changeGDC_addMon .= "<tr>\n";
                $changeGDC_addMon .= "<td>" . $mtPaymentTypes[$jbPaymentAddedInstallationArray[$i][2]] . $jbpTanOut . "&nbsp;&nbsp;</td><td align=\"right\">" . formatOutput($jobAddedInstallationJbpPriceGross, "float_rounded_2") . "&nbsp;&nbsp;</td><td>" . formatOutput($jbPaymentAddedInstallationArray[$i][4], "datetime", "1") . "&nbsp;&nbsp;</td><td>" . ($jbPaymentAddedInstallationArray[$i][5] != "0000-00-00 00:00:00" && $jbPaymentAddedInstallationArray[$i][5] != "" ? formatOutput($jbPaymentAddedInstallationArray[$i][5], "datetime", "1") : "") . "&nbsp;&nbsp;</td><td>" . $jbPaymentAddedInstallationArray[$i][8] . "&nbsp;&nbsp;</td>";
                $changeGDC_addMon .= "</tr>\n";
            endfor;

            $changeGDC_addMon .= "</table>\n";
            $changeGDC_addMon .= "<br></div>\n";
            $changeGDC_addMon .= "<br>";
         endif;
      endif;
      // ******************************************
   endif;
endif;   


// --- CHANGE PAYMENT MODE (If job NOT is finished and NOT exported and there is NO payment export, too !!!!) ---------------
$constJbpBookingEnabled = getParameterValue("0", "MASK_JOBDETAILS_JBP_BOOKING_ENABLED", $currentHqId);  // [= "1"] <=> Enabled
if ($globalParUseRelatedCustomer == "1" && $constJbpBookingEnabled == "1" && $automailer == "0" && $job_id != "") :
   $changePayment = "";
   $changePaymentStatus = "&nbsp;&nbsp;&nbsp;";

   // Get changing mode by parameter for either ALL or SINGLE payment rows in "jobpayment" will be changable to another payment method
   $constJbpBookingMode = getParameterValue("0", "MASK_JOBDETAILS_JBP_PAYMENTMODE_SINGLE_BOOKING_ENABLED", $currentHqId);  // [= "1"] <=> Single rows with 
   if ($constJbpBookingMode == "") : $constJbpBookingMode = getParameterValue("0", "MASK_JOBDETAILS_JBP_PAYMENTMODE_SINGLE_BOOKING_ENABLED", "0"); endif;

   if ($f_act == "changePayment") :

      if ($f_jbp_mode != "" && is_numeric($f_jbp_mode)) :

         $f_jbp_price_rest = str_replace (",", ".", $f_jbp_price_rest);
         if ($f_jbp_price_rest != "" && $f_jbp_price_rest != 0) :

            if ($f_jbp_csc_id != "") :
            
               // Set the current timestamp to store the data
               $currentTime = getDateTime("0");

               insertStmt($dbh_jbp, array("jb_id", $job_id, "tr_sort", "2", "csc_id", $f_jbp_csc_id, "jbp_mode", $f_jbp_mode, "jbp_price", $f_jbp_price_rest, "jbp_bookingtime", $currentTime));
               // $jbp_id_new = getLastInsertId();

               // Set job state to "complete"
               // if ($f_jbp_mode == "0") :
                  // Check for existing added installation ("addmont")
                  // if (!existsEntry("genericdatacontainer", array("gdc_obj_type", "jb", "gdc_gen_fieldname", "jb_addmont", "gdc_obj_id", $job_id, "gdc_content", ""))) :
                  if (!$jobHasAddedInstallation) :
                     updateStmt($dbh_jb, "jb_id", $job_id, array("jb_incomplete", "0"));
                     $job_incomplete = "0";
                     $f_jb_incomplete = "";
                  endif;
               // endif;

               // Write logdata into log database
               // writeToLogDB("118",$currentHqId,$job_id,$currentSessionUsrId,"","","","JBP_MODE=" . $f_jbp_mode);
            else:
               $changePaymentStatus = getLngt("Für die Buchung ist kein Kunde definiert!");
            endif;
         else:
            $changePaymentStatus = getLngt("Es ist kein Restbetrag vorhanden, der gebucht werden müsste!");
         endif;
      else:
         $changePaymentStatus = getLngt("Es wurde keine Bezahlart angegeben!");
      endif;
   endif;

   // ONLY show if job is not exported
   if ($automailer == "0" && $takeRealJobData) :

      // Get total business volume of the job
      $jbTotalBusinessVolume = getFieldValueFromId("job","jb_id",$job_id,"jb_totalprice");
      $jbSalesTaxRate = getFieldValueFromId("job","jb_id",$job_id,"jb_sales_tax_rate");
      $jbIncomplete = getFieldValueFromId("job","jb_id",$job_id,"jb_incomplete");

      // Get all payment rows associated to the current job
      $jbPaymentArray = getPaymentsReceived($job_id);
      $jbPaymentArrayLen = count($jbPaymentArray);
      $sumOfPaymentVolume = 0;
      $restOfPaymentVolume = 0;
      // if ($jbPaymentArrayLen > 0) :  // There is the case of no payment is done !!!!

         // Display existing rows
         $changePayment .= "<div>\n";
         $changePayment .= "<table>\n";
         $changePayment .= "<tr><td class=\"f10bp1\" colspan=\"6\">" . getLngt("Zahlungseingänge mit Zahlarten") . "<br></td></tr>\n";
         $changePayment .= "<tr><td><b>" . getLngt("Zahlart") . "</b></td><td><b>" . getLngt("Umsatz") . "</b></td><td><b>" . getLngt("Eingangszeitpunkt") . "</b></td><td><b>" . getLngt("Exportzeitpunkt") . "</b></td><td><b>" . getLngt("Counter-Umsatz") . "</b></td><td><b>" . getLngt("Sammelnummer") . "</b></td></tr>";
         // array($row["tr_sort"], $row["csc_id"], $row["jbp_mode"], $row["jbp_price"], $row["jbp_bookingtime"], $row["jbp_export_time"]);

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

             // Get gross value from the stores net value
             $jbpPriceGross = $jbPaymentArray[$i][3] * $taxFactor;

             // Collection number
             $outJbpcId = $jbPaymentArray[$i][9];
             if ($outJbpcId == "0") : $outJbpcId = ""; endif;
             if ($outJbpcId != "") : $outJbpcId = "<a href=\"../tools/payments.php?jbpc_id=" . $outJbpcId . "\" target=\"_blank\">" . $outJbpcId . "</a>"; endif;
// **** START ************************
// PROPRIETÄR FÜR IKEA !!!!!!!!
             if ($outJbpcId == "") :
                if ($jbpCsGrpId == "1" || $jbpCsGrpId == "11") :
                   if (existsEntry("genericdatacontainer",array("gdc_obj_type","jb","gdc_gen_fieldname","acquisitiontime","gdc_obj_id",$job_id))) :
                      if ($jbPaymentArray[$i][2] == "18") :
                         if ($f_act == "changeJbpTan") :
                            updateStmt($dbh_jbp, "jb_id", $job_id, array("jbp_tan", $f_jbp_tan));
                         else :
                            $f_jbp_tan = getFieldValueFromId($dbh_jbp, "jb_id", $job_id, "jbp_tan");
                            if ($f_jbp_tan == "") :
                              $f_jbp_tan = 0;
                            endif;
                         endif;
                         $outJbpcId .= "<select name=\"f_jbp_tan\" onChange=\"changeJbpTan();\">\n";
                         $paymentTypesRequestedLen = count($paymentTypesRequested);
                         for ($j = 0; $j < $paymentTypesRequestedLen; $j++) :
                             $outJbpcId .= "<option value=\"" . $paymentTypesRequested[$j] . "\" " . ($f_jbp_tan == $paymentTypesRequested[$j] ? "selected" : "") . ">" . $mtPaymentTypes[$paymentTypesRequested[$j]] . "</option>\n";
                         endfor;                         
                         $outJbpcId .= "</select>\n";
                      endif;
                   endif;
                endif;
             endif;
// **** END ************************
             $changePayment .= "<tr>\n";
             $changePayment .= "<td>" . $mtPaymentTypes[$jbPaymentArray[$i][2]] . "&nbsp;&nbsp;</td><td align=\"right\">" . formatOutput($jbpPriceGross, "float_rounded_2") . "&nbsp;&nbsp;</td><td>" . formatOutput($jbPaymentArray[$i][4], "datetime", "1") . "&nbsp;&nbsp;</td><td>" . ($jbPaymentArray[$i][5] != "0000-00-00 00:00:00" && $jbPaymentArray[$i][5] != "" ? formatOutput($jbPaymentArray[$i][5], "datetime", "1") : "") . "&nbsp;&nbsp;</td><td align=\"center\">" . ($jbPaymentArray[$i][6] == "1" ? getLngt("Ja") : "") . "&nbsp;&nbsp;</td><td align=\"center\">" . $outJbpcId . "&nbsp;&nbsp;</td>";
             $changePayment .= "</tr>\n";

             $sumOfPaymentVolume += $jbPaymentArray[$i][3];
         endfor;

         // Get rest volume to be payed
         $restOfPaymentVolume = $jbTotalBusinessVolume - $sumOfPaymentVolume;

         // Net value => Gross value [For display only !!!!]
         $jbTotalBusinessVolumeGross = $jbTotalBusinessVolume * $taxFactor;
         $sumOfPaymentVolumeGross = $sumOfPaymentVolume * $taxFactor;
         $restOfPaymentVolumeGross = $restOfPaymentVolume * $taxFactor;

         $changePayment .= "<tr><td class=\"f8bp1\">" . getLngt("Summe") . ":&nbsp;&nbsp;</td><td  class=\"f8bp1\" align=\"right\">" . formatOutput($sumOfPaymentVolumeGross, "float_rounded_2") . "&nbsp;&nbsp;</td><td  class=\"f8bp1\" colspan=\"3\">" . ($jbTotalBusinessVolumeGross != "" ? getLngt("von Bruttoauftragssumme") . "&nbsp;" . formatOutput($jbTotalBusinessVolumeGross, "float_rounded_2") . "&nbsp;&nbsp;[" . getLngt("Rest") . ":&nbsp;" . formatOutput($restOfPaymentVolumeGross, "float_rounded_2") . "]"  : "") . "</td></tr>\n";
         $changePayment .= "</table>\n";
         $changePayment .= "<br></div>\n";
      // endif;

      if ($restOfPaymentVolume != 0 && $jobIsAllowedToBeModified && $jobIsNotExported && $jobIsPayedByCarrier == "") :
         $changePayment .= "<div style=\"float:left\">\n";
         $changePayment .= "<input type=\"hidden\" name=\"f_jbp_price_rest\" value=\"" . $restOfPaymentVolume . "\">\n";  // Net value for internal representation
         $changePayment .= "<input type=\"hidden\" name=\"f_jbp_csc_id\" value=\"" . $jbpCscId . "\">\n";
         $changePayment .= "<select name=\"f_jbp_mode\">\n";
         $changePayment .= "<option value=\"\" selected>&nbsp;</option>\n";
         $paymentTypesRequestedLen = count($paymentTypesRequested);
         for ($i = 0; $i < $paymentTypesRequestedLen; $i++) :
             $changePayment .= "<option value=\"" . $paymentTypesRequested[$i] . "\">" . $mtPaymentTypes[$paymentTypesRequested[$i]] . "</option>\n";
         endfor;
         $changePayment .= "</select>\n";
         $changePayment .= "&nbsp;&nbsp;</div>\n";
         $changePayment .= defineButtonType10(getLngt("Restsumme verbuchen"), "action_book_payment_rest", "changePaymentMethod();", "200", "left", "3");
         $changePayment .= "<div>" . getLngt("[Bei Auswahl der Zahlart Bar wird der Auftrag abgeschlossen.]") . "</div>";
      endif;
      $changePayment .= "<div style\"float_left\">\n";
      $changePayment .= "<br><br><span class=\"f8np1_red\">" . $changePaymentStatus . "</span>";
      $changePayment .= "</div>\n";
   endif;
endif;


// --- DISPLAY ARTICLE ACCEPTANCE DATA ---------------
$outputArticleAcceptanceData = "";
if ($globalParUseRelatedCustomer == "1" && $automailer == "0" && $job_id != "") :
   $outputArticleAcceptanceData = getOutputArticleAcceptanceData($job_id);
endif;


// --- DISPLAY PHOTOS FROM MOBILE ---------------
$outputPhotos = "";
if ($globalParUseRelatedCustomer == "1" && $automailer == "0" && $job_id != "") :
   // [1] B2B
   $filenameArray = getImagesFromB2bObjects($job_id, "../temp/photos/", "jb");
   $filenameArrayLen = count($filenameArray);
   // [2] GDC
   $tmpPhotoFilenames = getFieldValueFromClause("genericdatacontainer", "gdc_content", "gdc_obj_type = 'jb' AND gdc_obj_id = '" . $job_id . "' AND gdc_gen_fieldname = 'mobile_photos'");
   // Display photos
   if ($tmpPhotoFilenames != "" || $filenameArrayLen > 0) :
      $tmpArrayLen = 0;
      if ($tmpPhotoFilenames != "") :
         $tmpPhotoFilenames = str_replace("|", "-,-", $tmpPhotoFilenames);
         if (!(strpos($tmpPhotoFilenames, "-,-") === FALSE)) :
            $tmpArray = spliti("-,-",$tmpPhotoFilenames);
         else :
            $tmpArray = array($tmpPhotoFilenames);
         endif;
         $tmpArrayLen = count($tmpArray);
      endif;
      if ($tmpArrayLen > 0 || $filenameArrayLen > 0) :
         $systemPath = "..";
         $tmpImgHeight = 100;
         $tmpImgWidth = 133;
         $outputPhotos .= "<table>";
         $outputPhotos .= "<tr><td class=\"f10bp1\" colspan=\"4\">" . getLngt("Fotos der Endgeräte des Abnahmeprotokolls") . "<br></td></tr>\n";
         $outputPhotos .= "<tr>";
         // GDC
         for ($i = 0; $i < $tmpArrayLen; $i++) {
             $outputPhotos .= "<td height=\"130\" width=\"160\" align=\"center\">";
             $outputPhotos .= "<a href=\"javascript:openImageViewer('" . $tmpArray[$i] . "','" . intval($tmpImgWidth * 8) . "','" . intval($tmpImgHeight * 8) . "','');\"><img src=\"" . $systemPath . "/documents/photos/" . $tmpArray[$i] . "\" border=\"" . "0" . "\" height=\"" . $tmpImgHeight . "\" width=\"" . $tmpImgWidth . "\"></a>";
             $outputPhotos .= "</td>";
             if ((($i + 1) % 4) == 0 && $i < ($tmpArrayLen - 1)) :
                $outputPhotos .= "</tr><tr>";
             endif;
         }
         // B2B
         for ($i = 0; $i < $filenameArrayLen; $i++) {
             $outputPhotos .= "<td height=\"130\" width=\"160\" align=\"center\">";
             $outputPhotos .= "<a href=\"javascript:openImageViewer('" . $filenameArray[$i] . "','" . intval($tmpImgWidth * 8) . "','" . intval($tmpImgHeight * 8) . "','../temp/photos/');\"><img src=\"" . $systemPath . "/temp/photos/" . $filenameArray[$i] . "\" border=\"" . "0" . "\" height=\"" . $tmpImgHeight . "\" width=\"" . $tmpImgWidth . "\"></a>";
             $outputPhotos .= "</td>";
             if ((($i + 1) % 4) == 0 && $i < ($tmpArrayLen - 1)) :
                $outputPhotos .= "</tr><tr>";
             endif;
         }
         $outputPhotos .= "</tr>";
         $outputPhotos .= "<table><br><br>";
      endif;
   endif;
endif;


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

   if ($f_act == "completeJob") :

      if ($f_jb_incomplete != "" && ($f_jb_incomplete == "0" || $f_jb_incomplete == "1")) :
         $doSwitchStatus = true;
         // Check abort conditions like not existing commission no. etc.
         if ($globalParUseRelatedCustomer != 1) :
            $constSwitchCompleteCheckCommNo = getParameterValue("0", "MASK_JOBDETAILS_BOOKJOB_COMMNO", $currentHqId);
            if ($constSwitchCompleteCheckCommNo == "1") :
               if ($f_jb_incomplete != "1") :   // Only check status change from unready to ready
                  $csNeedsCommissionNo = getFieldValueFromId("customer", "cs_id", $csIdPayer, "cs_commission_no");
                  $jbHasCommissionNo = getCountOfTable("tour", "jb_id = '" . $job_id . "' AND tr_commission_no != ''");
                  if ($csNeedsCommissionNo == "1" && $jbHasCommissionNo == 0) :
                     $doSwitchStatus = false;
                     $completeJobMsg = "<span class=\"f8np1_red\"><b>" . getLngt("ACHTUNG: Die erforderliche Kommissionsnummer fehlt leider noch!") . "</b></span>";
                     $statusMessage = $completeJobMsg;
                  endif;
               endif;
            endif;            
         endif;

         // Get "third country" state of the job regarding flag "jb_incomplete"
         if ($doSwitchStatus && $f_jb_incomplete == "0") :
            $jobThirdCountry = getFieldValueFromClause("genericdatacontainer", "gdc_content", "gdc_obj_type = 'jb' AND gdc_obj_id = '" . $job_id . "' AND gdc_gen_fieldname = 'jb_third_country'");
            if ($jobThirdCountry == "1") :
               $f_jb_incomplete = "1";
               $job_incomplete = $f_jb_incomplete;
               $completeJobMsg = "<span class=\"f8np1_red\"><b>" . getLngt("ACHTUNG: Der Auftrag ist ein Drittlandauftrag! Bitte den Status über die Auftragserfassung setzen") . "</b></span>";
               $statusMessage = $completeJobMsg;
            endif;
         endif;

         if ($doSwitchStatus) :
            if ($globalParUseRelatedCustomer == 1 || ($job_id_parent == "" || $job_id_parent == "0")) :   // Only jobs not having sub-jobs
            
               // 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,"","","","");
            
            elseif ($job_id_parent == "-1") :

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

                  $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";                        
            
                  $result = $db->query($tmpSqlquery);
                  if (DB::isError($result)) die ("$PHP_SELF 5: {$tmpSqlquery} " . $result->getMessage() . ": " . $sqlquery);
                 
                  // Iterate list of subjobs
                  while ($row = $result->fetch_assoc()):
                    $subJobIDs[] = $row["jb_id_sub"];
                  endwhile;
                  $result->free();
                  
                 $subJobIDsLen = count($subJobIDs);
                 if ($subJobIDsLen > 0) :

                     $tmpSqlquery = "SELECT jb.jb_id AS jb_id_sub"
                                    . " FROM " . $dbh_jb . " AS jb"
                                    . " WHERE jb.jb_id_parent IN (" . implode(",", $subJobIDs) . ")"
                                    . " ORDER BY jb.jb_id";                        
            
                     $result = $db->query($tmpSqlquery);
                     if (DB::isError($result)) die ("$PHP_SELF 5: {$tmpSqlquery} " . $result->getMessage() . ": " . $sqlquery);

                     while ($row = $result->fetch_assoc()):
                            $subJobIDs[] = $row["jb_id_sub"];
                     endwhile;
                     $result->free();
                  endif;

                  $subJobIDsLen = count($subJobIDs);
                  for ($i = 0; $i < $subJobIDsLen; $i++) :
                     // Update subjob with new status jb_incomplete
                     updateStmt($dbh_jb, "jb_id", $subJobIDs[$i], array("jb_incomplete", $f_jb_incomplete), "(hq_id = '" . $currentHqId . "' AND (ISNULL(jb_export_time)) OR jb_export_time = '0000-00-00 00:00:00')");
                                          
                     // Write logdata into log database
                     writeToLogDB(($f_jb_incomplete == "1" ? "14" : "13"),$currentHqId,$subJobIDs[$i],$currentSessionUsrId,"","","","");
                  endfor;

                  // Now update main 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;
         endif;
      endif;                  
   endif;
   
   if ($job_incomplete == "1") :
      $completeJobStatus .= "<span class=\"f8np1_red\"><b>" . getLngt("UNFERTIG!") . "</b></span>";
   else :
      $completeJobStatus .= "<span class=\"f8np1_green\"><b>" . getLngt("FERTIG!") . "</b></span>";
   endif;      

   if ($jobIsAllowedToBeModified && $jobIsNotExported) :
      $completeJob .= "<input type=\"hidden\" name=\"f_jb_incomplete\" value=\"" . ($job_incomplete == "1" ? "0" : "1") . "\">";
      $completeJob .= "<div style=\"float:left\">" . getLngt("Buchhaltungsstatus des Auftrags:") . " " . $completeJobStatus . "&nbsp;&nbsp;&nbsp;</div>\n";
      if ($jbAccessModeArr["1"]) :
         $completeJob .= defineButtonType10(getLngt("Auf&nbsp;") . ($job_incomplete == "1" ? getLngt("fertig") : getLngt("unfertig")) . getLngt("&nbsp;setzen"), "action_ready", "changeComplete();", "150", "left", "3");
      endif;
      $completeJob .= "<div>" . $completeJobMsg . "</div>";
   endif;
endif;   


// --- INVOICE TEXT ---------------
/*   
if ($job_id != "") :
   if ($f_act == "changeInvoiceText") :

      updateStmt($dbh_jb, "jb_id", $job_id, array("jb_invtext", $f_jb_invtext_new), "(hq_id = '" . $currentHqId . "')");
   endif;
endif;
*/
$f_jb_invtext = getFieldValueFromId($dbh_jb, "jb_id", $job_id, "jb_invtext");

$jobinvoicetext = "<div class=\"mc_table-header\" style=\"width: 580px;\">" . getLngt("(Vorläufiger) Rechnungstext:") . "</div>";
$jobinvoicetext .= "<div><textarea style=\"width: 600px;\" id=\"f_jb_invtext_new\" name=\"f_jb_invtext_new\" rows=\"15\" readonly>" . $f_jb_invtext . "</textarea></div>\n";
// $jobinvoicetext .= "<input type=\"button\" value=\"Rechnungstext speichern\" onClick=\"javascript:changeInvoiceText();\">\n";


// --- FREIGHT CHARGES TEXT ---------------
$f_jb_cr_invtext = getFieldValueFromId($dbh_jb, "jb_id", $job_id, "jb_invtext_cr");

$jobInvoiceCrText = "<div class=\"mc_table-header\" style=\"width: 580px;\">" . getLngt("(Vorläufiger) Frachtvergütungstext:") . "</div>";
$jobInvoiceCrText .= "<div><textarea style=\"width: 600px;\" id=\"f_jb_invtext_cr_dnew\" name=\"f_jb_invtext_cr_dnew\" rows=\"15\" readonly>" . $f_jb_cr_invtext . "</textarea></div>\n";


// --- INTERNAL REMARK ---------------
$jobinternalremark = "";
if ($automailer == "0") :
   if ($job_id != "") :
      if ($f_act == "changeInternalRemark") :   
         $f_jb_freetext_3_new = str_replace("'", "\"", $f_jb_freetext_3_new);

         updateStmt($dbh_jb, "jb_id", $job_id, array("jb_freetext_3", $f_jb_freetext_3_new), "(hq_id = '" . $currentHqId . "')");

         // Write logdata into log database
         writeToLogDB("200",$currentHqId,$job_id,$currentSessionUsrId,"","","","INTERNAL_REMARK=" . $f_jb_freetext_3_new);
      endif;
   endif;
   $f_jb_freetext_3 = getFieldValueFromId($dbh_jb, "jb_id", $job_id, "jb_freetext_3");

   $jobinternalremark .= "<div class=\"mc_table-header\" style=\"width: 580px;\">" . getLngt("Interne Bemerkung:") . "</div>";
   $jobinternalremark .= "<div><textarea style=\"width: 600px;\" id=\"f_jb_freetext_3_new\" name=\"f_jb_freetext_3_new\" rows=\"10\">" . $f_jb_freetext_3 . "</textarea></div>\n";
   if ($jbAccessModeArr["1"]) :
      $jobinternalremark .= defineButtonType10(getLngt("Interne&nbsp;Bemerkung&nbsp;speichern"), "action_save", "changeInternalRemark();", "220", "left", "3");
   endif;
endif;


// --- COURIER REMARK ---------------
$jobcourierremark = "";
if ($automailer == "0") :
   $f_jb_cr_remark = getFieldValueFromId($dbh_jb, "jb_id", $job_id, "jb_cr_remark");
   
   $jobcourierremark .= "<div class=\"mc_table-header\" style=\"width: 580px;\">" . getLngt("Anmerkungen Transporteur:") . "</div>";
   $jobcourierremark .= "<div><textarea style=\"width: 600px;\" id=\"f_jb_cr_remark\" name=\"f_jb_cr_remark\" rows=\"4\" readonly>" . $f_jb_cr_remark . "</textarea></div>\n";
endif;


// --- CUSTOMER REMARK ---------------
$jobcustomerremarktext = "";
if ($job_id != "") :
   $tmpSqlquery = "SELECT cmp.cmp_remark"
                  . " FROM " . $dbh_jb . " AS jb, costcenter AS csc, customer AS cs, company AS cmp"
                  . " WHERE jb.jb_id = '" . $job_id . "' AND jb.csc_id_payer = csc.csc_id AND csc.cs_id= cs.cs_id AND cs.cmp_id = cmp.cmp_id"
                  . " ORDER BY jb.jb_id";                        
   
   $result = $db->query($tmpSqlquery);
   if (DB::isError($result)) die ("$PHP_SELF 5: {$tmpSqlquery} " . $result->getMessage() . ": " . $sqlquery);

   $f_cmp_remark = "";
   while ($row = $result->fetch_assoc()):
      $f_cmp_remark = $row["cmp_remark"];
   endwhile;
   $result->free();

   $jobcustomerremarktext .= "<div class=\"mc_table-header\" style=\"width: 580px;\">" . getLngt("Bemerkung über Kunde:") . "</div>";
   $jobcustomerremarktext .= "<div><textarea style=\"width: 600px;\" id=\"f_cmp_remark\" name=\"f_cmp_remark\" rows=\"15\" readonly>" . $f_cmp_remark . "</textarea></div>\n";
endif;


// --- JOB FREETEXT ---------------
$jobfreetext1 = "";
if ($job_id != "") :
   $f_jb_freetext_1 = getFieldValueFromId($dbh_jb, "jb_id", $job_id, "jb_freetext_1");   
   $jobfreetext1 .= "<div class=\"mc_table-header\" style=\"width: 580px;\">" . getLngt("Auftragsfreitext:") . "</div>";
   $jobfreetext1 .= "<div><textarea style=\"width: 600px;\" id=\"f_jb_freetext_1\" name=\"f_jb_freetext_1\" rows=\"15\" readonly>" . $f_jb_freetext_1 . "</textarea></div>\n";
endif;

   
// --- SUB-JOBS ---------------
$listOfSubjobs = "";
if ($automailer == "0" && $job_id != "") :
   
   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(getLngt("Auftrag&nbsp;"), getLngt("Preis&nbsp;"), getLngt("ExtID&nbsp;"), getLngt("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 = "";
      $postParserField = "jb_id_sub";
      $mode = "1";             // Output from DB-RESULT
      $sortDBField = "";       // Used in following include-file for sorting per column;

      include ("../include/inc_list_defineoutput.inc.php");

      // Post parsing if necessary
      if ($postParserField != "") :
         $tableBody = substituteTagContent($tableBody, "<postparser>", "</postparser>", "<a href=\"javascript:popupWindow('../admin/jb_detail.php?job_id=[TAG_CONTENT]&dbhistory=" . $dbhistory . "','" . getLngt("Auftrag") . "','');\">[TAG_CONTENT]</a>");
      endif;

      $listOfSubjobs .= "<tr><td colspan=\"2\">" . getLngt("UNTERAUFTRÄGE:") . "</td></tr>\n";
      $listOfSubjobs .= $tableHeader . $tableBody;

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


// --- PARENT-JOB(S) ---------------
$listOfParentJobs = "";
if ($automailer == "0" && $job_id != "") :

   $jbIdParent = getFieldValueFromId("job", "jb_id", $job_id, "jb_id_parent");
   if ($jbIdParent != "" && is_numeric($jbIdParent) && $jbIdParent != "0") :

      $tmpSqlquery = "SELECT jb.jb_id AS jb_id_parent, 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 = '" . $jbIdParent . "'"
                     . " 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(getLngt("Auftrag&nbsp;"), getLngt("Preis&nbsp;"), getLngt("ExtID&nbsp;"), getLngt("Name"));
      $fieldArray = array("jb_id_parent", "business_volume", "cr_eid", "usr_name");
      
      $aligns = "l,r,l,l";
      $alignArray = spliti(",",$aligns);
      $alignTitles = "left";
      $widths = "30";
      $widthArray = spliti(",",$widths);
      $summationField = "";
      $postParserField = "jb_id_parent";
      $mode = "1";             // Output from DB-RESULT
      $sortDBField = "";       // Used in following include-file for sorting per column;

      include ("../include/inc_list_defineoutput.inc.php");

      // Post parsing if necessary
      if ($postParserField != "") :
         $tableBody = substituteTagContent($tableBody, "<postparser>", "</postparser>", "<a href=\"javascript:popupWindow('../admin/jb_detail.php?job_id=[TAG_CONTENT]&dbhistory=" . $dbhistory . "','" . getLngt("Auftrag") . "','');\">[TAG_CONTENT]</a>");
      endif;

      $listOfParentJobs .= "<tr><td colspan=\"2\">" . getLngt("HAUPTAUFTRAG:") . "</td></tr>\n";
      $listOfParentJobs .= $tableHeader . $tableBody;
      
      $result->free();
   endif;
endif;
?>


<?php
if ($automailer == "0") :
   if ($f_act == "printjob") :
      include_once ("../admin/jb_detail_print.php");
   else :
      if ($maskJobInternalRemarkItems == "1") :
         // Browser specific setup for special <div>....</div> as "actioncontainer"
         if ($isFirefox) :
            $actioncontainerDivPos = "style=\"position:fixed; top:0px; left:450; width:500px; height:700px; z-index:10; background-color:#AAAACC; border:grey 3px solid; box-shadow: 10px 20px 30px grey;\"";
         else :
            $actioncontainerDivPos = "";
?>
            <style type="text/css">
              #actioncontainer { position:absolute; top:0px; left:450px; width:500px; height:700px; z-index:10; background-color:#AAAACC; border:grey 3px solid; box-shadow: 10px 20px 30px grey;}     
              html>body #actioncontainer { position: fixed; }
            </style>
<?php   
         endif;
      endif;
?>

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

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

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

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

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

// Global definition of the internal remark item structure
var mtIntRemItems;
var trIntRemItemTexts;

function ajaxRequestContainerHtmlGet(url, item, content) {
  $.ajax({
    url: url,
    type: 'GET',
    dataType: 'html',
    data: content,
    async: false,
    cache: false
  }).done(function ( data ) {
    // $('#' + item).append(data);
    $('#' + item).html(data);
  });
}

// Get internal remark item structure
function getInternalRemarkItemData () {
  mtIntRemItems = new Array();
  trIntRemItemTexts = new Array();
  <?php if ($maskJobInternalRemarkItems == "1") : ?>
    ajaxRequestGet('../include/ajaxReqGeneric.php', 'incFile=inc_job.inc&fun=getJobInternalRemarkItems&par_01=' + encodeURI(escape(<?php echo $job_id ?>)) + '&retIdx=0&retParName=_RAW_TEXT_');
  <?php endif; ?>
}

function mailsend() {
  this.document.forms[0].f_act.value = 'mailsend';
  this.document.forms[0].submit();
}

function bookjob() {
  this.document.forms[0].f_act.value = 'bookjob';
  this.document.forms[0].submit();
}

function changeGDC_addMon() {
  this.document.forms[0].f_act.value = 'changeGDC_addMon';
  this.document.forms[0].submit();
}

function changePaymentMethod() {
  this.document.forms[0].f_act.value = 'changePayment';
  this.document.forms[0].submit();
}

function changeJbpTan() {
  this.document.forms[0].f_act.value = 'changeJbpTan';
  this.document.forms[0].submit();
}

function changeTourname() {
  this.document.forms[0].f_act.value = 'modifyTourname';
  this.document.forms[0].submit();
}

function changeComplete() {
  if (confirm('<?php echo getLngt("Status wirklich ändern?") ?>')) {
     this.document.forms[0].f_act.value = 'completeJob';
     this.document.forms[0].submit();
  }
}

function changeCourierOrder() {
  this.document.forms[0].f_act.value = 'changeCourierOrder';
  this.document.forms[0].submit();
}

function changeInternalRemark() {
  this.document.forms[0].f_act.value = 'changeInternalRemark';
  this.document.forms[0].submit();
}

function printjob() {
  this.document.forms[0].f_act.value = 'printjob';
  this.document.forms[0].submit();
}

function openJob2pdf() {
  var widthPopupWin = 1200;
  var heightPopupWin = 1024;
  var leftPopupWin = (screen.width / 2) - (widthPopupWin / 2) - 12;
  var topPopupWin = (screen.height / 2) - (heightPopupWin / 2) - 50;
  var popupWin;
  popupWin = window.open("../admin/pdf_generic.php?f_act=generatePDFJob&jbId=<?php echo ec($job_id) ?>&dbhistory=<?php echo ec($dbhistory) ?>","","dependent=yes,width=" + widthPopupWin + ",height=" + heightPopupWin +",left=" + leftPopupWin + ",top=" + topPopupWin + ",scrollbars=yes");
};

function openJobStation(jbId, trSort) {
  var widthPopupWin = 1200;
  var heightPopupWin = 800;
  var leftPopupWin = (screen.width / 2) - (widthPopupWin / 2) - 12;
  var topPopupWin = (screen.height / 2) - (heightPopupWin / 2) - 50;
  var popupWin;
  popupWin = window.open("../admin/pdf_generic_function.php?functionName=getStationData&par_01=" + jbId + "&par_02=" + trSort,"","dependent=yes,width=" + widthPopupWin + ",height=" + heightPopupWin +",left=" + leftPopupWin + ",top=" + topPopupWin + ",scrollbars=yes");
};

function openJob2AcceptanceProtocol() {
  var widthPopupWin = 1200;
  var heightPopupWin = 1024;
  var leftPopupWin = (screen.width / 2) - (widthPopupWin / 2) - 12;
  var topPopupWin = (screen.height / 2) - (heightPopupWin / 2) - 50;
  var popupWin;
  popupWin = window.open("../admin/metafield_special_cron.php?category=<?php echo ec(300) ?>&objId=<?php echo ec($job_id) ?>&cascadingObjType=jb&dbhistory=<?php echo ec($dbhistory) ?>&specialPageTitle=<?php echo getLngt("Abnahmeprotokoll") ?>&sendToClientFileDownload=1","","dependent=yes,width=" + widthPopupWin + ",height=" + heightPopupWin +",left=" + leftPopupWin + ",top=" + topPopupWin + ",scrollbars=yes");
};

function openJob2CustomerServiceProtocol() {
  var widthPopupWin = 1200;
  var heightPopupWin = 1024;
  var leftPopupWin = (screen.width / 2) - (widthPopupWin / 2) - 12;
  var topPopupWin = (screen.height / 2) - (heightPopupWin / 2) - 50;
  var popupWin;
  popupWin = window.open("../admin/metafield_special_cron.php?category=<?php echo ec(306) ?>&objId=<?php echo ec($job_id) ?>&cascadingObjType=jb&dbhistory=<?php echo ec($dbhistory) ?>&specialPageTitle=<?php echo getLngt("Kundendienstaufnahme") ?>&sendToClientFileDownload=1","","dependent=yes,width=" + widthPopupWin + ",height=" + heightPopupWin +",left=" + leftPopupWin + ",top=" + topPopupWin + ",scrollbars=yes");
};

function openJob2Invoice(category, pageTitle, parString) {
  var widthPopupWin = 1200;
  var heightPopupWin = 1024;
  var leftPopupWin = (screen.width / 2) - (widthPopupWin / 2) - 12;
  var topPopupWin = (screen.height / 2) - (heightPopupWin / 2) - 50;  
  var popupWin;
  popupWin = window.open("../admin/metafield_special_cron.php?category=" + category + "&objId=<?php echo ec($job_id) ?>&cascadingObjType=jb&dbhistory=<?php echo ec($dbhistory) ?>&specialPageTitle=" + pageTitle + ">&sendToClientFileDownload=1" + parString,"","dependent=yes,width=" + widthPopupWin + ",height=" + heightPopupWin +",left=" + leftPopupWin + ",top=" + topPopupWin + ",scrollbars=yes");
};

function openImageViewer(f_fileName, f_width, f_height, f_path) {
  var widthPopupWin = 1200;
  var heightPopupWin = 1024;
  var leftPopupWin = (screen.width / 2) - (widthPopupWin / 2) - 12;
  var topPopupWin = (screen.height / 2) - (heightPopupWin / 2) - 50;
  var popupWin;
  popupWin = window.open("../include/image_viewer.php?f_fileName=" + f_fileName + "&f_width=" + f_width + "&f_height=" + f_height + "&f_path=" + f_path,"","dependent=yes,width=" + widthPopupWin + ",height=" + heightPopupWin +",left=" + leftPopupWin + ",top=" + topPopupWin + ",scrollbars=yes");
};

// Opens a new (popup-)window with specified parameters
function popupWindow(url,title,config) {
  var widthPopupWin = screen.width - 80;
  var heightPopupWin = screen.height - 180;
  var leftPopupWin = (screen.width / 2) - (widthPopupWin / 2);
  var topPopupWin = (screen.height / 2) - (heightPopupWin / 2);
  var popup;
  popup = window.open(url,title, "dependent=yes,width=" + widthPopupWin + ",height=" + heightPopupWin +",left=" + leftPopupWin + ",top=" + topPopupWin + ",scrollbars=yes");
}

// Opens the internal remark action container
function openActionContainer(trId, trSort) {
  myhide('actioncontainer');
  $('#actionObjId').val(trId);
  vSetElementContent('ac_title', '<b><?php echo getLngt("Interne Gründe - Station") ?> ' + trSort + '</b>');
  vSetElementContent('ac_description', '<?php echo getLngt("Sie können verschiedene Gründe wählen!") ?>');  
  <?php
     for ($mt = 0; $mt < $mtIntRemItemLen; $mt++) :
         echo "vSetElementContent('ac_" . pad($mt,2) . "', '" . "<input type=\"checkbox\" id=\"f_int_rem_item_" . pad($mt,2) . "\" name=\"f_int_rem_item_" . pad($mt,2) . "\" value=\"0\">" . "&nbsp;&nbsp;" . $mtIntRemItem[$mt] . "');\n";
     endfor;
  ?>

  // Get tour remark freetext
  var trRemText = '';
  ajaxRequestGet('../include/ajaxReqLib.php', 'mode=7&db_table=genericdatacontainer&db_return_field=gdc_content&id_01=gdc_obj_type&value_01=tr&id_02=gdc_gen_fieldname&value_02=tr_int_rem&id_03=gdc_obj_id&value_03=' + trId);
  if (retValue != '') {
     trRemText = retValue;
  }
  vSetElementContent('ac_text', '<textarea id="f_int_rem_text" name="f_int_rem_text" cols="30" rows="5">' + trRemText + '</textarea>\n');

  // Set checkboxes if activated
  var mtLen = <?php echo $mtIntRemItemLen ?>;
  for (var i = 0; i < mtLen; i++) {
      if ((typeof trIntRemItemTexts[trId][i] !== 'undefined') && trIntRemItemTexts[trId][i] != '') {
      	 $('#f_int_rem_item_' + padl(i.toString(),2,'0')).prop('checked', true);
      }
  }
  myshow('actioncontainer');
}

// Saves the internal remark action container
function saveActionContainer() {
	var trId = $('#actionObjId').val();
	var items = '';  
  var mtLen = <?php echo $mtIntRemItemLen ?>;
  for (var i = 0; i < mtLen; i++) {
  	  if ($('#f_int_rem_item_' + padl(i.toString(),2,'0')).prop('checked')) {
      	 if (items != '') {items += ','};
      	 items += i;
      }
  }
  // var isOk;
	ajaxRequestGet('../include/ajaxReqGeneric.php', 'incFile=inc_job.inc&fun=setJobInternalRemarkItems&par_01=' + encodeURI(escape(trId)) + '&par_02=' + encodeURI(escape(items)) + '&retIdx=0&retParName=isOk');
	if (isOk == 'OK') {
	   var trRemarkFreetext = $('#f_int_rem_text').val();
	   ajaxRequestGet('../include/ajaxReqGeneric.php', 'incFile=inc_job.inc&fun=setTourInternalRemark&par_01=' + encodeURI(escape(trId)) + '&par_02=' + encodeURI(escape(trRemarkFreetext)) + '&retIdx=0&retParName=isOk&wrap_html=1');		 
	}
	// Store remark freetext for tour ID
	if (isOk == 'OK') {
     // Insert into log
     ajaxRequestGet('../include/ajaxReqLib.php', 'mode=300&db_id_field=148&db_op_field=jb&search_value=<?php echo $job_id ?>&id_01=STATION_ID&value_01=' + trId + '&id_02=REMARK_ITEMS&value_02=' + items + '&id_03=REMARK_TEXT&value_03=' + trRemarkFreetext);
		 alert('<?php echo getLngt("Die Auswahl wurde gespeichert!") ?>');
  } else {
  	 alert('<?php echo getLngt("Das Abspeichern hat leider nicht funktioniert!") ?>');
	}
  // Get internal remark item structure
  getInternalRemarkItemData();
  // Update output in tour list
  ajaxRequestContainerHtmlGet('../include/ajaxReqGeneric.php', 'out_tr_int_rem_' + padl(trId.toString(),2,'0'), 'mode=html&incFile=inc_job.inc&fun=getJobInternalRemarkItems&fixNumOfPars=3&par_01=' + encodeURI(escape(<?php echo $job_id ?>)) + '&par_02=2&par_03=' + encodeURI(escape(trId)) + '&retIdx=0&retParName=_RAW_TEXT_');

  // Close container window after storage
  if (isOk == 'OK') {
  	 closeActionContainer();
	}
}

// Closes the internal remark action container
function closeActionContainer () {
	$('#actionObjId').val('');
  myhide('actioncontainer');
}

function containerAction (elemId, elemVisual = '', elemVal = '_noAction_') {
	<?php if ($userTypeName == "hq" && $f_act != "mailsend" && $f_act != "printjob" && $f_act != "export") : ?>
	if (elemVal != '_noAction_') {
	   $('#' + elemId).val(elemVal);
  }
  if (elemVisual == 'hide') {
     myhide(elemId);
  } else if (elemVisual == 'show') {
  	 myshow(elemId);
  }
  <?php endif; ?>
}

function saveKM (jbId, elemId) {	
	<?php if ($userTypeName == "hq" && $f_act != "mailsend" && $f_act != "printjob" && $f_act != "export") : ?>
	var elemValOld = $('#kmValOld').val();
	elemValOld = elemValOld.replace(/,/, ".");
  if (elemId) {
  	if (checkIsNumeric(elemId, '<?php echo getLngt("Der KM-Wert muss numerisch sein!") ?>')) {
  		 elemVal = elemId.value;
  		 elemVal = elemVal.replace(/,/, ".");
  		 if (elemVal != elemValOld) {
  		 	  if (elemVal >= 0) {
  		 	     containerAction('km2Edit', 'hide');
             // Update or insert KM value in jobprice
             // Check existence of an entry
             ajaxRequestGet('../include/ajaxReqLib.php', 'mode=2&submode=1&db_table=jobprice&db_return_field=jbprc_price&clause=' + encodeURI(escape('jb_id=' + jbId + ' AND mt_sort=11')));
             if (retValue != '') {
             	 // Update
             	 ajaxRequestGet('../include/ajaxReqLib.php', 'mode=100&db_table=jobprice&db_id_field=jb_id&db_op_field=jbprc_price&new_content=' + elemVal + '&search_value=' + jbId + '&clause= ' + encodeURI(escape('mt_sort=11')));
             } else {
             	 // Insert
               ajaxRequestGet('../include/ajaxReqLib.php', 'mode=200&db_table=jobprice&db_op_field=jb_id---' + jbId + '---mt_sort---11---jbprc_price---' + elemVal + '---jbprc_remark---M');
             }
             // elemValOutput = elemVal.replace(/\./,",");
             // Insert into log
             ajaxRequestGet('../include/ajaxReqLib.php', 'mode=300&db_id_field=167&db_op_field=jb&search_value=' + jbId + '&id_01=KM_VAL_OLD&value_01=' + encodeURI(escape($('#kmValOld').val())) + '&id_02=KM_VAL_NEW&value_02=' + elemVal);
             // Refresh main output field with the new value
             elemValOutput = elemVal.replace(/\./,",");
             $('#km_span').html(elemValOutput);
             $('#kmValOld').val(elemValOutput);
             // Set "M" sign to mark this row for "set manuallyc
             ajaxRequestGet('../include/ajaxReqLib.php', 'mode=100&db_table=jobprice&db_id_field=jb_id&db_op_field=jbprc_remark&new_content=M&search_value=' + jbId + '&clause= ' + encodeURI(escape('mt_sort=11')));
             // Compute CO2 value based on new KM value
             if (elemVal > 0) {
                ajaxRequestGet('../include/ajaxReqGeneric.php', 'incPath=tools&incFile=co2e_sendReq&fun=sendReqCO2&par_01=' + jbId + '&retIdx=0');
                if (checkIsNaN(retValue, '<?php echo getLngt("Die Berechnung des CO2-Wertes schlug fehl!") ?>')) {
                   $('#co2_span').html(retValue);
                   $('#co2ValOld').val(retValue);
                }
             } else {
                // New KM value equals "0", set CO2 value to "0", too. The zero value in "elemVal" can be used!
                ajaxRequestGet('../include/ajaxReqLib.php', 'mode=100&db_table=jobprice&db_id_field=jb_id&db_op_field=jbprc_price&new_content=' + elemVal + '&search_value=' + jbId + '&clause= ' + encodeURI(escape('mt_sort=12')));
                // Refresh main output field with the new value
                $('#co2_span').html(elemVal);
                $('#co2ValOld').val(elemVal);                             	
             }
             // Rewrite invoice text without return parameter
             ajaxRequestGet('../include/ajaxReqGeneric.php', 'incPath=include&incFile=caglobal.inc.php&fun=mk_jb_invtext_full&par_01=' + jbId + '&retIdx=0');
             // Reload invoice text
             ajaxRequestGet('../include/ajaxReqLib.php', 'mode=0&db_table=job&db_id_field=jb_id&search_value=' + jbId + '&db_return_field=jb_invtext');
             if (retValue != '') {
             	  $('#f_jb_invtext_new').html(retValue);
             }
          } else {
       	     alert('<?php echo getLngt("Der KM-Wert sollte schon größer gleich 0 sein!") ?>');
          }
       } else {
       	  alert('<?php echo getLngt("Der KM-Wert hat sich nicht geändert!") ?>');
       }
    }
  } else {
  	alert('<?php echo getLngt("Das hat leider nicht geklappt!") ?>');
  }
	<?php endif; ?>
}

function saveCO2 (jbId, elemId) {	
	<?php if ($userTypeName == "hq" && $f_act != "mailsend" && $f_act != "printjob" && $f_act != "export") : ?>
	var elemValOld = $('#co2ValOld').val();
	elemValOld = elemValOld.replace(/,/, ".");
  if (elemId) {
  	if (checkIsNumeric(elemId, '<?php echo getLngt("Der CO2-Wert muss numerisch sein!") ?>')) {
  		 elemVal = elemId.value;
  		 elemVal = elemVal.replace(/,/, ".");
  		 if (elemVal != elemValOld) {
  		 	  containerAction('co2Edit', 'hide');
          // Update CO2 value in jobprice
          ajaxRequestGet('../include/ajaxReqLib.php', 'mode=100&db_table=jobprice&db_id_field=jb_id&db_op_field=jbprc_price&new_content=' + elemVal + '&search_value=' + jbId + '&clause= ' + encodeURI(escape('mt_sort=12')));
          elemVal = elemVal.replace(/\./,",");
          // Insert into log
          ajaxRequestGet('../include/ajaxReqLib.php', 'mode=300&db_id_field=166&db_op_field=jb&search_value=' + jbId + '&id_01=CO2_VAL_OLD&value_01=' + encodeURI(escape($('#co2ValOld').val())) + '&id_02=CO2_VAL_NEW&value_02=' + elemVal);
          // Refresh main output field with the new value
          $('#co2_span').html(elemVal);
          $('#co2ValOld').val(elemVal);
          // Rewrite invoice text without return parameter
          ajaxRequestGet('../include/ajaxReqGeneric.php', 'incPath=include&incFile=caglobal.inc.php&fun=mk_jb_invtext_full&par_01=' + jbId + '&retIdx=0');
          // Reload invoice text
          ajaxRequestGet('../include/ajaxReqLib.php', 'mode=0&db_table=job&db_id_field=jb_id&search_value=' + jbId + '&db_return_field=jb_invtext');
          if (retValue != '') {
          	  $('#f_jb_invtext_new').html(retValue);
          }
       } else {
       	  alert('<?php echo getLngt("Der CO2-Wert hat sich nicht geändert!") ?>');
       }
    }
  } else {
  	alert('<?php echo getLngt("Das hat leider nicht geklappt!") ?>');
  }
	<?php endif; ?>
}

function filterOptions (elemSearch, elemSelect) {
	let input = document.getElementById(elemSearch);
  let filter = input.value.toUpperCase();
  let select = document.getElementById(elemSelect);
  let options = select.getElementsByTagName('option');
  let firstVisibleOption = null;

  // The list will be filtered and the potential matches will be reduced
  for (let i = 0; i < options.length; i++) {
    let opt = options[i];
    let txtValue = opt.textContent || opt.innerText;

    if (txtValue.toUpperCase().indexOf(filter) > -1) {
      opt.style.display = "";
      // Wenn wir noch keine passende Option gespeichert haben,
      // ist diese die erste.
      if (firstVisibleOption === null) {
        firstVisibleOption = opt;
      }
    } else {
      opt.style.display = "none";
    }
  }

  // Selects the first option found
  if (firstVisibleOption) {
    // Setzt den Wert der Select-Box auf den Wert der ersten sichtbaren Option
    select.value = firstVisibleOption.value;
  } else {
    // Optional: Was passiert, wenn es keinen Treffer gibt
    select.selectedIndex = -1; // Setzt die Auswahl zurück
  }
}
-->
</script>
<noscript>
  <center>
  <b><br>JavaScript ist nicht verf&uuml;gbar. Bitte aktivieren Sie JavaScript<br><br>
        in Ihrem Browser, damit diese Seite ordnungsgem&auml;&szlig; funktioniert!</b><br><br>
  </center>
</noscript>
</head>
<body onLoad="<?php echo $phpCurrentNavigationOnLoad ?>myhide('actioncontainer');myhide('kmEdit');myhide('co2Edit');this.moveTo((screen.width * 0.5)-(document.body.offsetWidth * 0.5),(screen.height * 0.5)-(document.body.offsetHeight * 0.5));getInternalRemarkItemData();">

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

<?php
  // Additional output of the "invoice" job no. (Parent ID of the job)
  $parGlobalUseJbParentIdForInvoice = getParameterValue("0", "GLOBAL_USE_JB_PARENT_ID_FOR_INVOICE_NO", "0");
  $outJobNo = $job_id;
  if ($parGlobalUseJbParentIdForInvoice == "1") :
     $outJobNo = getJobIdOutput($job_id);
  endif;
?>

<div class="mc_page-header" id="mc_page-header">
  <?php echo getLngt("Auftrag") . "&nbsp;&nbsp;" . $outJobNo ?>
</div>

<div>
  <?php 
    echo defineButtonType10(getLngt("Aktualisieren"), "action_reload", "document.forms[0].submit();", "150", "left", "0");
    echo defineButtonType10(getLngt("Schließen"), "action_close", "window.close();", "150", "left", "10");
    if (false && $f_act != "mailsend" && $f_act != "printjob") :
       if ($jbAccessModeArr["1"]) :
          echo defineButtonType10(getLngt("Kopieren"), "action_copy", "", "150", "left", "0");
       endif;
       echo defineButtonType10(getLngt("Auftragshistorie"), "action_jbhistory", "", "150", "left", "0");
       echo defineButtonType10(getLngt("Transporteurshistorie"), "action_crhistory", "", "150", "left", "0");
    endif;
    if ($jobIsAllowedToBeModified) :
       echo defineButtonType10(getLngt("Druckansicht"), "action_print", "printjob();", "150", "left", "0");
       // if ($takeRealJobData) :
          echo defineButtonType10(getLngt("PDF"), "action_pdf", "openJob2pdf();", "150", "left", "0");
       // endif;
       if ($jbAccessModeArr["1"]) :  // $jobIsNotExported
          echo defineLinkButtonType10(getLngt("Dokumente") . ($jbNumOfFiles != "-1" ? ": " . $jbNumOfFiles : ""), "action_dt_jb", "../import/data_transfer.php?objType=jb&objId=" . ec($job_id), "150", "left", "10", "", "", "", "", "0");
       endif;
    endif;
    
    $maskJobLabelSize = getParameterValue("0", "MASK_JB_LABEL_SIZE", $currentHqId);
    if ($maskJobLabelSize == "") : $maskJobLabelSize = getParameterValue("0", "MASK_JB_LABEL_SIZE", "0"); endif;
    if ($maskJobLabelSize == "") : $maskJobLabelSize = "label60x40"; endif;
    if ($jbAccessModeArr["1"]) :
       echo defineButtonType10(getLngt("Etiketten"), "label", "openJob2Invoice('302','','&pdfPageSize=" . $maskJobLabelSize . "');", "220", "left", "0");
       echo defineButtonType10(getLngt("Etiketten Retoure"), "label", "openJob2Invoice('303','','&pdfPageSize=" . $maskJobLabelSize . "');", "220", "left", "3");
    endif;
  ?>
</div>

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

<form name="jb_detail" action="../admin/jb_detail.php" method="post">
  <input type="hidden" name="f_act" value="">
  <input type="hidden" name="job_id" value="<?php echo ec($job_id) ?>">
  <input type="hidden" name="customerId" value="<?php echo ec($customerId) ?>">
  <input type="hidden" name="cscIdRoot" value="<?php echo ec($cscIdRoot) ?>">
  <input type="hidden" name="cscIdActual" value="<?php echo ec($cscIdActual) ?>">
  <input type="hidden" name="empIdMaster" value="<?php echo ec($empIdMaster) ?>">
  <input type="hidden" name="dbhistory" value="<?php echo ec($dbhistory) ?>">
  <?php echo $phpCurrentNavigationInputHidden ?>
  <input type="hidden" name="deactivateMenu" value="<?php echo ec($deactivateMenu) ?>">

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

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

    <div <?php echo setStyleHtmlDiv("250px","left"); ?>></div>
    <div>
      <?php 
        if ($jobIsAllowedToBeModified) :
           $constMaskButtonAcceptanceProtocol = getParameterValue("0", "MASK_JOBDETAILS_BUTTON_ACCEPTANCE_PROTOCOL", $currentHqId);
           if ($constMaskButtonAcceptanceProtocol == "") : $constMaskButtonAcceptanceProtocol = getParameterValue("0", "MASK_JOBDETAILS_BUTTON_ACCEPTANCE_PROTOCOL", "0"); endif;
           if ($constMaskButtonAcceptanceProtocol == "1") :
           
              // Get payment method from jb_id (and tr_sort) to display the correct version of PDF links
              /*
              // IMPORTANT: Get mapping from payment method to mtfc category
              $parMappingPaymentmethodToMtfcCategory = getObjectBasedParameterValue("MAPPING_PAYMENT_TO_MTFC_CS", $tmpCsId, $currentHqId);
              if ($parMappingPaymentmethodToMtfcCategory == "") : $parMappingPaymentmethodToMtfcCategory = getObjectBasedParameterValue("MAPPING_PAYMENT_TO_MTFC_GRP", $tmpGrpId, $currentHqId); endif;
              $mappingArray = getKeyValueArrayFromString($parMappingPaymentmethodToMtfcCategory);
              */
           
              // echo defineButtonType10(getLngt("XXXX"), "action_invoice", "openJob2Invoice('" . $mappingArray[$jbpMode] . "');", "250", "left", "3");
              // echo defineButtonType10(getLngt("Etiketten"), "action_acceptance protocol", "openJob2Invoice('302','','&pdfPageSize=label60x40');", "220", "left", "3");
              if (($jobService & 1) == 1) :
                 echo defineButtonType10(getLngt("Auftragsbestätigung Lieferung"), "action_acceptance protocol", "openJob2Invoice('301');", "220", "left", "3");
              endif;
              if (($jobService & 2) == 2) :
                 echo defineButtonType10(getLngt("Auftragsbestätigung Montage"), "action_acceptance protocol", "openJob2Invoice('303');", "220", "left", "3");
              endif;
              echo defineButtonType10(getLngt("Auftragsbestätigung"), "action_invoice", "openJob2Invoice('304');", "220", "left", "3");
              echo defineButtonType10(getLngt("Frachtbrief"), "action_invoice2", "openJob2Invoice('305');", "220", "left", "3");
              echo defineButtonType10(getLngt("Abnahmeprotokoll"), "action_acceptance_protocol", "openJob2AcceptanceProtocol();", "220", "left", "3");
              if (false) :
                 echo defineButtonType10(getLngt("Kundendienstaufnahme"), "action_customer_service_protocol", "openJob2CustomerServiceProtocol();", "220", "left", "3");
              endif;
           endif;
        endif;
      ?>
    </div>
  </div>

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

  <div>
    <table cellspacing="0" cellpadding="0" vspace="0" hspace="0">    
      <tr>
        <td valign="top">
          <!-- JOB-DATA -->        
          <table cellspacing="0" cellpadding="0" vspace="0" hspace="0">    
            <tr><td class="mc_table-header" colspan="2"><?php echo getLngt("AUFTRAG:") ?></td></tr>
            <?php if ($automailer == "0") : echo $jobentry; endif; ?>
          </table>
        </td>
        <td>
          &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        </td>
        <td valign="top">
          <!-- COURIER-DATA -->        
          <table cellspacing="0" cellpadding="0" vspace="0" hspace="0">    
            <tr><td class="mc_table-header" colspan="2"><?php echo getLngt("TRANSPORTEUR:") ?></td></tr>
            <?php if ($automailer == "0") : echo $courierentry; endif; ?>
          </table>
          <br><br>
          <?php if ($automailer == "0" && $listOfSubjobs != "") : ?>
            <table cellspacing="0" cellpadding="0" vspace="0" hspace="0">
            <?php echo $listOfSubjobs ?>
            </table>
            <br><br>
          <?php endif; ?>
          <?php if ($automailer == "0" && $listOfParentJobs != "") : ?>
            <table cellspacing="0" cellpadding="0" vspace="0" hspace="0">
            <?php echo $listOfParentJobs ?>
            </table>
          <?php endif; ?>
        </td>      
        <td>
          &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        </td>
        <td valign="top">
          <!-- JOB-COSTS -->        
          <table cellspacing="0" cellpadding="0" vspace="0" hspace="0">
            <tr><td class="mc_table-header" colspan="6"><?php echo getLngt("KOSTEN:") ?></td></tr>
            <?php if ($job_orderer != "") : ?>
              <tr><td colspan="6"><?php echo getLngt("Besteller:") . "&nbsp;" . $job_orderer ?></td></tr>
            <?php endif; ?>
            <?php if ($automailer == "0") : echo $jobcosts; endif; ?>
          </table>          
          <br><br>
          <!-- JOB-FAVOURED-COURIERS -->        
          <table cellspacing="0" cellpadding="0" vspace="0" hspace="0">    
             <?php if ($automailer == "0") : echo $jobFavouredCouriers; endif; ?>
          </table>          
          <br><br>
          <!-- EMPLOYEE-DATA -->        
          <table cellspacing="0" cellpadding="0" vspace="0" hspace="0">
          	<tr><td class="mc_table-header" colspan="6"><?php echo getLngt("MITARBEITER:") ?></td></tr>
            <?php if ($automailer == "0") : echo $employeeentry; endif; ?>
          </table>
        </td>      
        <td>
          &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        </td>
      </tr>
    </table>
  </div>

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

  <!-- TOUR-DATA -->
  <div>
    <?php 
      if ($automailer == "0") : 
         echo "<table cellspacing=\"0\" cellpadding=\"0\" vspace=\"0\" hspace=\"0\">\n";
         echo "<caption class=\"mc_table-header\">" . getLngt("TOUR:") . "</caption>";
         echo $tourentry;
         echo "</table>";
      endif;
    ?>
  </div>
  <?php echo htmlDivLineSpacer("30px"); ?>
  <div>
    <?php if ($automailer == "0") : echo $modifyTourname; endif; ?>
  </div>
  <?php echo htmlDivLineSpacer("10px", "", "left"); ?>
  <div>
    <?php if ($automailer == "0") : echo $mailsend; endif; ?>
  </div>
  <?php echo htmlDivLineSpacer("10px", "", "left"); ?>
  <div>
    <?php if ($automailer == "0") : echo $changeCourier; endif; ?>
  </div>
  <?php echo htmlDivLineSpacer("10px"); ?>
  <div>
    <?php if ($automailer == "0") : echo $bookjob; endif; ?>
  </div>
  <?php echo htmlDivLineSpacer("10px", "", "left"); ?>
  <div>
    <?php 
      if ($automailer == "0") :
         if ($scanEventsHtml != "") :
            $scanEventsHtml = "<div class=\"f10bp1\"><b>" . getLngt("Scan-Events") . "</b></div>" . htmlDivLineSpacer("10px") . $scanEventsHtml;
            echo $scanEventsHtml;
         endif;
         if ($manualEventsHtml != "") :
            $manualEventsHtml = "<div class=\"f10bp1\"><b>" . getLngt("Manuelle Events") . "</b></div>" . htmlDivLineSpacer("10px") . $manualEventsHtml;
            echo $manualEventsHtml;
         endif;
      endif; 
     ?>
  </div>
  <?php echo htmlDivLineSpacer("10px", "", "left"); ?>
  <div>
    <?php if ($automailer == "0") : echo $outputTourarticle; endif; ?>
  </div>
  <?php echo htmlDivLineSpacer("10px"); ?>
  <div>
    <?php if ($automailer == "0") : echo $outputJobcalculator; endif; ?>
  </div>
  <?php echo htmlDivLineSpacer("10px"); ?>
  <div>
    <?php if ($automailer == "0") : echo $outputJobprice; endif; ?>
  </div>
  <?php echo htmlDivLineSpacer("10px"); ?>
  <div>
    <?php if ($automailer == "0") : echo $changeGDC_addMon; endif; ?>
  </div>
  <?php echo htmlDivLineSpacer("10px", "", "left"); ?>
  <div>
    <?php if ($automailer == "0") : echo $changePayment; endif; ?>
  </div>
  <?php echo htmlDivLineSpacer("10px", "", "left"); ?>
  <div>
    <?php if ($automailer == "0") : echo $outputArticleAcceptanceData; endif; ?>
  </div>
  <?php echo htmlDivLineSpacer("10px", "", "left"); ?>
  <div>
    <?php if ($automailer == "0") : echo $outputPhotos; endif; ?>
  </div>
  <?php echo htmlDivLineSpacer("10px", "", "left"); ?>
  <div>
    <?php if ($automailer == "0") : echo $completeJob; endif; ?>
  </div>
  <?php echo htmlDivLineSpacer("10px","","both"); ?>  

<div>
  <div <?php echo setStyleHtmlDiv("650","left"); ?>>
    <?php 
      if ($automailer == "0") : echo $jobinvoicetext; endif;
      echo htmlDivLineSpacer("20px");
      if (false) :
         if ($automailer == "0") : echo $jobInvoiceCrText; endif;
         echo htmlDivLineSpacer("20px");
      endif;
      if ($automailer == "0") : echo $jobcourierremark; endif;
      echo htmlDivLineSpacer("20px");
      if ($automailer == "0") : echo $jobinternalremark; endif;
    ?>
  </div>
  <div <?php echo setStyleHtmlDiv("650","left"); ?>>
    <?php
      if ($automailer == "0") : echo $jobcustomerremarktext; endif;
      echo htmlDivLineSpacer("20px");
      if ($automailer == "0") : echo $jobfreetext1; endif;
      echo htmlDivLineSpacer("20px");
    ?>
  </div>  
</div>

  <!-- Container for actions -->
  <?php if ($maskJobInternalRemarkItems == "1") : ?>
    <div id="actioncontainer" <?php echo $actioncontainerDivPos ?>>
    	<input type="hidden" id="actionObjType" name="actionObjType" value="">
    	<input type="hidden" id="actionObjId" name="actionObjId" value="">
    	
    	<?php echo defineButtonType08("Speichern", "action_actioncontainer_save", "saveActionContainer();", "100", "left", "10") ?>
    	<?php echo defineButtonType08("Schließen", "action_actioncontainer_close", "closeActionContainer();", "100", "", "") ?>
    	<?php echo htmlDivLineSpacer("30px"); ?>
    	
    	<div style="float:left;width:40px;height:100%">
    		&nbsp;
      </div>
      <div>
    	  <div id="ac_title"></div>
    	  <?php echo htmlDivLineSpacer("20px"); ?>
    	  <div id="ac_description"></div>
    	  <?php echo htmlDivLineSpacer("10px"); ?>
        <?php
           for ($mt = 0; $mt < $mtIntRemItemLen; $mt++) :
               echo "<div id=\"ac_" . pad($mt,2) . "\"></div>\n";
               echo htmlDivLineSpacer("5px");
           endfor;
        ?>
        <div id="ac_text"></div>
    	</div>
    </div>
  <?php endif; ?>

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

<?php
   endif;
endif;
?>
