<?php
/*=======================================================================
 *
 * job_options.php
 *
 * Autor: Carsten Annacker
 *
 =======================================================================*/

// TOBEDONE: Automatische Vermittlung

//print_r($HTTP_POST_VARS);

//require_once("HTML/IT.php");
include_once("../include/caglobal.inc.php");
trace_execution_time_start();
include_once("../include/global.inc.php");
include_once("../include/auth.inc.php");
include_once("../include/services_func.inc.php");
include_once("../geo/distance.php");
include_once("../include/inc_set_costsplit.inc.php");
include_once("../jobs/job_accesskeys.inc.php");
include_once("../locating/xServer.inc.php");
//include_once("../jobs/job_options.js.inc.php");
//if ($phpVersion >= "7.0"):
//  require_once("../PEAR/HTML/Template/IT.php");
//else:
//  require_once("HTML/IT.php");
//endif;
if (!(isset($check_jb_permanent_flag) && $check_jb_permanent_flag == true))
{
  include_once ("../admin/menu.php");
}

$usr_id_block = (isset($usr_id) ? $usr_id : 0);
// wenn von "check_jb_permanent.php" aufgerufen, dann sind
// die Variablen alle schon gesetzt
if (!(isset($check_jb_permanent_flag) && $check_jb_permanent_flag == true)):
  writeLog_("../log/job2_options_", var_export($HTTP_POST_VARS, true));
  list($csc_id_orderer_ec) = getHttpVars(array("csc_id_orderer"));
  getSecHttpVars("1", array("csc_id_orderer", "jb_id", "csc_id_start"));
  list ($dbhistory) = getHttpVars(array("dbhistory"));
  if ($dbhistory == "")
    $dbhistory = 0;
  getDBNames($dbhistory);
  list ($jb_copy) = getHttpVars(array("jb_copy"));

  if ($jb_copy == "")
    $jb_copy = "false";
  list ($toursubmit, $jobListOri, $cr_id_order, $jb_waittime_hour, $jb_waittime_minute,
    $jb_waitstorno, $jb_weight, $jb_crvh_length, $jb_crvh_width, $jb_crvh_height, $jb_crvh_position, $vht_id, $tag, $monat, $jahr, $stunde, $minute, $jb_permanent,
    $jb_tourname, $jb_fixprice, $jb_serviceprice, $jb_cr_price, $jb_cr_serviceprice, $jb_discount, $jb_discount_rate, $afterwards, $statusMessage, $jb_cash, $getPriceOnly,
    $csc_id_payer, $comp_payer, /*$jb_type,*/ $jb_globaljob, $jb_freetext_1, $jb_costsplit, $jb_permanent2,
    $jb_sales_tax_rate, $jb_sales_tax_rate_sign, $endetag, $endemonat, $endejahr, $jb_cr_filter, $jb_cr_filter_opt, $jb_status,
    $accept_all_addresses, $jb_id_org, $jb_status_manual, $jb_incomplete, $jb_dispoinfo, $jb_warntag, $jb_warnmonat, $jb_warnjahr, $jb_warnstunde, $jb_warnminute, $jb_jam_waittime,
    $jb_tourname_hidden_vht_id, $jb_tourname_hidden, $km_price_params, $request_token, $jb_commission_no) =
    getHttpVars(array("toursubmit", "jobList", "cr_id_order", "jb_waittime_hour",
      "jb_waittime_minute", "jb_waitstorno", "jb_weight", "jb_crvh_length", "jb_crvh_width", "jb_crvh_height", "jb_crvh_position", "vht_id", "tag", "monat", "jahr",
      "stunde", "minute", "jb_permanent", "jb_tourname", "jb_fixprice", "jb_serviceprice", "jb_cr_price", "jb_cr_serviceprice", "jb_discount", "jb_discount_rate", "afterwards",
      "statusMessage", "jb_cash_hidden", "getPriceOnly", "csc_id_payer", "comp_payer",
      /*"jb_type",*/ "jb_globaljob", "jb_freetext_1", "jb_costsplit_hidden", "jb_permanent2_hidden",
      "jb_sales_tax_rate", "jb_sales_tax_rate_sign", "endetag", "endemonat", "endejahr",
      "jb_cr_filter", "jb_cr_filter_opt", "jb_status", "accept_all_addresses", "jb_id_org", "jb_status_manual", "jb_incomplete", "jb_dispoinfo",
      "jb_warntag", "jb_warnmonat", "jb_warnjahr", "jb_warnstunde", "jb_warnminute", "jb_jam_waittime", "jb_tourname_hidden_vht_id", "jb_tourname_hidden", "km_price_params",
      "request_token", "jb_commission_no_hidden"
       ));
  if ($toursubmit == "Senden" && $getPriceOnly != 1 && $request_token != ""): // e.g. no request_token when storno
    $sp_id_request = $db->getOne("SELECT sp_id FROM phoenix_log.semaphor WHERE sp_obj_type = 'usr' AND sp_fieldname = 'request_token' AND sp_content = '" . $request_token . "'");
    if ($sp_id_request != "") // nur zur Sicherheit
      $sp_context = $db->getOne("SELECT sp_context FROM phoenix_log.semaphor WHERE sp_id = " . $sp_id_request);
    writeLog_("../log/job2_options_", "\$request_token = " . $request_token . ", \$sp_id_request = " . $sp_id_request . ", \$sp_context = " . $sp_context);
    if ($sp_id_request != "" && trim($sp_context) != "NOT_SENT"):
      writeLog_("../log/job2_options_", "double post for \$request_token = " . $request_token . " already been processed for jb_id = " . trim($sp_context));
      include_once("../include/email/htmlMimeMail.php");
      $mailObj = new htmlMimeMail();
      $mailObj->setFrom("support@assecutor.de");
      $mailObj->setSubject("Doppelter Post für Auftrag " . trim($sp_context) . "!");
      $mailObj->setText("Das request_token " . $request_token . " wurde doppelt gepostet!");
      $mailResult = $mailObj->send(array("ca@assecutor.de"), 'smtp');
      exit();
    endif;
  endif;
else:
  $usr_id_block = 1;
endif;

$sp_id = 0;
$sp_id_block = 0;
if ($toursubmit == "Senden" && $getPriceOnly != 1):
  $locked = "NOT_LOCKED";
  if ($jb_id == "") {
    do {
      do {
        $sp_id_block = $db->getOne("SELECT sp_id FROM phoenix_log.semaphor WHERE sp_obj_type = 'usr' AND sp_fieldname = 'job_options_user' AND (sp_obj_id = 0 OR sp_createtime < DATE_SUB(NOW(), INTERVAL 40 SECOND))");
        if ($sp_id_block == "" || $sp_id_block == 0)
          // Warte 100 Millisekunden (d.h. eine Zehntelsekunde)
          usleep(100000);
      } while ($sp_id_block == "" || $sp_id_block == 0);
      updateStmt("phoenix_log.semaphor", "sp_id", $sp_id_block, array("sp_obj_id", $usr_id_block, "sp_createtime", date("Y-m-d H:i:s")), "(sp_obj_id = 0 OR sp_createtime < DATE_SUB(NOW(), INTERVAL 40 SECOND))");
      $sp_id_block = $db->getOne("SELECT sp_id FROM phoenix_log.semaphor WHERE sp_obj_type = 'usr' AND sp_fieldname = 'job_options_user' AND sp_obj_id = " . $usr_id_block);
      if ($sp_id_block)
        $locked = "LOCKED";
    } while ($locked == "NOT_LOCKED");
  }
  insertStmt("phoenix_log.semaphor", array("sp_obj_type", "jb", "sp_obj_id", 0, "sp_fieldname", "job_options", "sp_content", $locked, "sp_context",
   ($jb_id != "" ? "EDIT_CS" : "NEW_CS") . ((isset($check_jb_permanent_flag) && $check_jb_permanent_flag == true) ? ",PERM" : "") . (isset($jb_storno) ? ",\$jb_storno=" . $jb_storno : ""),
   "sp_createtime", date("Y-m-d H:i:s")));
  $sp_id = getLastInsertId();
endif;

if (trim($jb_id_org) == "")
  list ($jb_id_org) = getHttpVars(array("jb_id_org"));
if (!isset($jb_storno))
  $jb_storno = 0;
// Kostenstellennummer des Kunden ist Parameter
if ($csc_id_orderer == "" && $csc_id_orderer != '0'):  
  reportDie ("$PHP_SELF: Parameter 'csc_id_orderer' fehlt!", false);
endif;
// wegen einer noch nicht geklärten Merkwürdigkeit (Session-Problematik) kann es manchmal passieren, dass $csc_id_orderer negativ ist;
if ($csc_id_orderer < 0)
  $csc_id_orderer = 0;
$self_service_discount = 0;
if ($csc_id_orderer != '0'):
  // Kundenauftrag
  $cs_id = getFieldValueFromId("costcenter", "csc_id", "$csc_id_orderer", "cs_id");
  $hq_id = getFieldValueFromId("customer", "cs_id", "$cs_id", "hq_id");
  $cs_ar = getFieldValueFromId("customer", "cs_id", "$cs_id", "cs_ar");
  // wenn Kundenauftrag, dann entscheidet der zentralenabhängige Modus darüber, ob manuell oder automatisch
  // ab 14.04.2020 muss berücksichtigt werden, dass es Kunden gibt, die manuelle Dispo anklicken können
  // ab 18.05.2020 overrult MASK_MANUAL_DISPOSITION_CUSTOMER_MANDATORY alles (d.h. alle Kundenaufträge gehen immer in die manuelle Dispo)
//  if ((MASK_MANUAL_DISPOSITION == '1' && getParameterValue("0", "CUSTOMER_MANUAL_DISPO_" . $cs_id, "0") != "1") || MASK_MANUAL_DISPOSITION_CUSTOMER_MANDATORY == '1'):
  // ab 12.07.2023 overrult das neue Feld customer.cs_ar alles (1 = autoranking, 0 = automatische Vermittlung)
  if ($cs_ar == 0):
    $jb_status_manual = 1;
  endif;
  // cs_invmode ist vom Bezahler abhängig!!!
//  $cs_invmode = getFieldValueFromId("customer", "cs_id", "$cs_id", "cs_invmode");
  if (getParameterValue("0", "CUSTOMER_MASK_JB_CREATOR_DISCOUNT_" . $cs_id, "0") == "1"):
    $self_service_discount = getParameterValue("0", "MASK_CS_SELF_SERVICE_DISCOUNT", $hq_id);
  endif;
else:
  // Zentralenauftrag
  // wenn von "check_jb_permanent.php" aufgerufen, dann ist hq_id gesetzt
  if (!(isset($check_jb_permanent_flag) && $check_jb_permanent_flag == true))
    $hq_id = $HTTP_SESSION_VARS['hq_id'];
// *** cs_invmode wird jetzt auch für Hansetrans aus der DB ermittelt
  // ACHTUNG: NUR HANSETRANS! MUSS UNBEDINGT AUS DB ERMITTELT WERDEN!
//  $cs_id = 0;
//  $cs_invmode = 1;
// ***
  $cs_id = getFieldValueFromId("costcenter", "csc_id", "$csc_id_orderer", "cs_id");
//  $cs_invmode = getFieldValueFromId("customer", "cs_id", "$cs_id", "cs_invmode");
// cs_id muss wieder auf 0 gesetzt werden, da vorerst hier
// die Unterscheidung Kundenauftrag/Zentralenauftrag getroffen wird
  $cs_id = 0;
// ***
endif;
//  // wegen einer noch nicht geklärten Merkwürdigkeit in auth.inc.php kann es manchmal passieren, dass
//  // $HTTP_SESSION_VARS['hq_id'] leer ist; dann wird hq_id einfach auf eins gesetzt
//  // (wir werden voraussichtlich für jede Zentrale einen eigenen MySQL-Server laufen haben, also
//  // ist hq_id sowieso immer 1)
//  if ($hq_id == "" || $hq_id <= 0)
//    $hq_id = 1;
$hq_workmode = getFieldValueFromId("headquarters", "hq_id", "$hq_id", "hq_workmode");
$jobbatch_mode = false;
$tr_sort_jobbatchmode = 0;

$jobMode = "undefiniert";
// *** Nur für's Logging
if ($toursubmit == "Senden"):
  $jobMode = "Neu";
  if ((isset($check_jb_permanent_flag) && $check_jb_permanent_flag == true)) $jobMode = "Fortsetzung Dauerauftrag"; // "*** DUPLICATION OF STANDING ORDER ***";
  if ($getPriceOnly == 1) $jobMode =  "Preisanfrage"; // "*** PRICE INQUIRY ***";
  if ($afterwards == "1" && $getPriceOnly != 1) $jobMode =  "Nacherfassung"; // "*** NEW FINISHED JOB ***";
  if ($jb_id != "" && $getPriceOnly != 1) $jobMode       =  (getFieldValueFromId("job", "jb_id", "$jb_id", "jb_status") == 2 ? "Nachträglich" : "Laufend"); // "*** EDIT FINISHED JOB ***";
  if ($jb_storno == 1 && $getPriceOnly != 1) $jobMode    =  "Storno kostenpflichtig"; // "*** CANCELLATION CREDIT NOTE WITH CANCELLATION COSTS    ***";
  if ($jb_storno == 2 && $getPriceOnly != 1) $jobMode    =  ($jb_status == 2 ? "Storno-Gutschrift für" : "Storno von") . " Auftrag Nr. $jb_id_copy"; // "*** CANCELLATION CREDIT NOTE WITHOUT CANCELLATION COSTS ***";
//  if ($jobMode == "") $jobMode     =  ""; // "*** NEW JOB ***";
//  writeLog("\n$jobMode\n" .
//    "Variables: \$jb_storno='$jb_storno', \$hq_workmode='$hq_workmode', \$cs_id='$cs_id', \$hq_id='$hq_id'\n" .
//    "HTTP Variables: \$csc_id_orderer='$csc_id_orderer', \$jb_id='$jb_id', \$toursubmit='$toursubmit',\n\$jobList='$jobListOri',\n\$cr_id_order='$cr_id_order',\$jb_waittime_hour='$jb_waittime_hour', " .
//    "\$jb_waittime_minute='$jb_waittime_minute', \$jb_waitstorno='$jb_waitstorno', \$jb_weight='$jb_weight', \$vht_id='$vht_id',\n\$tag='$tag', \$monat='$monat', \$jahr='$jahr', " .
//    "\$stunde='$stunde', \$minute='$minute', \$jb_permanent='$jb_permanent', \$jb_tourname='$jb_tourname',\n\$jb_fixprice='$jb_fixprice', \$afterwards='$afterwards', " .
//    "\$statusMessage='$statusMessage', \$jb_cash_hidden='$jb_cash', \$getPriceOnly='$getPriceOnly', \$csc_id_payer='$csc_id_payer', \$comp_payer='$comp_payer', " .
//    "\$jb_type='$jb_type', \$jb_globaljob='$jb_globaljob',\n\$jb_freetext_1='$jb_freetext_1',\n\$jb_costsplit_hidden='$jb_costsplit', \$jb_permanent2_hidden='$jb_permanent2', " .
//    "\$jb_sales_tax_rate='$jb_sales_tax_rate', \$jb_sales_tax_rate_sign='$jb_sales_tax_rate_sign',\n\$endetag='$endetag', \$endemonat='$endemonat', \$endejahr='$endejahr', " .
//    "\$jb_cr_filter='$jb_cr_filter', \$jb_cr_filter_opt='$jb_cr_filter_opt'\n");
// Bei der Änderung eines Auftrages soll festgehalten werden, was geändert wurde...
  if ($jb_id != "" && $getPriceOnly != 1):
  // gespeicherte Job-Daten holen
    list($csc_id_old, $vht_id_old, $jb_weight_old, $jb_crvh_length_old, $jb_crvh_width_old, $jb_crvh_height_old, $jb_crvh_position_old, $jb_ordertime_old, $jb_reserv_old, $jb_permanent_old, $vht_id_old,
      $cr_sid_old, $cr_id_order_old, $jb_waitstorno_old, $jb_waittime_old, $jb_fixprice_old, $jb_serviceprice_old, $csc_id_payer_old, $csc_id_payer_cash_old,
      /*$jb_type,*/ $jb_globaljob_old, $jb_freetext_1_old, $jb_payment_old, $jb_permanent2_old,
      $jb_sales_tax_rate_old, $jb_sales_tax_rate_sign_old, $jp_permenddat_old, $jb_cr_filter_old, $jb_cr_filter_opt_old,
      $jb_status_old, $cr_id_permanent_old, $jb_incomplete_old, $jb_dispoinfo_old, $hq_id_exec_old, $jb_longhaul_old, $jb_commission_no_old) =
      getFieldsValueFromId("job", "jb_id", $jb_id,
        array("csc_id", "vht_id", "jb_weight", "jb_crvh_length", "jb_crvh_width", "jb_crvh_height", "jb_crvh_position", "jb_ordertime", "jb_reserv", "jb_permanent",
          "vht_id", "cr_sid", "cr_id_order", "jb_waitstorno", "jb_waittime", "jb_fixprice", "jb_serviceprice", "csc_id_payer", "csc_id_payer_cash",
          /*"jb_type",*/ "jb_globaljob", "jb_freetext_1", "jb_payment", "jb_permanent2",
          "jb_sales_tax_rate", "jb_sales_tax_rate_sign", "jp_permenddat", "jb_cr_filter", "jb_cr_filter_opt",
          "jb_status", "cr_id_permanent", "jb_incomplete", "jb_dispoinfo", "hq_id_exec", "jb_longhaul", "jb_commission_no"));
  endif;
  // gespeicherte Tour-Daten holen
  $i = 1;
  do {
    if (existsEntry("tour", array("jb_id", $jb_id, "tr_sort", $i))):
      $tourFound = 1;      
      list($csc_id_old_[$i], $tr_comp_old_[$i], $tr_person_old_[$i], $ad_street_old_[$i], $tr_hsno_old_[$i],
        $ad_zipcode_old_[$i], $ad_city_old_[$i], $ad_country_old_[$i], $tr_remark_old_[$i], $tr_status_old_[$i], $tr_ware_from_to_old_[$i], $tr_commission_no_old_[$i], $tr_mediationarea_id_old_[$i],
        $tr_status_old_[$i], $tr_sign_old_[$i], $tr_signname_old_[$i], $tr_finishtime_old_[$i]) =
          getTourData($jb_id, $i, $dbh_tr);
     else:
       $tourFound = 0;
     endif;
    $i++;
  } while ($tourFound == 1);
  $i_tour_max_old = $i - 1;
endif;
// *** Nur für's Logging ENDE

if ($jb_storno > 0)
  $jb_tourname = "";

$jb_fixprice_ori = $jb_fixprice;
$jb_fixprice = (float) str_replace(",", ".", $jb_fixprice);
$jb_serviceprice_ori = $jb_serviceprice;
$jb_serviceprice = (float) str_replace(",", ".", $jb_serviceprice);
$jb_cr_price_ori = $jb_cr_price;
$jb_cr_price = (float) str_replace(",", ".", $jb_cr_price);
if (MASK_CR_PRICE_MODE == "1") {
  $jb_cr_serviceprice = (float) str_replace(",", ".", $jb_cr_serviceprice);
}
$addressValid = "ok";
$job_is_new = true;
// Preise werden immer ermittelt, auch wenn $getPriceOnly != 1 (ist halt einfacher)
$fullPrice = 0.00;
$jb_subtotal = 0;
$jb_totalprice = 0;
$discount_sign = "";
//$fullDiscount = 0.00;
$fullCrPrice = 0.00;
$jb_cr_subtotal = 0.00;
$jb_cr_price_total = 0.00;
if (!isset($self_service_discount)) {
  $self_service_discount = 0.00;
} else {
  $self_service_discount = (float) $self_service_discount;
};
$tmp_discount = 0;
$tmp_discount_rate = 0;
$is_EU = false;
$eu_countrycodes = explode(",", trim(getParameterValue("0", "EU_COUNTRYCODES", "0")));
$is_EU_only = true;
$is_foreign = false;
$gross_price = 0;
$distance = 0;
$fuel_cr_markup = 0;
$jb_price_km = 0;

if ($toursubmit == "Senden"):
  // Wenn als Preis-Update aufgerufen, dann enthält die Joblist leider
  // ein garstiges Zeichen (Â) welches zuerst herausgefiltert werden muss
//  $jobListOri = str_replace("Â", "", $jobListOri);
//  writeLog_("../log/job2_options_", var_export($jobListOri, true));
  if (!(strpos ($jobListOri, "Â") === false)):
  // "utf8_decode" auf dem mps1 macht "¹" und "²" kaputt...!
//    $jobListOri = utf8_decode($jobListOri); 
//    $jobListOri = iconv("UTF-8", "ISO-8859-1", $jobListOri);
// http://php.net/manual/de/function.iconv.php
//Logic from http://twiki.org/cgi-bin/view/Codev/InternationalisationUTF8
    $jobListOri = preg_replace("/([\xC2\xC3])([\x80-\xBF])/e", "chr(ord('\\1')<<6&0xC0|ord('\\2')&0x3F)", $jobListOri);
//    writeLog_("../log/job2_options_", var_export($jobListOri, true));
  endif;
  // Jobliste in ein 2-dim. Array umwandeln
  $jobList = $jobListOri;
  $jobList = explode("¹", $jobList);
  for ($i = 0; $i < count($jobList); $i++):
    $jobList[$i] = explode("²", $jobList[$i]);
  endfor;
endif;

$jsAddNewExternCostcenter = "";
$tr_tracking_flag = false;
$setMediation_area_idArr = array();

$assigned_cr_id = "";
$prev_jb_id = "";
// wenn Button "Senden" gedrückt, dann Auftrag speichern
// (wenn nicht, dann ist dies der erste Aufruf beim Anfordern der Seite)
if ($toursubmit == "Senden" && $getPriceOnly != 1):
  // Transaktionsstart
  TA("BEGIN");
  // Auftragsdaten in Array speichern
  if ($afterwards == "1"):
    // Nacherfassung: Job ist bereits erledigt
    $insertStmtArr = array("csc_id", $csc_id_orderer, "jb_status", "2");
    // die einzelnen Touren sind auch erledigt
    $tr_status = "1";
    // der gewünschte Kurier ist dann der annehmende Kurier
// !!!!!!
    array_push ($insertStmtArr, "cr_id",
      getFieldValueFromId("couriervehicle", "crvh_sid", $cr_id_order, "cr_id"),
      "cr_sid", $cr_id_order);
  else:
    // normaler Auftrag (keine Nacherfassung)
    // ODER nachträgliche Änderung
    if ($jb_id != ""):
      // $jb_id gesetzt -> nachträgliche Änderung eines bestehenden Auftrags.
      $job_is_new = false;
      // status darf nicht geändert werden!
      // Es sei denn, jb_status = "9" (Disponentenauftrag),
      // -> muss dann auf 0 gesetzt werden wenn Kurier angegegeben
      // ... ODER jb_globaljob = 1 und jb_status = 8 oder 9 (z.B. jb_globaljob vergessen und nachträglich hinzugefügt)
      if ((getFieldValueFromId("job", "jb_id", "$jb_id", "jb_status") == "9" && $cr_id_order != "") ||
        ((getFieldValueFromId("job", "jb_id", "$jb_id", "jb_status") == "8" || getFieldValueFromId("job", "jb_id", "$jb_id", "jb_status") == "9") && $jb_globaljob == 1)):
        $insertStmtArr = array("csc_id", $csc_id_orderer, "jb_status", "0");
      else:
        $insertStmtArr = array("csc_id", $csc_id_orderer);
      endif;
      // die einzelnen Touren sind noch NICHT erledigt
// TOBEDONE: Nachträgliche Änderungen von teilweise erledigten Aufträgen
      $tr_status = "0";
    else:
      // neuer Auftrag: jb_status = 0
      // (wenn Disposition gewünscht (hq.hq_workmode == "1"), dann jb_status = 9)
      // Achtung: Bei Vorbestellung darf natürlich nicht jb_status = 9 gesetzt werden,
      // wenn ein Kurier angegeben ist
//      if ((!($tag == "" || $monat == "" || $jahr == "" || $stunde == "" || $minute == "") &&
//        $cr_id_order != "") || $jb_globaljob == 1):
        // Dauerauftrag oder Vorbestellung oder Frühauftrag
      if ($cr_id_order != ""):
        // Wenn mit Kurierangabe, dann dem Kurier sofort zuweisen,
        // wenn workmode = 1, oder wenn workmode = 2, dann aber nur, wenn kein Dauerauftrag/Vorbestellung
        if ((!($tag != "" && $monat != "" && $jahr != "" && $stunde != "" && $minute != "") || $jb_globaljob == 1)
          || $hq_workmode == "1"):
          $insertStmtArr = array("csc_id", $csc_id_orderer, "jb_status", "0"); // Offener (anzunehmender) Auftrag
          // Kurier-ID merken
          $assigned_cr_id = getFieldValueFromId("couriervehicle", "crvh_sid", $cr_id_order, "cr_id");
        // Wenn mit Kurierangabe, aber Dauerauftrag/Reservierung, dann ins Autoranking wenn workmode = 2
        elseif ($hq_workmode == "2"):
          // Autoranking bekommt jb_status = 8
          $insertStmtArr = array("csc_id", $csc_id_orderer, "jb_status", "8");          
        endif;
        // Wenn Kurier angegeben, dann auch die cr_sid setzen
        if ($cr_id_order != ""):
          array_push ($insertStmtArr,
            "cr_id_order", getFieldValueFromId("couriervehicle", "crvh_sid", $cr_id_order, "cr_id"),
            "cr_sid", $cr_id_order, "cr_id_permanent", $cr_id_order);
        endif;
      else:
        // Ohne Kurierangabe
        if ($hq_workmode == "1" && $jb_globaljob != 1):
          // Adhoc-Auftrag: Disposition vornehmen (jb_status = 9) (nicht wenn an alle Kuriere!)
          $insertStmtArr = array("csc_id", $csc_id_orderer, "jb_status", "9");
        elseif ($hq_workmode == "2" && $jb_globaljob != 1):
          // Autoranking bekommt jb_status = 8  (nicht wenn an alle Kuriere!)
          $insertStmtArr = array("csc_id", $csc_id_orderer, "jb_status", "8");
        else:
          // Börsenmodus!!! oder an alle Kuriere
          $insertStmtArr = array("csc_id", $csc_id_orderer, "jb_status", "0");
        endif;
      endif;
      // die einzelnen Touren sind auch noch NICHT erledigt
      $tr_status = "0";
    endif;
    if (isset($cs_invmode))
      array_push ($insertStmtArr, "jb_invmode", $cs_invmode);
  endif;

  // wenn Annahmezeit gesetzt, dann übernehmen, sonst leer lassen
  if (MASK_WAITTIME_ENABLED == "1"):
    if ($jb_waittime_hour != "" && $jb_waittime_minute != ""):
      $today = getdate();
      $jb_waittime = $today['year'] . "-" . $today['mon'] . "-" . $today['mday'] . " "
        . "$jb_waittime_hour:$jb_waittime_minute:00";
      array_push ($insertStmtArr, "jb_waittime", $jb_waittime);
    endif;
  endif;
//  if ($jb_waitstorno != "")
    array_push ($insertStmtArr, "jb_waitstorno", $jb_waitstorno);
//  if ($jb_weight != "" && $jb_weight != 0)
    array_push ($insertStmtArr, "jb_weight", $jb_weight,
      "jb_crvh_length", $jb_crvh_length, "jb_crvh_width", $jb_crvh_width,
      "jb_crvh_height", $jb_crvh_height, "jb_crvh_position", $jb_crvh_position
    );
  if ($vht_id != "" && $vht_id != 0)
    array_push ($insertStmtArr, "vht_id", $vht_id);
  else
    $vht_id = 2;
//  if ($jb_globaljob != "")
    array_push ($insertStmtArr, "jb_globaljob", $jb_globaljob);
//  if ($jb_type != "")
//    array_push ($insertStmtArr, "jb_type", $jb_type);
//  if ($jb_freetext_1 != ""):
    array_push ($insertStmtArr, "jb_freetext_1", my_str_check_http($jb_freetext_1));
//  endif;
    array_push ($insertStmtArr, "jb_dispoinfo", my_str_check_http($jb_dispoinfo));
    // Warningtime
    $jb_warningtime = "";
    if (!($jb_warntag == "" || $jb_warnmonat == "" || $jb_warnjahr == "" || $jb_warnstunde == "" || $jb_warnminute == "")):
      $jb_warningtime = "$jb_warnjahr-$jb_warnmonat-$jb_warntag $jb_warnstunde:$jb_warnminute:00";
    endif;
    array_push ($insertStmtArr, "jb_warningtime", $jb_warningtime);
//  if ($jb_cr_filter != "") // Filer müssen auch löschbar sein!!!

  $mandatory_filters = trim(getParameterValue("0", "MASK_MANDATORY_FILTERS", $hq_id));
//echo $jb_cr_filter . "|" . $mandatory_filters . "<br>\n";
  if ($mandatory_filters != ''):
    $mandatory_filtersArr = explode(",", $mandatory_filters);
    for ($i = 0; $i < count($mandatory_filtersArr); $i++):
      if (!in_array ($mandatory_filtersArr[$i], explode(",", $jb_cr_filter)))
        $jb_cr_filter .= (trim($jb_cr_filter) == "" ? "" : ",") . $mandatory_filtersArr[$i];
    endfor;
  endif;
//echo $jb_cr_filter . "<br>\n"; die();

  array_push ($insertStmtArr, "jb_cr_filter", $jb_cr_filter);
//  if ($jb_cr_filter_opt != "")
  array_push ($insertStmtArr, "jb_cr_filter_opt", $jb_cr_filter_opt);
  // wenn Datum gesetzt, dann übernehmen, sonst aktuelle Zeit (nur wenn nicht Nachbearbeitung!!!)
  $jb_ordertime = "";
  if ($tag == "" || $monat == "" || $jahr == "" || $stunde == "" || $minute == ""):
    if ($jb_id == ""):
      $today = getdate();
      $jb_ordertime = $today['year'] . "-" . $today['mon'] . "-" . $today['mday'] . " "
        . $today['hours'] . ":" . $today['minutes'] . ":" . $today['seconds'];
    else:
      $jb_ordertime = $db->getOne("SELECT jb_ordertime FROM job WHERE jb_id = '$jb_id'");
    endif;
  else:
    $jb_ordertime = "$jahr-$monat-$tag $stunde:$minute:00";
    // Vorbestellung
    $jb_reserv = 0;
    if ($afterwards != "1"):
      $jb_reserv = 1;
    endif;
    if ($jb_permanent != "" && $jb_permanent != 0):
      $jb_reserv = 1;
      // Dauerauftrag
      array_push ($insertStmtArr, "jb_permanent", $jb_permanent);
      array_push ($insertStmtArr, "jb_permanent2", $jb_permanent2);
      if ($endetag != "" && $endemonat != "" && $endejahr != ""):
         $jp_permenddat = "$endejahr-$endemonat-$endetag 00:00:00";
         array_push ($insertStmtArr, "jp_permenddat", $jp_permenddat);
      endif;
    endif;
    array_push ($insertStmtArr, "jb_reserv", $jb_reserv);
  endif;
  if ($jb_ordertime != "")
    array_push ($insertStmtArr, "jb_ordertime", $jb_ordertime);
  if ($afterwards == "1"):
    // Nacherfassung: Job ist bereits erledigt
    // 'finishtime' ist 'ordertime'
    array_push ($insertStmtArr, "jb_finishtime", $jb_ordertime);
    $today = getdate();
    $jb_booktime = $today['year'] . "-" . $today['mon'] . "-" . $today['mday'] . " "
      . $today['hours'] . ":" . $today['minutes'] . ":" . $today['seconds'];
    array_push ($insertStmtArr, "jb_booktime", $jb_booktime);
  endif;
  // Festpreis?
//  if ($jb_fixprice != "" && $jb_fixprice != 0) // Festpreis muss auch gelöscht werden können,
                                                 // wenn nachträglich geändert
  if (isset($jb_storno) && $jb_storno > 0):
    $jb_fixprice = $jb_fixprice * -1;
    $jb_serviceprice = $jb_serviceprice * -1;
    $jb_cr_price = $jb_cr_price * -1;
  endif;
  array_push ($insertStmtArr, "jb_fixprice", $jb_fixprice, "jb_serviceprice", $jb_serviceprice, "jb_cr_subprice", $jb_cr_price);
  if ($jb_discount == 1)
    $tmp_discount_rate = $jb_discount_rate;
  $jb_totalprice = $jb_fixprice * (1 - ($tmp_discount_rate / 100));
  $jb_sales_tax_rate_sign_new = $db->getOne("SELECT tx_sign FROM tax WHERE tx_id = '$jb_sales_tax_rate_sign'");
  array_push ($insertStmtArr,
    "jb_sales_tax_rate", $jb_sales_tax_rate, "jb_sales_tax_rate_sign", $jb_sales_tax_rate_sign_new);
//// wegen einer noch nicht geklärten Merkwürdigkeit in auth.inc.php kann es manchmal passieren, dass
//// $HTTP_SESSION_VARS['hq_id'] leer ist; dann wird hq_id einfach auf eins gesetzt
//// (wir werden voraussichtlich für jede Zentrale einen eigenen MySQL-Server laufen haben, also
//// ist hq_id sowieso immer 1)
//if ($hq_id == "" || $hq_id <= 0)
//  $hq_id = 1;
// hq_id (Lizenznehmer) holen und speichern
  array_push ($insertStmtArr, "hq_id", $hq_id);
//  // emp_id (Erfasser des Auftrags) holen und speichern
//  $emp_id = getFieldValueFromId("employee", "usr_id", $HTTP_SESSION_VARS['usr_id'], "emp_id");
  // $usr_id speichern statt $emp_id, weil auch Zentrale kann Aufträge eingeben
  // Auftragsdaten abspeichern und Auftrags-ID merken
  if ($job_is_new)
    // usr_id nur bei Ersterfassung speichern
    array_push ($insertStmtArr, "emp_id", $usr_id);
//print_r ($insertStmtArr);
  if (!$job_is_new && (!isset($jb_storno) || $jb_storno == 0))
  {
    // $wenn $jb_id gesetzt ist, dann handelt es sich um die nachträgliche Änderung
    // eines bestehenden Auftrages!
//print_r ($insertStmtArr);
    if ($getPriceOnly != 1) {
      updateStmt("job", "jb_id", $jb_id, $insertStmtArr);
    // zugehörige Einträge in tour und tourservice werden gelöscht,
    // da sie unten wieder aufgebaut werden - NICHT MEHR: Unterschriften könnten gelöscht werden!!! -
//    deleteStmt("tour", "jb_id = $jb_id");
    // nur tourservices werden gelöscht, damit geänderte Preise berücksichtigt werden
      deleteStmt("tourservice", "jb_id = $jb_id");
      $statusMessageTxt = "Der Auftrag wurde geändert!";
      $killAfterUpdate = true;
    }
  } else {
    // neuer Auftrag, wie es sich gehört
    if ($getPriceOnly != 1):
      array_push ($insertStmtArr, "jb_createtime", date("Y-m-d H:i:s"));
      if (!(isset($_copy_jobs_flag) && $_copy_jobs_flag == true) || (isset($_copy_jobs_flag_ori) && $_copy_jobs_flag_ori == true)
        || (isset($jb_storno) && $jb_storno > 0)):
//        if (isset($jb_storno) && $jb_storno > 0):
//        endif;
        insertStmt("job", $insertStmtArr);
        $jb_id = getLastInsertId();
        // Wenn bereits ein Kurier zugewiesen wurde, dann muss dies hier berücksichtigt werden!
        if ($assigned_cr_id != ""):
          // Kurier muss auf occupied gesetzt werden, wenn angegeben und keine Reservierung/Dauerauftrag
          $tmpArr = array("cr_occupied", 1);
          updateStmt("courier", "cr_id", $assigned_cr_id, $tmpArr);
          // Wenn automatische Vermittlung ($hq_workmode == "2"), dann muss hier auch autoranking berücksichtigt werden!
          if ($hq_workmode == "2"):
            // Set current assigning time for revoking a job if not taken by the courier
            $currentTime = getDateTime("0");
            if (existsEntry("autoranking",array("jb_id",$jb_id,"cr_id",$cr_id))) :
              $tmpArr = array("ar_challenge", "0", " ar_lastassigntime", $currentTime);
              updateStmt("autoranking", "jb_id", $jb_id, $tmpArr,"cr_id = '" . $cr_id . "'");
            else :
              $tmpArr = array("jb_id", $jb_id, "cr_id", $assigned_cr_id, "ar_challenge", "0", "ar_lastassigntime", $currentTime);
              insertStmt("autoranking", $tmpArr);
            endif;
          endif;
        endif;
        if (isset($jb_storno) && $jb_storno > 0):
          $jb_invtext = ($jb_status == 2 ? "Storno-Gutschrift für" : "Storno von");
          $today = getdate();
          $tmp_cr_sid = getFieldValueFromId("job", "jb_id", $jb_id_copy, "cr_sid");
          $tmp_cr_id = getFieldValueFromId("couriervehicle", "crvh_sid", $tmp_cr_sid, "cr_id");
          $tmpArr = array(
            "jb_storno", ($jb_storno == 1 ? 3 : 4),
            "jb_invtext",  mkLineBreaks("$jb_invtext Auftrag Nr. $jb_id_copy", INV_MAXCOLS, 10, true),
            "jb_status", 2,
            "cr_id", $tmp_cr_id,
            "cr_sid", $tmp_cr_sid,
            "cr_id_order", getFieldValueFromId("job", "jb_id", $jb_id_copy, "cr_id_order"),
            "jb_ordertime", getFieldValueFromId("job", "jb_id", $jb_id_copy, "jb_ordertime"),
            "jb_taketime", getFieldValueFromId("job", "jb_id", $jb_id_copy, "jb_taketime"),
            "jb_sales_tax_rate", getFieldValueFromId("job", "jb_id", $jb_id_copy, "jb_sales_tax_rate"),
            "jb_sales_tax_rate_sign", getFieldValueFromId("job", "jb_id", $jb_id_copy, "jb_sales_tax_rate_sign"),
            "jb_finishtime", $today['year'] . "-" . $today['mon'] . "-" . $today['mday'] . " "
              . $today['hours'] . ":" . $today['minutes'] . ":" . $today['seconds'],
            "jb_booktime", $today['year'] . "-" . $today['mon'] . "-" . $today['mday'] . " "
              . $today['hours'] . ":" . $today['minutes'] . ":" . $today['seconds']);
          updateStmt("job", "jb_id", $jb_id, $tmpArr);
          // Originialauftrag updaten
            // wenn ein Kurier zugewiesen war, dann miuss dieser Kurier auch in beiden Jobs als annehmender eingetragen
            // werden, da sonst beim Export (jb_storno = 1 und jb_storno = 3, weil mit kosten) dieser
            // Auftrag keinem Kurier zugewiesen werden kann!
            // Aufträge ohne Kuriere dürfen _nicht kostenpflichtig_ storniert werden können!
          updateStmt("job", "jb_id", $jb_id_copy, array("jb_id_copy", $jb_id, "cr_id", $tmp_cr_id));
          // Job-Kopie wg. Storno-Gutschrift
          // d.h. die alten tourservices müssen kopiert und mit negativen Werten versehen werden
          // die Funktion "saveservicecosts" legt in diesem Fall keine neuen Kosten an
          // jb_totalprice muss hier berücksichtigt werden!
          $jb_subtotal_storno = (-1 * $db->getOne("SELECT jb_subtotalprice FROM job WHERE jb_id = '$jb_id_copy'"));
          $jb_totalprice_storno = (-1 * $db->getOne("SELECT jb_totalprice FROM job WHERE jb_id = '$jb_id_copy'"));
          $jb_cr_price_storno = (-1 * $db->getOne("SELECT jb_cr_price FROM job WHERE jb_id = '$jb_id_copy'"));
          $sqlquery = "SELECT csc_id, tr_sort, srv_id, trs_srv_name, srvt_id, trs_srvt_name, trs_price, trs_discount FROM tourservice WHERE jb_id = '$jb_id_copy'";
          $res = $db->query($sqlquery);
          if (DB::isError($res)) reportDie ("$PHP_SELF: '$sqlquery': " . $res->getMessage());
          $i = 0;
          $csc_id_arr = array();
          while ($row = $res->fetch_assoc()):
            // Für jeden Posten des Storno-Jobs wird eine Gutschrift generiert
            $tmpArr = array("jb_id", $jb_id, "tr_sort", $row['tr_sort'], "srv_id", $row['srv_id'], "trs_srv_name",
              $row['trs_srv_name'], "srvt_id", $row['srvt_id'], "trs_srvt_name", $row['trs_srvt_name'],
              "trs_price", (-1 * $row['trs_price']), "trs_discount", $row['trs_discount'], "csc_id", $row['csc_id']);
            insertStmt("tourservice", $tmpArr);
            // Zahler merken wg. Stornokosten
            $csc_id_arr[$row['csc_id']] = "dummy";
            $i++;
          endwhile;
          $res->free();
          // Storno mit Kosten?
          if ($jb_storno == 1):
            $srvt_name = $db->getOne(
              "SELECT mt_value FROM metatype WHERE mt_sort = '$vht_id' AND mt_type = 'vehicletype'");
            $storno_price = getServiceValues(
              $db->getOne("SELECT srv_id FROM service WHERE srv_name = 'Storno' AND hq_id = '$hq_id'"),
              $db->getOne("SELECT srvt_id FROM servicetype WHERE srvt_name = '$srvt_name' AND hq_id = '$hq_id'"),
              $cs_id, $hq_id, $jb_ordertime, 1);
            $costsplit_divisor = count($csc_id_arr);
            foreach($csc_id_arr as $key_csc_id => $val_dummy) {
              $tmpArr = array(
                "jb_id", $jb_id, "tr_sort", $i, "srv_id", 0, "trs_srv_name",
                "Stornogebühr", "srvt_id", 0, "trs_srvt_name", "",
                "trs_price", ($storno_price / $costsplit_divisor), "trs_discount", 0, "csc_id", $key_csc_id);
              insertStmt("tourservice", $tmpArr);
            }
          endif;
        endif;
      else:
        // Auftragsduplikation
        // Duplikation der Originaldaten in eine neue Datenbank wg. Neuberechnung
        // war am Angang nötig wg. Änderung der Kostenberechnung
        array_push ($insertStmtArr, "jb_id", $jb_id_copy);
        $jb_id = $jb_id_copy;
        insertStmt("job", $insertStmtArr);
      endif;      
      $statusMessageTxt = "Der Auftrag wurde gespeichert!\\nAuftragsnummer: $jb_id";
      $prev_jb_id = $jb_id;
      // wenn der Auftrag aus der Kundenbestandsliste generiert wurde,
      // soll die Maske gleich wieder geschlossen werden
//      if ($csc_id_orderer != "" && $csc_id_orderer != "0")
//        $killAfterUpdate = true;
//      else
        $killAfterUpdate = false;
    endif;
  }

// Job WURDE GESCHRIEBEN

  // Servicetype-Name (Fahrrad etc.)
  $srvt_name = $db->getOne(
    "SELECT mt_value FROM metatype WHERE mt_sort = '$vht_id' AND mt_type = 'vehicletype'");
  // Ermittlung der Kostenübernahme
  // wenn Fixpreis, dann keine Kostenerfassung in tourservice
//  if (($jb_fixprice == "" || $jb_fixprice == 0) && $jb_fixprice != "0.00"):
    $costsplit_count = 0;
    // Kostenteilung? (wenn kein payer gesetzt)
    for ($i = 0; $i < count($jobList); $i++):
      if ($jobList[$i][JL_CSC_ID] == ""):
        if ($jobList[$i][JL_TR_COMP] == "" ||
          $jobList[$i][JL_AD_STREET] == "" ||
          $jobList[$i][JL_TR_HSNO] == "" ||
          $jobList[$i][JL_AD_ZIPCODE] == "" ||
          $jobList[$i][JL_AD_CITY] == ""):
          // Abbruchbedingung: csc_id leer und nicht genügend Angaben für eine
          // neue Kostenstelle -> Auftrag vollständig durchlaufen
            break;
        endif;
      else:
        // csc_id gesetzt:
        // wenn Kostenteilung, dann diese Kostenstelle mitzählen
        $costsplit_count++;
        if ($jobList[$i][JL_CSC_ID_PAYER] == "true"):
          $csc_id_payer = $jobList[$i][JL_CSC_ID];
          // Payer gefunden:
          // Anzahl Payer auf 1 setzen
          $costsplit_count = 1;
          // Grundpreis des Auftrags (Anfahrtskosten) speichern
          // wenn Kostensplit, wird er später anteilig bei jeder Etappenstelle einzeln gespeichert
//          saveServiceCosts("Grundpreis", $srvt_name, $hq_id, $cs_id, $jb_id, 0, $jb_ordertime, 0, 1, $getPriceOnly, $jb_cash, (($jb_costsplit == "false" || MASK_CASH_PAYER_SELECT == "1") ? $tmpCsc_id_payer : ""), $jb_storno, false, false, false);
          break;
        endif;
      endif;
    endfor;
//  endif;

  // potentiellen Drittzahler berücksichtigen.
  // Der wird direkt übergeben und ist in der job_list nicht vorhanden!!!
  if ($csc_id_payer != "" && $csc_id_payer != "0")
    $costsplit_count = 1;
//  $csc_id_payer = "";
  // Barzahlung berücksichtigen
  if ($jb_cash == "true"):
    // Achtung: wenn MASK_CASH_PAYER_SELECT gesetzt, dann ist auf jeden Fall ein Bezahler
    // gesetzt, der natürlich auch erhalten bleiben muss!
    if (MASK_CASH_PAYER_SELECT != "1"):
      $csc_id_payer = "-1";
      if (CSC_ID_PAYER_CASH != ""):
        $csc_id_payer = CSC_ID_PAYER_CASH;
      endif;
    endif;
    $costsplit_count = 1;
    // Barzahlung
    $jb_payment = 2;
  else:
    // Zahlungsmodus festhalten
    if ($jb_costsplit == "true" && MASK_CASH_PAYER_SELECT != "1"): // Achtung: MASK_CASH_PAYER_SELECT entscheidet, ob 'jb_costsplit' Rechnungszahlung bedeutet!
      // Rechnung mit Kostensplit
      $jb_payment = 1;
    else:
      // Rechnung an den angegebenen Bezahler
      $jb_payment = 0;
    endif;
  endif;

  if ($csc_id_payer == 0 || $csc_id_payer == ""): // csc_id_payer == 0 ==> Kostensplit
    $cs_invmode = getFieldValueFromId("headquarters", "hq_id", "$hq_id", "hq_invmode");
    $cs_id = 0;
  else:
    $cs_id = getFieldValueFromId("costcenter", "csc_id", "$csc_id_payer", "cs_id");
    // invmode ermitteln (ist abhängig von dem aktuellen Bezahler), kann neuerdings auch von der Ksotenstelle bestimmt werden
    if (getParameterValue("0", "COSTCENTER_INV_MODE_" . $csc_id_payer, "0") != "") {
      $cs_invmode = getParameterValue("0", "COSTCENTER_INV_MODE_" . $csc_id_payer, "0");
    } else {
      $cs_invmode = getFieldValueFromId("customer", "cs_id", "$cs_id", "cs_invmode");
    }
  endif;
  if (MASK_CR_PRICE_MODE == "1") {
    $vhtSrvt_name = $db->getOne("SELECT mt_value FROM metatype WHERE mt_sort = '$vht_id' AND mt_type = 'vehicletype'");
    $fuel_cr_markup = getFuelMarkupCr($vhtSrvt_name, (trim($cs_id) != "" ? $cs_id : 0), $hq_id, $jb_ordertime);
//writeLog_("../log/job2_options_", "\$jb_id=|$jb_id|\$vhtSrvt_name=|$vhtSrvt_name|");
//writeLog_("../log/job2_options_", "\$jb_id=|$jb_id|\$fuel_cr_markup=|$fuel_cr_markup|");
  }

  // Der Bezahler steht jetzt erst fest; da es neuerdings einen Fall gibt, wo der Bezahler im Zusammenhang mit seinen Wunschkurieren
  // den Status bestimmt, muss das hier jetzt abgefackelt werden (wenn mind. ein Wunschkurier vorhanden, dann kein autoranking)
  // Darf natürlich kein Storno oder Dauerauftrag bzw. Reservierung sein!
  $job_fav_crs = $db->getOne("SELECT COUNT(*) FROM customercourier WHERE cs_id = $cs_id AND cscr_relation = 1");
  if ($job_fav_crs > 0 &&
    MASK_FAVOURED_COURIER_MANUAL == "1" && $afterwards != "1" && $job_is_new && (!isset($jb_storno) || $jb_storno == 0)
     && (/*(($jb_permanent == "" || $jb_permanent == 0) &&  $jb_reserv != 1) && */$assigned_cr_id == "")): 
    $tmpArr = array("jb_status", "9", "jb_cr_fav", 1);
    updateStmt("job", "jb_id", $jb_id, $tmpArr);
  elseif (($job_fav_crs) > 0):
    $tmpArr = array("jb_cr_fav", 1);
    updateStmt("job", "jb_id", $jb_id, $tmpArr);
  endif;

  $jb_mediationarea_id = "";
  $jb_mediationarea_name = "";
  // Mediation-Area (PLZ-Bereiche oder Vermittlungsbereiche) für Auftragsliste festhalten
  // jetzt MODE_INTERMEDIATION statt $hq_invmode (letzterer nur noch für Abrechnung, aber nicht mehr für Vermittlung)
  if (MODE_INTERMEDIATION == 1):
    $jb_mediationarea_id = $db->getOne(
      "SELECT srvp_id FROM serviceplz WHERE srvp_plz = '" . $jobList[0][JL_AD_ZIPCODE] . "'");
    $jb_mediationarea_name = $jobList[0][JL_AD_ZIPCODE];
  elseif(MODE_INTERMEDIATION == 2 || MODE_INTERMEDIATION == 3):
    $srvp_id = $db->getOne(
      "SELECT srvp_id FROM serviceplz WHERE srvp_plz = '" . $jobList[0][JL_AD_ZIPCODE] . "'");
    $jb_mediationarea_id = $db->getOne(
//      "SELECT srvpa_id FROM serviceplzareamapping WHERE srvp_id = '" . $srvp_id . "'");
      "SELECT srvpam.srvpa_id FROM serviceplzareamapping AS srvpam, serviceplzarea AS srvpa WHERE srvpam.srvp_id = '" . $srvp_id . "' AND srvpam.srvpa_id = srvpa.srvpa_id AND srvpa.hq_id = '$hq_id'");
    $jb_mediationarea_name = $db->getOne(
       "SELECT srvpa_name FROM serviceplzarea WHERE srvpa_id = '" . $jb_mediationarea_id . "'");
  endif;
  $hq_id_exec = $db->getOne("SELECT hq_id FROM serviceplz WHERE srvp_plz = '" . $jobList[0][JL_AD_ZIPCODE] . "'");
  if ($hq_id_exec == "")
    $hq_id_exec = $hq_id;

  // Den noch fehlenden Rotz zum bestehenden Auftrag hinzuschreiben..
  $tmpArr = array(
    "jb_payment", $jb_payment,
    "jb_mediationarea_id", $jb_mediationarea_id,
    "jb_mediationarea_name", $jb_mediationarea_name,
    "hq_id_exec", $hq_id_exec);
  updateStmt("job", "jb_id", $jb_id, $tmpArr);

  // ************************************************************************************************

  // Ab hier werden Preise ermittelt und ggfs. gespeichert

  // Treibstoffzuschlag in Prozent ermitteln
  $jb_markup = getFuelMarkup($srvt_name, $cs_id, $hq_id, $jb_ordertime);
  // Achtung: Beim Speichern in tourservice (bzw. Aufruf von saveservicecosts)
  // Barzahlung mit ausgewähltem Bezahler berücksichtigen!
  $tmpCsc_id_payer = $csc_id_payer;
  if ($jb_payment == 2 && MASK_CASH_PAYER_SELECT == "1"):
    if (CSC_ID_PAYER_CASH != ""):
      $tmpCsc_id_payer = CSC_ID_PAYER_CASH;
    else:
      $tmpCsc_id_payer = "-1";
    endif;
  endif;
  // Achtung: "Listenkunden" bekommen immer einen Fixpreis "0.00"
  if (($db->getOne("SELECT cs_jobbatch from customer WHERE cs_id = $cs_id") == 1) /* && ($jb_fixprice == "" || $jb_fixprice == 0)*/ && $afterwards != "1"):
    // Nicht Listenmodus wenn Nacherfassung!!!
    $jb_fixprice = "0.00";
    // Preis soll für den Eintrag ins Bemerkungsfeld ermittelt, aber nicht als offizieller Preis gespeichert werden
    $jobbatch_mode = true;
  endif;
//echo "$jb_fixprice<br>";
  if (($jb_fixprice == "" || $jb_fixprice == 0 || $jobbatch_mode == true) /* && $jb_fixprice != "0.00"*/ && getFieldValueFromClause("parameter", "par_value", "par_key='MASK_CS_DONT_MAKE_STANDARD_PRICE_" . $cs_id . "'") != "1" && getParameterValue("0", "CUSTOMER_MASK_CALCULATOR_USAGE_ONLY_" . $cs_id, "0") != "1"):
//echo "Grundpreisberechnung<br>";    
    list ($fp, $fd, $fpm, $final_cr_price, $final_cr_discount, $final_cr_price_markup, $customer_specific, $special_address, $validfrom) =
      saveServiceCosts("Grundpreis", $srvt_name, $hq_id, $cs_id, $jb_id, 0, $jb_ordertime, 0, $costsplit_count, (($getPriceOnly == 1 || $jobbatch_mode) ? 1 : 0), $jb_cash, (($jb_costsplit == "false" || MASK_CASH_PAYER_SELECT == "1") ? $tmpCsc_id_payer : ""), $jb_storno, false, false, false, $jb_markup, $fuel_cr_markup, $vht_id);
      $gross_price += $fp;
      $fullPrice += round($fp * ((100-$fd)/100), 2);
      $jb_subtotal += round($fpm * ((100-$fd)/100), 2);
      $discount_sign = ($special_address || $discount_sign == "**" ? "**"
      : ($discount_sign = ($fd > 0 || $customer_specific || $discount_sign == "*" ? "*" : "")));
      $jb_cr_subtotal += round($final_cr_price_markup * ((100-$fd-$self_service_discount)/100), 2);
      $fullCrPrice += round($final_cr_price * ((100-$fd-$self_service_discount)/100), 2);
  endif;
//echo "Fixpreis direkt<br>";

  if (!($jb_fixprice == "" || $jb_fixprice == 0) || $jobbatch_mode == true /* && $jb_fixprice != "0.00"*/):
    if ($jb_storno == 0):
        // Km-Preis?
//echo ($km_price_params) . "<br>\n";
      $km_price_paramsArrArr = array();
      if (!(strpos($km_price_params, "|") === FALSE)) {
        $km_price_paramsArr = explode("|", $km_price_params);
        $jb_price_km = (float) str_replace(",", ".", explode(" ", $km_price_paramsArr[0])[0]);
        if ($km_price_paramsArr[3] != "zone") {
          $price_per_km = explode(" ", $km_price_paramsArr[1])[0];
          $basic_price = explode(" ", trim(str_replace("+", "", $km_price_paramsArr[2])))[0];
          $km_price_params = str_replace(",", ".", $jb_price_km . "|" . $price_per_km . "|" . $basic_price);
        } else {
          $km_price_paramsArr[1] = str_replace("[n]", "(n)", str_replace("(", "", str_replace(")", "", str_replace("(n)", "[n]", $km_price_paramsArr[1]))));
          $km_price_paramsArrArr = explode("+", $km_price_paramsArr[1]);
          if ($km_price_paramsArr[4] != "") {
            if ($km_price_paramsArr[4][strlen($km_price_paramsArr[4]) - 1] == ",")
              $km_price_paramsArr[4] = substr($km_price_paramsArr[4], 0, strlen($km_price_paramsArr[4]) - 1);
            $ro_types = explode(";", $km_price_paramsArr[4]);
            deleteStmt("phoenix_log.route", "jb_id = " . $jb_id);
            $db_geo = get_db_geo();
            if (is_null($db_geo)) {
              $db_geo = getDbConnectionSpecial("172.16.0.111:3711", "address_geo", $dblogin, $dbpassword);
              $res = $db_geo->query('SET NAMES latin1');
              if (DB::isError($res)) reportDie ("$PHP_SELF: 'SET NAMES latin1' : " . $res->getMessage());
            }
            $sqlquery = "SELECT di_id, di_distance, di_duration, di_polyline, di_modify FROM address_geo.distance WHERE di_id IN (" . str_replace(";", ",", $km_price_paramsArr[4]) . ")";
            writeLog_xServer("job2_options: [" . $sqlquery . "]");
            $res = $db_geo->query($sqlquery);
            if (DB::isError($res)) reportDie ("$PHP_SELF: '$sqlquery' : " . $res->getMessage());
            $cnt = 0;
            while ($row = ($phpVersion >= "8.0" ? $res->fetch_assoc() : $res->fetchRow())):
              insertStmt("phoenix_log.route", array("jb_id", $jb_id, "di_id", $row["di_id"], "ro_distance", $row["di_distance"], "ro_duration", $row["di_duration"], "ro_polyline", $row["di_polyline"], "ro_num", ++$cnt,
              "ro_type", (!(strpos($ro_types[1], $row["di_id"]) === false) ? 1 : 0), "ro_date", $row["di_modify"]));
            endwhile;
            $res->free();

          }
          $fixprice_min = $km_price_paramsArr[5];
	}
      }
      // Fixpreis wird direkt (unter Berücksichtigung eines evtl. Discounts und des Treibstoffzuschlages) in der tourservice-Tabelle gespeichert
      $tmpArr = array(
        "jb_id", $jb_id, "tr_sort", 0, "srv_id", 0, "trs_srv_name",
        "Fixpreis", "srvt_id", 0, "trs_srvt_name", (isset($km_price_paramsArr[3]) && $km_price_paramsArr[3] != "zone" ? $km_price_params : $fixprice_min),
        "trs_price", round($jb_fixprice * (1 + ($jb_markup / 100)), 2) - round(round($jb_fixprice * (1 + ($jb_markup / 100)), 2) * $self_service_discount / 100, 2),
        "trs_discount", $tmp_discount_rate, "csc_id",
        (($jb_costsplit == "false" || MASK_CASH_PAYER_SELECT == "1") ? ($jb_cash == "true" ? CSC_ID_PAYER_CASH : $tmpCsc_id_payer) : ""));
      insertStmt("tourservice", $tmpArr);
      $tr_sort = 1;
      foreach($km_price_paramsArrArr as $trs_srv_name) {
        $tmpArr = array(
          "jb_id", $jb_id, "tr_sort", $tr_sort++, "srv_id", 0, "trs_srv_name",
          trim($trs_srv_name), "srvt_id", 0, "trs_srvt_name", "z",
          "trs_price", 0, "trs_discount", 0, "csc_id",
          (($jb_costsplit == "false" || MASK_CASH_PAYER_SELECT == "1") ? ($jb_cash == "true" ? $CSC_ID_PAYER_CASH_VAR : $tmpCsc_id_payer) : ""));
        insertStmt("tourservice", $tmpArr);
      }
    endif;
  endif;
  if (!($jb_serviceprice == "" || $jb_serviceprice == 0)):
    if ($jb_storno == 0):
      // Servicepreis wird direkt in der tourservice-Tabelle gespeichert (ohne Treibstoffzuschlag)
      $tmpArr = array(
        "jb_id", $jb_id, "tr_sort", 0, "srv_id", 0, "trs_srv_name",
        "Servicepreis", "srvt_id", 0, "trs_srvt_name", "",
        "trs_price", $jb_serviceprice, "trs_discount", $tmp_discount_rate, "csc_id",
        (($jb_costsplit == "false" || MASK_CASH_PAYER_SELECT == "1") ? ($jb_cash == "true" ? CSC_ID_PAYER_CASH : $tmpCsc_id_payer) : ""));
      insertStmt("tourservice", $tmpArr);
    endif;
  endif;

  $jsAddNewExternCostcenter = "";
  $prev_ad_id = "";
  $prev_tr_mediationarea_id = 0;
  $jb_tourdata1 = "";
  $jb_tourdata2 = "";
  $jb_tourdata3 = "";
  // die einzelnen Etappenstellen abspeichern
  for ($i = 0; $i < count($jobList); $i++):
    $csc_id = $jobList[$i][JL_CSC_ID];


    // *** Externe Kostenstelle (Anfang) ***

    if ($csc_id == ""):
      // Wenn csc_id leer, dann muss eine neue externe Kostenstelle
      // angelegt werden; das Sendeformular muss sicherstellen, dass
      // alle notwendigen Informationen (Firma, Strasse, Nr., PLZ, Ort)
      // vorhanden sind!
      // Die neue externe Kostenstelle darf niemals Zahler sein!
      //
      if ($jobList[$i][JL_TR_COMP] == "" ||
        $jobList[$i][JL_AD_STREET] == "" ||
        $jobList[$i][JL_TR_HSNO] == "" ||
        $jobList[$i][JL_AD_ZIPCODE] == "" ||
        $jobList[$i][JL_AD_CITY] == "")
        // Abbruchbedingung: csc_id leer und nicht genügend Angaben für eine
        // neue Kostenstelle
        break;
      // die Adresse der neuen KSt speichern/überprüfen (wenn nicht gültig, dann Abbruch!)
      // die neue Adresse wird in jedem Fall gespeichert, ob nur Preisanfrage oder
      // neuer Auftrag
      list($ad_id, $tr_hsno, $tr_comp, $tr_remark, $tr_person, $tr_phone) =
        insertAddress($jobList[$i][JL_AD_STREET] . "|" . $jobList[$i][JL_TR_HSNO],
          $jobList[$i][JL_AD_ZIPCODE], $jobList[$i][JL_AD_CITY], $csc_id, $jobList[$i][JL_AD_COUNTRY], ($accept_all_addresses == "1"));
      if ($ad_id == "" && $accept_all_addresses != "1"):
        // address invalid -> I must die...
        // error-message is in tr_person, rest is empty
        $statusMessageTxt = $tr_person;
        $addressValid = "";
        break;
      endif;
      if (MASK_CREATE_EXTERN_COSTCENTER != "1"):
        $csc_id = CSC_ID_PAYER_EXTERN;
//        $cs_id = getFieldValueFromId("costcenter", "csc_id", "$csc_id", "cs_id");
      else:
        // Da haben wir den Salat: Wenn Zentralenauftrag (cs_id = 0), dann neuer externer Kunde
        // statt neue externe Kostenstelle
        if ($cs_id != 0): // => nicht Zentralenauftrag
          // Kundenauftrag -> neue externe Kostenstelle
          // Prüfen, ob die Kostenstelle "Extern" vorhanden ist
          if (!existsEntry("costcenter", array("cs_id", $cs_id, "csc_name", "Extern"))):
            // Neue Kostenstelle "Extern" anlegen, die neue externe Kostenstellen aufnimmt
            $csc_id_root = getFieldValueFromId("customer", "cs_id", "$cs_id", "csc_id");
            $csc_name_root = getFieldValueFromId("costcenter", "csc_id", "$csc_id_root", "csc_name");
            $tmpArr = array(
              "cs_id", $cs_id, "csc_pre_id", $csc_id_root,
              "csc_name", "Extern", "csc_path", "//" . my_str_check($csc_name_root) . "//",  "csc_is_extern", 1);
            insertStmt("costcenter", $tmpArr);
            $csc_pre_id = getLastInsertId();
            $csc_path = "//" . my_str_check($csc_name_root) . "//Extern//";
          else:
            // Kostenstelle "Extern" ist vorhanden; diese wird Parent der
            // neuen externen Kostenstelle
            $csc_pre_id = $db->getOne(
              "SELECT csc_id FROM costcenter WHERE cs_id = '$cs_id' AND csc_name = 'Extern'");
            $csc_path = my_str_check($db->getOne(
              "SELECT csc_path FROM costcenter WHERE csc_id = '$csc_pre_id'") .
             $db->getOne(
              "SELECT csc_name FROM costcenter WHERE csc_id = '$csc_pre_id'")) . "//";
          endif;
          // Die Kostenstelle Extern (neu angelegt oder bestehend) ist Parent der neuen Kostenstelle
        endif;

        // *** Folgendes gilt für beide Fälle (Kunden- oder Zentralenauftrag) ***
        $csc_name = $jobList[$i][JL_TR_COMP];      
        //
        if ($cs_id != 0):
          // Kundenauftrag: neue externe Kostenstelle
          // eindeutigen Namen für die neue Kostenstelle finden
          if ($getPriceOnly != 1): // nicht wenn nur Preisabfrage
            $j = 0;
            while (existsEntry("costcenter", array("cs_id", $cs_id, "csc_name", $csc_name))):
              $csc_name = $jobList[$i][JL_TR_COMP] . "_" . ++$j;
            endwhile;
            // Neue externe Kostenstelle mit eindeutigem Namen unter "Extern" anlegen
            $tmpArr = array("cs_id", $cs_id, "csc_pre_id", $csc_pre_id,
              "csc_name", $csc_name, "csc_path", $csc_path, "csc_is_extern", 1);
            insertStmt("costcenter", $tmpArr);
            $csc_id = getLastInsertId();
          endif;
        else:
          // Zentralenauftrag: Neuer Kunde nötig
          // Neuen Kunden anlegen (nicht wenn nur Preisabfrage)
          //
          // Neue Kostenstelle für den neuen Kunden anlegen
          if ($getPriceOnly != 1):
            $tmpArr = array("csc_name", $csc_name, "csc_is_extern", 1);
            insertStmt("costcenter", $tmpArr);
            $csc_id = getLastInsertId();
             // Insert company
            $tmpArr = array("cmp_comp", $jobList[$i][JL_TR_COMP], "ad_id", $ad_id,
              "cmp_hsno", $tr_hsno, "cmp_authenticated", "1");
            insertStmt("company", $tmpArr);
            $cmp_id_new = getLastInsertId();
            // Insert customer
            // ACHTUNG: cs_invmode HARTKODIERT NUR FÜR HANSETRANS! Sollte eigentlich aus DB geholt werden...
// MC: cs_invmode auf "2" setzen... (bzw. default in Abhängigkeit von Zentrale)
            $tmpArr = array("cmp_id", $cmp_id_new, "hq_id", $hq_id, "csc_id", $csc_id, "cs_invmode", 2);
            insertStmt("customer", $tmpArr);
            $cs_id_new = getLastInsertId();
            // Update new costcenter with new customer
            $tmpArr = array("cs_id", $cs_id_new);
            updateStmt("costcenter", "csc_id", $csc_id, $tmpArr);
            // Update the costcenteraddresses (without type '4' which follows below)
            $tmpArr =
              array("csc_id", $csc_id, "cscad_comp", $jobList[$i][JL_TR_COMP], "ad_id", $ad_id, "adt_id", 1, "cscad_hsno", $tr_hsno, "cscad_remark", "", "cscad_person", "", "cscad_phone", "");
            insertStmt("costcenteraddress", $tmpArr);
            $tmpArr =
              array("csc_id", $csc_id, "cscad_comp", $jobList[$i][JL_TR_COMP], "ad_id", $ad_id, "adt_id", 2, "cscad_hsno", $tr_hsno, "cscad_remark", "", "cscad_person", "", "cscad_phone", "");
            insertStmt("costcenteraddress", $tmpArr);
            $tmpArr =
              array("csc_id", $csc_id, "cscad_comp", $jobList[$i][JL_TR_COMP], "ad_id", $ad_id, "adt_id", 3, "cscad_hsno", $tr_hsno, "cscad_remark", "", "cscad_person", "", "cscad_phone", "");
            insertStmt("costcenteraddress", $tmpArr);
          endif;
        endif;
        // *** Folgendes gilt wieder für beide Fälle (Kunden- oder Zentralenauftrag) ***
        // Neue Costcenteraddress Typ "Lieferadresse" anlegen (nicht wenn nur Preisabfrage)
        if ($getPriceOnly != 1):
          $sqlStmt =
            "INSERT INTO costcenteraddress (csc_id, cscad_comp, adt_id, ad_id, cscad_hsno, cscad_remark, cscad_person, cscad_phone) " .
            "VALUES ($csc_id, '" . $jobList[$i][JL_TR_COMP] .
            "', 4, $ad_id, '" . $jobList[$i][JL_TR_HSNO] . "', '" .
            $jobList[$i][JL_TR_REMARK] . "', '" . $jobList[$i][JL_TR_PERSON] . "', '')";
          $res = $db->query($sqlStmt);
          if (DB::isError($res)) reportDie ("$PHP_SELF: '$sqlStmt': " . $res->getMessage());
          if ($cs_id != 0):
            // Kundenauftrag
// war noch für die alte Version mit den Drop-Down-Listen der csc_ids...
//            $jsAddNewExternCostcenter .= "addOption(\"job_tour\", \"tourForm\", \"von_csc_id\", \"" . $csc_name. "\", false, false);\n"
//              . "addOption(\"job_tour\", \"tourForm\", \"nach_csc_id\", \"" . $csc_name. "\", false, false);\n";
            $jsAddNewExternCostcenter = "";
          endif;
        endif;
      endif;
    endif;

    // *** Externe Kostenstelle (Ende) ***


    // *** Kostenstelle liegt vor (Anfang) ***

    // Ab hier liegt eine gültige csc_id vor (neu angelegt oder bestehend)
    // (nicht bei nur Preisanfrage)
    // *** Speichern der Etappenstelle in Tour ***
    // zuerst Spiechern/Ermitteln ob Adresse gültig
    list($ad_id, $tr_hsno, $tr_comp, $tr_remark, $tr_person, $tr_phone) =
      insertAddress($jobList[$i][JL_AD_STREET] . "|" . $jobList[$i][JL_TR_HSNO],
        $jobList[$i][JL_AD_ZIPCODE], $jobList[$i][JL_AD_CITY], $csc_id, $jobList[$i][JL_AD_COUNTRY], ($accept_all_addresses == "1"));
    // PLZ und Ort werden für einfachere Übersicht in jb_tourdata zwischengespeichert
    $jb_tourdata1 .= ($jb_tourdata1 == "" ? "" : ";") . $jobList[$i][JL_AD_ZIPCODE];
    $jb_tourdata2 .= ($jb_tourdata2 == "" ? "" : ";") . $jobList[$i][JL_AD_CITY];
    $jb_tourdata3 .= ($jb_tourdata3 == "" ? "" : ";") . (trim($jobList[$i][JL_AD_COUNTRY]) == "" ? "DE" : $jobList[$i][JL_AD_COUNTRY]);
    // tr_phone ist neu für Hamburg
    $tr_phone = $db->getOne("SELECT cscad_phone FROM costcenteraddress INNER JOIN costcenter ON costcenteraddress.csc_id = costcenter.csc_id" .
      " WHERE costcenteraddress.csc_id = $csc_id AND costcenteraddress.adt_id = 4");
    if ($ad_id == "" && $accept_all_addresses != "1"):
      // address invalid -> I must die...
      // error-message is in tr_person, rest is empty
//      $statusMessageTxt = "Houston, we've got a problem...";
      $statusMessageTxt = $tr_person;
      $addressValid = "";
      break;
    endif;
    // Ergänzen der fehlenden Angaben
//    if ($jobList[$i][JL_TR_HSNO] != "")
      $tr_hsno = my_str_check_mobile($jobList[$i][JL_TR_HSNO]);
//    if ($jobList[$i][JL_TR_COMP] != "")
      $tr_comp = my_str_check_mobile($jobList[$i][JL_TR_COMP]);
//    if ($jobList[$i][JL_TR_PERSON] != "")
      $tr_person = my_str_check_mobile($jobList[$i][JL_TR_PERSON]);
//    $tr_remark = "";
    if (/*$jobList[$i][JL_TR_REMARK] != "" && */ $jobList[$i][JL_HIDE_TR_REMARK] != "false")
      $tr_remark = my_str_check_mobile($jobList[$i][JL_TR_REMARK]);
    // Wenn Fuhrlohn angezeigt werden soll, erstmal den alten entfernen
    if ((MASK_JB_CR_PRICE_2_TR_REMARK == "1" || MASK_JB_MEASURES_2_TR_REMARK == "1") && (!(strpos($tr_remark, "[[") === false) || !(strpos($tr_remark, "||") === false))):
      if (!(strpos($tr_remark, "||") === false)) {
        $jb_cr_priceStr = strstr($tr_remark, "||");
        $jb_cr_priceStr = substr($jb_cr_priceStr, 0, strpos($jb_cr_priceStr, "||", 2) + 2);
      } else {
        $jb_cr_priceStr = strstr($tr_remark, "[[");
        $jb_cr_priceStr = substr($jb_cr_priceStr, 0, strpos($jb_cr_priceStr, "]]", 2) + 2);
      }
      $tr_remark = str_replace("\n" . $jb_cr_priceStr, "", $tr_remark);
      $tr_remark = str_replace($jb_cr_priceStr, "", $tr_remark);
    endif;    
    $tr_remark = str_replace("\n*** ZAHLT BAR ***", "", $tr_remark);    
    $tr_remark = str_replace("*** ZAHLT BAR ***", "", $tr_remark);
//    $tr_remark = preg_replace("/\n\*\*\* FESTPREIS \(LISTE\) EUR .* \*\*\*/", "", $tr_remark);
//    $tr_remark = preg_replace("/\*\*\* FESTPREIS \(LISTE\) EUR .* \*\*\*/", "", $tr_remark);
    $tr_remark_add = "";
    if (MASK_JB_CR_PRICE_2_TR_REMARK == "1" && (($i + 1) == 1)):
      $tr_remark_add = "{JB_CR_PRICE_TOTAL}";
      if (trim($jb_toll) != "")
        $tr_remark_add .= "Maut: " . str_replace(".", ",", $jb_toll) . " EUR\n";
    endif;
    // Maße und Gewichte
    if (MASK_JB_MEASURES_2_TR_REMARK == "1" && (($i + 1) == 1)):      
      if ($jb_weight > 0) { $tr_remark_add .= "Maximalgewicht: " . $jb_weight . " kg\n";}
      if ($jb_crvh_length > 0) { $tr_remark_add .= my_str_check_mobile("Länge: ") . $jb_crvh_length . " cm\n";}
      if ($jb_crvh_width > 0) { $tr_remark_add .= "Breite: " . $jb_crvh_width . " cm\n";}
      if ($jb_crvh_height > 0) { $tr_remark_add .= my_str_check_mobile("Höhe: ") . $jb_crvh_height . " cm\n";}
      if ($jb_crvh_position  > 0) { $tr_remark_add .= my_str_check_mobile("Plätze: ") . $jb_crvh_position . "\n";}
    endif;
    if ($tr_remark_add != "") {
      $tr_remark .= "\n[[\n" . $tr_remark_add . "]]";
      $tr_remark = str_replace("\n\n[[", "\n[[", $tr_remark);
    }
    if ($jb_cash == "true" && $jobList[$i][JL_CSC_ID_PAYER] == "true")
      // Wenn Barzahlung und Bezahler angegeben, dann hier festhalten!
      $tr_remark .= "\n*** ZAHLT BAR ***";
    if ($jobbatch_mode == true && $jobList[$i][JL_CSC_ID_PAYER] == "true")
      // Wenn Listenzahler und Bezahler angegeben, dann hier tournummer merken,
      // damit zum Schluß hier der Preis gespeichert werden kann!
      $tr_sort_jobbatchmode = ($i + 1);
    $tr_ware_from_to = 0; // Weder Abholung noch Anlieferung
    if ($jobList[$i][JL_TR_WARE_FROM] == "true")
      $tr_ware_from_to = 2; // Nur Abholung
    if ($jobList[$i][JL_TR_WARE_TO] == "true")
      $tr_ware_from_to += 1; // Nur Anlieferung: 1; Abholung + Anlieferung: 3
    $tr_photo = "";
    if ($jobList[$i][JL_TR_PHOTO] == "true" ||
      ((getFieldValueFromClause("parameter", "par_value", "par_key='MASK_TR_PHOTO_CS_" . getFieldValueFromId("costcenter", "csc_id", "$csc_id_payer", "cs_id") . "'") == "2" ||
        getFieldValueFromClause("parameter", "par_value", "par_key='MASK_TR_PHOTO_CS_" . getFieldValueFromId("costcenter", "csc_id", "$csc_id_payer", "cs_id") . "'") == "3")
       && $i > 0)):
      $tr_photo = getFieldValueFromClause("parameter", "par_value", "par_key='MASK_MIN_MAX_TR_PHOTO_CS_" . getFieldValueFromId("costcenter", "csc_id", "$csc_id_payer", "cs_id") . "'");
//echo "MASK_MIN_MAX_TR_PHOTO_CS_" . getFieldValueFromId("costcenter", "csc_id", "$csc_id_payer", "cs_id") . ", " . $tr_photo; die();
      if ($tr_photo == "")
        $tr_photo = "1|1"; // Default: Mindestens ein Photo, höchstens eins (d.h. genau ein Foto)
    endif;
//    if ($jobList[$i][JL_TR_COMMISSION_NO] != "")
      $tr_commission_no = my_str_check_mobile($jobList[$i][JL_TR_COMMISSION_NO]);
    $tr_tracking = my_str_check_mobile($jobList[$i][JL_TR_TRACKING]);
    $tr_mediationarea_id = $jobList[$i][JL_TR_MEDIATIONAREA_ID];
    if ($tr_mediationarea_id == -1)
      $tr_mediationarea_id = getMediationarea_id($hq_id, $jobList[$i][JL_AD_ZIPCODE], $jobList[$i][JL_AD_STREET], $tr_hsno);
    if ($job_is_new): // Neuer Auftrag -> neue Tour
      // Auftragsänderung mit neuer Tour
      if ($getPriceOnly != 1):
        $tmpArr = array( "jb_id", $jb_id, "ad_id", $ad_id, "tr_sort", ($i + 1),
            "csc_id", $csc_id, "tr_comp", $tr_comp, "tr_person", $tr_person, "tr_phone", $tr_phone,
            "tr_remark", $tr_remark, "tr_hsno", $tr_hsno, "tr_status", "0", "tr_ware_from_to", $tr_ware_from_to,
            "tr_commission_no", $tr_commission_no, "tr_mediationarea_id", $tr_mediationarea_id);
        insertStmt("tour", $tmpArr);
        $tr_id = getLastInsertId();
        if (trim($tr_photo) != "")
          insertStmt("genericdatacontainer", array("gdc_obj_type", "tr", "gdc_obj_id", $tr_id, "gdc_gen_fieldname", "tr_photo", "gdc_content", $tr_photo, "gdc_context", $jb_id));
        if (trim($tr_tracking) != "") {
          insertStmt("genericdatacontainer", array("gdc_obj_type", "tr", "gdc_obj_id", $tr_id, "gdc_gen_fieldname", "tr_tracking", "gdc_content", $tr_tracking, "gdc_context", ""));
          $tr_tracking_flag = true;
	    }
      endif;
    else:
      // Testen, ob Eintrag schon vorhanden, falls geänderter Auftrag
      $tr_id = $db->getOne(
        "SELECT tr_id FROM tour WHERE jb_id = '$jb_id' AND tr_sort = '" . ($i + 1) . "'");
      if ($tr_id != ""):
         // Auftragsänderung -> ändern der bestehenden Tour wenn vorhanden
         $tr_sign = $db->getOne(
           "SELECT tr_status FROM tour WHERE jb_id = '$jb_id' AND tr_sort = '" . ($i + 1) . "'");
//        if ($tr_sign != ""):
//          if ($getPriceOnly != 1):
//            $statusMessageTxt = "Etappenstelle Nr. " . ($i + 1) . " ist bereits unterschrieben und kann nicht mehr geändert werden!";
//            $addressValid = "";
//          endif;
//        else:
           // Status darf nicht gändert werden
          if ($getPriceOnly != 1):
            $tmpArr = array("ad_id", $ad_id,
              "csc_id", $csc_id, "tr_comp", $tr_comp, "tr_person", $tr_person, "tr_phone", $tr_phone,
              "tr_remark", $tr_remark, "tr_hsno", $tr_hsno, "tr_ware_from_to", $tr_ware_from_to,
              "tr_commission_no", $tr_commission_no, "tr_mediationarea_id", $tr_mediationarea_id);
            updateStmt("tour", "", "", $tmpArr, "jb_id = '$jb_id' AND tr_sort = '" . ($i + 1) . "'");
            if (trim($tr_tracking) == "") {
              deleteStmt("genericdatacontainer", "gdc_obj_type = 'tr' AND gdc_obj_id = " . $tr_id . " AND gdc_gen_fieldname = 'tr_tracking'");
			} else {
              $gdc_content = $db->getOne("SELECT gdc_content FROM genericdatacontainer WHERE gdc_obj_type = 'tr' AND gdc_gen_fieldname = 'tr_tracking' AND gdc_obj_id = " . $tr_id);
              $gdc_content_arr = explode("|", $gdc_content);
              if (count($gdc_content_arr) > 1) {
                $gdc_content_add = "|" . $gdc_content_arr[1] . "|" . $gdc_content_arr[2];
              }
              if (trim($gdc_content) != "") {
                updateStmt("genericdatacontainer", "gdc_obj_id", $tr_id, array("gdc_content", $tr_tracking . $gdc_content_add), "gdc_obj_type = 'tr' AND gdc_gen_fieldname = 'tr_tracking'");
			  } else {
                insertStmt("genericdatacontainer", array("gdc_obj_type", "tr", "gdc_obj_id", $tr_id, "gdc_gen_fieldname", "tr_tracking", "gdc_content", $tr_tracking, "gdc_context", ""));
			  }
              $tr_tracking_flag = true;
			}
          endif;
//        endif;
      else:
        // Neue Tour im bestehenden Auftrag!
        // -> Dies wird nur zugelassen wenn "Taximodus"
        // (Erste Etappenstelle angegeben, zweite wird nachträglich angegeben)
        $tour_cnt = $db->getOne("SELECT COUNT(*) FROM tour WHERE jb_id = '$jb_id'");
//        if ($jb_status != 1): // -	Beim nachträglichen Ändern einer Tour Sync-Problem wegen ‚jb_status' klären!
          // Auftrag ist noch in der manuellen oder automatischen Vermittlung, oder der Kurier hat ihn noch ni
          // genau eine Etappenstelle vorhanden => Taximodus
          if ($getPriceOnly != 1):
            $tmpArr = array( "jb_id", $jb_id, "ad_id", $ad_id, "tr_sort", ($i + 1),
              "csc_id", $csc_id, "tr_comp", $tr_comp, "tr_person", $tr_person, "tr_phone", $tr_phone,
              "tr_remark", $tr_remark, "tr_hsno", $tr_hsno, "tr_status", "0", "tr_ware_from_to", $tr_ware_from_to,
              "tr_commission_no", $tr_commission_no, "tr_mediationarea_id", $tr_mediationarea_id);
            insertStmt("tour", $tmpArr);
          endif;
//        else:
//          // Auftrag ist bereits vermittelt oder fertig
//          $statusMessageTxt = "Der Auftrag ist bereits vermittelt, es können keine Etappenstellen mehr hinzugefügt werden!";
//          $addressValid = "";
//          break;
//        endif;
      endif;
    endif;
    // Prüfen, ob aktuelle Etappenstelle der Bezahler des Auftrags ist
    // es muss im Verlauf genau einen JL_CSC_ID_PAYER geben, der "true" ist
    // ODER Kostenteilung!!!
    if($jobList[$i][JL_CSC_ID_PAYER] == "true")
      $csc_id_payer = $csc_id;
    if ($jb_fixprice == "" || $jb_fixprice == 0 || $jobbatch_mode == true):
      // - Grundpreis bei Kostensplit ab Etappenstelle 1
//      if ($costsplit_count > 1)
//        saveServiceCosts("Grundpreis", $srvt_name, $hq_id, $cs_id, $jb_id, ($i + 1), $jb_ordertime, 0, $costsplit_count, (($getPriceOnly == 1 || $jobbatch_mode) ? 1 : 0), $jb_cash, (($jb_costsplit == "false" || MASK_CASH_PAYER_SELECT == "1") ? $tmpCsc_id_payer : ""), $jb_storno, false, false);

      if ($cs_invmode == 0):
//        // - Preis für weitere Etappen ab Etappenstelle 3
//        if (($i + 1) > 2):
//          list ($fp, $fd, $fpm, $final_cr_price, $final_cr_discount, $final_cr_price_markup, $customer_specific, $special_address, $validfrom) =
//            saveServiceCosts("Weitere<br>Adressen", $srvt_name, $hq_id, $cs_id, $jb_id, ($i + 1), $jb_ordertime, 0, $costsplit_count, (($getPriceOnly == 1 || $jobbatch_mode) ? 1 : 0), $jb_cash, (($jb_costsplit == "false" || MASK_CASH_PAYER_SELECT == "1") ? $tmpCsc_id_payer : ""), $jb_storno, false, false, false, $jb_markup, $fuel_cr_markup, $vht_id);
//          $gross_price += $fp;
//          $fullPrice += round($fp * ((100-$fd)/100), 2);
//          $jb_subtotal += round($fpm * ((100-$fd)/100), 2);
//          $discount_sign = ($special_address || $discount_sign == "**" ? "**"
//          : ($discount_sign = ($fd > 0 || $customer_specific || $discount_sign == "*" ? "*" : "")));
//          $jb_cr_subtotal += round($final_cr_price_markup * ((100-$fd-$self_service_discount)/100), 2);
//          $fullCrPrice += round($final_cr_price * ((100-$fd-$self_service_discount)/100), 2);
//        endif;
//        // - Preis für Entfernungskilometer ab Etappenstelle 2
//        if (($i + 1) > 1):
//          $distance = ceil(getDistancePerID($ad_pre_id, $tr_pre_hsno, $ad_id, $tr_hsno));
//          list ($fp, $fd, $fpm, $final_cr_price, $final_cr_discount, $final_cr_price_markup, $customer_specific, $special_address, $validfrom) =
//            saveServiceCosts("km-Preis", $srvt_name, $hq_id, $cs_id, $jb_id, ($i + 1), $jb_ordertime, $distance, $costsplit_count, (($getPriceOnly == 1 || $jobbatch_mode) ? 1 : 0), $jb_cash, (($jb_costsplit == "false" || MASK_CASH_PAYER_SELECT == "1") ? $tmpCsc_id_payer : ""), $jb_storno, false, false, false, $jb_markup, $fuel_cr_markup, $vht_id);
//          $gross_price += $fp;
//          $fullPrice += round($fp * ((100-$fd)/100), 2);
//          $jb_subtotal += round($fpm * ((100-$fd)/100), 2);
//          $discount_sign = ($special_address || $discount_sign == "**" ? "**"
//          : ($discount_sign = ($fd > 0 || $customer_specific || $discount_sign == "*" ? "*" : "")));
//          $jb_cr_subtotal += round($final_cr_price_markup * ((100-$fd-$self_service_discount)/100), 2);
//          $fullCrPrice += round($final_cr_price * ((100-$fd-$self_service_discount)/100), 2);
//        endif;
      elseif(getFieldValueFromClause("parameter", "par_value", "par_key='MASK_CS_DONT_MAKE_STANDARD_PRICE_" . $cs_id . "'") != "1" && getParameterValue("0", "CUSTOMER_MASK_CALCULATOR_USAGE_ONLY_" . $cs_id, "0") != "1"):
        // Preisbestimmung aus PLZ-Matrix ab Etappenstelle 2
        if (($i + 1) > 1):
          // die Hamburger Fake-PLZs sind für Preisberechnung wichtig
          $ad_id1 = $prev_ad_id . "³" . $tr_pre_hsno;
          $zipcode1 = false;
          if ($prev_tr_mediationarea_id != 0):
            $ad_id1 = $prev_tr_mediationarea_id;
            $zipcode1 = true;
          endif;
          $ad_id2 = $ad_id . "³" . $tr_hsno;
          $zipcode2 = false;
          if ($tr_mediationarea_id != 0):
            $ad_id2 = $tr_mediationarea_id;
            $zipcode2 = true;
          endif;        
          //ab hier geht's normal weiter
          list ($fp, $fd, $fpm, $final_cr_price, $final_cr_discount, $final_cr_price_markup, $customer_specific, $special_address, $validfrom) =
            saveServiceCosts($ad_id1, $ad_id2, $hq_id, $cs_id, $jb_id, ($i + 1), $jb_ordertime, $distance, $costsplit_count, (($getPriceOnly == 1 || $jobbatch_mode) ? 1 : 0), $jb_cash, (($jb_costsplit == "false" || MASK_CASH_PAYER_SELECT == "1") ? $tmpCsc_id_payer : ""), $jb_storno, $zipcode1, $zipcode2, false, $jb_markup, $fuel_cr_markup, $vht_id);
          $gross_price += $fp;
          $fullPrice += round($fp * ((100-$fd)/100), 2);
          $jb_subtotal += round($fpm * ((100-$fd)/100), 2);
          $discount_sign = ($special_address || $discount_sign == "**" ? "**"
          : ($discount_sign = ($fd > 0 || $customer_specific || $discount_sign == "*" ? "*" : "")));
          $jb_cr_subtotal += round($final_cr_price_markup * ((100-$fd-$self_service_discount)/100), 2);
          $fullCrPrice += round($final_cr_price * ((100-$fd-$self_service_discount)/100), 2);
        endif;
        $prev_ad_id = $ad_id;
        $prev_tr_mediationarea_id = $tr_mediationarea_id;
      endif;
      $ad_pre_id = $ad_id;
      $tr_pre_hsno = $tr_hsno;
    endif;

    // *** Kostenstelle liegt vor (Ende) ***
  endfor;
  // Wenn Etappenstellen gelöscht wurden, müssen sie auch in der Datenbank gelöscht werden!
  deleteStmt("tour", "jb_id = $jb_id AND tr_sort >= '" . ($i + 1) . "'");

  // Wenn nur eine Etappenstelle vorhanden, dann jb_incomplete für Nachbearbeitung setzen (Taximodus)
//  if ($i == 1):
//    $tmpArr = array("jb_incomplete", 1);
//  else:
//    $tmpArr = array("jb_incomplete", 0);
//  endif;
//  updateStmt("job", "jb_id", $jb_id, $tmpArr);
  if ($addressValid == "ok"):
    // Überprüfen, ob bei der Änderung eines Auftrages Etappenstellen gelöscht wurden
// MC: To test this get the next $i ...
//    if (!$job_is_new): // geänderter Auftrag
//      $ad_id_test = $db->getOne(
//        "SELECT ad_id FROM tour WHERE jb_id = '$jb_id' AND tr_sort = '" . ($i + 1) . "'");
//      if ($ad_id_test != ""):
//        // Es existieren noch weitere Einträge -> mind. eine Etappenstelle gelöscht
//        $statusMessageTxt = "Bei der Änderung eines Auftrages können keine Etappenstellen gelöscht werden!";
//        $addressValid = "";
//      endif;
//    endif;
    // der Bezahler des jobs wurde während des Speicherns der Touren ermittelt
    // und wird jetzt gespeichert
    if ($csc_id_payer != "")
      if ($getPriceOnly != 1):
        $tmpArr = array("csc_id_payer", $csc_id_payer);
        if ($jb_payment == 2 && MASK_CASH_PAYER_SELECT == "1"):
          if (CSC_ID_PAYER_CASH != ""):
            $tmpArr = array("csc_id_payer", CSC_ID_PAYER_CASH, "csc_id_payer_cash", $csc_id_payer);
          else:
            $tmpArr = array("csc_id_payer", "-1", "csc_id_payer_cash", $csc_id_payer);
          endif;
        endif;
        // 02.06.2023: Wenn der Auftrag mehr als ein Jahr in der Zukunft liegt, ist das vemutlich ein Irrtum, der
        $jb_ordertime_vals = getValsFromDate($jb_ordertime);
        if (!(isset($jb_storno) && $jb_storno > 0) && mktime(0, 0, 0, date("m"), date("d"), date("Y") + 1) <= mktime(0, 0, 0, $jb_ordertime_vals[1], $jb_ordertime_vals[2], $jb_ordertime_vals[0])):
          include_once("../include/email/htmlMimeMail.php");
          $mailObj = new htmlMimeMail();
          $mailObj->setFrom("auto-mailer@assecutor.de");
          $mailObj->setBcc("support@assecutor.de");
          $mailObj->setSubject("Auftragsdatum von " . $jb_id . " liegt mehr als ein Jahr in der Zukunft.");
          $mailObj->setText("Auftrag " . $jb_id . " ist vielleicht versehentlich mit dem Datum " . $jb_ordertime_vals[2] . "." . $jb_ordertime_vals[1] . "." . $jb_ordertime_vals[0] . " erfasst worden.\n ");
          $mailResult = $mailObj->send(array(MAIL_SURVEY_ADDRESS_TO), 'smtp');
        endif;
        updateStmt("job", "jb_id", $jb_id, $tmpArr);
      endif;
    if (($jb_costsplit == "true" && MASK_CASH_PAYER_SELECT != "1") && !(isset($jb_storno) && $jb_storno > 0))
      setCostsplit($jb_id);
    // Wenn Tourname angegeben, prüfen, ob bereits existent;
    // wenn ja, dann löschen
    if ($jb_tourname != ""):
      if ($getPriceOnly != 1)
        if (existsEntry("job", array("jb_tourname", $jb_tourname, "csc_id_payer", $csc_id_payer)) ||
            existsEntry("job", array("jb_tourname", $jb_tourname, "csc_id_payer_cash", $csc_id_payer))):
          $tmpArr = array("jb_tourname", NULL);
          updateStmt("job", "jb_tourname", $jb_tourname, $tmpArr, "(csc_id_payer = $csc_id_payer OR csc_id_payer_cash = $csc_id_payer)");
        endif;
      $tmpArr = array("jb_tourname", $jb_tourname);
//      array_push ($insertStmtArr, "jb_tourname", $jb_tourname);
      updateStmt("job", "jb_id", $jb_id, $tmpArr);
    endif;
    // Porto ermitteln und speichern; kompletten Preis speichern
    if ($jb_fixprice == 0 && !(isset($jb_storno) && $jb_storno > 0)):
      // wenn Fixpreis oder Storno, dann jb_subtotal bereits vorhanden
      // sonst ermittelten Standardpreis nehmen
      // $jb_subtotal bereits definiert
      $jb_totalprice = $fullPrice;
      if ($jb_cr_price == 0 && MASK_CR_PRICE_MODE == "1"):
        $jb_cr_price_total = $fullCrPrice;
        $jb_cr_price_rate = get_cr_price_rate($hq_id, $cs_id, $jb_ordertime, $vhtSrvt_name, $vht_id);
//writeLog_("../log/job2_options_", "\$jb_id=|$jb_id|\$jb_cr_price=|$jb_cr_price|");
      endif;
    else:
      if (isset($jb_storno) && $jb_storno > 0):
        $jb_totalprice = $jb_totalprice_storno;
        $jb_subtotal = $jb_subtotal_storno;
        $jb_cr_price_total = $jb_cr_price_storno;
      else:
        $jb_subtotal = round($jb_fixprice * (1 - ($tmp_discount_rate / 100)), 2);
        $jb_totalprice = round($jb_subtotal * (1 + ($jb_markup / 100)), 2);
        if (MASK_CR_PRICE_MODE == "1") {
          if ($jb_cr_price == 0) {
            list($jb_cr_subtotal, $jb_cr_price_rate) =
              getCr_price_global($jb_subtotal, $hq_id, $cs_id, $jb_ordertime, $vhtSrvt_name, $vht_id);
writeLog_("../log/job2_options_", "\$jb_id=|$jb_id|\$jb_cr_subtotal=|$jb_cr_subtotal|\$jb_cr_price_rate=|$jb_cr_price_rate|");
          } else {
            $jb_cr_price = round($jb_cr_price * (1 - ($tmp_discount_rate / 100)), 2);
            $jb_cr_subtotal = $jb_cr_price;
          }        
        }
        $gross_price = round($jb_fixprice * (1 + ($jb_markup / 100)), 2);
        $jb_totalprice = round(($gross_price - round($gross_price * $self_service_discount / 100, 2)) * (1 - ($tmp_discount_rate / 100)), 2);
        $jb_subtotal = round($jb_subtotal * ((100 - $self_service_discount) / 100), 2);
      endif;
    endif;
    $jb_totalprice += round($jb_serviceprice * (1 - ($tmp_discount_rate / 100)), 2);
    $jb_subtotal += round($jb_serviceprice * (1 - ($tmp_discount_rate / 100)), 2);
    $jb_cr_serviceprice = round($jb_cr_serviceprice * (1 - ($tmp_discount_rate / 100)), 2);
    // wenn Listenkunde, auch hier natürlich $jb_totalprice auf 0!!!
    if ($jobbatch_mode == true):
      $jb_subtotal = 0;
      $jb_totalprice = 0;
      $jb_cr_subtotal = 0;
    endif;
    if (MASK_CR_PRICE_MODE == "1") {
      if ($jb_cr_serviceprice == 0)
        list($jb_cr_serviceprice, $jb_cr_serviceprice_rate) =
          getCr_price_global($jb_serviceprice, $hq_id, $cs_id, $jb_ordertime, $vhtSrvt_name, $vht_id);
//die($jb_serviceprice .", ". $jb_cr_serviceprice . ", " . $jb_cr_serviceprice_rate);
    }
    if (MASK_CR_PRICE_MODE == "1" && strtotime(MASK_CR_PRICE_MODE_DATE) <= strtotime($jb_ordertime) && (!isset($jb_storno) || $jb_storno == 0)) {
      $jb_cr_subtotal = round($jb_cr_subtotal * (1 - ($self_service_discount / 100)), 2);
      $jb_cr_price_total = round($jb_cr_subtotal * (1 + ($fuel_cr_markup / 100)), 2) + $jb_cr_serviceprice;
      $jb_cr_subtotal += $jb_cr_serviceprice;
//writeLog_("../log/job2_options_", "\$jb_id=|$jb_id|\$jb_cr_price_total=|$jb_cr_price_total|");
    }
    list($usr_name, $usr_firstname) = getFieldsValueFromId("user", "usr_id", $usr_id, array("usr_name", "usr_firstname"));
    $jb_commission_no = my_str_check($jb_commission_no);
    $jb_commission_no_old = my_str_check($jb_commission_no_old);
    updateStmt("job", "jb_id", $jb_id, array("jb_postage",
      $db->getOne("SELECT cmp.cmp_postage"
        . " FROM costcenter AS csc, customer AS cs, company AS cmp"
        . " WHERE cmp.cmp_id = cs.cmp_id        AND"
        . "       cs.cs_id = csc.cs_id          AND"
        . "       csc.csc_id = '$csc_id_payer'"),
        "jb_totalprice", $jb_totalprice, "jb_subtotalprice", $jb_subtotal, "jb_cr_price", $jb_cr_price_total, "jb_markup", $jb_markup, "jb_tourdata", $jb_tourdata1 . "|" . $jb_tourdata2 . "|" . $jb_tourdata3, "jb_origin", 4, "jb_orderer", $usr_firstname . " " . $usr_name, "jb_commission_no", $jb_commission_no));
//echo $jb_totalprice . "|<br>\n";die();
    $db->query("DELETE FROM jobprice WHERE jb_id = " . $jb_id);
    $insert_clause = 
      /*($jb_cr_markup > 0 ?*/ "(" . $jb_id . ", 1, " . $fuel_cr_markup . ",''), " /*: "")*/ .
      ($jb_cr_price > 0 ? "(" . $jb_id . ", 2, " . $jb_cr_price . ",''), " : "") .
//      ($jb_cr_fixserviceprice > 0 ? "(" . $jb_id . ", 3, " . $jb_cr_fixserviceprice . ",''), " : "") .
//      ($jb_cr_serviceprice > 0 ? "(" . $jb_id . ", 4, " . $jb_cr_serviceprice . ",''), " : "") .
      ($jb_cr_serviceprice > 0 ? "(" . $jb_id . ", 3, " . $jb_cr_serviceprice . ",''), " : "") .
      ($jb_cr_subtotal > 0 && isset($jb_cr_price_rate) && $jb_cr_price_rate > 0 ? "(" . $jb_id . ", 5, " . $jb_cr_price_rate . ",''), " : "") .
      ($jb_cr_serviceprice > 0 && $jb_cr_serviceprice_rate > 0 ? "(" . $jb_id . ", 6, " . $jb_cr_serviceprice_rate . ",''), " : "") .
//      ($jb_cr_agio > 0 ? "(" . $jb_id . ", 7, " . $jb_cr_agio . ",''), " : "") .
      ($jb_cr_subtotal > 0 ? "(" . $jb_id . ", 10, " . $jb_cr_subtotal . ",''), " : "") .
      ($self_service_discount > 0 ? "(" . $jb_id . ", 13, " . $self_service_discount . ", '" . $gross_price . "'), " : "");
//echo "INSERT INTO jobprice (jb_id, mt_sort, jbprc_price, jbprc_remark) VALUES " . substr($insert_clause, 0, strlen($insert_clause) - 2); die();
    $db->query("INSERT INTO jobprice (jb_id, mt_sort, jbprc_price, jbprc_remark) VALUES " . substr($insert_clause, 0, strlen($insert_clause) - 2));
    if ($jb_price_km > 0) {
      $db->query("INSERT INTO jobprice (jb_id, mt_sort, jbprc_price) VALUES (" . $jb_id . ", 15, " . $jb_price_km . ")");
    }
    // Rechnungstext erzeugen
    if (!(isset($jb_storno) && $jb_storno > 0)):
      mk_jb_invtext($jb_id, false);
    endif;
    // Job entsperren, falls gesperrt gewesen (Nachbearbeitung)
    updateStmt("job", "jb_id", $jb_id, array("jb_locktime", NULL, "jb_lockuser", NULL));

    // BWV_Auftrag?
    $jb_longhaul = 0;
    $tmpArr = array();
    list($total_km, $total_km_osm) = get_job_distance($jb_id);
    if ($total_km == -1)
      $total_km = $db->getOne("SELECT jbprc_price FROM jobprice WHERE jb_id = " . $jb_id . " AND mt_sort = 11");
//echo $total_km . "|" . $tourCount . "|" . getParameterValue("0", "LONGHAUL_KM", "0");
    if ($total_km > 0 && $tourCount > 1 && $total_km / ($tourCount - 1) >= getParameterValue("0", "LONGHAUL_KM", "0")) {
	  $jb_longhaul = 1;
      $tmpArr = array("jb_status", 9);
    }
    array_push ($tmpArr, "jb_longhaul", $jb_longhaul);
    updateStmt("job", "jb_id", $jb_id, $tmpArr);

    if (MASK_CR_PRICE_MODE == "1") {
      deleteStmt("genericdatacontainer", "gdc_obj_type = 'jb' AND gdc_obj_id = $jb_id AND gdc_gen_fieldname = 'jb_cr_serviceprice'");
    // Service-Fuhrlohn wird extra gespeichert
//echo "|" . $jb_cr_serviceprice . "|";
      if (trim($jb_cr_serviceprice) != "" && $jb_cr_serviceprice != 0)
        insertStmt("genericdatacontainer", array("gdc_obj_type", "jb", "gdc_obj_id", $jb_id, "gdc_gen_fieldname", "jb_cr_serviceprice", "gdc_content", $jb_cr_serviceprice, "gdc_context", ""));
    }
    deleteStmt("genericdatacontainer", "gdc_obj_type = 'jb' AND gdc_obj_id = $jb_id AND gdc_gen_fieldname = 'jb_job_jam'");
    if (trim($jb_jam_waittime) != "" && trim($jb_jam_waittime) != "undefined" && $jb_jam_waittime != 0):
	  $jb_jam_waittime *= 60;
      if ($jb_reserv == 1)
        $jb_jam_waittime = getParameterValue("0", "CS_JB_JAM_WAITTIME_RESERVATION_DEFAULT", "0") * -60; // (5 Min.); // Zeitzone beachten?
         // was passiert wenn von den Zuzuweisenden ins Autoranking gkippt wird?
      $jb_job_jam = date("Y-m-d H:i:s", strtotime($jb_ordertime) + $jb_jam_waittime);
      insertStmt("genericdatacontainer", array("gdc_obj_type", "jb", "gdc_obj_id", $jb_id, "gdc_gen_fieldname", "jb_job_jam", "gdc_content", $jb_job_jam, "gdc_context", ""));
    endif;
    if (getParameterValue("0", "MASK_CUSTOMER_INCOMPLETE_" . $cs_id, "0") == "1") // 28.06.2021: Neuer Parameter für STH912809
      $jb_incomplete = 1;
    // Prüfen, ob jb_incomplete-Flag gesetzt werden muss
    check_jb_incomplete($jb_id, $jb_incomplete);
    // Prüfen, ob jb_serviceprice gesetzt werden muss
    if ($job_is_new)
      check_jb_serviceprice($jb_id, $hq_id, $jb_ordertime);
    // manuelle Disposition gewünscht => overrult alles
    if ($jb_status_manual == 1 && !(isset($jb_storno) && $jb_storno > 0)):
      $tmpArr = array("jb_status", 9);
      updateStmt("job", "jb_id", $jb_id, $tmpArr);
    endif;

    // Mitarbeiter speichern
//    $tmpArr = array("jb_id", $jb_id, "usr_id", $usr_id, "jbemp_description", ($job_is_new == true ? "Erfassung" : "Änderung"));
//    insertStmt("jobemployee", $tmpArr);
//    $tmpArr = array("jb_id", $jb_id, "usr_id", $usr_id, "hq_id", $hq_id, "logo_id", ($job_is_new == true ? 1 : 2), "logo_description", $jobMode);
//    insertStmt("phoenix_log.log", $tmpArr);
    // Falls Listenkundenauftrag, der offiziell einen Nullpreis hat, den Preis im Bemerkungstextfeld speichern
//    if ($jobbatch_mode == true):
//      if ($tr_sort_jobbatchmode == 0)
//        $tr_sort_jobbatchmode = 1;
//      $tr_remark = $db->getOne("SELECT tr_remark FROM tour WHERE jb_id = $jb_id AND tr_sort = $tr_sort_jobbatchmode");
//      $tr_remark .= "\n*** FESTPREIS (LISTE) EUR " . sprintf("%01.2f", $fullPrice) . " ***";
//      $tmpArr = array("tr_remark", $tr_remark);
//      updateStmt("tour", "jb_id", $jb_id, $tmpArr, "tr_sort = " . $tr_sort_jobbatchmode);
//    endif;

    deleteStmt("genericdatacontainer", "gdc_obj_type = 'jb' AND gdc_obj_id = " . $jb_id . " AND gdc_gen_fieldname = 'jb_blink'");
    if (trim($jb_tourname_hidden_vht_id) != "" && $jb_tourname_hidden_vht_id != $vht_id && !($jb_fixprice == "" || $jb_fixprice == 0))
      insertStmt("genericdatacontainer", array("gdc_obj_type", "jb", "gdc_obj_id", $jb_id, "gdc_gen_fieldname", "jb_blink", "gdc_content", "1", "gdc_context", ""));

    if (MASK_CR_PRICE_MODE == "1"):
      $tr_remark = $db->getOne("SELECT tr_remark FROM tour WHERE jb_id = $jb_id AND tr_sort = 1");
      if ($jb_cr_price_total > 0):
        $tr_remark = str_replace("{JB_CR_PRICE_TOTAL}", "Frachtverguetung: " . str_replace(".", ",", sprintf("%01.2f", $jb_cr_price_total)) . " EUR\n", $tr_remark);
      else:
        $tr_remark = str_replace("\n[[\n{JB_CR_PRICE_TOTAL}]]", "", $tr_remark);
        $tr_remark = str_replace("{JB_CR_PRICE_TOTAL}", "", $tr_remark);
      endif;
      $filters_text = "";
      if ($tr_tracking_flag)
        $filters_text = "~~~\n" . "Bitte achten sie auf eine aktive GPS-Verbindung während dieses Auftrags, da der/die Empfänger über ihr voraussichtliches Eintreffen auf dem Laufenden gehalten wird.\n"
          . str_replace("~~~\n", "", $filters_text) . "~~~\n";
      $tmpArr = array("tr_remark", $filters_text . $tr_remark);
      updateStmt("tour", "jb_id", $jb_id, $tmpArr, "tr_sort = 1");
    endif;
    $job_checkboxes = "";
    if ($afterwards == 1) { $job_checkboxes .= ", `Nacherfassung´"; }
    if ($jb_globaljob == 1) { $job_checkboxes .= ", `An alle Kuriere´"; }
    if ($jb_status_manual == 1) { $job_checkboxes .= ", `Manuelle Disposition´"; }
    if ($jb_incomplete == 1) { $job_checkboxes .= ", `Noch unvollständig´"; }
    if (isset($jb_tourname_overwrite) && $jb_tourname_overwrite == 1) { $job_checkboxes .= ", `Gespeicherte Tour überschreiben´"; }
    if (isset($jb_id_insurance) && $jb_id_insurance != 0) { $job_checkboxes .= ", `Höherversicherung (" . $jb_id_insurance . ")´"; }
    if ($jb_tourname_hidden != "") { $job_checkboxes .= ", `Konserve \"" . $jb_tourname_hidden . "\"´"; }
    if ($request_token != "") { // e.g. no request_token when storno
      writeLog_("../log/job2_options_", "\$request_token = " . $request_token . ", \$sp_id_request = " . $sp_id_request . ", \$sp_context = " . $sp_context);
      updateStmt("phoenix_log.semaphor", "sp_id", $sp_id_request, array("sp_context", (trim($sp_context) != "NOT_SENT" ? $sp_context . "," : "") . $jb_id));
    }
    if (trim($jb_id_org) == "") {
      $changes_text = "";
      $changes_str = "";
      if (!$job_is_new):
        // Analyse der Änderungen vornehmen, falls es eine Änderung war
        if ($vht_id_old != $vht_id) { $changes_text .= ", Fahrzeugtyp"; $changes_str .= "|\$vht_id_old=$vht_id_old|\$vht_id=$vht_id"; }
//  $csc_id != 
        if ($jb_weight_old != $jb_weight) { $changes_text .= ", Maximalgewicht"; $changes_str .= "|\$jb_weight_old=$jb_weight_old|\$jb_weight=$jb_weight"; }
        if ($jb_crvh_length_old != $jb_crvh_length) { $changes_text .= ", Länge"; $changes_str .= "|\$jb_crvh_length_old=$jb_crvh_length_old|\$jb_crvh_length=$jb_crvh_length"; }
        if ($jb_crvh_width_old != $jb_crvh_width) { $changes_text .= ", Breite"; $changes_str .= "|\$jb_crvh_width_old=$jb_crvh_width_old|\$jb_crvh_width=$jb_crvh_width"; }
        if ($jb_crvh_height_old != $jb_crvh_height) { $changes_text .= ", Höhe"; $changes_str .= "|\$jb_crvh_height_old=$jb_crvh_height_old|\$jb_crvh_height=$jb_crvh_height"; }
        if ($jb_crvh_position_old != $jb_crvh_position) { $changes_text .= ", Stellplätze"; $changes_str .= "|\$jb_crvh_position_old=$jb_crvh_position_old|\$jb_crvh_position=$jb_crvh_position"; }
//        if ($jb_ordertime_old != $jb_ordertime) { $changes_text .= ", Datum und/oder Uhrzeit"; $changes_str .= "|\$jb_ordertime_old=$jb_ordertime_old|\$jb_ordertime=$jb_ordertime"; }
//        if ($jb_reserv_old != $jb_reserv) { $changes_text .= ", "; $changes_str .= "|\$jb_reserv_old = $jb_reserv_old|\$jb_reserv = $jb_reserv"; }
        if ($jb_permanent_old != $jb_permanent) { $changes_text .= ", Dauerauftragsrhythmus"; $changes_str .= "|\$jb_permanent_old=$jb_permanent_old|\$jb_permanent=$jb_permanent"; }
//        if ($cr_sid_old != $cr_sid) { $changes_text .= ", "; $changes_str .= "|\$cr_sid=$cr_sid"; }
//        if ($cr_id_order_old != $cr_id_order) { $changes_text .= ", "; $changes_str .= "|\$cr_id_order=$cr_id_order"; }
        if ($jb_waitstorno_old != $jb_waitstorno_old) { $changes_text .= ", Storno bei Nichtverfügbarkeit"; $changes_str .= "|\$jb_waitstorno_old=$jb_waitstorn_old|\$jb_waitstorno=$jb_waitstorno"; }
//        if ($jb_waittime_old != $jb_waittime) { $changes_text .= ", "; $changes_str .= "|\$jb_waittime_old=$jb_waittime_old|\$jb_waittime=$jb_waittime"; }
        $jb_fixprice_compare = ($jb_fixprice == "" ? "0.00" : $jb_fixprice);
        if ($jb_fixprice_old != $jb_fixprice_compare) { $changes_text .= ", Festpreis"; $changes_str .= "|\$jb_fixprice_old=$jb_fixprice_old|\$jb_fixprice=$jb_fixprice_compare"; }
        $jb_serviceprice_compare = ($jb_serviceprice == "" ? "0.00" : $jb_serviceprice);
        if ($jb_serviceprice_old != $jb_serviceprice_compare) { $changes_text .= ", Servicepreis"; $changes_str .= "|\$jb_serviceprice_old=$jb_serviceprice_old|\$jb_serviceprice=$jb_serviceprice_compare"; }
        if ($csc_id_payer_old != $csc_id_payer || ($csc_id_payer_cash_old != $csc_id_payer_cash && $csc_id_payer_cash != "")) { $changes_text .= ", Zahler oder Zahlungsmodus"; $changes_str .= "|\$csc_id_payer_old=$csc_id_payer_old|\$csc_id_payer=$csc_id_payer|\$csc_id_payer_cash_old=$csc_id_payer_cash_old|\$csc_id_payer_cash=$csc_id_payer_cash"; }
//        if ($jb_globaljob_old != $jb_globaljob && $jb_globaljob != "") { $changes_text .= ", `An alle Kuriere´ an oder aus"; $changes_str .= "|\$jb_globaljob_old=$jb_globaljob_old|\$jb_globaljob=$jb_globaljob"; }
        if (my_str_check($jb_freetext_1_old) != my_str_check_http($jb_freetext_1)) { $changes_text .= ", Rechnungstext"; $changes_str .= "|\$jb_freetext_1_old=" . my_str_check($jb_freetext_1_old) . "|\$jb_freetext_1=" . my_str_check_http($jb_freetext_1); }
//        if ($jb_payment_old != $jb_payment) { $changes_text .= ", Fahrzeuganforderung"; $changes_str .= "|\$jb_payment_old=$jb_payment_old|\$jb_payment=$jb_payment"; }
        if ($jb_permanent2_old != $jb_permanent2) { $changes_text .= ", Dauerauftragsrhythmus-Tage"; $changes_str .= "|\$jb_permanent2_old=$jb_permanent2_old|\$jb_permanent2=$jb_permanent2"; }
        if ($jb_sales_tax_rate_old != $jb_sales_tax_rate) { $changes_text .= ", MwSt-Satz"; $changes_str .= "|\$jb_sales_tax_rate_old=$jb_sales_tax_rate_old|\$jb_sales_tax_rate=$jb_sales_tax_rate"; }
        if ($jb_sales_tax_rate_sign_old != $jb_sales_tax_rate_sign_new) { $changes_text .= ", MwSt-Kennzeichen"; $changes_str .= "|\$jb_sales_tax_rate_sign_old=$jb_sales_tax_rate_sign_old|\$jb_sales_tax_rate_sign=$jb_sales_tax_rate_sign"; }
        if ($jp_permenddat_old != $jp_permenddat) { $changes_text .= ", Dauerauftragsenddatum"; $changes_str .= "|\$jp_permenddat_old=$jp_permenddat_old|\$jp_permenddat=$jp_permenddat"; }
        if ($jb_cr_filter_old != $jb_cr_filter) { $changes_text .= ", Kurierfilter"; $changes_str .= "|\$jb_cr_filter_old=$jb_cr_filter_old|\$jb_cr_filter=$jb_cr_filter"; }
        if ($jb_cr_filter_opt_old != $jb_cr_filter_opt) { $changes_text .= ", optionale Kurierfilter"; $changes_str .= "|\$jb_cr_filter_opt_old=$jb_cr_filter_opt_old|\$jb_cr_filter_opt=$jb_cr_filter_opt"; }
        if ($jb_dispoinfo_old != $jb_dispoinfo) { $changes_text .= ", Dispo-Info"; $changes_str .= "|\$jb_dispoinfo_old=$jb_dispoinfo_old|\$jb_dispoinfo=$jb_dispoinfo"; }
//        if ($jb_status_old != $jb_status) { $changes_text .= ", Auftragsstatus"; $changes_str .= "|\$jb_status_old=$jb_status_old|\$jb_status=$jb_status"; }
//        if ($cr_id_permanent_old != $cr_id_permanent) { $changes_text .= ", "; $changes_str .= "|\$cr_id_permanent_old=$cr_id_permanent_old|\$cr_id_permanent=$cr_id_permanent"; }
//        if ($jb_incomplete_old == 1 && $jb_incomplete == "" || $jb_incomplete_old == 0 && $jb_incomplete == "1") { $changes_text .= ", `Noch unvollständig´ an oder aus"; $changes_str .= "|\$jb_incomplete_old=$jb_incomplete_old|\$jb_incomplete=$jb_incomplete"; }
        if ($hq_id_exec_old != $hq_id_exec) { $changes_text .= ", Ausführende NL:"; $changes_str .= "|\$hq_id_exec_old=$hq_id_exec_old|\$hq_id_exec=$hq_id_exec"; }
        if ($jb_longhaul_old != $jb_longhaul) { $changes_text .= ", BWV-Auftrag"; $changes_str .= "|\$jb_longhaul_old=$jb_longhaul_old|\$jb_longhaul=$jb_longhaul"; }
        if ($jb_commission_no_old != $jb_commission_no)  { $changes_text .= ", Rechnungskommission"; $changes_str .= "|\$jb_commission_no_old=$jb_commission_no_old|\$jb_commission_no=$jb_commission_no"; }
        $tr_add_str = "";
        $tr_del_str = "";
        $i = 1;
        do {
          if (existsEntry("tour", array("jb_id", $jb_id, "tr_sort", $i))){
            $tourFound = 1;
            if ($i < $i_tour_max_old) {
              list($csc_id, $tr_comp, $tr_person, $ad_street, $tr_hsno,
                $ad_zipcode, $ad_city, $ad_country, $tr_remark, $tr_status, $tr_ware_from_to, $tr_commission_no, $tr_mediationarea_id, $tr_status, $tr_sign, $tr_signname, $tr_finishtime) =
                  getTourData($jb_id, $i, $dbh_tr);
            } else {
              $tr_add_str .= "$i, "; 
              $changes_text .= ", $i. Etappe hinzugefügt";
            }
          } else {
            $tourFound = 0;
            if ($i < $i_tour_max_old):
              $csc_id = $tr_comp = $tr_person = $ad_street = $tr_hsno =
                $ad_zipcode = $ad_city = $ad_country = $tr_remark = $tr_status = $tr_ware_from_to = $tr_commission_no = $tr_mediationarea_id = $tr_status = $tr_sign = $tr_signname = $tr_finishtime = "";
              $tr_del_str .= "$i, "; 
            endif;
          }
          if ($i < $i_tour_max_old) {
            if ($csc_id != $csc_id_old_[$i]) { $changes_text .= ", $i. Kostenstelle"; $changes_str .= "|\$csc_id_$i=".$csc_id."|\$csc_id_old_$i=".$csc_id_old_[$i]; }
            if ($tr_comp != $tr_comp_old_[$i]) { $changes_text .= ", $i. Firma"; $changes_str .= "|\$tr_comp_$i=".$tr_comp."|\$tr_comp_old_$i=".$tr_comp_old_[$i]; }
            if ($tr_person != $tr_person_old_[$i]) { $changes_text .= ", $i. Person"; $changes_str .= "|\$tr_person_$i=".$tr_person."|\$tr_person_old_$i=".$tr_person_old_[$i]; }
            if ($ad_street != $ad_street_old_[$i]) { $changes_text .= ", $i. Straße"; $changes_str .= "|\$ad_street_$i=".$ad_street."|\$ad_street_old_$i=".$ad_street_old_[$i]; }
            if ($tr_hsno != $tr_hsno_old_[$i]) { $changes_text .= ", $i. Hausnummer"; $changes_str .= "|\$tr_hsno_$i=".$tr_hsno."|\$tr_hsno_old_$i=".$tr_hsno_old_[$i]; }
            if ($ad_zipcode != $ad_zipcode_old_[$i]) { $changes_text .= ", $i. PLZ"; $changes_str .= "|\$ad_zipcode_$i=".$ad_zipcode."|\$ad_zipcode_old_$i=".$ad_zipcode_old_[$i]; }
            if ($ad_city != $ad_city_old_[$i]) { $changes_text .= ", $i. Ort"; $changes_str .= "|\$ad_city_$i=".$ad_city."|\$ad_city_old_$i=".$ad_city_old_[$i]; }
            if ($ad_country != $ad_country_old_[$i]) { $changes_text .= ", $i. Ort"; $changes_str .= "|\$ad_country_$i=".$ad_country."|\$ad_country_old_$i=".$ad_country_old_[$i]; }
            if ($tr_remark != $tr_remark_old_[$i]) { $changes_text .= ", $i. Bemerkung"; $changes_str .= "|\$tr_remark_$i=".$tr_remark."|\$tr_remark_old_$i=".$tr_remark_old_[$i]; }
//            if ($tr_status != $tr_status_old_[$i]) { $changes_text .= ", $i. Status"; $changes_str .= "|\$tr_status_$i=".$tr_status."|\$tr_status_old_$i=".$tr_status_old_[$i]; }
            if ($tr_ware_from_to != $tr_ware_from_to_old_[$i]) { $changes_text .= ", $i. An/Ab"; $changes_str .= "|\$tr_ware_from_to_$i=".$tr_ware_from_to."|\$tr_ware_from_to_old_$i=".$tr_ware_from_to_old_[$i]; }
            if ($tr_commission_no != $tr_commission_no_old_[$i]) { $changes_text .= ", $i. Kommissionsnummer"; $changes_str .= "|\$tr_commission_no_$i=".$tr_commission_no."|\$tr_commission_no_old_$i=".$tr_commission_no_old_[$i]; }
            if ($tr_mediation_area_id != $tr_mediation_area_id_old_[$i]) { $changes_text .= ", $i. Bereich"; $changes_str .= "|\$tr_mediation_area_id_$i=".$tr_mediation_area_id."|\$tr_mediation_area_id_old_$i=".$tr_mediation_area_id_old_[$i]; }
          }
          $i++;
        } while ($tourFound == 1 || $i < $i_tour_max_old);
        if ($tr_add_str != "") {
          $changes_str .= "|\$tr_add=" . substr($tr_add_str, 0, -2);
        }
        if ($tr_del_str != "") {
          $changes_str .= "|\$tr_del=" . substr($tr_del_str, 0, -2);
          if ($jb_status != 2 && $tr_status_all == 1) {
		    if ($jb_finishtime_new == "0000-00-00 00:00:00")
		      $jb_finishtime_new = date("Y-m-d H:i:s");
            updateStmt("job", "jb_id", $jb_id, array("jb_status", 2, "jb_finishtime", $jb_finishtime_new));
          }
        }
        if ($jb_id_permanent_pre != "") { $changes_str .= "|\$jb_id_permanent_pre=$jb_id_permanent_pre"; }
        if ($changes_text == ""):
          $changes_text = ", keine Änderung der Auftragsdaten";
        else:
          // Versionszähler bei jeder echten Änderung hochzählen
          $tmpArr = array("jb_version", $db->getOne("SELECT jb_version FROM job WHERE jb_id = '$jb_id'") + 1);
          updateStmt("job", "jb_id", $jb_id, $tmpArr);
        endif;
      endif;
      $changes_text .= $job_checkboxes;
      if ($changes_text != "")
        $changes_text = " (" . substr($changes_text, 2) . ")";
      writeToLogDB(($job_is_new == true ? 162 : 163), $hq_id, $jb_id, $usr_id, "", "", "", $jobMode . $changes_text . $changes_str . ($hq_id_exec != $hq_id ? "|HQ_ID_EXEC=$hq_id_exec" : "") . ($jb_longhaul == 1 ? "|JB_LONGHAUL=$jb_longhaul" : ""));
    }
    else
    {
      if ($job_checkboxes != "")
        $job_checkboxes = " (" . substr($job_checkboxes, 2) . ")";
      if ($jobMode == "Neu") // neuer Job, hier aus Kopie; $jobMode kann hier auch noch Nacherfassung sein
        $jobMode = "Erfassung aus Kopie";
//        $jobMode = "Erfassung aus Kopie von Nr. $jb_id_org";
      writeToLogDB(25, $hq_id, $jb_id, $usr_id, "", "", "", $jobMode . $job_checkboxes . "|JB_ID_ORG=$jb_id_org" . ($hq_id_exec != $hq_id ? "|HQ_ID_EXEC=$hq_id_exec" : ""));
    }


// HIER PDA-COMMAND EINFÜHREN!!!
//insertPDACommand
//      $currentTime = getDateTime("0");
//
//insertPDACommand($hq_id, $crId, "4", "1", $jb_id_storno, $currentTime, ""); 


//writeLog_("../log/job2_options_", trace_execution_time_stop() . " '../jobs/job_options.php' job saved, '$jobMode': \$jb_id=$jb_id_log , \$usr_id=$usr_id, \$job_is_new=$job_is_new, \$getPriceOnly=$getPriceOnly");    // Transaktion abschliessen
//trace_execution_time_start();
    TA("COMMIT");
    if ($sp_id_block > 0) {
      updateStmt("phoenix_log.semaphor", "sp_id", $sp_id_block, array("sp_obj_id", 0));
    }
    if (!existsEntry("job", array("jb_id", $jb_id))):
      if ($sp_id > 0) {
        $db->query("UPDATE phoenix_log.semaphor SET sp_obj_id = " . $jb_id . ", sp_content = CONCAT(sp_content, '-FAIL (" . $usr_id . ", " . date("Y-m-d H:i:s") . ")') WHERE sp_id = " . $sp_id);
      }
      $post_vars = "";
      foreach($HTTP_POST_VARS as $key => $value) {
		$post_vars .= "<input type=\"hidden\" name=\"" . $key . "\" value=\"" . $value . "\">\n";
      }
      include_once("../include/email/htmlMimeMail.php");
      $mailObj = new htmlMimeMail();
//      $mailObj->setFrom("auto-mailer@assecutor.de");
      $mailObj->setFrom("support@assecutor.de");
      $mailObj->setSubject("Auftrag " . $jb_id . " wurde nicht geschrieben!");
      $mailObj->setText($post_vars);
      $mailResult = $mailObj->send(array("ca@assecutor.de"), 'smtp');
//      $mailResult = $mailObj->send(array("support@assecutor.de"), 'smtp');
    else:
      if ($sp_id > 0) {
        $db->query("UPDATE phoenix_log.semaphor SET sp_obj_id = " . $jb_id . ", sp_content = CONCAT(sp_content, '-OK (" . $usr_id . ", " . date("Y-m-d H:i:s") . ")') WHERE sp_id = " . $sp_id);
      }
    endif;
    $jb_id_log = $jb_id;
  else:
    // Transaktion abbrechen
    TA("ROLLBACK");
    if ($sp_id_block > 0) {
      updateStmt("phoenix_log.semaphor", "sp_id", $sp_id_block, array("sp_obj_id", 0));
    }
    if ($sp_id > 0) {
      $db->query("UPDATE phoenix_log.semaphor SET sp_obj_id = " . $jb_id . ", sp_content = CONCAT(sp_content, '-RB (" . $usr_id . ", " . date("Y-m-d H:i:s") . "), \$addressValid = \"" . $addressValid . "\"') WHERE sp_id = " . $sp_id);
    }
    // Fenster nach Meldung nicht schliessen
    $killAfterUpdate = false;
// Hier liegt der Hase im Pfeffer wg. der fehlerhaften neuen Jobs nach Adressänderungen in einem bestehenden Auftrag
    if ($job_is_new)
      $jb_id = "";
  endif;
  TA("END");
  $statusMessage = $statusMessageTxt;
//writeLog_("../log/job2_options_", trace_execution_time_stop() . " '../jobs/job_options.php' job saved, '$jobMode': \$jb_id=$jb_id_log , \$usr_id=$usr_id, \$job_is_new=$job_is_new, \$getPriceOnly=$getPriceOnly");
//trace_execution_time_start();

elseif ($toursubmit == "Senden" && $getPriceOnly == 1):
      // Nur Preisermittlung
      // Auch hier muss der payer bekannt sein, da cs_inv_mode von ihm abhängt
  // Servicetype-Name (Fahrrad etc.)
  $srvt_name = $db->getOne(
    "SELECT mt_value FROM metatype WHERE mt_sort = '$vht_id' AND mt_type = 'vehicletype'");
  // Ermittlung der Kostenübernahme
  // wenn Fixpreis, dann keine Kosterfassung in tourservice
    $costsplit_count = 0;
    for ($i = 0; $i < count($jobList); $i++):
      if ($jobList[$i][JL_CSC_ID] == ""):
        if ($jobList[$i][JL_TR_COMP] == "" ||
          $jobList[$i][JL_AD_STREET] == "" ||
          $jobList[$i][JL_TR_HSNO] == "" ||
          $jobList[$i][JL_AD_ZIPCODE] == "" ||
          $jobList[$i][JL_AD_CITY] == ""):
          // Abbruchbedingung: csc_id leer und nicht genügend Angaben für eine
          // neue Kostenstelle -> Auftrag vollständig durchlaufen
            break;
        endif;
      else:
        // csc_id gesetzt:
        // wenn Kostenteilung, dann diese Kostenstelle mitzählen
        $costsplit_count++;
        if ($jobList[$i][JL_CSC_ID_PAYER] == "true"):
          $csc_id_payer = $jobList[$i][JL_CSC_ID];
          // Payer gefunden:
          // Anzahl Payer auf 1 setzen
          $costsplit_count = 1;
          // Grundpreis des Auftrags (Anfahrtskosten) speichern
          // wenn Kostensplit, wird er später anteilig bei jeder Etappenstelle einzeln gespeichert
//          saveServiceCosts("Grundpreis", $srvt_name, $hq_id, $cs_id, $jb_id, 0, $jb_ordertime, 0, 1, (($getPriceOnly == 1 || $jobbatch_mode) ? 1 : 0), $jb_cash, (($jb_costsplit == "false" || MASK_CASH_PAYER_SELECT == "1") ? $csc_id_payer : ""), $jb_storno, false, false, false);
          break;
        endif;
      endif;
    endfor;

  // potentiellen Drittzahler berücksichtigen.
  // Der wird direkt übergeben und ist in der job_list nicht vorhanden!!!
  if ($csc_id_payer != "" && $csc_id_payer != "0")
    $costsplit_count = 1;
//  $csc_id_payer = "";
  // Barzahlung berücksichtigen
  if ($jb_cash == "true"):
    // Achtung: wenn MASK_CASH_PAYER_SELECT gesetzt, dann ist auf jeden Fall ein Bezahler
    // gesetzt, der natürlich auch erhalten bleiben muss!
    if (MASK_CASH_PAYER_SELECT != "1"):
      $csc_id_payer = "-1";
      if (CSC_ID_PAYER_CASH != ""):
        $csc_id_payer = CSC_ID_PAYER_CASH;
      endif;
    endif;
    $costsplit_count = 1;
  endif;

  // invmode ermitteln (ist abhängig von dem aktuellen Bezahler)
  $cs_id = getFieldValueFromId("costcenter", "csc_id", "$csc_id_payer", "cs_id");
  $cs_invmode = getFieldValueFromId("customer", "cs_id", "$cs_id", "cs_invmode");
      // Preise sollen auch ermittelt werden können, wenn nur Adresse
      // vorhanden (sogar wenn falsch!) -> nur im PLZ zu PLZ-Modus möglich
  $jb_ordertime = "";
  if ($tag == "" || $monat == "" || $jahr == "" || $stunde == "" || $minute == ""):
    if ($jb_id == ""):
      $today = getdate();
      $jb_ordertime = $today['year'] . "-" . $today['mon'] . "-" . $today['mday'] . " "
        . $today['hours'] . ":" . $today['minutes'] . ":" . $today['seconds'];
    else:
      $jb_ordertime = $db->getOne("SELECT jb_ordertime FROM job WHERE jb_id = '$jb_id'");
    endif;
  else:
    $jb_ordertime = "$jahr-$monat-$tag $stunde:$minute:00";
  endif;
  // Grundpreis
  // Servicetype-Name (Fahrrad etc.)
  $srvt_name = $db->getOne(
    "SELECT mt_value FROM metatype WHERE mt_sort = '$vht_id' AND mt_type = 'vehicletype'");

  // Auch Treibstoffzuschlag in Prozent ermitteln
  $jb_markup = getFuelMarkup($srvt_name, (trim($cs_id) != "" ? $cs_id : 0), $hq_id, $jb_ordertime);
  list ($fp, $fd, $fpm, $final_cr_price, $final_cr_discount, $final_cr_price_markup, $customer_specific, $special_address, $validfrom) =
    saveServiceCosts("Grundpreis", $srvt_name, $hq_id, $cs_id, $jb_id, 0, $jb_ordertime, 0, $costsplit_count, (($getPriceOnly == 1 || $jobbatch_mode) ? 1 : 0), $jb_cash, (($jb_costsplit == "false" || MASK_CASH_PAYER_SELECT == "1") ? $csc_id_payer : ""), $jb_storno, false, false, false, $jb_markup, $fuel_cr_markup, $vht_id);
  $fullPrice += round($fp * ((100-$fd)/100), 2);
  $discount_sign = ($special_address || $discount_sign == "**" ? "**"
  : ($discount_sign = ($fd > 0 || $customer_specific || $discount_sign == "*" ? "*" : "")));
  $jb_cr_subtotal += round($final_cr_price_markup * ((100-$fd-$self_service_discount)/100), 2);
  $fullCrPrice += round($final_cr_price * ((100-$fd-$self_service_discount)/100), 2);
  // PLZ-Preis
//print_r($jobList);
  // Anzahl Kostenstellen für Preisberechnung ermitteln
  $maxTour = count($jobList);
  for ($i = 0; $i < count($jobList); $i++):
    if ($jobList[$i][JL_CSC_ID] == ""):
      if ($jobList[$i][JL_TR_COMP] == "" ||
        $jobList[$i][JL_AD_STREET] == "" ||
        $jobList[$i][JL_TR_HSNO] == "" ||
        $jobList[$i][JL_AD_ZIPCODE] == "" ||
        $jobList[$i][JL_AD_CITY] == ""):
        // Abbruchbedingung: csc_id leer und nicht genügend Angaben für eine
         // neue Kostenstelle -> Auftrag vollständig durchlaufen
          $maxTour = $i - 1;
           break;
      endif;
    endif;
  endfor;
  for ($i = 0; $i < $maxTour; $i++):
//reportDie ($jobList[$i][JL_AD_ZIPCODE] . ", " . $jobList[$i+1][JL_AD_ZIPCODE]);
      // die Hamburger Fake-PLZs sind für Preisberechnung wichtig ...
//print_r($jobList);
//reportDie ("'" . $jobList[$i][JL_TR_MEDIATIONAREA_ID] . "'");
    // ... und Berlin hat noch eine andere Extra-Wurst:
    // Bestimmte wohldefinierte Adressen sind bestimmten Bereichen zugeordnet ...
    // ... somit muss die vollständige Adresse übergeben werden!
    $ad_id1 = $jobList[$i][JL_AD_ZIPCODE] . "³" . $jobList[$i][JL_AD_STREET] . "³" . $jobList[$i][JL_TR_HSNO];
    $zipcode1 = false;
    if ($jobList[$i][JL_TR_MEDIATIONAREA_ID] != 0):
       $ad_id1 = $jobList[$i][JL_TR_MEDIATIONAREA_ID];
      if ($ad_id1 == -1):
        $ad_id1 = getMediationarea_id($hq_id, $jobList[$i][JL_AD_ZIPCODE], $jobList[$i][JL_AD_STREET], $jobList[$i][JL_TR_HSNO]);
        array_push ($setMediation_area_idArr, $i, $ad_id1);
      endif;
       $zipcode1 = true;
    endif;
    $ad_id2 = $jobList[$i+1][JL_AD_ZIPCODE] . "³" . $jobList[$i+1][JL_AD_STREET] . "³" . $jobList[$i+1][JL_TR_HSNO];
    $zipcode2 = false;
    if ($jobList[$i+1][JL_TR_MEDIATIONAREA_ID] != 0):
      $ad_id2 = $jobList[$i+1][JL_TR_MEDIATIONAREA_ID];
      if ($ad_id2 == -1):
        $ad_id2 = getMediationarea_id($hq_id, $jobList[$i+1][JL_AD_ZIPCODE], $jobList[$i+1][JL_AD_STREET], $jobList[$i+1][JL_TR_HSNO]);
        array_push ($setMediation_area_idArr, $i+1, $ad_id2);
      endif;
      $zipcode2 = true;
    endif;
    //ab hier geht's normal weiter
//reportDie ("saveServiceCosts($ad_id1, $ad_id2, $hq_id, $cs_id, $jb_id, ($i + 1), $jb_ordertime, $distance, $costsplit_count, $getPriceOnly, $jb_cash, " . (($jb_costsplit == "false" || MASK_CASH_PAYER_SELECT == "1") ? $csc_id_payer : "") . ", $jb_storno, $zipcode1, $zipcode2);");
    list ($fp, $fd, $fpm, $final_cr_price, $final_cr_discount, $final_cr_price_markup, $customer_specific, $special_address, $validfrom) =
      saveServiceCosts($ad_id1, $ad_id2, $hq_id, $cs_id, $jb_id, ($i + 1), $jb_ordertime, $distance, $costsplit_count, $getPriceOnly, $jb_cash, (($jb_costsplit == "false" || MASK_CASH_PAYER_SELECT == "1") ? $csc_id_payer : ""), $jb_storno, $zipcode1, $zipcode2, true, $jb_markup, $fuel_cr_markup, $vht_id);
    $fullPrice += round($fp * ((100-$fd)/100), 2);
    $discount_sign = ($special_address || $discount_sign == "**" ? "**"
    : ($discount_sign = ($fd > 0 || $customer_specific || $discount_sign == "*" ? "*" : "")));
    $jb_cr_subtotal += round($final_cr_price_markup * ((100-$fd-$self_service_discount)/100), 2);
    $fullCrPrice += round($final_cr_price * ((100-$fd-$self_service_discount)/100), 2);
  endfor;
endif;

/* ********************************************************************** */
// Inhalt des Frames aufbauen und ausgeben
//
// nur wenn if $getPriceOnly != 1 UND WENN NICHT von "check_jb_permanent.php" aufgerufen

if ($getPriceOnly != 1 &&
  !(isset($check_jb_permanent_flag) && $check_jb_permanent_flag == true)):
  // Wartezeiten für die Annahme durch den gewünschten Kurier
  //$jb_waittime_options = addOptionsFromTable(
  //  "metatype", "mt_sort", "mt_value", "mt_sort", "mt_type = 'waittime'");
  // Fahrzeugtypen
  $mask_exclude_vht_ids_cs = getParameterValue("0", "MASK_EXCLUDE_VHT_IDS_CS", $hq_id);
  if ($mask_exclude_vht_ids_cs != "")
    $mask_exclude_vht_ids_cs = " AND NOT mt_sort IN (" . $mask_exclude_vht_ids_cs . ")";
  $vht_id_options = addOptionsFromTable(
    "metatype", "mt_sort", "mt_value", "mt_sort", "mt_type = 'vehicletype' AND mt_sort > 0" . $mask_exclude_vht_ids_cs,
    getFieldValueFromId("headquarters", "hq_id", "$hq_id", "hq_vht_default"));
  // gespeicherte Touren
  $savedTour_options = addOptionsFromTable(
    "job", "jb_id", "jb_tourname", "jb_tourname", "csc_id_payer = '$csc_id_orderer' AND LENGTH(jb_tourname) > 0");
// gespeicherte Touren darf nicht mehr disabled sein, da durch die Auswahl der Referesh ausgelöst wird!
//  $savedTour_disabled = ($savedTour_options == "") ? "disabled" : "";
  $savedTour_disabled = "";
// Dauerauftrags-Rhythmen
  $jb_permanent_options = addOptionsFromTable(
    "metatype", "mt_sort", "mt_value", "mt_sort", "mt_type = 'permanent'");
  $jb_sales_tax_rate_sign_options = addOptionsFromTable(
    "tax", "tx_id", "tx_sign", "tx_sign", "", "4");
// Default-Steuersatz
  $sales_tax_rate_value = $db->getOne("SELECT tx_value FROM tax WHERE tx_id = 4");

  // Die externen Kostenstellen werden in ein Javascript-Array geschrieben,
  // damit später überprüft werden kann, ob eine gewählte Etappenstelle
  // Bezahler sein kann

  if ($cs_id != 0):
    // Kundenauftrag -> nur externe Kostenstelle des Kunden übernehmen
    $sqlquery = "SELECT costcenter.csc_id, costcenter.csc_path, costcenter.csc_is_extern" .
      " FROM costcenter, costcenteraddress " .
      " WHERE costcenter.csc_id = costcenteraddress.csc_id" .
      " AND costcenter.cs_id = '$cs_id' AND costcenteraddress.adt_id = '4'";
    $res = $db->query($sqlquery);
    if (DB::isError($res)) reportDie ("$PHP_SELF: '$sqlquery': " . $res->getMessage());
//    $csc_id_extern_list = "var csc_id_extern_list = new Array();\n";
    // Erkennungsmerkmal ist csc_path, welcher hier erst einmal ermittelt
    // werden muss
    $csc_id_root = getFieldValueFromId("customer", "cs_id", "$cs_id", "csc_id");
    $csc_name_root = getFieldValueFromId("costcenter", "csc_id", "$csc_id_root", "csc_name");
    $csc_path_start = "//" . my_str_check($csc_name_root) . "//Extern//";
    // externe Kostenstellen in Array schreiben
//    $i = 0;
//    while ($row = $res->fetch_assoc()):
//      if (substr($row["csc_path"], 0, strlen($csc_path_start)) == $csc_path_start)
//        $csc_id_extern_list .= "csc_id_extern_list[" . $i++ . "] = \"" . $row["csc_id"] . "\";\n";
//    endwhile;
//    $res->free();
  else:
//    // Zentralenauftrag -> nur externe Kostenstelle des Zentrale übernehmen
//    $res = $db->query("SELECT costcenter.csc_id " .
//      " FROM costcenter, customer " .
//      " WHERE costcenter.cs_id = customer.cs_id" .
//      " AND customer.hq_id = '$hq_id' AND costcenter.csc_is_extern = '1'");
//    if (DB::isError($res))
//      reportDie ("$PHP_SELF: 'SELECT costcenter.csc_id, costcenter.csc_path ...': " . $res->getMessage());
//    $csc_id_extern_list = "var csc_id_extern_list = new Array();\n";
//    $i = 0;
//    while ($row = $res->fetch_assoc()):
//      $csc_id_extern_list .= "csc_id_extern_list[" . $i++ . "] = \"" . $row["csc_id"] . "\";\n";
//    endwhile;
//    $res->free();
  endif;
  // jb_id must be modified according to current action
  if ($toursubmit == "Senden"):
    if ($addressValid != ""): // Auftrag ok
      if ($killAfterUpdate):
        $jb_id = "killMe"; // Aufrag wurde geändert, Auftragserfassung beenden
      else:
        $jb_id = ""; // Neuer Auftrag wurde gespeichert, nächster Auftrag kann eingegeben werden
      endif;
    else:
      $jb_id = $jb_id; // Änderung war nicht ok, jb_id muss erhalten bleiben
    endif;
  else:
    $jb_id = $jb_id; // Erster Aufruf: wenn jb_id gesetzt, dann Änderung, sonst erste Neuerfassung
  endif;


//  if ($phpVersion >= "7.0"):
//    $tpl = new HTML_Template_IT();
//  else:
//    $tpl = new IntegratedTemplate();
//  endif;
//  $tpl->loadTemplatefile("job_options.tpl.htm", true, true);
  $output = file_get_contents("job_options.tpl.htm");
//  $tpl->setCurrentBlock("javascript");
  $output = str_replace("{_csc_id_extern_list_}",  /* $csc_id_extern_list . */ $jsAddNewExternCostcenter, $output);
//  $tpl->setVariable("_ph_", getPublicHolidays(getDateTime("year"), "1", "1"));
  $output = str_replace("{_hq_id_}", $hq_id, $output);
  $output = str_replace("{_cs_id_}", $cs_id, $output);
  $output = str_replace("{_cs_id_ec_}", ec($cs_id), $output);
  $output = str_replace("{_csc_id_orderer_}", $csc_id_orderer, $output);
  $output = str_replace("{_csc_id_orderer_ec_}", $csc_id_orderer_ec, $output);
  $output = str_replace("{_csc_id_orderer_root_ec_}", ec(getFieldValueFromId("employee", "usr_id", "$usr_id", "csc_id")), $output);
  $output = str_replace("{_jb_id_}", $jb_id, $output);
  $output = str_replace("{_jb_copy_}", $jb_copy, $output);
  $output = str_replace("{_dbhistory_}", $dbhistory, $output);
  $output = str_replace("{_self_service_discount_}", $self_service_discount, $output);
  /*     
   => Funktion "getParameterValue" in dbglobal, also erreichbar
 
   => Parameter "$emp_id" ist schon immer in der Session definiert und existiert
 
   => $empModeCopyJob holt den Parameter für Auftragskopie
          0 = Default = Dispo-Modus = wie jetzt  
          1 = Buchhaltungs-Modus = Kopie mit Datum, Fahrzeugtyp und Fahrer
 
      $empModeLaterJob holt den Parameter für das Nacherfassungs-Flag
          0 = Default = Dispo-Modus = wie jetzt = Flag nicht gesetzt
          1 = Buchhaltungs-Modus = Flag automatisch gesetzt
  */  
  $output = str_replace("{_empModeCopyJob_}", getParameterValue($emp_id, "MODE_COPY_JOB"), $output);
  $output = str_replace("{_empModeLaterJob_}", getParameterValue($emp_id, "MODE_LATER_JOB"), $output);
  $output = str_replace("{_prev_jb_id_}", $prev_jb_id, $output);
  $output = str_replace("{_cr_id_order_list_}", "var MASK_COURIER_SORT_BY_OCCUPIED = \"0\";\n" . (isset($cr_id_order_list) ? $cr_id_order_list : "") . (isset($customercourier_list) ? $customercourier_list : ""), $output);
  $output = str_replace("{_when_}", "var when = \"" . date("H:i") . "\";", $output);
  $output = str_replace("{_hq_id_}", $hq_id, $output);
  $output = str_replace("{_cs_jbedit_cr_}", getFieldValueFromId("customer", "cs_id", "$cs_id", "cs_jbedit_cr"), $output);
  if (getFieldValueFromId("customer", "cs_id", "$cs_id", "cs_jbedit_cr") == "1"):
    $output = str_replace("{_cs_jbedit_cr_list_}", getCustomerCouriers($db, $cs_id), $output);
  else:
    $output = str_replace("{_cs_jbedit_cr_list_}", "", $output);
  endif;
  if (trim($db->getOne("SELECT cs_filter_jbedit FROM customer WHERE cs_id = $cs_id")) != ""):
    $output = str_replace("{_cs_jbedit_cs_filter_}", "1", $output);
  else:
    $output = str_replace("{_cs_jbedit_cs_filter_}", "", $output);
  endif;
  $output = str_replace("{_cs_jbedit_filter_list_}", getCustomerFilters($db, $cs_id), $output); 
  $output = str_replace("{_csc_id_payer_cash_}", CSC_ID_PAYER_CASH, $output);
  $output = str_replace("{_cash_payer_select_}", MASK_CASH_PAYER_SELECT, $output);
  $output = str_replace("{_auto_refresh_}", MASK_AUTO_REFRESH, $output);
  $output = str_replace("{_commission_no_on_}", MASK_COMMISSION_NO, $output);
  $output = str_replace("{_ask_defaultpayer_change_}", MASK_ASK_DEFAULTPAYER_CHANGE, $output);
  $output = str_replace("{_manual_disposition_}", MASK_MANUAL_DISPOSITION, $output);
  $output = str_replace("{_mask_cr_price_mode_}", MASK_CR_PRICE_MODE, $output);
  $output = str_replace("{_mask_maxtour_}", MASK_MAXTOUR, $output);
  $output = str_replace("{_hq_workmode_}", $hq_workmode, $output);
  $output = str_replace("{statusMessage}", $statusMessage, $output);
  if ($addressValid != "ok"):

    // restore values submitted in the form
    // ONLY job_options!!! (the other forms do still exist)
    $javascript = "var addressValid = false;\n";

    // Kurierfilter berücksichtigen
    $jb_cr_filter_list = array_merge(explode(",", $jb_cr_filter), explode(",", $jb_cr_filter_opt));

    // Erst alle Kurierfilter zurücksetzen
    $javascript .=
      "for (var i = 0; i < parent.job_options.cfl.length; i++)\n" .
      "  parent.job_options.cfl[i][3] == 0;\n";
    // Alle Kurierfilter neu setzen
    for ($i = 0; $i <= count($jb_cr_filter_list); $i++)
    {
      $javascript .=
        "for (var i = 0; i < parent.job_options.cfl.length; i++)\n" .
        "{\n" .
        "  if (parent.job_options.cfl[i][0] == \"" . trim($jb_cr_filter_list[$i]) . "\")\n" .
        "  {\n" .
        "    parent.job_options.cfl[i][3] = 1;\n" .
        "    break;\n" .
        "  }\n" .
        "}\n";
    }
//    if ($jb_cr_filter . $jb_cr_filter_opt != "")
//      $javascript .=
//        "parent.job_options.document.tourOptions.jb_cr_filterButton.value = \"Filter*\";";

    $javascript .=
      setJavascriptOpenerFormVals("job_options", "tourOptions",
      array("cr_id_order" => $cr_id_order, "vht_id" => $vht_id, "jb_weight" => $jb_weight,
        "jb_crvh_length" => $jb_crvh_length, "jb_crvh_width" => $jb_crvh_width,
        "jb_crvh_height" => $jb_crvh_height, "jb_crvh_position" => $jb_crvh_position,
        "jb_permanent" => $jb_permanent,
        "jahr" => $jahr, "monat" => $monat, "tag" => $tag, "stunde" => $stunde,
        "minute" => $minute, "endejahr" => $endejahr, "endemonat" => $endemonat, "endetag" => $endetag,
        "savedTour" => "", "jb_fixprice" => $jb_fixprice_ori, "jb_serviceprice" => $jb_serviceprice_ori,
        "jb_cr_price" => $jb_cr_price_ori,
        "jb_freetext_1" => my_str_check_http($jb_freetext_1),
        "jb_dispoinfo" => my_str_check_http($jb_dispoinfo),
        "jb_warnjahr" => $jb_warnjahr, "jb_warnmonat" => $jb_warnmonat, "jb_warntag" => $jb_warntag, "jb_warnstunde" => $jb_warnstunde,
        "jb_warnminute" => $jb_warnminute,
        "jb_cr_filter" => $jb_cr_filter,
        "jb_cash_hidden" => $jb_cash, "jb_costsplit_hidden" => $jb_costsplit,
        "jb_cr_filter_opt" => $jb_cr_filter_opt, "jb_permanent2_hidden" => $jb_permanent2,
        "jb_sales_tax_rate" => $jb_sales_tax_rate, "jb_sales_tax_rate_sign" => $jb_sales_tax_rate_sign,
        "jb_tourname" => $jb_tourname, "jobList" => my_str_check_http($jobListOri)), ""
      );
    if (MASK_CR_PRICE_MODE == "1") {
      $javascript .=
        setJavascriptOpenerFormVals("job_options", "tourOptions",
          array("jb_cr_serviceprice" => $jb_cr_serviceprice), "");
    }
    if (MASK_WAITTIME_ENABLED == "1"):
      $javascript .=
        setJavascriptOpenerFormVals("job_options", "tourOptions",
        array("jb_waittime_hour" => $jb_waittime_hour, "jb_waittime_minute" => $jb_waittime_minute), ""
      );
    endif;
    $javascript .=
      setJavascriptOpenerChecked("job_options", "tourOptions", "jb_waitstorno",
        (($jb_waitstorno != "1") ? "false" : "true"), "") .
      setJavascriptOpenerChecked("job_options", "tourOptions", "afterwards",
        (($afterwards != "1") ? "false" : "true"), "") .
      setJavascriptOpenerChecked("job_options", "tourOptions", "jb_status_manual",
        (($jb_status_manual != "1") ? "false" : "true"), "") .
      setJavascriptOpenerChecked("job_options", "tourOptions", "jb_incomplete",
        (($jb_incomplete != "1") ? "false" : "true"), "") .
      setJavascriptOpenerChecked("job_options", "tourOptions", "jb_globaljob",
        (($jb_globaljob != "1") ? "false" : "true"), "") .
      setJavascriptOpenerDisabled("job_options", "tourOptions", "jb_permanent",
        (($jb_reserv == 1 || $jb_permanent != "") ? "false" : "true"), "") .
      "checkJb_permanent();\n" .
      setJavascriptOpenerChecked("job_options", "tourOptions", "jb_permanent2_0",
        ((substr($jb_permanent2, 0, 1) != "1") ? "false" : "true"), "") .
      setJavascriptOpenerChecked("job_options", "tourOptions", "jb_permanent2_1",
        ((substr($jb_permanent2, 1, 1) != "1") ? "false" : "true"), "") .
      setJavascriptOpenerChecked("job_options", "tourOptions", "jb_permanent2_2",
        ((substr($jb_permanent2, 2, 1) != "1") ? "false" : "true"), "") .
      setJavascriptOpenerChecked("job_options", "tourOptions", "jb_permanent2_3",
        ((substr($jb_permanent2, 3, 1) != "1") ? "false" : "true"), "") .
      setJavascriptOpenerChecked("job_options", "tourOptions", "jb_permanent2_4",
        ((substr($jb_permanent2, 4, 1) != "1") ? "false" : "true"), "") .
      setJavascriptOpenerChecked("job_options", "tourOptions", "jb_permanent2_5",
        ((substr($jb_permanent2, 5, 1) != "1") ? "false" : "true"), "") .
      setJavascriptOpenerChecked("job_options", "tourOptions", "jb_permanent2_6",
        ((substr($jb_permanent2, 6, 1) != "1") ? "false" : "true"), "") .
      "checkJb_permanent2();\n" .
      ($comp_payer != "" ? "setCsc_id_payer('$csc_id_payer', '$comp_payer');\n" : "");
    // cs_eid_list wiederherstellen, sonst haut es mit dem Bezahler nicht hin...
    $payer_found = false;
    for ($i = 0; $i < count($jobList); $i++):
      $csc_id = $jobList[$i][JL_CSC_ID];      
      $javascript .= javascriptAdd_cs_eid($csc_id, "");
      if ($csc_id == $csc_id_payer):
        $payer_found = true;
      endif;
    endfor;
    // Wenn Drittzahler, dann auch dessen Daten wiederherstellen
    if (!$payer_found):
      $javascript .= javascriptAdd_cs_eid($csc_id_payer, "");
    endif;
    // Wenn der Originalaufrag einen Festpreis hatte und ein Discount berücksichtigt wurde,
    // dann muss die entsprechende Checkbox gesetzt sein!
    if ($jb_fixprice != "" || $jb_serviceprice != ""):
      $javascript .=
        setJavascriptOpenerChecked("job_options", "tourOptions", "jb_discount",
          (($jb_discount > 0) ? "true" : "false"), "");
    endif;
    $javascript .=
      "checkSendTour();\n";
  else:
    $javascript = "var addressValid = true;\n";
  endif;

  $output = str_replace("{_javascript_}", $javascript, $output);

  if ($csc_id_orderer != '0'):
    // Kundenauftrag: Immer Rechnungszahler, immer der Kunde selbst!
    // d.h. er wird in der Maske als Drittzahler eingestellt
    $comp_payer = $db->getOne(
      "SELECT cmp.cmp_comp FROM company AS cmp, customer AS cs, costcenter AS csc" .
      " WHERE cmp.cmp_id = cs.cmp_id AND cs.cs_id = csc.cs_id AND csc.csc_id = '$csc_id_orderer'");
    $comp_payer = my_str_check_js($comp_payer);
    $javascript =
      "setCsc_id_payer('$csc_id_orderer', '$comp_payer');\n";
//      "curCsc_id_payer=$csc_id_orderer;\n";
    $javascript .= javascriptAdd_cs_eid($csc_id_orderer, "");
    $output = str_replace("{_csc_id_start_code_js_}", $javascript, $output);
    if (!defined("MASK_WAITTIME_ENABLED"))
      define ("MASK_WAITTIME_ENABLED", "0");
    if (!defined("MASK_DATESELECTFIELDS_ENABLED"))
      define ("MASK_DATESELECTFIELDS_ENABLED", "0");
    if (!defined("MASK_CHECK_DISCOUNT"))
      define ("MASK_CHECK_DISCOUNT", "1");
    if (!defined("MASK_SERVICE_PRICE"))
      define ("MASK_SERVICE_PRICE", "1");
    define ("CUSTOMER_JOB", "1");
  else:
    $output = str_replace("{_csc_id_start_code_js_}", mkCsc_id_start($csc_id_start), $output);
    define ("CUSTOMER_JOB", "0");
  endif;

//  $tpl->parseCurrentBlock("javascript");

//  $tpl->setCurrentBlock("touroptions");
  $output = str_replace("{_csc_id_orderer_}", ec($csc_id_orderer), $output);
  $_request_token_ = date("YmdHis") . str_pad(gettimeofday()["usec"], 6, '0') . (isset($usr_id) ? $usr_id : "000000");
  insertStmt("phoenix_log.semaphor", array("sp_obj_type", "usr", "sp_obj_id", (isset($usr_id) ? $usr_id : "000000"), "sp_fieldname", "request_token", "sp_content", $_request_token_, "sp_context", "NOT_SENT", "sp_createtime", date("Y-m-d H:i:s")));
  $output = str_replace("{_request_token_}", $_request_token_, $output);
  $output = str_replace("{_ec_jb_id_}", ec($jb_id), $output);
  if (MASK_WAITTIME_ENABLED != "1"):
    $output = str_replace("{WAITTIME_DISABLED_START}", "<!--", $output);
    $output = str_replace("{WAITTIME_DISABLED_END}", "-->", $output);
  else:
    $output = str_replace("{WAITTIME_DISABLED_START}", "", $output);
    $output = str_replace("{WAITTIME_DISABLED_END}", "", $output);
  endif;
  if (MASK_DATESELECTFIELDS_ENABLED != "1"):
    $output = str_replace("{DATESELECTFIELDS_DISABLED_START}", "<!--", $output);
    $output = str_replace("{DATESELECTFIELDS_DISABLED_END}", "-->", $output);
    $output = str_replace("{DATEINPUTFIELDS_DISABLED_START}", "", $output);
    $output = str_replace("{DATEINPUTFIELDS_DISABLED_END}", "", $output);
    $output = str_replace("{TIMESELECTFIELDS_DISABLED_START}", "<!--", $output);
    $output = str_replace("{TIMESELECTFIELDS_DISABLED_END}", "-->", $output);
    $output = str_replace("{TIMEINPUTFIELDS_DISABLED_START}", "", $output);
    $output = str_replace("{TIMEINPUTFIELDS_DISABLED_END}", "", $output);
  else:
    $output = str_replace("{DATESELECTFIELDS_DISABLED_START}", "", $output);
    $output = str_replace("{DATESELECTFIELDS_DISABLED_END}", "", $output);
    $output = str_replace("{DATEINPUTFIELDS_DISABLED_START}", "<!--", $output);
    $output = str_replace("{DATEINPUTFIELDS_DISABLED_END}", "-->", $output);
    $output = str_replace("{TIMESELECTFIELDS_DISABLED_START}", "", $output);
    $output = str_replace("{TIMESELECTFIELDS_DISABLED_END}", "", $output);
    $output = str_replace("{TIMEINPUTFIELDS_DISABLED_START}", "<!--", $output);
    $output = str_replace("{TIMEINPUTFIELDS_DISABLED_END}", "-->", $output);
  endif;
  if (MASK_CHECK_DISCOUNT != "1"):
    $output = str_replace("{DISCOUNT_DISABLED_START}", "<!--", $output);
    $output = str_replace("{DISCOUNT_DISABLED_END}", "-->", $output);
  else:
    $output = str_replace("{DISCOUNT_DISABLED_START}", "", $output);
    $output = str_replace("{DISCOUNT_DISABLED_END}", "", $output);
  endif;
  if (MASK_SERVICE_PRICE != "1"):
    $output = str_replace("{SERVICEPRICE_DISABLED_START}", "<!--", $output);
    $output = str_replace("{SERVICEPRICE_DISABLED_END}", "-->", $output);
  else:
    $output = str_replace("{SERVICEPRICE_DISABLED_START}", "", $output);
    $output = str_replace("{SERVICEPRICE_DISABLED_END}", "", $output);
  endif;
  if (CUSTOMER_JOB == "1"):
    $output = str_replace("{CUSTOMER_DISABLED_START}", "<!--", $output);
    $output = str_replace("{CUSTOMER_DISABLED_END}", "-->", $output);
    // Steuern hartcodiert auf 16% für Kundenaufträge
    $output = str_replace("{CUSTOMER_JB_SALES_TAX_RATE}",
      "<input type=\"hidden\" name=\"jb_sales_tax_rate_sign\" value=\"4\">" .
      "<input type=\"hidden\" name=\"jb_sales_tax_rate\" value=\"$sales_tax_rate_value\">", $output
    );
    if (getFieldValueFromId("customer", "cs_id", "$cs_id", "cs_jbedit_cr") != "1"):
      $output = str_replace("{CUSTOMER_COURIER_DISABLED_START}", "<!--", $output);
      $output = str_replace("{CUSTOMER_COURIER_DISABLED_END}", "-->", $output);
    else:
      $output = str_replace("{CUSTOMER_COURIER_DISABLED_START}", "", $output);
      $output = str_replace("{CUSTOMER_COURIER_DISABLED_END}", "", $output);
    endif;  
    if (trim($db->getOne("SELECT cs_filter_jbedit FROM customer WHERE cs_id = $cs_id")) == ""):
      $output = str_replace("{CUSTOMER_FILTER_DISABLED_START}", "<!--", $output);
      $output = str_replace("{CUSTOMER_FILTER_DISABLED_END}", "-->", $output);
    else:
      $output = str_replace("{CUSTOMER_FILTER_DISABLED_START}", "", $output);
      $output = str_replace("{CUSTOMER_FILTER_DISABLED_END}", "", $output);
    endif;
    $output = str_replace("{RANKING_JB2CRVH_MEASURE_DISABLED_START}", "<!--", $output);
    $output = str_replace("{RANKING_JB2CRVH_MEASURE_DISABLED_END}", "-->", $output);
    $RANKING_JB2CRVH_MEASURE_CS_IDS = $db->getOne("SELECT par_text FROM parameter WHERE hq_id = " . $hq_id . " AND par_key = 'RANKING_JB2CRVH_MEASURE_CS_IDS'");
    if (!in_array ($cs_id, explode(",", $RANKING_JB2CRVH_MEASURE_CS_IDS))):
      $output = str_replace("{RANKING_JB2CRVH_MEASURE_ENABLED_START}", "<!--", $output);
      $output = str_replace("{RANKING_JB2CRVH_MEASURE_ENABLED_END}", "-->", $output);
    else:
      $output = str_replace("{RANKING_JB2CRVH_MEASURE_ENABLED_START}", "", $output);
      $output = str_replace("{RANKING_JB2CRVH_MEASURE_ENABLED_END}", "", $output);
    endif;
//    if (getParameterValue("0", "CUSTOMER_MANUAL_DISPO_" . $cs_id, "0") != "1"):
      $output = str_replace("{CUSTOMER_MANUAL_DISPO_START}", "<!--", $output);
      $output = str_replace("{CUSTOMER_MANUAL_DISPO_END}", "-->", $output);
//    else:
//      $output = str_replace("{CUSTOMER_MANUAL_DISPO_START}", "", $output);
//      $output = str_replace("{CUSTOMER_MANUAL_DISPO_END}", "", $output);
//    endif;
  else:
    if (RANKING_JB2CRVH_MEASURE == "1"):
      $output = str_replace("{RANKING_JB2CRVH_MEASURE_ENABLED_START}", "", $output);
      $output = str_replace("{RANKING_JB2CRVH_MEASURE_ENABLED_END}", "", $output);
    else:
      $output = str_replace("{RANKING_JB2CRVH_MEASURE_DISABLED_START}", "<!--", $output);
      $output = str_replace("{RANKING_JB2CRVH_MEASURE_DISABLED_END}", "-->", $output);
    endif;
  endif;  

  $output = str_replace("{_cr_id_options_}", (isset($cr_id_options) ? $cr_id_options : ""), $output);
  //$output = str_replace("{_jb_waittime_options_}", $jb_waittime_options, $output);
  $output = str_replace("{_vht_id_options_}", $vht_id_options, $output);
  $output = str_replace("{_savedTour_disabled_}", $savedTour_disabled, $output);
  $output = str_replace("{_savedTour_options_}", $savedTour_options, $output);
  $output = str_replace("{_jb_permanent_options_}", $jb_permanent_options, $output);
  $output = str_replace("{_jb_sales_tax_rate_sign_options_}", $jb_sales_tax_rate_sign_options, $output);
  $output = str_replace("{_sales_tax_rate_value_}", $sales_tax_rate_value, $output);

  // *** TABINDICES und ACCESSKEYS ***
  $ti = 0;
  $output = str_replace("{_cr_id_order_tabindex_}", ++$ti, $output);
  $output = str_replace("{_crSidList_tabindex_}", ++$ti, $output);
  $output = str_replace("{_crSidList_accesskey_}", _CRSIDLIST_ACCESSKEY_, $output);
  $output = str_replace("{_jb_cr_filter_tabindex_}", ++$ti, $output);
  $output = str_replace("{_jb_cr_filter_accesskey_}", _JB_CR_FILTER_ACCESSKEY_, $output);
  $output = str_replace("{_jb_waitstorno_tabindex_}", ++$ti, $output);
  if (MASK_WAITTIME_ENABLED == "1"):
    $output = str_replace("{_jb_waittime_hour_tabindex_}", ++$ti, $output);
    $output = str_replace("{_jb_waittime_minute_tabindex_}", ++$ti, $output);
  endif;
  $output = str_replace("{_vht_id_tabindex_}", ++$ti, $output);
  $output = str_replace("{_jb_weight_tabindex_}", ++$ti, $output);
  $output = str_replace("{_jb_crvh_length_tabindex_}", ++$ti, $output);
  $output = str_replace("{_jb_crvh_width_tabindex_}", ++$ti, $output);
  $output = str_replace("{_jb_crvh_height_tabindex_}", ++$ti, $output);
  $output = str_replace("{_jb_crvh_position_tabindex_}", ++$ti, $output);
  $output = str_replace("{_tag_tabindex_}", ++$ti, $output);
  $output = str_replace("{_monat_tabindex_}", ++$ti, $output);
  $output = str_replace("{_jahr_tabindex_}", ++$ti, $output);
  $output = str_replace("{_stunde_tabindex_}", ++$ti, $output);
  $output = str_replace("{_minute_tabindex_}", ++$ti, $output);
//  $output = str_replace("{_jb_type_tabindex_}", ++$ti, $output);
//  $output = str_replace("{_jb_type_accesskey_}", _JB_TYPE_ACCESSKEY_, $output);
  $output = str_replace("{_endetag_tabindex_}", ++$ti, $output);
  $output = str_replace("{_endemonat_tabindex_}", ++$ti, $output);
  $output = str_replace("{_endejahr_tabindex_}", ++$ti, $output);
  $output = str_replace("{_jb_permanent_tabindex_}", ++$ti, $output);
  $output = str_replace("{_jb_permanent2_0_tabindex_}", ++$ti, $output);
  $output = str_replace("{_jb_permanent2_1_tabindex_}", ++$ti, $output);
  $output = str_replace("{_jb_permanent2_2_tabindex_}", ++$ti, $output);
  $output = str_replace("{_jb_permanent2_3_tabindex_}", ++$ti, $output);
  $output = str_replace("{_jb_permanent2_4_tabindex_}", ++$ti, $output);
  $output = str_replace("{_jb_permanent2_5_tabindex_}", ++$ti, $output);
  $output = str_replace("{_jb_permanent2_6_tabindex_}", ++$ti, $output);
  $output = str_replace("{_savedTour_tabindex_}", ++$ti, $output);
  $output = str_replace("{_jb_tourname_tabindex_}", ++$ti, $output);
  $output = str_replace("{_jb_tourname_}", "", $output);
  $output = str_replace("{_jb_tourname_overwrite_tabindex_}", ++$ti, $output);
  $output = str_replace("{_jb_fixprice_tabindex_}", ++$ti, $output);
  $output = str_replace("{_jb_serviceprice_tabindex_}", ++$ti, $output);
  $output = str_replace("{_jb_discount_tabindex_}", ++$ti, $output);
  $output = str_replace("{_jb_sales_tax_rate_tabindex_}", ++$ti, $output);
  $output = str_replace("{_jb_sales_tax_rate_sign_tabindex_}", ++$ti, $output);
  $output = str_replace("{_afterwards_tabindex_}", ++$ti, $output);
  $output = str_replace("{_afterwards_accesskey_}", _AFTERWARDS_ACCESSKEY_, $output);
  $output = str_replace("{_jb_globaljob_tabindex_}", ++$ti, $output);
//  $output = str_replace("{_jb_globaljob_accesskey_}", _JB_GLOBALJOB_ACCESSKEY_, $output);
  $output = str_replace("{_jb_status_manual_tabindex_}", ++$ti, $output);
  $output = str_replace("{_jb_status_manual_accesskey_}", _JB_STATUS_MANUAL_ACCESSKEY_, $output);
  $output = str_replace("{_jb_incomplete_tabindex_}", ++$ti, $output);
  $output = str_replace("{_jb_incomplete_accesskey_}", _JB_INCOMPLETE_ACCESSKEY_, $output);
  $output = str_replace("{_toursubmit_tabindex_}", ++$ti, $output);
  $output = str_replace("{_toursubmit_accesskey_}", _TOURSUBMIT_ACCESSKEY_, $output);
  // *** ***

//  $tpl->parseCurrentBlock("touroptions");
//  include("../jobs/shrink.inc.php");
//  $html_code = $tpl->get();
//  echo htmlShrink($html_code, true);
//  $tpl->show();
  echo $output;
elseif (!(isset($check_jb_permanent_flag) && $check_jb_permanent_flag == true)):
  $jb_subtotal = round($jb_fixprice * ((100-$self_service_discount)/100), 2);
  $jb_subtotal = round($jb_subtotal * (1 - ($tmp_discount_rate / 100)), 2);
  $jb_totalprice = round($jb_subtotal * (1 + ($jb_markup / 100)) + $jb_serviceprice * (1 - ($tmp_discount_rate / 100)), 2);
  $jb_markup_text = "";
  if ($jb_markup > 0)
    $jb_markup_text = " (" . str_replace(".", ",", sprintf("%01.2f", $jb_markup)) . "% Tz.)";
  $javascript = "";
  // falls mediation_areas ermittelt wurden, diese setzen    
  for ($ma = 0; $ma < count($setMediation_area_idArr); $ma += 2)   
    $javascript .= "parent.job_options.setJobList(" . $setMediation_area_idArr[$ma] . ", " . JL_TR_MEDIATIONAREA_ID . ", " . $setMediation_area_idArr[$ma+1] . ");\n";
  if ($self_service_discount > 0) $discount_sign .= " (-" . $self_service_discount . "%)";
  $javascript .=
    "parent.job_options.document.tourOptions.jb_markup.value = $jb_markup;\n" .
    (MASK_CALCULATOR_SRV_SRC == "1" ? getCustomerServices($db, $cs_id) : "") .
    "parent.job_tour.document.tourForm.currentPrice.value = " .
      "\"" . /*"Standard Preis: " .*/ str_replace(".", ",", sprintf("%01.2f", $fullPrice)) . " EUR" . $discount_sign . $jb_markup_text . "\";\n" .
    "if (parent.job_options.document.tourOptions.jb_fixprice.value != \"\") {" .
//    "  parent.job_tour.document.tourForm.currentPrice.value = parent.job_options.formatPrice(String(parseFloat(parent.job_options.document.tourOptions.jb_fixprice.value.replace(/,/,\".\")))) + \" EUR\"};\n";
    "  parent.job_tour.document.tourForm.currentPrice.value = '" . str_replace(".", ",", sprintf("%01.2f", $jb_totalprice)) . "' + \" EUR" . ($self_service_discount > 0 ? " (-" . $self_service_discount . "%)" : "") . $jb_markup_text . "\"};\n";
//  if ($discount_sign == "*" && ($jb_fixprice == "" || $jb_fixprice = 0))
//    $javascript .=
//      "parent.job_options.document.tourOptions.jb_fixprice.value = '" . str_replace(".", ",", sprintf("%01.2f", $fullPrice)) . "';";
  $javascript .=
    "self.setTimeout('parent.job_options.writeJob()', 1)\n";
//  $javascript =
//    "opener.parent.frames[" . JOB_TOUR . "].document.forms[" . TOURFORM ."].elements[\"currentPrice\"].value = " .
//    "\"" . str_replace(".", ",", ("$fp - $fd")) . " EUR\";\n";
//  $javascript .= javascriptOpenerRefreshAndClose(1);

  // Inhalt des temporären Fensters erzeugen und ausgeben
//  if ($phpVersion >= "7.0"):
//    $tpl = new HTML_Template_IT();
//  else:
//    $tpl = new IntegratedTemplate();
//  endif;
  $output = file_get_contents(GETDATAHTMLTPL);
  $output = str_replace("{_javascript_}", $javascript, $output);
//  include("../jobs/shrink.inc.php");
//  $html_code = $tpl->get();
//  echo htmlShrink($html_code, true);
  echo $output;
endif;

if (!isset($jb_id_log)) $jb_id_log = "undefined";
writeLog_("../log/job2_options_", trace_execution_time_stop() . " '../jobs2/job_options.php' executed, '$jobMode': \$jb_id=$jb_id_log , \$usr_id=$usr_id, \$job_is_new=$job_is_new, \$getPriceOnly=$getPriceOnly, \$csc_id_payer=$csc_id_payer");

?>
