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

// TOBEDONE: Automatische Vermittlung

include_once("../include/caglobal.inc.php");
trace_execution_time_start();
include_once("../include/global.inc.php");
list ($hq_id_job) = getHttpVars(array("hq_id_job"));
include_once("../include/auth.inc.php");
if (isset($HTTP_SESSION_VARS)) $_SESSION = $HTTP_SESSION_VARS;
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/job_options_", var_export($_POST, 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"));
  list ($disp) = getHttpVars(array("disp"));

  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_tourname_overwrite, $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_hiddenFreetext_1, $jb_costsplit, $jb_permanent2, $jb_multi, $jb_multi_factor,
    $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_id_parent, $tmp_add_jb_ids, $tmp_add_sids, $tmp_add_prices,
    $tmp_add_srvs, $tmp_add_srvts, $tmp_add_mult, $tmp_add_mult_price, $jb_dispoinfo, $jb_warntag, $jb_warnmonat, $jb_warnjahr, $jb_warnstunde, $jb_warnminute, $jb_jam_waittime, $jb_offer, $jb_markup,
    $jb_cr_markup, $cr_id_order_hidden, $cr_id_orders, $ask_mailrecipients, $sendmail, $jb_toll, $jb_id_permanent_pre, $jb_cashpayer_mail, $do_delete_suborder, $cr_price_threshold_override,
    $cr_price_block_override, $hq_id, $km_price_params, $jb_km, $jb_id_insurance, $jb_value_of_goods, $special_case, $special_case_ori, $jb_insurance_rate, $self_service_discount, $jb_tourname_hidden,
    $cs_invmail, $jb_origin, $jb_origin_other, $request_token, $jb_orderer, $jb_commission_no, $jb_bwv, $jb_offer_mail) =
    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_tourname_overwrite", "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_hiddenFreetext_1", "jb_costsplit_hidden", "jb_permanent2_hidden", "jb_multi", "jb_multi_factor",
      "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_id_parent",
      "tmp_add_jb_ids", "tmp_add_sids", "tmp_add_prices", "tmp_add_srvs", "tmp_add_srvts", "tmp_add_mult", "tmp_add_mult_price", "jb_dispoinfo",
      "jb_warntag", "jb_warnmonat", "jb_warnjahr", "jb_warnstunde", "jb_warnminute", "jb_jam_waittime",
      "jb_offer", "jb_markup", "jb_cr_markup", "cr_id_order_hidden", "cr_id_orders", "ask_mailrecipients", "sendmail", "jb_toll", "jb_id_permanent_pre", "jb_cashpayer_mail_hidden", "do_delete_suborder",
      "cr_price_threshold_override", "cr_price_block_override", "hq_id", "km_price_params", "jb_km", "jb_id_insurance", "jb_value_of_goods", "special_case", "special_case_ori", "jb_insurance_rate",
      "self_service_discount", "jb_tourname_hidden", "cs_invmail_hidden", "jb_origin_hidden", "jb_origin_other_hidden", "request_token", "jb_orderer_hidden", "jb_commission_no_hidden", "jb_bwv",
      "jb_offer_mail_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/job_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/job_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" : "NEW") . ((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 (!isset($jb_id_org) || 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;
$cs_invmode = 0;
if ($csc_id_orderer != '0'):
  // Kundenaufrag
  $cs_id = getFieldValueFromId("costcenter", "csc_id", "$csc_id_orderer", "cs_id");
  $hq_id = getFieldValueFromId("customer", "cs_id", "$cs_id", "hq_id");
  // wenn Kundenauftrag, dann entscheidet der zentralenabhängige Modus darüber, ob manuell oder automatisch
  if (MASK_MANUAL_DISPOSITION == '1' || getParameterValue("0", "MASK_MANUAL_DISPO_MANDATORY_" . $cs_id, "0") == "1"):
    $jb_status_manual = 1;
  endif;
  // cs_invmode ist vom Bezahler abhängig!!!
//  $cs_invmode = getFieldValueFromId("customer", "cs_id", "$cs_id", "cs_invmode");
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))
    if ($hq_id == "")
      $hq_id = $HTTP_SESSION_VARS['hq_id'];
    if ($hq_id_job != "")
      $hq_id = $hq_id_job;
// *** 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;

$CSC_ID_PAYER_CASH_VAR = getParameterValue("0", "CSC_ID_PAYER_CASH", $hq_id);
//  // 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");
$hq_invmode = getFieldValueFromId("headquarters", "hq_id", "$hq_id", "hq_invmode");
$jobbatch_mode = false;
$tr_sort_jobbatchmode = 0;
$tr_sort_cashpayer = 0;
$is_EU = false;
$eu_countrycodes = explode(",", trim(getParameterValue("0", "EU_COUNTRYCODES", "0")));
$is_EU_only = true;
$is_foreign = false;
$is_globaljob = false;
$gross_price = 0;
$distance = 0;
$jb_tourname_old = "";

// *** Nur für's Logging
if ($toursubmit == "Senden"):
  $jobMode = "";
  if ((isset($check_jb_permanent_flag) && $check_jb_permanent_flag == true)) $jobMode = 
    (isset($jb_id_ori) ? "\$jb_id_ori=$jb_id_ori" : "") .
    (isset($jb_id_ori_copy) ? "\$jb_id_ori_copy=$jb_id_ori_copy" : "") .
    (isset($jb_id_permanent_pre1) ? "|\$jb_id_permanent_pre1=$jb_id_permanent_pre1" : ""); // "*** DUPLICATION OF STANDING ORDER ***";
  if ($getPriceOnly == 1) $jobMode =  "Preisanfrage"; // "*** PRICE INQUIRY ***";
  if (isset($afterwards) && $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...
  $jb_offer_old = 0;
  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, $jb_cr_price_old, $csc_id_payer_old, $csc_id_payer_cash_old,
      $jb_type_old, $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_id_parent_old, $jb_dispoinfo_old, $jb_offer_old, $jb_warningtime_old, $jb_markup_old, $hq_id_dispo_old, $jb_longhaul_old, $jb_origin_old, $jb_orderer_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", "jb_cr_price", "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_id_parent", "jb_dispoinfo", "jb_offer", "jb_warningtime", "jb_markup", "hq_id_dispo", "jb_longhaul", "jb_origin", "jb_orderer", "jb_commission_no"));
    if (MASK_CR_PRICE_MODE == "1") {
      $jb_cr_serviceprice_old = $db->getOne("SELECT gdc_content FROM genericdatacontainer WHERE gdc_obj_type = 'jb' AND gdc_obj_id = " . $jb_id . " AND gdc_gen_fieldname = 'jb_cr_serviceprice'");
//      $jb_cr_markup_old = $db->getOne("SELECT gdc_content FROM genericdatacontainer WHERE gdc_obj_type = 'jb' AND gdc_obj_id = " . $jb_id . " AND gdc_gen_fieldname = 'jb_cr_markup'");
      $jb_cr_markup_old = $db->getOne("SELECT jbprc_price FROM jobprice WHERE jb_id = " . $jb_id . " AND mt_sort IN (" . JB_CR_MARKUP . ", " . JB_CR_MARKUP_MAN . ")");
    }
    $jb_km_old = $db->getOne("SELECT jbprc_price FROM jobprice WHERE jb_id = " . $jb_id . " AND mt_sort = 11");
    $jb_hiddenFreetext_1_old = $db->getOne("SELECT gdc_content FROM genericdatacontainer WHERE gdc_obj_type = 'jb' AND gdc_obj_id = " . $jb_id . " AND gdc_gen_fieldname = 'jb_hiddenFreetext_1'");
    $jb_cashpayer_mail_old = $db->getOne("SELECT gdc_content FROM genericdatacontainer WHERE gdc_obj_type = 'jb' AND gdc_obj_id = " . $jb_id . " AND gdc_gen_fieldname = 'jb_cashpayer_mail'");
    $jb_offer_mail_old = $db->getOne("SELECT gdc_content FROM genericdatacontainer WHERE gdc_obj_type = 'jb' AND gdc_obj_id = " . $jb_id . " AND gdc_gen_fieldname = 'jb_offer_mail'");
    $jb_toll_old = $db->getOne("SELECT gdc_content FROM genericdatacontainer WHERE gdc_obj_type = 'jb' AND gdc_obj_id = " . $jb_id . " AND gdc_gen_fieldname = 'jb_toll'");
    $jb_origin_other_old = $db->getOne("SELECT gdc_content FROM genericdatacontainer WHERE gdc_obj_type = 'jb' AND gdc_obj_id = " . $jb_id . " AND gdc_gen_fieldname = 'jb_origin_other'");
  endif;
  // $jb_tourname muss immer geholt werden, denn wenn eine Konserve geändert wird, dann muss das immer der aktuelle Preis sein!
  $i = 1;
  if (trim($jb_id) != ""):
    $jb_tourname_old = $db->getOne("SELECT jb_tourname FROM job WHERE jb_id = " . $jb_id);
    // gespeicherte Tour-Daten holen
    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, "tour");
        $tr_id_old_[$i] = $db->getOne("SELECT tr_id FROM tour WHERE jb_id = " . $jb_id . " AND tr_sort = " . $i);
        $tr_photo_old_[$i] = $db->getOne("SELECT gdc_content FROM genericdatacontainer WHERE gdc_obj_type = 'tr' AND gdc_obj_id = " . $tr_id_old_[$i] . " AND gdc_gen_fieldname = 'tr_photo'");
      else:
        $tourFound = 0;
      endif;
      $i++;
    } while ($tourFound == 1);
  endif;
  $i_tour_max_old = $i - 1;
endif;

// *** Nur für's Logging ENDE
writeLog_("../log/job_options_", "\$jb_tourname_old = " . $jb_tourname_old);

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

$jb_fixprice_ori = $jb_fixprice;
$jb_fixprice = (float) str_replace(",", ".", $jb_fixprice);
$jb_markup_ori = isset($jb_markup) ? $jb_markup : "";
$jb_markup = (float) str_replace(",", ".", isset($jb_markup) ? $jb_markup : "0");
$jb_cr_markup_ori = isset($jb_cr_markup) ? $jb_cr_markup : "";
$jb_cr_markup = (float) str_replace(",", ".", isset($jb_cr_markup) ? $jb_cr_markup : "0");
$jb_toll_ori = $jb_toll;
if (trim($jb_toll != ""))
  $jb_toll = (float) str_replace(",", ".", $jb_toll);
$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_ori = $jb_cr_serviceprice;
  $jb_cr_serviceprice = (float) str_replace(",", ".", $jb_cr_serviceprice);
}
$jb_cr_fixserviceprice = 0.0;
$jb_km_ori = $jb_km;
$jb_km = (float) str_replace(",", ".", $jb_km);
if (trim($jb_value_of_goods) != "")
  $jb_value_of_goods = (float) str_replace(",", ".", $jb_value_of_goods);
$addressValid = "ok";
$job_is_new = true;
$tmp_discount = 0;
$tmp_discount_rate = 0;
if ($jb_discount == 1)
  $tmp_discount_rate = $jb_discount_rate;
// Preise werden immer ermittelt, auch wenn $getPriceOnly != 1 (ist halt einfacher)
$fullPrice = 0.00;
$jb_subtotal = 0.00;
$jb_totalprice = 0.00;
$discount_sign = "";
$discount_sign_cr = "";
//$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;
};
$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/job_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/job_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 (isset($afterwards) && $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", "99");
        $is_globaljob = true;
      else:
        $insertStmtArr = array("csc_id", $csc_id_orderer);
      endif;
      // Sonderfall: Wenn Auftragsänderung, kann normalerweise der Fahrer nicht mehr geändert werden.
      // Ausnahme: wenn über den Calculator das jeweilige 750-Fahrzeug eingetragen wird. Dann ist der Auftrag
      // erledigt (sonst geht Calc. nicht), und deshalb muss wie bei einer Nacherfassung auch der
      // annehmende Kurier angepasst werden!          
//      if ($cr_id_order_hidden != "" && (substr($cr_id_order_hidden, -3) == "751" || substr($cr_id_order_hidden, -3) == "750")):
      if ($cr_id_order_hidden != "" && (substr($cr_id_order_hidden, -3) == substr(MASK_INVOICE_SIDS_SID, -3, 2) . "6" || substr($cr_id_order_hidden, -3) == substr(MASK_INVOICE_SIDS_SID, -3, 2) . "5")):
        array_push ($insertStmtArr, "cr_id",
          getFieldValueFromId("couriervehicle", "crvh_sid", $cr_id_order_hidden, "cr_id"),
          "cr_sid", $cr_id_order_hidden);
      endif;

      // Unerauftrag wurde gelöscht und der Fahrer muss daher neu gespeichert werden
      if ($do_delete_suborder == "1"):
        array_push ($insertStmtArr, "cr_id",
          getFieldValueFromId("couriervehicle", "crvh_sid", $cr_id_order, "cr_id"),
          "cr_sid", $cr_id_order);
      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
//writeLog_("../log/job_options_", "\$jb_id = " . $jb_id . ", MASK_COURIER_IMMEDIATE = " . MASK_COURIER_IMMEDIATE . ", MASK_COURIER_IMMEDIATE = " . getParameterValue("0", "MASK_COURIER_IMMEDIATE", $hq_id) . ", \$check_jb_permanent_flag = " . $check_jb_permanent_flag);
        if ((!($tag != "" && $monat != "" && $jahr != "" && $stunde != "" && $minute != "") || $jb_globaljob == 1)
          || $hq_workmode == "1" || (getParameterValue("0", "MASK_COURIER_IMMEDIATE", $hq_id) == "1" && !(isset($check_jb_permanent_flag) && $check_jb_permanent_flag == true))):
          $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", "99");
          $is_globaljob = true;
        endif;
      endif;
      // die einzelnen Touren sind auch noch NICHT erledigt
      $tr_status = "0";
    endif;
    array_push ($insertStmtArr, "jb_invmode", isset($cs_invmode) ? $cs_invmode : 0);
  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);
//  if ($jb_globaljob != "")
    array_push ($insertStmtArr, "jb_globaljob", $jb_globaljob);
//  if ($jb_type != "")
    array_push ($insertStmtArr, "jb_type", $jb_type);
    array_push ($insertStmtArr, "jb_id_parent", $jb_id_parent);
//  if ($jb_freetext_1 != ""):
    array_push ($insertStmtArr, "jb_freetext_1", my_str_check_http($jb_freetext_1));
    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);
    array_push ($insertStmtArr, "jb_offer", $jb_offer);
//  endif;
//  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);

  $filters_text = "";
  $filters_sql = $jb_cr_filter . (trim($jb_cr_filter) == "" || trim($jb_cr_filter_opt) == "" ? "" : ",") . $jb_cr_filter_opt;
  $filters_sql = str_replace(",", "','", $filters_sql);
  if ($filters_sql != "") {
    $sqlquery = "SELECT crf_longtext FROM courierfilter WHERE crf_short IN ('" . $filters_sql . "')";
    $res = $db->query($sqlquery);
    if (DB::isError($res)) reportDie ("$PHP_SELF: '$sqlquery': " . $res->getMessage());
    while ($row = $res->fetch_assoc()):
      if (trim($row['crf_longtext']) != "")
        $filters_text .= $row['crf_longtext'] . "\n";
    endwhile;
    $res->free();
  }
  if ($filters_text != "")
    $filters_text = "~~~\n". $filters_text . "~~~\n";
  // wenn Datum gesetzt, dann übernehmen, sonst aktuelle Zeit (nur wenn nicht Nachbearbeitung!!!)
  $jb_ordertime = "";
  if ($tag == "" || $monat == "" || $jahr == "" || $stunde == "" || $minute == ""):
    if ($jb_id == "" || $db->getOne("SELECT jb_reserv FROM job WHERE jb_id = '$jb_id'") == 1 || ($jb_offer == 0 && $jb_offer_old == 1)):
      $today = getdate();
      $jb_ordertime = $today['year'] . "-" . $today['mon'] . "-" . $today['mday'] . " "
        . $today['hours'] . ":" . $today['minutes'] . ":" . $today['seconds'];
      array_push ($insertStmtArr, "jb_reserv", 0);
    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 (isset($afterwards) && $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 23:59:59";
         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 (isset($afterwards) && $afterwards == "1"):
    // Nacherfassung: Job ist bereits erledigt
    // 'finishtime' und 'taketime' ist 'ordertime'
    array_push ($insertStmtArr, "jb_finishtime", $jb_ordertime);
    array_push ($insertStmtArr, "jb_taketime", $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;
    if (trim($jb_toll != ""))
      $jb_toll = sprintf("%01.2f", $jb_toll * -1);
  endif;
  array_push ($insertStmtArr, "jb_fixprice", $jb_fixprice, "jb_serviceprice", $jb_serviceprice, "jb_cr_subprice", $jb_cr_price);
  $jb_sales_tax_rate_sign_new = $db->getOne("SELECT tx_sign FROM tax WHERE tx_id = '$jb_sales_tax_rate_sign'");
  $jb_sales_tax_rate = $db->getOne("SELECT tx_value FROM tax WHERE tx_id = '$jb_sales_tax_rate_sign'");
  $jb_ordertime_vals = getValsFromDate($jb_ordertime);
  if (($hq_id == 2 || $hq_id == 3 || $hq_id == 5) && $jb_markup > 0 && mktime(0, 0, 0, 11, 16, 2021) > mktime(0, 0, 0, $jb_ordertime_vals[1], $jb_ordertime_vals[2], $jb_ordertime_vals[0])):
    $jb_markup_ori = 0;
    $jb_markup = 0;
  endif;
  if ($jb_sales_tax_rate > 0 && mktime(0, 0, 0, 7, 1, 2020) > mktime(0, 0, 0, $jb_ordertime_vals[1], $jb_ordertime_vals[2], $jb_ordertime_vals[0])):
    $jb_sales_tax_rate = 19;
  endif;
  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;
//  // 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", isset($usr_id) ? $usr_id : 0);
    // bei einem zu ändernden Job darf die originale hq_id nicht geändert werden (insbesondere im Falle der Ferntour)
    array_push ($insertStmtArr, "hq_id", $hq_id);
  endif;

//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) {
      // Wenn eine ursprüngliche Nacherfassung geändert wird, dann muss auch die Finishtime angepasst werden, wenn die Ordertime geändert wurde! Ganz wichtig!!!
      $was_afterwards = job_was_afterwards($jb_id);
      if ($was_afterwards) {
        if ($jb_ordertime != "") {
          // 'finishtime' und 'taketime' ist 'ordertime'
          array_push ($insertStmtArr, "jb_finishtime", $jb_ordertime);
          array_push ($insertStmtArr, "jb_taketime", $jb_ordertime);
        }
      }
      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!" . $statusMessageTxt;
      $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"):
            // ar_cr_order muss im Falle einer Reservierung und Anforderung eines Fahrers auf 1 gesetzt werden, damit das Autoranking weiß, dass
            // der Kurier für die Reservierung explizt angefordert wurde, womit der Auftrag bei nicht-Vorhandesein des angeforderten Fahrers
            // wieder in die Vermittlung (in die zuzuweisenden) zurückgeht, ansonsten würde er weiteren Fahrern angeboten werden
            $ar_cr_order = 0;
            if ($jb_reserv == 1)
              $ar_cr_order = 1;
            // 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, "ar_cr_order", $ar_cr_order);
              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, "ar_cr_order", $ar_cr_order);
              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;
          // zu guter Letzt: evtl. bestehende Unteraufträge löschen!
          deleteJobChildren($jb_id_copy);
        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_tourname_old == "" ? $jb_ordertime : date("Y-m-d H:i:s")), 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 (isset($jb_cash) && $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_VAR != ""):
        $csc_id_payer = $CSC_ID_PAYER_CASH_VAR;
      endif;
    endif;
    $costsplit_count = 1;
    // Barzahlung
    $jb_payment = 2;
  else:
    // Zahlungsmodus festhalten
    if (isset($jb_costsplit) && $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;

  $hq_id_sales = $hq_id;
  if ($csc_id_payer == 0 || $csc_id_payer == ""): // csc_id_payer == 0 ==> Kostensplit
    $cs_invmode = $hq_invmode;
    $cs_id = 0;
  else:
    $cs_id = getFieldValueFromId("costcenter", "csc_id", "$csc_id_payer", "cs_id");
    $hq_id_sales = getFieldValueFromId("customer", "cs_id", $cs_id, "hq_id");
    // Noch was Neues: Wenn beim Kunden hinterlegt ist, dass bei der Abholung bei diesem Kunden dessen Konditionen (cs_jbcond = 1) gelten soll,
    // dann gelten für die Preisermittlung nicht die Konditionen des Zahlers!
    $cs_id_cond = getFieldValueFromId("costcenter", "csc_id", $jobList[0][JL_CSC_ID], "cs_id");
    $cs_jbcond = getFieldValueFromId("customer", "cs_id", $cs_id_cond, "cs_jbcond");
    if ($cs_jbcond == 1)
      $cs_id = $cs_id_cond;
    // invmode ermitteln (ist abhängig von dem aktuellen Bezahler), kann neuerdings auch von der Kostenstelle 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");
    }
    $cmp_postage_old = $db->getOne("SELECT cmp_postage FROM customer AS cs, company AS cmp WHERE cmp.cmp_id = cs.cmp_id AND cs_id = " . $cs_id);
    $cmp_postage = $cmp_postage_old;
  endif;

  if (trim($jb_markup_ori) == "") {
    $jb_markup = getFuelMarkup($srvt_name, (trim($cs_id) != "" ? $cs_id : 0), $hq_id, $jb_ordertime);
  }
  if (MASK_CR_PRICE_MODE == "1") {
    if (trim($jb_cr_markup_ori) == "") {
      $vhtSrvt_name = $db->getOne("SELECT mt_value FROM metatype WHERE mt_sort = '$vht_id' AND mt_type = 'vehicletype'");
      $jb_cr_markup = getFuelMarkupCr($vhtSrvt_name, (trim($cs_id) != "" ? $cs_id : 0), $hq_id, $jb_ordertime);
    }
  }
  // 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 &&
    getParameterValue("0", "MASK_FAVOURED_COURIER_MANUAL", $hq_id) == "1" && isset($afterwards) && $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_dispo = $db->getOne("SELECT hq_id FROM serviceplz WHERE srvp_plz = '" . $jobList[0][JL_AD_ZIPCODE] . "'");
  if ($hq_id_dispo == "")
    $hq_id_dispo = $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_dispo", $hq_id_dispo,
    "hq_id_sales", $hq_id_sales);
  updateStmt("job", "jb_id", $jb_id, $tmpArr);

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

  // Ab hier werden Preise ermittelt und ggfs. gespeichert

  // Achtung: Beim Speichern in tourservice (bzw. Aufruf von saveservicecosts)
  // Barzahlung mit ausgewähltem Bezahler berücksichtigen!
  $tmpCsc_id_payer = $csc_id_payer;
  // $tmpCsc_id_payer zum Ermitteln und Speichern des tatsächlichen Zahlers. Der übergebene csc_id_payer soll für das Logging erhaslten bleiben.
  // Wichtig für Barzahlung: $tmpCsc_id_payer ist hier immer der System-Barzahler, während in csc_id_payer festgehalten wird, wer der in der Realität zahlende Barzahler ist.
  if ($jb_payment == 2):
    // 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"):
      $tmpCsc_id_payer = "-1";
      if ($CSC_ID_PAYER_CASH_VAR != ""):
        $tmpCsc_id_payer = $CSC_ID_PAYER_CASH_VAR;
      endif;
    endif;
  endif;

  // aus bisher nicht geklärten Gründen ist $tmpCsc_id_payer manchmal 0;
  // kann nur im Barzahlungsfall auftreten, deshlab hier sicherstellen, dass dann auch die Barzahler-ID hier drin steht
  if ($tmpCsc_id_payer == 0 || $tmpCsc_id_payer == "")  
    $tmpCsc_id_payer = getParameterValue("0", "CSC_ID_PAYER_CASH", $hq_id);
  // 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"*/):
//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_tourname_old == "" ? $jb_ordertime : date("Y-m-d H:i:s")), 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, $jb_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>";
  $di_ids = array();
  if (!($jb_fixprice == "" || $jb_fixprice == 0) || $jobbatch_mode == true /* && $jb_fixprice != "0.00"*/):
    if ($jb_storno == 0):
      // Km-Preis?
      $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("job_options: [" . $sqlquery . "]");
            writeLog_xServer("job_options: [" . "\$db_geo ist " . (is_null($db_geo) ? "" : "nicht ") . "null" . "]");
            if (!is_null($db_geo)) {
              $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())):
//                writeLog_xServer("job_options: [" . var_export(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[2], $row["di_id"]) === false) ? 2 : (!(strpos($ro_types[1], $row["di_id"]) === false) ? 1 : 0)), "ro_date", $row["di_modify"]), true) . "]");
                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[2], $row["di_id"]) === false) ? 2 : (!(strpos($ro_types[1], $row["di_id"]) === false) ? 1 : 0)), "ro_date", $row["di_modify"]));
              endwhile;
              $res->free();
            } else {
              $di_ids = explode(",", str_replace(";", ",", $km_price_paramsArr[4]));
              foreach($di_ids as $di_id) {
                insertStmt("phoenix_log.route", array("jb_id", $jb_id, "di_id", $di_id, "ro_distance", 0, "ro_duration", 0, "ro_polyline", 0, "ro_num", ++$cnt));
              }
            }
          }
          $fixprice_min = $km_price_paramsArr[5];
	}
      }
//echo ($km_price_params) . "<br>\n";
//print_r ($km_price_paramsArrArr) . "<br>\n";die();
      // 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_VAR : $tmpCsc_id_payer) : ""));
//die();
      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 und ggfs. ohne Rabatt)       
      $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",
        ((getParameterValue("0", "INV_SERVICEPRICE_DISCOUNT", $hq_id) == "1") ? $tmp_discount_rate : 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;

  $prev_ad_id = "";
  $prev_tr_mediationarea_id = 0;
  $jb_tourdata1 = "";
  $jb_tourdata2 = "";
  $jb_tourdata3 = "";
  $insertedOrUpdatedTr_ids = "";

  // 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
//echo "insertAddress($jobList[$i][JL_AD_STREET], $jobList[$i][JL_AD_ZIPCODE], $jobList[$i][JL_AD_CITY], $csc_id, $jobList[$i][JL_AD_COUNTRY], ($accept_all_addresses == \"1\"))";
      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" && !(isset($jb_storno) && $jb_storno > 0)):
        // address invalid -> I must die...
        // error-message is in tr_person, rest is empty
        $statusMessageTxt = $tr_person;
        $addressValid = "";
        break;
      endif;
      if ($is_EU_only) {
//echo $jobList[$i][JL_AD_COUNTRY] . "<br>\n";
        $is_EU_only = in_array($jobList[$i][JL_AD_COUNTRY], $eu_countrycodes);
//echo "is_EU_only = " . $is_EU_only . "<br>\n";
      }
      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
//echo "\n<br>insertAddress(".$jobList[$i][JL_AD_STREET].",". $jobList[$i][JL_AD_ZIPCODE].",". $jobList[$i][JL_AD_CITY].",". $csc_id.",". $jobList[$i][JL_AD_COUNTRY]."," . ($accept_all_addresses == "1") .")";

    if (!$is_foreign)
      $is_foreign = $jobList[$i][JL_AD_COUNTRY] != "DE";
    $jb_tourdata2_add = "";
    $tmp_accept_all_addresses = isset($accept_all_addresses) ? $accept_all_addresses : false;
    $insertAddressDistrictCity = getParameterValue("0", "MASK_INSERTADDRESS_DISTRICT_" . getFieldValueFromId("costcenter", "csc_id", "$csc_id_payer", "cs_id"), "0");
    if ($insertAddressDistrictCity != "" && !(strpos($jobList[$i][JL_AD_CITY], $insertAddressDistrictCity) === false)):
      $addresses = checkCityZipcode($jobList[$i][JL_AD_ZIPCODE], $jobList[$i][JL_AD_CITY], $jobList[$i][JL_AD_STREET], "2");
//print_r($addresses);
      for($matchedCount = 1; $matchedCount <= count($addresses); $matchedCount++):
        if (trim($addresses["st_district"][$matchedCount]) != "" && strpos($jobList[$i][JL_AD_CITY], $addresses["st_district"][$matchedCount]) === false):
//          $jobList[$i][JL_AD_CITY] .= "-" . $addresses["st_district"][$matchedCount];
//          $tmp_accept_all_addresses = "1";
          $jb_tourdata2_add = "-" . $addresses["st_district"][$matchedCount];
          break;
        endif;
      endfor;
    endif;
//echo $jobList[$i][JL_AD_CITY]; die();

    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], ($tmp_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_tourdata2_add;
    $jb_tourdata3 .= ($jb_tourdata3 == "" ? "" : ";") . (trim($jobList[$i][JL_AD_COUNTRY]) == "" ? "DE" : $jobList[$i][JL_AD_COUNTRY]);
    if ($is_EU_only)
      $is_EU_only = in_array($jobList[$i][JL_AD_COUNTRY], $eu_countrycodes);
//    if (!$is_EU)
//      $is_EU = (trim($jobList[$i][JL_AD_COUNTRY]) == "DE" || trim($jobList[$i][JL_AD_COUNTRY]) == "") ? false : true;
    // 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" && !(isset($jb_storno) && $jb_storno > 0)):
      // 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);
      }
//echo str_replace("\n", "&lt;br&gt;<br>", "|" . $jb_cr_priceStr . "|") . "<hr>";
//echo str_replace("\n", "&lt;br&gt;<br>", $tr_remark) . "<hr>";
      $tr_remark = str_replace("\r\n\r\n" . $jb_cr_priceStr, "", $tr_remark);
      $tr_remark = str_replace("\r\n" . $jb_cr_priceStr, "", $tr_remark);
      $tr_remark = str_replace("\n". $jb_cr_priceStr, "", $tr_remark);
      $tr_remark = str_replace($jb_cr_priceStr, "", $tr_remark);
//echo str_replace("\n", "&lt;br&gt;<br>", $tr_remark) . "<hr>";die();
    endif;    
    // Wenn Barzahlung vorhanden, hier erstmal entfernen
    $tr_remark = str_replace("\n*** ZAHLT BAR ***", "", $tr_remark);    
    $tr_remark = str_replace("*** ZAHLT BAR ***", "", $tr_remark);
    $tr_remark = str_replace("\n*** LIEFERSCHEIN ZUR ZENTRALE STADTBOTE ***", "", $tr_remark);
    $tr_remark = str_replace("*** LIEFERSCHEIN ZUR ZENTRALE STADTBOTE ***", "", $tr_remark);
//    $tr_remark = preg_replace("/\n\*\*\* FESTPREIS \(LISTE\) EUR .* \*\*\*/", "", $tr_remark);
//    $tr_remark = preg_replace("/\*\*\* FESTPREIS \(LISTE\) EUR .* \*\*\*/", "", $tr_remark);
    if (MASK_CR_PRICE_MODE == "1" && !(strpos($tr_remark, "*** Bitte im Auftrag STADTBOTE Bar") === false)):
      $barStr = strstr($tr_remark, "*** Bitte im Auftrag STADTBOTE Bar");
      $barStr = substr($barStr, 0, strpos($barStr, "kassieren und quittieren. ***") + strlen("kassieren und quittieren. ***"));
      $tr_remark = str_replace("\n" . $barStr, "", $tr_remark);
      $tr_remark = str_replace($barStr, "", $tr_remark);
    endif;
//echo str_replace("\n", "&lt;br&gt;<br>", $tr_remark) . "<hr>";die();
    // Wenn Fuhrlohn angezeigt werden soll, hier hinzufügen
    $tr_remark_add = "";
    if (MASK_JB_CR_PRICE_2_TR_REMARK == "1" && (($i + 1) == 1) && MASK_CR_PRICE_MODE == "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 (isset($jb_cash) && $jb_cash == "true" && $jobList[$i][JL_CSC_ID_PAYER] == "true"):
      // Wenn Barzahlung und Bezahler angegeben, dann hier festhalten!
//      $tr_remark .= "\n*** ZAHLT BAR ***";
//$honk=substr($tr_remark, strlen($tr_remark)-1, strlen($tr_remark));
//echo str_replace("\n", "&lt;br&gt;<br>", $tr_remark) . "<hr>";
      $tr_remark .= "\n*** ZAHLT BAR ***";
      if (MASK_CR_PRICE_MODE == "1"):
        $tr_sort_cashpayer = ($i + 1);
      endif;
//echo str_replace("\n", "&lt;br&gt;<br>", "|" . $honk . "|" . $tr_remark) . "<hr>";die();
    endif;
//echo str_replace("\n", "&lt;br&gt;<br>", $tr_remark) . "<hr>";
    if (in_array ("LZ", explode(",", $jb_cr_filter_opt)) && ($i + 1) == 1)
      $tr_remark .= "\n*** LIEFERSCHEIN ZUR ZENTRALE STADTBOTE ***";
    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") . "'") == "1" ||
        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") . "'");
      if ($tr_photo == ""):
        $tr_photo = "1|1"; // Default: Mindestens ein Photo, höchstens eins (d.h. genau ein Foto)
      endif;
    elseif (getFieldValueFromClause("parameter", "par_value", "par_key='MASK_MIN_MAX_TR_PHOTO_CS_" . getFieldValueFromId("costcenter", "csc_id", "$csc_id_payer", "cs_id") . "'") == "0|0"):
        $tr_photo = "0|0"; // Foto verhindern
    endif;
    // 08.09.2021: Zum Testen soll jede Station mir einer Foto-Möglichkeit versehen werden, wenn keines extra angefordert ist
    $gdc_context_add = "";
    if ($tr_photo == "" && getParameterValue("0", "MASK_TR_PHOTO_FORCE", "0") == "1" &&
      getFieldValueFromClause("parameter", "par_value", "par_key='MASK_TR_PHOTO_CS_" . getFieldValueFromId("costcenter", "csc_id", "$csc_id_payer", "cs_id") . "'") != "1") {
      $tr_photo = getParameterValue("0", "MASK_MIN_MAX_TR_PHOTO_FORCE", "0");
      $gdc_context_add = "|forced";
    }

//    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 = isset($jobList[$i][JL_TR_MEDIATIONAREA_ID]) ? $jobList[$i][JL_TR_MEDIATIONAREA_ID] : 0;
    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, "tr_mediationarea_name", (isset($di_ids[$i]) ? $di_ids[$i] : ""));
            "tr_commission_no", $tr_commission_no, "tr_mediationarea_id", $tr_mediationarea_id);
        insertStmt("tour", $tmpArr);
        $tr_id = getLastInsertId();
//        if ($tr_id == $jb_id || $tr_id == 0)
          writeLog_("../log/tours_missing_", "INSERT INTO tour (jb_id, ad_id, tr_sort, csc_id, tr_comp, tr_person, tr_phone, tr_remark, tr_hsno, tr_status, tr_ware_from_to, tr_commission_no, tr_mediationarea_id)" .
            "VALUES ('" . $jb_id . "', '" . $ad_id . "', '" . ($i + 1) . "', '" . $csc_id . "', '" . my_str_check($tr_comp) . "', '" . my_str_check($tr_person) . "', '" . $tr_phone . "', '" . my_str_check($tr_remark) . "', '" . my_str_check($tr_hsno) . "', '0', '" . $tr_ware_from_to . "', '" . $tr_commission_no . "', '" . my_str_check($tr_mediationarea_id) . "');");
        $insertedOrUpdatedTr_ids .= "," . $tr_id;
        writeLog_("../log/job_options_", "\$jb_id = " . $jb_id . ", \$tr_sort = " . ($i + 1) . ", \$insertedOrUpdatedTr_ids = " . $insertedOrUpdatedTr_ids);
        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 . $gdc_context_add));
        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
      // TOBEDONE: Vertauschen ist nicht berücksichtigt!!! 28.04.2016: Ab jetzt schon
//      $ad_id_test = $db->getOne(
//        "SELECT ad_id FROM tour WHERE jb_id = '$jb_id' AND tr_sort = '" . ($i + 1) . "'");
//      if ($ad_id_test != ""):
      $tr_id = trim($jobList[$i][JL_TR_ID]);
      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_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, "tr_sort", ($i + 1), "tr_mediationarea_name", (isset($di_ids[$i]) ? $di_ids[$i] : ""));
              "tr_commission_no", $tr_commission_no, "tr_mediationarea_id", $tr_mediationarea_id, "tr_sort", ($i + 1));
          // Bei b2b-Importen darf importierte Rufnummer nicht überschreiben
            if ($db->getOne("SELECT jb_id FROM phoenix_log.log WHERE jb_id = '$jb_id' AND logo_id = 102") != $jb_id)
              array_push ($tmpArr, "tr_phone", my_str_check($tr_phone));
//            updateStmt("tour", "", "", $tmpArr, "jb_id = '$jb_id' AND tr_sort = '" . ($i + 1) . "'");
            updateStmt("tour", "", "", $tmpArr, "jb_id = '$jb_id' AND tr_id = " . $tr_id);
            $insertedOrUpdatedTr_ids .= "," . $tr_id;
            writeLog_("../log/job_options_", "\$jb_id = " . $jb_id . ", \$tr_sort = " . ($i + 1) . ", \$insertedOrUpdatedTr_ids = " . $insertedOrUpdatedTr_ids);
            deleteStmt("genericdatacontainer", "gdc_obj_type = 'tr' AND gdc_obj_id = " . $tr_id . " AND gdc_gen_fieldname = 'tr_photo'");
            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 . $gdc_context_add));
            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);
//              "tr_commission_no", $tr_commission_no, "tr_mediationarea_id", $tr_mediationarea_id, "tr_mediationarea_name", (isset($di_ids[$i]) ? $di_ids[$i] : ""));
            insertStmt("tour", $tmpArr);
            $tr_id = getLastInsertId();
//            if ($tr_id == $jb_id || $tr_id == 0)
              writeLog_("../log/tours_missing_", "INSERT INTO tour (jb_id, ad_id, tr_sort, csc_id, tr_comp, tr_person, tr_phone, tr_remark, tr_hsno, tr_status, tr_ware_from_to, tr_commission_no, tr_mediationarea_id)" .
                "VALUES ('" . $jb_id . "', '" . $ad_id . "', '" . ($i + 1) . "', '" . $csc_id . "', '" . my_str_check($tr_comp) . "', '" . my_str_check($tr_person) . "', '" . $tr_phone . "', '" . my_str_check($tr_remark) . "', '" . my_str_check($tr_hsno) . "', '0', '" . $tr_ware_from_to . "', '" . $tr_commission_no . "', '" . my_str_check($tr_mediationarea_id) . "') ;");
             $insertedOrUpdatedTr_ids .= "," . $tr_id;
            writeLog_("../log/job_options_", "\$jb_id = " . $jb_id . ", \$tr_sort = " . ($i + 1) . ", \$insertedOrUpdatedTr_ids = " . $insertedOrUpdatedTr_ids);
            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 . $gdc_context_add));
          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_tourname_old == "" ? $jb_ordertime : date("Y-m-d H:i:s")), 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_tourname_old == "" ? $jb_ordertime : date("Y-m-d H:i:s")), 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, $jb_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_tourname_old == "" ? $jb_ordertime : date("Y-m-d H:i:s")), $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, $jb_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;
      else:
        // 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_tourname_old == "" ? $jb_ordertime : date("Y-m-d H:i:s")), $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, $jb_cr_markup, $vht_id);
//echo "'$prev_tr_mediationarea_id, $ad_id1; $tr_mediationarea_id, $ad_id2'<br>\n";
//reportDie ("saveServiceCosts($ad_id1, $ad_id2, $hq_id, $cs_id, $jb_id, ($i + 1), ($jb_tourname_old == "" ? $jb_ordertime : date("Y-m-d H:i:s")), $distance, $costsplit_count, $getPriceOnly, $jb_cash, " . (($jb_costsplit == "false" || MASK_CASH_PAYER_SELECT == "1") ? $tmpCsc_id_payer : "") . ", $jb_storno, $zipcode1, $zipcode2, ". false .");");
          $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 == "*" ? "*" : "")));
          if ($fd > 0) $discount_sign = " (-" . $fd . "%)";
          $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);
          $discount_sign_cr = "";
          if ($fd+$self_service_discount > 0) $discount_sign_cr = " (-" . ($fd+$self_service_discount) . "%)";
        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;

  // Anzahl der Touren bestimmt neben dem Preis, ob die Tour eine Ferntour ist
  $tourCount = $i;
  
  // 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;
    // Zu löschende tr_ids merken für nachfolgende Löschung in der genericdatacontainer)
    $sqlquery = "SELECT tr_id FROM tour WHERE jb_id = " . $jb_id . 
      ($insertedOrUpdatedTr_ids != "" ? " AND tr_id NOT IN (" . substr($insertedOrUpdatedTr_ids, 1) . ")" : "");
    writeLog_("../log/job_options_", $sqlquery);
    $res = $db->query($sqlquery);
    $tr_ids_to_be_deleted = "";
    if (DB::isError($res)) reportDie ("$PHP_SELF: '$sqlquery': " . $res->getMessage());
    while ($row = $res->fetch_assoc()):
      $tr_ids_to_be_deleted .= "," . $row["tr_id"];
    endwhile;
    $res->free();
    // Wenn Etappenstellen gelöscht wurden, müssen sie auch in der Datenbank gelöscht werden!
    // TOBEDONE: Unterschriften dürfen nicht gelöscht werden!!!
    
//    deleteStmt("tour", "jb_id = $jb_id AND tr_sort >= '" . ($i + 1) . "'");
    deleteStmt("tour", "jb_id = $jb_id " .
      ($insertedOrUpdatedTr_ids != "" ? " AND tr_id NOT IN (" . substr($insertedOrUpdatedTr_ids, 1) . ")" : ""));
//  echo $tr_ids_to_be_deleted;die();
    if ($tr_ids_to_be_deleted != "")
      deleteStmt("genericdatacontainer", "gdc_obj_type = 'tr' AND gdc_obj_id IN (" . substr($tr_ids_to_be_deleted, 1) . ") AND gdc_gen_fieldname = 'tr_photo'");

    // 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, "csc_id_payer_cash", 0);
        $cs_invmail_old = "";
        if (isset($cs_invmail) && trim($cs_invmail) != "") {
          $cs_invmail_old = $db->getOne("SELECT usr_inv_email from customer, employee, user WHERE cs_id = " . $cs_id . " AND customer.cs_admin = employee.emp_id AND employee.usr_id = user.usr_id");
//          $db->query("UPDATE customer AS cs, employee AS emp, user AS usr SET usr.usr_inv_email = '" . $cs_invmail . "' WHERE cs.cs_id = " . $cs_id . " AND cs.cs_admin = emp.emp_id AND emp.usr_id = usr.usr_id");
          $retArr = userSetFieldAndExportFlag($db->getOne("SELECT usr.usr_id FROM customer AS cs, employee AS emp, user AS usr WHERE cs.cs_id = " . $cs_id . " AND cs.cs_admin = emp.emp_id AND emp.usr_id = usr.usr_id"), "usr", "usr_inv_email", $cs_invmail);
writeLog_("../log/job_options_", "\$cs_id = " . $cs_id . ", \$cs_invmail = " . $cs_invmail . ", \$retArr = " . json_encode($retArr));
          $db->query("UPDATE customer AS cs, company AS cmp SET cmp_postage = 0 WHERE cmp.cmp_id = cs.cmp_id AND cs_id = " . $cs_id);
          $cmp_postage = 0;
        }
        // Bei einem Dispo24-Mitarbeiter entscheidet die hq_id des zahlenden Kunden über die Niederlassung
//        $empHqList = getParameterValue("0", "HEADQUARTERS_MULTIPLE_ACCESS_EMPLOYEES", "0") . "|300001";
//        if (isset($emp_id) && isInParameterString($emp_id, $empHqList)) {
//          array_push ($tmpArr, "hq_id", getFieldValueFromId("customer", "cs_id", $cs_id, "hq_id"));
//        }
        if ($jb_payment == 2 && MASK_CASH_PAYER_SELECT == "1"):
          if ($CSC_ID_PAYER_CASH_VAR != ""):
            $tmpArr = array("csc_id_payer", $CSC_ID_PAYER_CASH_VAR, "csc_id_payer_cash", $csc_id_payer);
          else:
            $tmpArr = array("csc_id_payer", "-1", "csc_id_payer_cash", $csc_id_payer);
          endif;
        endif;

        // 25.03.2022: Wenn aufgrund eines Problems in der DB die tour-Tabelle nicht geschrieben wurde, dann Alarm-Mail senden
        $tr_sorts = "";
        for($j = 1; $j <= $tourCount; $j++):
          if (!existsEntry("tour", array("jb_id", $jb_id, "tr_sort", $j))):
            if ($tr_sorts != "")
              $tr_sorts .= ", ";
            $tr_sorts .= $j;
          endif;
        endfor;
        if ($tr_sorts != ""):
          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 komplett geschrieben!");
          $mailObj->setText("In Auftrag " . $jb_id . " (hq_id = " . $hq_id . ") wurde(n) folgende Station(en) nicht in die tour-Tabelle geschrieben: " . $tr_sorts . ".\nDetails zu den betreffenden Stationen siehe tours_missing_" . date("Ym") . ".log.");
          $mailResult = $mailObj->send(array("ca@assecutor.de"), 'smtp');
//          $mailResult = $mailObj->send(array("support@assecutor.de"), 'smtp');
        endif;

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

        // 07.08.2018: Aufrund eines fälschlichen nicht reproduzierbaren externen Zahlers in Auftrag 17719291 soll hier eine Warnmail erfolgen, wenn das nochmal passiert
        if ($jb_payment != 2 && $csc_id_payer == CSC_ID_PAYER_EXTERN):
          include_once("../include/email/htmlMimeMail.php");
          $mailObj = new htmlMimeMail();
//          $mailObj->setFrom("auto-mailer@assecutor.de");
          $mailObj->setFrom("support@assecutor.de");
          $mailObj->setSubject("Externer Zahler in Auftrag $jb_id");
          $mailObj->setText("Externer Zahler $csc_id_payer in Auftrag $jb_id\n");
          $mailResult = $mailObj->send(array("ca@assecutor.de"), 'smtp');
        endif;

        // 22.01.2010: 
        $ad_country_payer = $db->getOne("SELECT ad_country FROM costcenteraddress, address WHERE costcenteraddress.ad_id = address.ad_id AND costcenteraddress.csc_id = $csc_id_payer AND costcenteraddress.adt_id = 2"); 
        if ($ad_country_payer != "DE" && $ad_country_payer != "" && $ad_country_payer != "LI" && $ad_country_payer != "NO" && $ad_country_payer != "IS" &&
            $ad_country_payer != "HR" && $ad_country_payer != "MC" && $ad_country_payer != "AL" && $ad_country_payer != "MK" && $ad_country_payer != "CH"):
          $is_EU = true;
          array_push ($tmpArr, "jb_sales_tax_rate", 0.00, "jb_sales_tax_rate_sign", "0");
          // Nur für's Logging
          $jb_sales_tax_rate = 0.00;
          $jb_sales_tax_rate_sign_new = "0";
        endif;
        updateStmt("job", "jb_id", $jb_id, $tmpArr);
      endif;
//    if ($is_EU)
    // 20.05.2025: Lt. Task #1042 soll Filter "EU" immer gesetzt sein, wenn eine Station _nicht_ in Deutschland ist
    if ($is_foreign)
      if ($getPriceOnly != 1):
        $jb_cr_filter_new = $jb_cr_filter;
        if (!in_array ("EU", explode(",", $jb_cr_filter)))
          $jb_cr_filter_new .= (trim($jb_cr_filter) == "" ? "" : ",") . "EU";
        if (!in_array ("AL", explode(",", $jb_cr_filter)) && strtotime(getParameterValue("0", "MASK_FILTER_AL_DATE", "0")) <= strtotime($jb_ordertime))
          $jb_cr_filter_new .= (trim($jb_cr_filter) == "" ? "" : ",") . "AL";
        if ($jb_cr_filter != $jb_cr_filter_new)
          updateStmt("job", "jb_id", $jb_id, array("jb_cr_filter", $jb_cr_filter_new));
      endif;
    if ((isset($jb_costsplit) && $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 (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:
      if ($jb_fixprice == 0):
        // wenn Fixpreis, dann jb_subtotal bereits vorhanden
        // sonst ermittelten Standardpreis nehmen
        // $jb_subtotal bereits ermittelt
        $jb_totalprice = $fullPrice;
        if ($jb_cr_price == 0 && MASK_CR_PRICE_MODE == "1"):
//          $jb_cr_price = $jb_cr_subtotal; // resultierender Endpreis wäre falsch, wenn Grundpreis TSZ-frei sit (wie derzeit noch in Hamburg)
          $jb_cr_price_total = $fullCrPrice;
          $jb_cr_price_rate = get_cr_price_rate($hq_id, $cs_id, $jb_ordertime, $vhtSrvt_name, $vht_id);
        endif;
      else:
        $jb_subtotal = round($jb_fixprice * (1 - ($tmp_discount_rate / 100)), 2);
        if (MASK_CR_PRICE_MODE == "1") {
          if ($jb_cr_price == 0) {
            list($jb_cr_price, $jb_cr_price_rate) =
              getCr_price_global($jb_subtotal, $hq_id, $cs_id, ($jb_tourname_old == "" ? $jb_ordertime : date("Y-m-d H:i:s")), $vhtSrvt_name, $vht_id);
          } else {
            $jb_cr_price = round($jb_cr_price * (1 - ($tmp_discount_rate / 100)), 2);
          }
        }
        $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;
      if (getParameterValue("0", "INV_SERVICEPRICE_DISCOUNT", $hq_id) == "1"):
        $jb_subtotal += round($jb_serviceprice * (1 - ($tmp_discount_rate / 100)), 2);
        $jb_totalprice += round($jb_serviceprice * (1 - ($tmp_discount_rate / 100)), 2);
        $jb_cr_serviceprice = round($jb_cr_serviceprice * (1 - ($tmp_discount_rate / 100)), 2);
      else:
        $jb_subtotal += $jb_serviceprice;
        $jb_totalprice += $jb_serviceprice;
      endif;
      // wenn Listenkunde, auch hier natürlich $jb_totalprice auf 0!!!
      if ($jobbatch_mode == true):
        $jb_subtotal = 0;
        $jb_totalprice = 0;
        $jb_cr_price = 0;
      endif;
      if (MASK_CR_PRICE_MODE == "1") {
        if ($jb_cr_serviceprice == 0 && !($jb_serviceprice == "" || $jb_serviceprice == 0))
          list($jb_cr_serviceprice, $jb_cr_serviceprice_rate) =
            getCr_price_global($jb_serviceprice, $hq_id, $cs_id, ($jb_tourname_old == "" ? $jb_ordertime : date("Y-m-d H:i:s")), $vhtSrvt_name, $vht_id);
      }
      if (MASK_CR_PRICE_MODE == "1" && strtotime(MASK_CR_PRICE_MODE_DATE) <= strtotime($jb_ordertime)) {
        // wenn $jb_cr_price_total schon definiert, dann steht der Endpreis für den Fuhrlohn bereits fest (z. B. PLZ-Preis)
        if ($jb_cr_price_total == 0) {
          $jb_cr_subtotal = round($jb_cr_price * (1 - ($self_service_discount / 100)), 2);
          $jb_cr_price_total = round($jb_cr_subtotal * (1 + ($jb_cr_markup / 100)), 2);
        }
        $jb_cr_subtotal += $jb_cr_serviceprice;
        $jb_cr_price_total += $jb_cr_serviceprice;
      }
    endif;
//    $jb_hq_id_exec_price_rate = (float) getParameterValue("0", "MASK_HQ_ID_EXEC_PRICE_RATE", $hq_id);
    // Sollte eigentlich nicht sein, aber der Fehler ist nicht zu finden
    if ($jb_origin == "") {
      writeLog_("../log/job_options_", "\$jb_origin_old = " . $jb_origin_old . ", \$jb_origin = " . $jb_origin);
      $jb_origin = $jb_origin_old;
    }
    $jb_orderer = my_str_check($jb_orderer);
    $jb_orderer_old = my_str_check($jb_orderer_old);
    $jb_commission_no = my_str_check($jb_commission_no);
    $jb_commission_no_old = my_str_check($jb_commission_no_old);
    // Treibstoffzuschlag auch auf Fuhrlohn
    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_hq_id_exec_price", (round(($jb_totalprice - $jb_cr_price_total) * $jb_hq_id_exec_price_rate, 2) + $jb_cr_price_total), */ "jb_markup", $jb_markup, "jb_tourdata", $jb_tourdata1 . "|" . $jb_tourdata2 . "|" . $jb_tourdata3, "jb_origin", $jb_origin, "jb_orderer", $jb_orderer, "jb_commission_no", $jb_commission_no));
    if ($self_service_discount > 0)
      $db->query("UPDATE jobprice SET jbprc_remark = '" . $gross_price . "' WHERE jb_id = " . $jb_id . " AND mt_sort = 13");

    // Rechnungstext erzeugen
    if (!(isset($jb_storno) && $jb_storno > 0)):
      mk_jb_invtext($jb_id, false, $tmp_add_srvs, $tmp_add_srvts, $tmp_add_mult, $tmp_add_mult_price, $tmp_add_sids, $tmp_add_prices);
    endif;
    // Job entsperren, falls gesperrt gewesen (Nachbearbeitung)
    updateStmt("job", "jb_id", $jb_id, array("jb_locktime", NULL, "jb_lockuser", NULL));
    // manuelle Disposition gewünscht => overrult alles
    // oder die Tour ist eine Ferntour (aber nicht bei Nacherfassungen!!!)
    // oder Auftrag ist nur Angebot
    if (!(isset($jb_storno) && $jb_storno > 0)):
      if ($jb_offer == 1 || $jb_status_manual == 1 || ($jb_totalprice >= 150.0 && $tourCount == 2 && $job_is_new && getParameterValue("0", "LONGHAUL_ACTIVE", 0) == "1" && $afterwards != "1")):
        $tmpArr = array("jb_status", 9);
        // wenn Ferntour, dann muss zusätzlich Flag "jb_longhaul" gesetzt werden
        if (($jb_totalprice >= 150.0 && $tourCount = 2) && (getParameterValue("0", "LONGHAUL_ACTIVE", 0) == "1")):
          array_push ($tmpArr, "jb_longhaul", 1);
        endif;
        updateStmt("job", "jb_id", $jb_id, $tmpArr);
      endif;
    endif;

    // BWV_Auftrag?
    $jb_longhaul = 0;
    $tmpArr = array();
    $check_bwv = true;
    list($total_km, $total_km_osm) = get_job_distance($jb_id);
    $check_bwv = false;
    if ($total_km == -1)
      $total_km = $db->getOne("SELECT jbprc_price FROM jobprice WHERE jb_id = " . $jb_id . " AND mt_sort = 11");
    if ($total_km > 0 && $tourCount > 1 && $total_km / ($tourCount - 1) >= getParameterValue("0", "LONGHAUL_KM", "0")) {
	  $jb_longhaul = 1;
	  if ($job_is_new && $afterwards != "1")
        $tmpArr = array("jb_status", 9);
      if (!in_array ("BWV", explode(",", $jb_cr_filter_opt)))
        array_push($tmpArr, "jb_cr_filter_opt", $jb_cr_filter_opt . (trim($jb_cr_filter_opt) == "" ? "" : ",") . "BWV");
    }
    writeLog_("../log/job_options_", "\$jb_longhaul = " . $jb_longhaul . " (\$total_km = " . $total_km . ", \$tourCount = " . $tourCount . ", LONGHAUL_KM = " . getParameterValue("0", "LONGHAUL_KM", "0") . ", \$total_km / (\$tourCount - 1) = " . $total_km / ($tourCount - 1) . ")");
    array_push ($tmpArr, "jb_longhaul", $jb_longhaul);

    $logstr_foreign = "";
    // Auslands-Auftrag?
    if ($jobList[0][JL_AD_COUNTRY] != "DE" && $jobList[0][JL_AD_COUNTRY] != "D" && $jobList[0][JL_AD_COUNTRY] != "") {
      $coords_start = get_coords($jobList[0][JL_AD_COUNTRY], $jobList[0][JL_AD_ZIPCODE], $jobList[0][JL_AD_CITY], $jobList[0][JL_AD_STREET], $jobList[$i][JL_TR_HSNO]);
      $coords_end = get_coords($jobList[$tourCount-1][JL_AD_COUNTRY], $jobList[$tourCount-1][JL_AD_ZIPCODE], $jobList[$tourCount-1][JL_AD_CITY], $jobList[$tourCount-1][JL_AD_STREET], $jobList[$tourCount-1][JL_TR_HSNO]);
      $sqlquery = // "SELECT hq_id, hq_mnemonic, hq_gps_long, hq_gps_lat FROM headquarters WHERE hq_gps_long > 0 AND hq_gps_lat > 0";
        "(SELECT hq_id, hq_mnemonic, hq_gps_long, hq_gps_lat" .
        " FROM headquarters WHERE hq_gps_long > 0 AND hq_gps_lat > 0 ORDER BY (SQRT(POW(ABS(hq_gps_lat - " . $coords_start[0] . "),2) + POW(ABS(hq_gps_long - " . $coords_start[1] . "),2)) * 111) LIMIT 3)" .
        " UNION " .
        "(SELECT hq_id, hq_mnemonic, hq_gps_long, hq_gps_lat" .
        " FROM headquarters WHERE hq_gps_long > 0 AND hq_gps_lat > 0 ORDER BY (SQRT(POW(ABS(hq_gps_lat - " . $coords_end[0] . "),2) + POW(ABS(hq_gps_long - " . $coords_end[1] . "),2)) * 111) LIMIT 3)";
      $res = $db->query($sqlquery);
      if (DB::isError($res)) reportDie ("$PHP_SELF: '$sqlquery': " . $res->getMessage());
      $round_kms_min = 0;
      $hq_id_min = 0;
      while ($row = $res->fetch_assoc()):
        $round_kms = get_job_distance($jb_id, "km", $tr_sort = 0, $row["hq_gps_lat"], $row["hq_gps_long"], $row["hq_gps_lat"], $row["hq_gps_long"]);
        if ($round_kms_min == 0 || $round_kms[0] < $round_kms_min) {
          $round_kms_min = $round_kms[0];
          $hq_id_min = $row["hq_id"];
        }
        $logstr_foreign .= ($logstr_foreign != "" ? ";" : "") . $row["hq_mnemonic"] . ":" . $round_kms[0];
      endwhile;
      $res->free();
      array_push ($tmpArr, "hq_id_dispo", $hq_id_min);
    }
    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
      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_toll'");
    // Maut wird extra gespeichert
    if (trim($jb_toll) != "")
      insertStmt("genericdatacontainer", array("gdc_obj_type", "jb", "gdc_obj_id", $jb_id, "gdc_gen_fieldname", "jb_toll", "gdc_content", $jb_toll, "gdc_context", (isset($jb_toll_context) ? $jb_toll_context : "")));

    deleteStmt("genericdatacontainer", "gdc_obj_type = 'jb' AND gdc_obj_id = " . $jb_id . " AND gdc_gen_fieldname = 'jb_hiddenFreetext_1'");
    // Für die Fahrer nicht sichtbarer Rechnungtext wird extra gespeichert
    if (trim($jb_hiddenFreetext_1) != "")
      insertStmt("genericdatacontainer", array("gdc_obj_type", "jb", "gdc_obj_id", $jb_id, "gdc_gen_fieldname", "jb_hiddenFreetext_1", "gdc_content", $jb_hiddenFreetext_1, "gdc_context", ""));

    deleteStmt("genericdatacontainer", "gdc_obj_type = 'jb' AND gdc_obj_id = $jb_id AND gdc_gen_fieldname = 'jb_id_permanent_pre'");
    if (isset($jb_id_permanent_pre) && $jb_id_permanent_pre != "")
      insertStmt("genericdatacontainer", array("gdc_obj_type", "jb", "gdc_obj_id", $jb_id, "gdc_gen_fieldname", "jb_id_permanent_pre", "gdc_content", $jb_id_permanent_pre, "gdc_context", date("Y-m-d H:i:s")));
//    deleteStmt("genericdatacontainer", "gdc_obj_type = 'jb' AND gdc_obj_id = $jb_id AND gdc_gen_fieldname = 'jb_multi'");
//    if ($jb_multi != "")
//      insertStmt("genericdatacontainer", array("gdc_obj_type", "jb", "gdc_obj_id", $jb_id, "gdc_gen_fieldname", "jb_multi", "gdc_content", $jb_multi_factor, "gdc_context", date("Y-m-d H:i:s")));

//    deleteStmt("genericdatacontainer", "gdc_obj_type = 'jb' AND gdc_obj_id = $jb_id AND gdc_gen_fieldname = 'jb_cashpayer_mail' AND gdc_context = ''");
//    if (trim($jb_cashpayer_mail) != "")
//      insertStmt("genericdatacontainer", array("gdc_obj_type", "jb", "gdc_obj_id", $jb_id, "gdc_gen_fieldname", "jb_cashpayer_mail", "gdc_content", $jb_cashpayer_mail, "gdc_context", ""));
    if (existsEntry("genericdatacontainer", array("gdc_obj_type", "jb", "gdc_obj_id", $jb_id, "gdc_gen_fieldname", "jb_cashpayer_mail"))) {
      updateStmt("genericdatacontainer", "gdc_obj_id", $jb_id, array("gdc_content", $jb_cashpayer_mail), "gdc_obj_type = 'jb' AND gdc_gen_fieldname = 'jb_cashpayer_mail'");
	} else {
      if (trim($jb_cashpayer_mail) != "")
        insertStmt("genericdatacontainer", array("gdc_obj_type", "jb", "gdc_obj_id", $jb_id, "gdc_gen_fieldname", "jb_cashpayer_mail", "gdc_content", $jb_cashpayer_mail, "gdc_context", ""));
	}
    if (existsEntry("genericdatacontainer", array("gdc_obj_type", "jb", "gdc_obj_id", $jb_id, "gdc_gen_fieldname", "jb_offer_mail"))) {
      updateStmt("genericdatacontainer", "gdc_obj_id", $jb_id, array("gdc_content", $jb_offer_mail), "gdc_obj_type = 'jb' AND gdc_gen_fieldname = 'jb_offer_mail'");
	} else {
      if (trim($jb_offer_mail) != "")
        insertStmt("genericdatacontainer", array("gdc_obj_type", "jb", "gdc_obj_id", $jb_id, "gdc_gen_fieldname", "jb_offer_mail", "gdc_content", $jb_offer_mail, "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) != "" && $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;

    deleteStmt("genericdatacontainer", "gdc_obj_type = 'jb' AND gdc_obj_id = $jb_id AND gdc_gen_fieldname = 'jb_origin_other' AND gdc_context = ''");
    if (trim($jb_origin_other) != "")
      insertStmt("genericdatacontainer", array("gdc_obj_type", "jb", "gdc_obj_id", $jb_id, "gdc_gen_fieldname", "jb_origin_other", "gdc_content", $jb_origin_other, "gdc_context", ""));

    deleteStmt("genericdatacontainer", "gdc_obj_type = 'jb' AND gdc_obj_id = $jb_id AND gdc_gen_fieldname = 'jb_bwv' AND gdc_context = ''");
    if ($jb_bwv == "1")
      insertStmt("genericdatacontainer", array("gdc_obj_type", "jb", "gdc_obj_id", $jb_id, "gdc_gen_fieldname", "jb_bwv", "gdc_content", $jb_bwv, "gdc_context", ""));

    // Kinderaufträge bearbeiten
    // ... falls im Calculator
    if (getParameterValue("0", "MASK_CHILDREN_TAX_HARDCODED", 0) == "1"):
      saveJobChildren($jb_id,
         array("hq_id", $hq_id, "vht_id", $vht_id, "jb_payment", $jb_payment,
              "jb_status", "2", "jb_autoranking", "0", "jb_type", $jb_type, "emp_id", $usr_id, 
              "jb_postage", 0, "jb_invmode", $jb_invmode, "jb_freetext_1", "",
              "jb_sales_tax_rate", 0, "jb_sales_tax_rate_sign", '4'),
        $tmp_add_jb_ids, $tmp_add_sids, $tmp_add_prices, $jb_markup, $tmp_discount_rate, $jb_serviceprice);
    else:
      saveJobChildren($jb_id,
         array("hq_id", $hq_id, "vht_id", $vht_id, "jb_payment", $jb_payment,
              "jb_status", "2", "jb_autoranking", "0", "jb_type", $jb_type, "emp_id", (isset($usr_id) ? $usr_id : 0), 
              "jb_postage", 0, "jb_invmode", (isset($jb_invmode) ? $jb_invmode : 0), "jb_freetext_1", "",
              "jb_sales_tax_rate", $jb_sales_tax_rate, "jb_sales_tax_rate_sign", $jb_sales_tax_rate_sign_new),
        $tmp_add_jb_ids, $tmp_add_sids, $tmp_add_prices, $jb_markup, $tmp_discount_rate, $jb_serviceprice);
    endif;
    $jb_third_country_old = $db->getOne("SELECT gdc_content FROM genericdatacontainer WHERE gdc_obj_type = 'jb' AND gdc_obj_id = " . $jb_id . " AND gdc_gen_fieldname = 'jb_third_country'");
//echo "is_EU_only = " . $is_EU_only . "<br>\n";
//echo "jb_third_country_old = " . $jb_third_country_old . "<br>\n";
    if (!$is_EU_only) {
      if ($jb_third_country_old != "1") {
        insertStmt("genericdatacontainer", array("gdc_obj_type", "jb", "gdc_obj_id", $jb_id, "gdc_gen_fieldname", "jb_third_country", "gdc_content", "1", "gdc_context", ""));
        // Log-Eintrag "Anforderung des Versenderstatus bestätigt durch #Name" wird am Ende eingetragen, damit das nicht der erste Log-Eintrag ist
//        writeToLogDB(151, $hq_id, $jb_id, $usr_id, "", "", "", "");
        if ($job_is_new) {
          $jb_incomplete = "1";
        }
//      } else {
////echo "jb_incomplete_old = " . $jb_incomplete_old . "<br>\n";
////echo "jb_incomplete = " . $jb_incomplete . "<br>\n";
//        if ($jb_incomplete == "" && $jb_incomplete_old == "1")
//        // Log-Eintrag "Umsatzsteuerrechtlich korrekte Abrechnung bestätigt durch #Name"
//          writeToLogDB(152, $hq_id, $jb_id, $usr_id, "", "", "", "");
      }
	} else {
      deleteStmt("genericdatacontainer", "gdc_obj_type = 'jb' AND gdc_obj_id = " . $jb_id . " AND gdc_gen_fieldname = 'jb_third_country'");
	}
// TOBEDONE: - Eintrag in genericdatacontainer für Export wenn !is_eu_only
// - Neue log_operation für Bestätigungen (Abfrage bei Erfassung und dann Hinweis bei späterem Entfernen von jb_incomplete)
    // Prüfen, ob jb_incomplete-Flag gesetzt werden muss
    check_jb_incomplete($jb_id, $jb_incomplete); //nach saveJobChildren, damit evtl. Unteraufträge auch mit verarztet werden

    // Prüfen, ob jb_serviceprice gesetzt werden muss
    if ($job_is_new)
      check_jb_serviceprice($jb_id, $hq_id, $jb_ordertime);

    // Fuhrlohn berechnen (auch bei einem geänderten Auftrag evtl. nötig, daher immer aufrufen)
//    setCr_price($jb_id);

    $db->query("DELETE FROM jobprice WHERE jb_id = " . $jb_id . " AND (mt_sort < 11 OR mt_sort = 15)");
    $insert_clause = 
      /*($jb_cr_markup > 0 ?*/ "(" . $jb_id . ", " . (trim($jb_cr_markup_ori) == "" ? 1 : 9) . ", " . $jb_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 . "), " : "") .
      (isset($jb_cr_price_rate) && $jb_cr_price_rate > 0 ? "(" . $jb_id . ", 5, " . $jb_cr_price_rate . "), " : "") .
      (isset($jb_cr_serviceprice_rate) && $jb_cr_serviceprice_rate > 0 ? "(" . $jb_id . ", 6, " . $jb_cr_serviceprice_rate . "), " : "") .
//      ($jb_cr_agio > 0 ? "(" . $jb_id . ", 7, " . $jb_cr_agio . "), " : "") .
      (trim($jb_markup_ori != "") ? "(" . $jb_id . ", 8, " . $jb_markup . "), " : "") .
      ($jb_cr_subtotal > 0 || $jb_cr_subtotal < 0 ? "(" . $jb_id . ", 10, " . $jb_cr_subtotal . "), " : "");
    $db->query("INSERT INTO jobprice (jb_id, mt_sort, jbprc_price) VALUES " . substr($insert_clause, 0, strlen($insert_clause) - 2));
    if ((!isset($jb_km_old) || $jb_km_old != $jb_km) && trim($jb_km_ori != "")) {
      $db->query("DELETE FROM jobprice WHERE jb_id = " . $jb_id . " AND mt_sort IN (11, 12)");
      $db->query("INSERT INTO jobprice (jb_id, mt_sort, jbprc_price, jbprc_remark) VALUES (" . $jb_id . ", 11, " . $jb_km . ", 'm')");
    }
    if ($jb_price_km > 0) {
      $db->query("INSERT INTO jobprice (jb_id, mt_sort, jbprc_price) VALUES (" . $jb_id . ", 15, " . $jb_price_km . ")");
    }

// UPDATE jobprice SET  mt_sort = 10 WHERE mt_sort = 8
    // 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 = my_str_check_mobile($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;

    updateStmt("genericdatacontainer", "gdc_obj_id", $jb_id, array("gdc_content", "0", "gdc_context", date("Y-m-d H:i:s")), "gdc_obj_type = 'jb' AND gdc_gen_fieldname = 'jb_blink' AND gdc_content = '1'");
    if (MASK_CR_PRICE_MODE == "1"):
      $tr_remark = my_str_check_mobile($db->getOne("SELECT tr_remark FROM tour WHERE jb_id = " . $jb_id . " AND tr_sort = 1"));
//echo str_replace("\n", "&lt;br&gt;<br>", $tr_remark) . "<hr>";die();
      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;


      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);
//echo str_replace("\n", "&lt;br&gt;<br>", $tr_remark) . "<hr>";die();
      updateStmt("tour", "jb_id", $jb_id, $tmpArr, "tr_sort = 1");
      if ($tr_sort_cashpayer > 0):
        if ($tr_sort_cashpayer != 1)
          $tr_remark = my_str_check_mobile($db->getOne("SELECT tr_remark FROM tour WHERE jb_id = " . $jb_id . " AND tr_sort = " . $tr_sort_cashpayer));
        $jb_totalprice_tax = round(($jb_totalprice  + (float) $jb_toll) * ($jb_sales_tax_rate / 100), 2);
//echo str_replace("\n", "&lt;br&gt;<br>", $tr_remark);
        $tr_remark = str_replace("*** ZAHLT BAR ***", "*** Bitte im Auftrag STADTBOTE Bar " . str_replace(".", ",", sprintf("%01.2f", $jb_totalprice + (float) $jb_toll)) . " EUR zzgl. " .
          str_replace(".", ",", sprintf("%01.2f", $jb_totalprice_tax)) . " EUR MwSt (Gesamt " . str_replace(".", ",", sprintf("%01.2f", $jb_totalprice + (float) $jb_toll + $jb_totalprice_tax)) .
          " EUR) kassieren und quittieren. ***", $tr_remark);
//echo str_replace("\n", "&lt;br&gt;<br>", $tr_remark);
        $tmpArr = array("tr_remark", $tr_remark);
        updateStmt("tour", "jb_id", $jb_id, $tmpArr, "tr_sort = " . $tr_sort_cashpayer);
      endif;
    endif;

    if ($jb_id_insurance != "" && ($special_case_ori == 0 || $special_case == 0)) {
      deleteStmt("genericdatacontainer", "gdc_obj_type = 'jb' AND gdc_obj_id = " . $jb_id . " AND gdc_gen_fieldname = 'jb_id_insurance'");
      deleteStmt("job", "jb_id = " . $jb_id_insurance);
      deleteStmt("tour", "jb_id = " . $jb_id_insurance);
      deleteStmt("tourservice", "jb_id = " . $jb_id_insurance);
    }
    if ($jb_value_of_goods != "" && ($special_case_ori == 0 || $special_case == 0)) {
      $jb_id_insurance = saveJobInsurance($jb_id, $csc_id_payer, $vht_id, $jb_ordertime, $jb_value_of_goods, $jb_insurance_rate, $special_case);
      insertStmt("genericdatacontainer", array("gdc_obj_type", "jb", "gdc_obj_id", $jb_id, "gdc_gen_fieldname", "jb_id_insurance", "gdc_content", $jb_id_insurance, "gdc_context", $jb_value_of_goods . "|" . $jb_insurance_rate . "|" . $special_case));
      updateStmt("job", "jb_id", $jb_id_insurance, array("jb_origin", 8, "jb_orderer", $jb_orderer));
//      insertStmt("genericdatacontainer", array("gdc_obj_type", "jb", "gdc_obj_id", $jb_id, "gdc_gen_fieldname", "jb_origin_other", "gdc_content", "Höherversicherung", "gdc_context", ""));
    } else {
      $jb_id_insurance = 0;
    }

    $job_checkboxes = "";
    if ($job_is_new) {
      $jb_origin_text = "Auftragsherkunft ";
      switch ($jb_origin) {
        case 0:
            $jb_origin_text .= "ohne&nbsp;Angabe";
            break;
        case 1:
            $jb_origin_text .= "Telefon";
            break;
        case 2:
            $jb_origin_text .= "Mail";
            break;
        case 3:
            $jb_origin_text .= "Schnittstelle";
            break;
        case 4:
            $jb_origin_text .= "KAE";
            break;
        case 5:
            $jb_origin_text .= "Dauerauftrag";
            break;
        case 6:
            $jb_origin_text .= "Sonstiges (". $jb_origin_other . ")";
            break;
        default:
            $jb_origin_text .= "unbekannt";
      }
      $job_checkboxes = ", `" . $jb_origin_text . "´";
    }
    if (isset($afterwards) && $afterwards == 1) { $job_checkboxes .= ", `Nacherfassung´"; }
    if ($jb_globaljob == 1) { $job_checkboxes .= ", `An alle Kuriere´"; }
    if (isset($jb_status_manual) && $jb_status_manual == 1) { $job_checkboxes .= ", `Manuelle Disposition´"; }
    if ($jb_incomplete == 1) { $job_checkboxes .= ", `Noch unvollständig´"; }
    if ($jb_offer == 1) { $job_checkboxes .= ", `Angebot´"; }
    if (isset($jb_tourname_overwrite) && $jb_tourname_overwrite == 1) { $job_checkboxes .= ", `Gespeicherte Tour überschreiben´"; }
    if ($jb_id_insurance != 0) { $job_checkboxes .= ", `Höherversicherung (" . $jb_id_insurance . ")´"; }
    if ($special_case == 1) { $job_checkboxes .= ", `Sonderfall´"; }
    if (isset($jb_tourname_hidden) && $jb_tourname_hidden != "") { $job_checkboxes .= ", `Konserve \"" . $jb_tourname_hidden . "\"´"; }
    $jb_multi_str = "";
    if ((isset($jb_multi_factor) && $jb_multi_factor > 1)) { $jb_multi_str .= "|\$jb_multi_factor=$jb_multi_factor"; }
    if ((isset($jb_multi_factor_ori) && $jb_multi_factor_ori > 1 && !isset($i_multi))) { $jb_multi_str .= "|\$jb_multi_factor=$jb_multi_factor_ori"; }
    if (isset($i_multi)) {
	  $jb_multi_str .= "|\$i_multi=$i_multi";
      $usr_id = $db->getOne("SELECT usr_id FROM phoenix_log.log WHERE jb_id = " . $jb_id_ori_copy . " AND logo_id IN (1,25)");
    }

    $changes_text_add = "";
    $changes_str_add = "";
    if ($job_is_new) {
      if ($hq_id_dispo != $hq_id) { $changes_str_add .= "|hq_id_dispo=$hq_id_dispo"; }
      if ($logstr_foreign != "") { $changes_str_add .= "|ROUND_KMS=" . $logstr_foreign; }
      if ($jb_longhaul == 1) { $changes_str_add .= "|JB_LONGHAUL=$jb_longhaul"; }
    }
    if (isset($cs_invmail) && $cs_invmail_old != $cs_invmail) { $changes_text_add .= ", Rechnungs-Email"; $changes_str_add .= "|\$cs_invmail_old=$cs_invmail_old|\$cs_invmail=$cs_invmail"; }
    if ($cmp_postage_old != $cmp_postage) { $changes_text_add .= ", Porto"; $changes_str_add .= "|\$cmp_postage_old=$cmp_postage_old|\$cmp_postage=$cmp_postage"; }

    if ($request_token != "") { // e.g. no request_token when storno
      writeLog_("../log/job_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 = "";
      $pda_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"; $pda_changes_text .= "#$jb_id, Maximalgewicht"; }
        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"; $pda_changes_text .= "#$jb_id, Länge"; }
        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"; $pda_changes_text .= "#$jb_id, Breite"; }
        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"; $pda_changes_text .= "#$jb_id, Höhe"; }
        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"; $pda_changes_text .= "#$jb_id, Stellplätze"; }
        if ($jb_ordertime_old != $jb_ordertime) { $changes_text .= ", Datum und/oder Uhrzeit"; $changes_str .= "|\$jb_ordertime_old=$jb_ordertime_old|\$jb_ordertime=$jb_ordertime"; $pda_changes_text .= "#$jb_id, Datum bzw. Uhrzeit"; }
//        if ($jb_reserv == 1 && ($jb_ordertime_old != $jb_ordertime)) { $changes_text .= ", Datum und/oder Uhrzeit"; $changes_str .= "|\$jb_ordertime_old=$jb_ordertime_old|\$jb_ordertime=$jb_ordertime"; $pda_changes_text .= "#$jb_id, Datum bzw. Uhrzeit"; }
        if ($jb_reserv_old != $jb_reserv && $jb_reserv != "") { $changes_text .= ", Vorbestellung"; $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 (MASK_CR_PRICE_MODE == "1") {
          $jb_cr_serviceprice_compare = ($jb_cr_serviceprice == "0" ? "" : $jb_cr_serviceprice);
          if ($jb_cr_serviceprice_old != $jb_cr_serviceprice_compare) { $changes_text .= ", Servicevergütung"; $changes_str .= "|\$jb_cr_serviceprice_old=$jb_cr_serviceprice_old|\$jb_cr_serviceprice=$jb_cr_serviceprice"; $pda_changes_text .= "#$jb_id, Servicevergütung\n"; }
          if ($jb_cr_price_old != $jb_cr_price_total && $jb_cr_price_total != "") { $changes_text .= ", Frachtvergütung"; $changes_str .= "|\$jb_cr_price_old=$jb_cr_price_old|\$jb_cr_price=$jb_cr_price_total"; $pda_changes_text .= "#$jb_id, Frachtvergütung\n"; }
	    }
        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"; $pda_changes_text .= "#$jb_id, Zahler oder Zahlungsmodus\n"; }
//        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 (my_str_check($jb_hiddenFreetext_1_old) != my_str_check_http($jb_hiddenFreetext_1)) { $changes_text .= ", verborgener Rechnungstext"; $changes_str .= "|\$jb_hiddenFreetext_1_old=" . my_str_check($jb_hiddenFreetext_1_old) . "|\$jb_hiddenFreetext_1=" . my_str_check_http($jb_hiddenFreetext_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_warningtime_old == "0000-00-00 00:00:00")
          $jb_warningtime_old = "";
        if ($jb_warningtime_old != $jb_warningtime) { $changes_text .= ", Enddatum/-uhrzeit der Dispo-Info"; $changes_str .= "|\$jb_warningtime_old=$jb_warningtime_old|\$jb_warningtime=$jb_warningtime";}
//        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 ($jb_cashpayer_mail_old != $jb_cashpayer_mail) { $changes_text .= ", Barzahler-Erledigungsmail"; $changes_str .= "|\$jb_cashpayer_mail_old=$jb_cashpayer_mail_old|\$jb_cashpayer_mail=$jb_cashpayer_mail"; }
        if ($jb_offer_mail_old != $jb_offer_mail) { $changes_text .= ", Angebots-Mail"; $changes_str .= "|\$jb_offer_mail_old=$jb_offer_mail_old|\$jb_offer_mail=$jb_offer_mail"; }
        if ($jb_markup_old != $jb_markup) { $changes_text .= ", Treibstoffzuschlag"; $changes_str .= "|\$jb_markup_old=$jb_markup_old|\$jb_markup=$jb_markup"; }
        if (MASK_CR_PRICE_MODE == "1") {
          if ($jb_cr_markup_old != $jb_cr_markup) { $changes_text .= ", Treibstoffzuschlag"; $changes_str .= "|\$jb_cr_markup_old=$jb_cr_markup_old|\$jb_cr_markup=$jb_cr_markup"; $pda_changes_text .= "#$jb_id, Treibstoffzuschlag\n"; }
        }
        if ($jb_toll_old != $jb_toll) { $changes_text .= ", Maut"; $changes_str .= "|\$jb_toll_old=$jb_toll_old|\$jb_toll=$jb_toll"; $pda_changes_text .= "#$jb_id, Maut\n"; }
        if ($jb_km_old != $jb_km && trim($jb_km != "")) { $changes_text .= ", Kilometer"; $changes_str .= "|\$jb_km_old=$jb_km_old|\$jb_km=$jb_km"; }
        if ($hq_id_dispo_old != $hq_id_dispo) { $changes_text .= ", Ausführende NL:"; $changes_str .= "|\$hq_id_dispo_old=$hq_id_dispo_old|\$hq_id_dispo=$hq_id_dispo"; }
        if ($jb_longhaul_old != $jb_longhaul) { $changes_text .= ", BWV-Auftrag"; $changes_str .= "|\$jb_longhaul_old=$jb_longhaul_old|\$jb_longhaul=$jb_longhaul"; }
        if ($jb_origin_old != $jb_origin)  { $changes_text .= ", Auftragseingang"; $changes_str .= "|\$jb_origin_old=$jb_origin_old|\$jb_origin=$jb_origin"; }
        if ($jb_origin_other_old != $jb_origin_other)  { $changes_text .= ", Auftragseingang-Sonstiges"; $changes_str .= "|\$jb_origin_other_old=$jb_origin_other_old|\$jb_origin_other=$jb_origin_other"; }
        if ($jb_orderer_old != $jb_orderer)  { $changes_text .= ", Besteller"; $changes_str .= "|\$jb_orderer_old=$jb_orderer_old|\$jb_orderer=$jb_orderer"; }
        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;
        $tr_status_all = 1;
        $jb_finishtime_new = "0000-00-00 00:00:00";
        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, $tr_id) =
                  getTourData($jb_id, $i, "tour");
              $tr_photo = $db->getOne("SELECT gdc_content FROM genericdatacontainer WHERE gdc_obj_type = 'tr' AND gdc_obj_id = " . $tr_id . " AND gdc_gen_fieldname = 'tr_photo' AND NOT (gdc_context LIKE '%|forced')");
//echo "<br>$i" . $tr_photo;
            } else {
              $tr_add_str .= "$i, "; 
              $changes_text .= ", Station $i hinzugefügt";
              $pda_changes_text .= "#$jb_id/$i, hinzugefügt\n";
            }
          } 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, "; 
              $changes_text .= ", Station $i gelöscht";
              $pda_changes_text .= "#$jb_id/$i, gelöscht\n";
            endif;
          }
          if ($i < $i_tour_max_old && $tourFound == 1) {
            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]; $pda_changes_text .= "#$jb_id/$i, Firma\n"; }
            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]; $pda_changes_text .= "#$jb_id/$i, Person\n"; }
            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]; $pda_changes_text .= "#$jb_id/$i, Straße\n"; }
            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]; $pda_changes_text .= "#$jb_id/$i, Hausnummer\n"; }
            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]; $pda_changes_text .= "#$jb_id/$i, PLZ\n"; }
            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]; $pda_changes_text .= "#$jb_id/$i, Ort\n"; }
            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]; $pda_changes_text .= "#$jb_id/$i, Land\n"; }
            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]; $pda_changes_text .= "#$jb_id/$i, Bemerkung\n"; }
//            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]; $pda_changes_text .= "#$jb_id/$i, Status"; }
            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]; $pda_changes_text .= "#$jb_id/$i, An/Ab\n"; }
            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]; $pda_changes_text .= "#$jb_id/$i, Kommissionsnummer\n"; }
            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]; }
            if ($tr_photo != $tr_photo_old_[$i]) { $changes_text .= ", $i. Foto"; $changes_str .= "|\$tr_photo_$i=".str_replace("|", "/", $tr_photo)."|\$tr_photo_old_$i=".str_replace("|", "/", $tr_photo_old_[$i]);  $pda_changes_text .= "#$jb_id/$i, Foto\n"; }
            // 28.05.2021: After deleting a station it has to be checked, whether this causes a job to be finished now
            if ($jb_status != 2 && $tr_status_all == 1 && $tourFound == 1) {
              if ($tr_status == "1") {
                if ($tr_finishtime != "" && $tr_finishtime != "0000-00-00 00:00:00" && strtotime($jb_finishtime_new) < strtotime($tr_finishtime))
                  $jb_finishtime_new = $tr_finishtime;
              } else {
                $tr_status_all = 0;
              } 
            }
          }
          $i++;
        } while ($tourFound == 1 || $i < $i_tour_max_old);
        if ($tr_add_str != "") {
          $changes_str .= "|\$tr_add=" . substr($tr_add_str, 0, -2);
          // 29.04.2021: After adding a station the automail has to be sent another time
          if ($jb_status_manual == 1) {
            updateStmt("job", "jb_id", $jb_id, array("jb_automailsent", "0"));
            deleteStmt("phoenix_log.semaphor", "sp_obj_type = 'jb' AND sp_obj_id = " . $jb_id . " AND sp_fieldname = 'automailer' AND sp_context = 'LOCKED'");
          }
        }
        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);
          // Bei einem laufenden PDA-Auftrag (jb_status = 1) PDA-Kommando absetzen, damit der Fahrer informiert ist...
          if (getFieldValueFromId("job", "jb_id", "$jb_id", "jb_status") == 1 && $pda_changes_text != ""):
            $crId = getFieldValueFromId("job", "jb_id", "$jb_id", "cr_id");
            if ($crId != ""):
              // Execution Time: 20 Sekunden von jetzt an; damit soll sichergestellt werden, dass die geänderten Daten bereits auf dem PDA vorliegen,
              //   _bevor_ die Änderungsmitteilung den Fahrer aus dem Schlaf weckt...
              $pdaCommandExecTime = getdate(mktime(date("H"), date("i"), date("s") + 20, date("m"), date("d"), date("Y")));
              $pdaCommandExecTimeMySQL = $pdaCommandExecTime['year'] . "-" . sprintf("%02d", $pdaCommandExecTime['mon']) . "-" . sprintf("%02d", $pdaCommandExecTime['mday']) .
                " " . sprintf("%02d", $pdaCommandExecTime['hours']) . ":" . sprintf("%02d", $pdaCommandExecTime['minutes']) . ":" . sprintf("%02d", $pdaCommandExecTime['seconds']);
              // Expiration Time: 36 Stunden von Auftragszeit oder von jetzt an (je nachdem was später ist);
              // die Nachricht soll nicht noch Tage später den Fahrer erschrecken, wenn der Auftrag schon lange vorbei ist
              // und er schon gar nicht mehr weiß, was das überhaupt für ein Auftrag gewesen ist...
              $pdaCommandExpireTimeFromNow = getdate(mktime(date("H") + 36, date("i"), date("s"), date("m"), date("d"), date("Y")));
              $jb_ordertime_vals = getValsFromDate(getFieldValueFromId("job", "jb_id", $jb_id, "jb_ordertime"));
              $pdaCommandExpireTimeFromOrdertime = getdate(mktime($jb_ordertime_vals[3] + 36, $jb_ordertime_vals[4], $jb_ordertime_vals[5],
                $jb_ordertime_vals[1], $jb_ordertime_vals[2], $jb_ordertime_vals[0]));
//echo "<br>\$pdaCommandExpireTimeFromNow:<br>";
//print_r ($pdaCommandExpireTimeFromNow);
//echo "<br>\$pdaCommandExpireTimeFromOrdertime:<br>";
//print_r ($pdaCommandExpireTimeFromOrdertime);
              if ($pdaCommandExpireTimeFromNow > $pdaCommandExpireTimeFromOrdertime):              
                $pdaCommandExpireTime = $pdaCommandExpireTimeFromNow;
              else:
                $pdaCommandExpireTime = $pdaCommandExpireTimeFromOrdertime;
              endif;
//echo "<br>\$pdaCommandExpireTime:<br>";
//print_r ($pdaCommandExpireTime);
              $pdaCommandExpireTimeMySQL = $pdaCommandExpireTime['year'] . "-" . sprintf("%02d", $pdaCommandExpireTime['mon']) . "-" . sprintf("%02d", $pdaCommandExpireTime['mday']) .
                " " . sprintf("%02d", $pdaCommandExpireTime['hours']) . ":" . sprintf("%02d", $pdaCommandExpireTime['minutes']) . ":" . sprintf("%02d", $pdaCommandExpireTime['seconds']);
//echo "<br>\$pdaCommandExpireTimeMySQL:<br>";
//echo $pdaCommandExpireTimeMySQL;
              insertPDACommand($hq_id, $crId, "7", "1", $pda_changes_text, $pdaCommandExecTimeMySQL, $pdaCommandExpireTimeMySQL);
            endif;
          endif;
        endif;
      endif;
      $changes_text .= $job_checkboxes;
      if ($changes_text != "")
        $changes_text = " (" . substr($changes_text, 2) . ")";
      writeToLogDB(($job_is_new == true ? (!(isset($check_jb_permanent_flag) && $check_jb_permanent_flag == true) ? 1 : 161) : 2), $hq_id, $jb_id, (isset($usr_id) ? $usr_id : 0), "", "", "", $jobMode . $changes_text . $changes_text_add . $jb_multi_str . $changes_str . $changes_str_add);
    }
    else
    {
      if ($job_checkboxes != "")
        $job_checkboxes = " (" . substr($job_checkboxes, 2) . ")";
      if ($jobMode == "") // 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 . $changes_text_add . $job_checkboxes . "|JB_ID_ORG=$jb_id_org" . $jb_multi_str . $changes_str_add);
    }
    if (isset($tr_del_str) && $tr_del_str != "" && $jb_status != 2 && $tr_status_all == 1) {
      writeToLogDB(4, $hq_id, $jb_id, $usr_id, "", "", "", "finished due to deleting station(s) by " . $jb_finishtime_new);
      $crId = getFieldValueFromId("job", "jb_id", "$jb_id", "cr_id");
      $today = getdate();
      $now = $today['year'] . "-" . sprintf("%02d", $today['mon']) . "-" . sprintf("%02d", $today['mday']) . " " .
        sprintf("%02d", $today['hours']) . ":" . sprintf("%02d", $today['minutes']) . ":" . sprintf("%02d", $today['seconds']);
      $cmd_exec_limit = date("Y-m-d H:i:s", mktime(date("H"), date("i"), date("s"), date("m"), date("d"), date("Y") + 1));
      // 20.08.2025: cmd_command changed from 3 to 5
      insertPDACommand($hq_id, $crId, "5", "1", $jb_id, $now, $cmd_exec_limit);
    }
    if (!$is_EU_only && $jb_third_country_old != "1")
      // Log-Eintrag "Anforderung des Versenderstatus bestätigt durch #Name"
      writeToLogDB(151, $hq_id, $jb_id, $usr_id, "", "", "", "");
// Erst hier Log-Eintrag wenn jb_incomplete immer noch incomplete
    if (!$is_EU_only && $jb_third_country_old == "1" && $db->getOne("SELECT jb_incomplete FROM job WHERE jb_id = " . $jb_id) == 0 && $jb_incomplete_old == "1") {
      // Log-Eintrag "Umsatzsteuerrechtlich korrekte Abrechnung bestätigt durch #Name"
      writeToLogDB(152, $hq_id, $jb_id, $usr_id, "", "", "", "");
    }
    if (isset($cr_price_threshold_override) && trim($cr_price_threshold_override) != "") {
      // Log-Eintrag "Überschreiten der Fuhrlohnschwelle bestätigt #Name"
      writeToLogDB(153, $hq_id, $jb_id, $usr_id, "", "", "", $cr_price_threshold_override);
    }
    if (isset($cr_price_block_override) && trim($cr_price_block_override) != "") {
      // Log-Eintrag "Überschreiten der Fuhrlohnsperre bestätigt #Name"
      writeToLogDB(154, $hq_id, $jb_id, $usr_id, "", "", "", $cr_price_block_override);
    }
//writeLog_("../log/job_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));
    }
//    deleteStmt("phoenix_log.semaphor","sp_obj_type = 'jb' AND sp_obj_id = 0 AND sp_fieldname = 'job_options'");
    // 11.07.2024: falls das COMMIT nicht geklappt hat, eine Alarm-Mail senden
    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_block . ", " . date("Y-m-d H:i:s") . ")') WHERE sp_id = " . $sp_id);
      }
/*
       $params = "";
       foreach($HTTP_POST_VARS as $key=>$value) { $params .= $key.'='.$value.'&'; }
       rtrim($fields_string, '&');
//    $options = array(
//        'http' => array(
//            'header'  => "Content-type: text/html; charset=iso-8859-1\r\n",
//            'method'  => 'POST',
//            'content' => $params
//        )
//    );
    $result = file_get_contents("https://ext01.sb-test.assecutor.de/jobs/job_options.php?" . $params);
print_r($params);
die($result);
*/
      $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_block . ", " . date("Y-m-d H:i:s") . ")') WHERE sp_id = " . $sp_id);
      }
    endif;

//echo "\$is_globaljob = " . $is_globaljob;
    if ($is_globaljob):
      $cmd = "php ../service/service_aaa_multi_check.php acapella7890 " . $jb_id . " >> " . "../log/service_aaa_multi_check_" . date("Ym") . ".log" . " 2>&1 &";
      exec($cmd); 
    endif;
    $dummy = file ("http://www.assecutor.de/stadtbote/tools/check_address_caller.php?jb_id=$jb_id&hq_id=$hq_id&inst=" . getParameterValue("0", "GLOBAL_UNIQUE_DB_INSTANCE_NO", "0"));
//    $cmd = "php ../sysadmin/check_special_chars.php " . $jb_id . " >> ../log/check_special_chars.stdout+err 2>&1 &";
//    exec($cmd);
    // check whether there is something to do with jb_cr_price
    if (getFieldValueFromId("job", "jb_id", "$jb_id", "jb_status") == 2)
      check_cr_agio($jb_id);
    photosToBeMadeForLastStation($jb_id);
    if ($job_is_new)
      initJobSemaphors($jb_id);
    if (!isset($jb_multi) || $jb_multi == "")
      $jb_multi = "0";
    if (!isset($jb_multi_factor) || $jb_multi_factor == "")
      $jb_multi_factor = "1";
//echo "job_options: php ../jobs/check_jb_permanent.php " . $jb_id . " " . $jb_multi . " " . $jb_multi_factor . " >> " . "../log/check_jb_permanent_multi_" . date("Ym") . ".log" . " 2>&1 &";
    if ($jb_multi == "1" || $jb_multi_factor != "1") {
      $cmd = "php ../jobs/check_jb_permanent.php " . $jb_id . " " . $jb_multi . " " . $jb_multi_factor . " " . $cr_id_orders . " >> " . "../log/check_jb_permanent_multi_" . date("Ym") . ".log" . " 2>&1 &";
      exec($cmd);
    }
    $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_block . ", " . 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");
  if ((isset($sendmail) && $sendmail == "1") || ($job_is_new && $jb_offer == 1 && trim($jb_offer_mail) != "")):
    $job_id = $jb_id;
    $f_email = str_replace(" ", "", $ask_mailrecipients);
    $currentHqId = $hq_id;
    $job_crSid = "undefined";
    // Define constants
    $constMailSenderAddress = getParameterValue("0", "MAIL_SENDER_ADDRESS", $currentHqId);
    // Set action parameters
    $f_act = "mailsend";
    $mailResult = FALSE;
    // Standalone process
    $automailer = "1";
    $mailTextJobStatus = "CHANGE";
    if ($jb_offer == 1) {
      $f_email = str_replace(" ", "", $jb_offer_mail);
      if ($job_is_new)
        $mailTextJobStatus = "OFFER";
      else
        $mailTextJobStatus = "OFFER_CHANGE";
    }
    include_once ('../include/email/htmlMimeMail.php');
    include_once ("../admin/jb_detail.php");          
    // Get current mail status            
    if ($mailResult) :
      $statusSent = "OK";
      $statusMessageTxt .= "\\nEine Mail wurde versandt an \\\"" . $f_email . "\\\".";
    else:
      $statusSent = "NOT OK";
      $statusMessageTxt .= "\\nDie Mail an " . $f_email . " konnte nicht versandt werden.";
    endif;
    // Write logdata into log file
    $logFile = substr(getParameterValue("0", "AUTOMAILER_LOGFILE", $currentHqId), 0, -4) . "." . strtolower($mailTextJobStatus) . ".log";
    writeToFile($logFile, "[Job: " . $job_id . "] [Time: " . getDateTime("0") . "] [From: " . $constMailSenderAddress . "] [To: " . $f_email . "] [SID: " . $job_crSid . "] [" . $mailTextJobStatus . "] [Status: " . $statusSent . "]");
  endif;

  $statusMessage = $statusMessageTxt;
//writeLog_("../log/job_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_tourname_old == "" ? $jb_ordertime : date("Y-m-d H:i:s")), 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_VAR != ""):
        $csc_id_payer = $CSC_ID_PAYER_CASH_VAR;
      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");
  // Noch was Neues: Wenn beim Kunden hinterlegt ist, dass bei der Abholung bei diesem Kunden dessen Konditionen (cs_jbcond = 1) gelten soll,
  // dann gelten für die Preisermittlung nicht die Konditionen des Zahlers!
  $cs_id_cond = getFieldValueFromId("costcenter", "csc_id", $jobList[0][JL_CSC_ID], "cs_id");
  $cs_jbcond = getFieldValueFromId("customer", "cs_id", $cs_id_cond, "cs_jbcond");
  if ($cs_jbcond == 1)
    $cs_id = $cs_id_cond;
    
  $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;
  $vhtSrvt_name = $db->getOne("SELECT mt_value FROM metatype WHERE mt_sort = '$vht_id' AND mt_type = 'vehicletype'");
  if (trim($jb_markup_ori) == "") {
    $jb_markup = getFuelMarkup($vhtSrvt_name, (trim($cs_id) != "" ? $cs_id : 0), $hq_id, $jb_ordertime);
  }
  if (MASK_CR_PRICE_MODE == "1") {
    if (trim($jb_cr_markup_ori) == "") {
      $jb_cr_markup = getFuelMarkupCr($vhtSrvt_name, (trim($cs_id) != "" ? $cs_id : 0), $hq_id, $jb_ordertime);
    }
  }

  // Grundpreis
  // Servicetype-Name (Fahrrad etc.)
  $srvt_name = $db->getOne(
    "SELECT mt_value FROM metatype WHERE mt_sort = '$vht_id' AND mt_type = 'vehicletype'");

  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_tourname_old == "" ? $jb_ordertime : date("Y-m-d H:i:s")), 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, $jb_cr_markup, $vht_id);
//  $gross_price += $fullPrice;
  $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] == "")
      $jobList[$i][JL_TR_MEDIATIONAREA_ID] = 0;
    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] == "")
      $jobList[$i+1][JL_TR_MEDIATIONAREA_ID] = 0;
    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
    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_tourname_old == "" ? $jb_ordertime : date("Y-m-d H:i:s")), $distance, $costsplit_count, $getPriceOnly, $jb_cash, (($jb_costsplit == "false" || MASK_CASH_PAYER_SELECT == "1") ? $csc_id_payer : ""), $jb_storno, $zipcode1, $zipcode2, true, $jb_markup, $jb_cr_markup, $vht_id);
//echo "'".$jobList[$i][JL_TR_HSNO].",$ad_id1;".$jobList[$i+1][JL_TR_HSNO].",$ad_id2'<br>\n";
//reportDie ("saveServiceCosts($ad_id1, $ad_id2, $hq_id, $cs_id, $jb_id, ($i + 1), ($jb_tourname_old == "" ? $jb_ordertime : date("Y-m-d H:i:s")), $distance, $costsplit_count, $getPriceOnly, $jb_cash, " . (($jb_costsplit == "false" || MASK_CASH_PAYER_SELECT == "1") ? $csc_id_payer : "") . ", $jb_storno, $zipcode1, $zipcode2, ". true .");");
    $fullPrice += round($fp * ((100-$fd)/100), 2);
    $discount_sign = ($special_address || $discount_sign == "**" ? "**"
    : ($discount_sign = ($fd > 0 || $customer_specific || $discount_sign == "*" ? "*" : "")));
    if ($fd > 0)
      $discount_sign = " (-" . $fd . "%";
    if ($self_service_discount > 0)
      $discount_sign .= " KAE";
    if ($fd > 0)
      $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);
    $discount_sign_cr = "";
    if ($fd+$self_service_discount > 0) $discount_sign_cr = " (-" . ($fd+$self_service_discount) . "%)";
  endfor;
endif;

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

if (isset($recalc_price_flag) && $recalc_price_flag == true)
  return;  

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 = getParameterValue("0", "MASK_EXCLUDE_VHT_IDS", $hq_id);
  if ($mask_exclude_vht_ids != "")
    $mask_exclude_vht_ids = " AND NOT mt_sort IN (" . $mask_exclude_vht_ids . ")";
  $vht_id_options = addOptionsFromTable(
    "metatype", "mt_sort", "mt_value", "mt_sort", "mt_type = 'vehicletype' AND mt_sort > 0" . $mask_exclude_vht_ids,
    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_permanent_options = 
    "<option value=\"1\">werktags</option>" .
    "<option value=\"2\">werktags mit Sa.</option>" .
    "<option value=\"3\">t&auml;glich</option>" .
    "<option value=\"4\">w&ouml;chentlich</option>" .
    "<option value=\"5\">vierzehnt&auml;gig</option>" .
    "<option value=\"11\">vierw&oumlchentlich</option>" .
    "<option value=\"6\">monatlich</option>" .
    "<option value=\"7\">zum Monatsende</option>" .
    "<option value=\"8\">15. u. Monatsende</option>" .
    "<option value=\"10\">16. u. Monatsanfang</option>" .
    "<option value=\"9\">feiertags</option>";
  $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;


  $_csc_id_extern_list_ = /* $csc_id_extern_list . */ $jsAddNewExternCostcenter;
//  $_ph_", getPublicHolidays(getDateTime("year"), "1", "1"));
  $_hq_id_ = $hq_id;
  $_md_id_ = $md_id;
  $_cs_id_ = $cs_id;
  $_csc_id_orderer_ = $csc_id_orderer;
  $_csc_id_orderer_ec_ = $csc_id_orderer_ec;
  $_jb_id_ = $jb_id;
  $_jb_copy_ = $jb_copy;
  $_dbhistory_ = $dbhistory;

  /*     
   => 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
  */ 
  if ($disp != "true") {
    $_empModeCopyJob_ = getParameterValue($emp_id, "MODE_COPY_JOB");
    $_empModeLaterJob_ = getParameterValue($emp_id, "MODE_LATER_JOB");
    $_empModeLaterJobWithNormal_ = MODE_LATER_JOB_WITH_NORMAL;
  }
  $_prev_jb_id_ = $prev_jb_id;
  $_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 : "");
  $_when_ = "var when = \"" . date("H:i") . "\";";
  $_cs_jbedit_cr_ = getFieldValueFromId("customer", "cs_id", "$cs_id", "cs_jbedit_cr");
  if (getFieldValueFromId("customer", "cs_id", "$cs_id", "cs_jbedit_cr") == "1"):
    $_cs_jbedit_cr_list_ = getCustomerCouriers($db, $cs_id);
  endif;
  if (trim($db->getOne("SELECT cs_filter_jbedit FROM customer WHERE cs_id = $cs_id")) != ""):
    $_cs_jbedit_cs_filter_ = "1";
  endif;
  $_cs_jbedit_filter_list_ = getCustomerFilters($db, $cs_id);
  $_cur_jb_status_ = getFieldValueFromId("job", "jb_id", "$jb_id", "jb_status");
  $_is_b2b_ = ($jb_id != "" && is_numeric($jb_id) ? ($db->getOne("SELECT jb_id FROM phoenix_log.log WHERE logo_id = 102 AND jb_id = " . $jb_id) == $jb_id ? "1" : "0") : "0");
  $_csc_id_payer_cash_ = $CSC_ID_PAYER_CASH_VAR;
  $_cash_payer_select_ = MASK_CASH_PAYER_SELECT;
  $_auto_refresh_ = MASK_AUTO_REFRESH;
  $_commission_no_on_ = MASK_COMMISSION_NO;
  $_ask_defaultpayer_change_ = MASK_ASK_DEFAULTPAYER_CHANGE;
  $_manual_disposition_ = MASK_MANUAL_DISPOSITION;
  $_MASK_CALCULATOR_TYPE_ = MASK_CALCULATOR_TYPE;
  $_MASK_CALCULATOR_SRV_ = MASK_CALCULATOR_SRV;
  $_MASK_CALC_CR_PRICE_ = MASK_CALC_CR_PRICE;  
  $_MASK_CR_PRICE_MODE_ = MASK_CR_PRICE_MODE;
  $_MASK_CALC_SIDS_ = MASK_CALC_SIDS;  
  $_CSC_ID_PAYER_EXTERN_ = CSC_ID_PAYER_EXTERN;
  $_MASK_MAXTOUR_ = MASK_MAXTOUR;
  $_MASK_MAX_TR_REMARK_ = MASK_MAX_TR_REMARK;
  $_MASK_CS_PROV_DEFAULT_ = (MASK_CS_PROV_DEFAULT == "" ? 0 : MASK_CS_PROV_DEFAULT);
  $_MASK_INVOICE_SHOW_SIDS_ = MASK_INVOICE_SHOW_SIDS;
  $_MASK_INVOICE_SIDS_SID_ = MASK_INVOICE_SIDS_SID;  
  $_MASK_INVOICE_SIDS_SID0_ = getParameterValue("0", "MASK_INVOICE_SIDS_SID0", "0");
  $_MASK_INVOICE_SIDS_SID1_ = getParameterValue("0", "MASK_INVOICE_SIDS_SID1", "0");
  $_EMAIL_CRVHSID_NO_MAIL_Arr = explode(",", getParameterValue("0", "EMAIL_CRVHSID_NO_MAIL", $hq_id));
  $_EMAIL_CRVHSID_NO_MAIL_ = "";
  foreach($_EMAIL_CRVHSID_NO_MAIL_Arr as $val)
    $_EMAIL_CRVHSID_NO_MAIL_ .= "'" . $val . "',";
  if ($_EMAIL_CRVHSID_NO_MAIL_ != "")
    $_EMAIL_CRVHSID_NO_MAIL_ = substr($_EMAIL_CRVHSID_NO_MAIL_, 0, -1);
  $_MASK_JB_REPORT_BUTTON_ENABLED_PERMANENT_ = getParameterValue("0", "MASK_JB_REPORT_BUTTON_ENABLED_PERMANENT", $hq_id);
  $_MASK_HIDDEN_FREETEXT_ = getParameterValue("0", "MASK_HIDDEN_FREETEXT", $hq_id);
  $_MASK_BIKE_FILTER_ = MASK_BIKE_FILTER;
  $_MASK_COMMISSION_NO_MANDATORY = MASK_COMMISSION_NO_MANDATORY;
  $_MASK_HIDE_STANDARD_PRICE_IF_KM_PRICE = getParameterValue("0", "MASK_HIDE_STANDARD_PRICE_IF_KM_PRICE", $hq_id);

  $_EU_COUNTRYCODES_Arr = explode(",", getParameterValue("0", "EU_COUNTRYCODES", "0"));
  $_EU_COUNTRYCODES_ = "";
  foreach($_EU_COUNTRYCODES_Arr as $val)
    $_EU_COUNTRYCODES_ .= "'" . $val . "',";
  if ($_EU_COUNTRYCODES_ != "")
    $_EU_COUNTRYCODES_ = substr($_EU_COUNTRYCODES_, 0, -1);

  $_cs_srv_list_ = (MASK_CALCULATOR_SRV_SRC == "1" ? "var cs_srv_list = [];\nvar cs_srvt_list = [];\nvar cs_price_list = [];\n" : "");
  $_hq_workmode_ = $hq_workmode;
  $statusMessage = $statusMessage;

  // Externe Kostenstelle vordefinieren
  $javascript = javascriptAdd_cs_eid(CSC_ID_PAYER_EXTERN, "");
  
  $empHqList = getParameterValue("0", "HEADQUARTERS_MULTIPLE_ACCESS_EMPLOYEES", "0") . "|300001";
  if ($userType == "1" && $empHqList != ""):
    $empHqListGlobaljobs = getParameterValue("0", "HEADQUARTERS_MULTIPLE_ACCESS_EMPLOYEES_GLOBALJOBS", "0");
//echo "'$emp_id', '$empHqListGlobaljobs'" . ", '$hq_id', |" . isInParameterString($hq_id, $empHqListGlobaljobs) . "|, |" . isInParameterString($emp_id, $empHqList) . "|";
    if ($empHqListGlobaljobs != "" && isInParameterString($emp_id, $empHqList) && !isInParameterString($hq_id, $empHqListGlobaljobs)) :
      $javascript .= "parent.job_options.document.tourOptions.jb_globaljob.disabled=true;\n";
    endif;
  endif;
  
  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_hiddenFreetext_1" => my_str_check_http($jb_hiddenFreetext_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_jam_waittime" => $jb_jam_waittime,
        "jb_cr_filter" => $jb_cr_filter, "jb_markup" => $jb_markup_ori, "jb_cr_markup" => $jb_cr_markup_ori, "jb_toll" => $jb_toll_ori,
        "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_id_parent" => $jb_id_parent, "jb_type" => $jb_type,
        "jb_tourname" => $jb_tourname, "jb_km" => $jb_km_ori, "jobList" => my_str_check_http($jobListOri)), ""
      );
    if (MASK_CR_PRICE_MODE == "1") {
      $javascript .=
        setJavascriptOpenerFormVals("job_options", "tourOptions",
          array("jb_cr_serviceprice" => $jb_cr_serviceprice_ori), "");
    }
    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"), "") .
      setJavascriptOpenerChecked("job_options", "tourOptions", "jb_offer",
        (($jb_offer != "1") ? "false" : "true"), "") .
      setJavascriptOpenerDisabled("job_options", "tourOptions", "jb_permanent",
        (($jb_reserv == 1 || $jb_permanent != "") ? "false" : "true"), "") .
      "checkJb_permanent(0);\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;

  $_javascript_ = $javascript;

  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";
    $javascript .= javascriptAdd_cs_eid($csc_id_orderer, "");
    $_csc_id_start_code_js_ = $javascript;
    define ("MASK_WAITTIME_ENABLED", "0");
    define ("MASK_DATESELECTFIELDS_ENABLED", "0");
    define ("MASK_CHECK_DISCOUNT", "1");
    define ("MASK_SERVICE_PRICE", "1");
    define ("CUSTOMER_JOB", "1");
  else:
    $_csc_id_start_code_js_ = mkCsc_id_start($csc_id_start);
    define ("CUSTOMER_JOB", "0");
  endif;

//  $_csc_id_orderer_ = ec($csc_id_orderer);
  $_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")));
  $_ec_jb_id_ = ec($jb_id);
  if (MASK_WAITTIME_ENABLED != "1"):
    $WAITTIME_DISABLED_START = "<!--";
    $WAITTIME_DISABLED_END = "-->";
  endif;
  $DATESELECTFIELDS_DISABLED_START = "";
  $DATESELECTFIELDS_DISABLED_END = "";
  $TIMESELECTFIELDS_DISABLED_START = "";
  $TIMESELECTFIELDS_DISABLED_END = "";
  $DATEINPUTFIELDS_DISABLED_START = "";
  $DATEINPUTFIELDS_DISABLED_END = "";
  $TIMEINPUTFIELDS_DISABLED_START = "";
  $TIMEINPUTFIELDS_DISABLED_END = "";
  if (MASK_DATESELECTFIELDS_ENABLED != "1"):
    $DATESELECTFIELDS_DISABLED_START = "<!--";
    $DATESELECTFIELDS_DISABLED_END = "-->";
    $TIMESELECTFIELDS_DISABLED_START = "<!--";
    $TIMESELECTFIELDS_DISABLED_END = "-->";
  else:
    $DATEINPUTFIELDS_DISABLED_START = "<!--";
    $DATEINPUTFIELDS_DISABLED_END = "-->";
    $TIMEINPUTFIELDS_DISABLED_START = "<!--";
    $TIMEINPUTFIELDS_DISABLED_END = "-->";
  endif;
  $DISCOUNT_DISABLED_START = "";
  $DISCOUNT_DISABLED_END = "";
  if (MASK_CHECK_DISCOUNT != "1"):
    $DISCOUNT_DISABLED_START = "<!--";
    $DISCOUNT_DISABLED_END = "-->";
  endif;
  $SERVICEPRICE_DISABLED_START = "";
  $SERVICEPRICE_DISABLED_END = "";
  if (MASK_SERVICE_PRICE != "1" || MASK_MARKUP_MODE == "2"):
    $SERVICEPRICE_DISABLED_START = "<!--";
    $SERVICEPRICE_DISABLED_END = "-->";
  endif;
  $CUSTOMER_DISABLED_START = "";
  $CUSTOMER_DISABLED_END = "";
  $CUSTOMER_COURIER_DISABLED_START = "";
  $CUSTOMER_COURIER_DISABLED_END = "";
  $CUSTOMER_FILTER_DISABLED_START = "";
  $CUSTOMER_FILTER_DISABLED_END = "";
  $CUSTOMER_JB_SALES_TAX_RATE = "";
  if (CUSTOMER_JOB == "1"):
    $CUSTOMER_DISABLED_START = "<!--";
    $CUSTOMER_DISABLED_END = "-->";
    // Steuern hartcodiert auf 16% für Kundenaufträge
    $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\">";
    if (getFieldValueFromId("customer", "cs_id", "$cs_id", "cs_jbedit_cr") != "1"):
      $CUSTOMER_COURIER_DISABLED_START = "<!--";
      $CUSTOMER_COURIER_DISABLED_END = "-->";
    endif;
    if (trim($db->getOne("SELECT cs_filter_jbedit FROM customer WHERE cs_id = $cs_id")) == ""):
      $CUSTOMER_FILTER_DISABLED_START = "<!--";
      $CUSTOMER_FILTER_DISABLED_END = "-->";
    endif;
  endif;
  $CALCULATOR_DISABLED_START = "";
  $CALCULATOR_DISABLED_END = "";
  if (MASK_CALCULATOR != "1"):
    $CALCULATOR_DISABLED_START = "<!--";
    $CALCULATOR_DISABLED_END = "-->";
  endif;
  $RANKING_JB2CRVH_MEASURE_DISABLED_START = "";
  $RANKING_JB2CRVH_MEASURE_DISABLED_END = "";
  $RANKING_JB2CRVH_MEASURE_ENABLED_START = "";
  $RANKING_JB2CRVH_MEASURE_ENABLED_END = "";
  if (RANKING_JB2CRVH_MEASURE == "1"):
    $RANKING_JB2CRVH_MEASURE_DISABLED_START = "<!--";
    $RANKING_JB2CRVH_MEASURE_DISABLED_END = "-->";
  else:
    $RANKING_JB2CRVH_MEASURE_ENABLED_START = "<!--";
    $RANKING_JB2CRVH_MEASURE_ENABLED_END = "-->";
  endif;

  $_cr_id_options_ = (isset($cr_id_options) ? $cr_id_options : "");
  //$_jb_waittime_options_ = $jb_waittime_options;
  $_vht_id_options_ = $vht_id_options;
  $_savedTour_disabled_ = $savedTour_disabled;
  $_savedTour_options_ = $savedTour_options;
  $_jb_permanent_options_ = $jb_permanent_options;
  $_jb_sales_tax_rate_sign_options_ = $jb_sales_tax_rate_sign_options;
  $_sales_tax_rate_value_ = $sales_tax_rate_value;
  $_jb_type_ = MASK_JB_TYPE_DEFAULT;

  if ($hq_id == 1):
    define ("BUNDESLAND", "HB");
  elseif ($hq_id == 2):
    define ("BUNDESLAND", "HH");
  elseif ($hq_id == 3):
    define ("BUNDESLAND", "BE");
  elseif ($hq_id == 4):
    define ("BUNDESLAND", "NI");
  elseif ($hq_id == 5):
    define ("BUNDESLAND", "HE");
  elseif ($hq_id == 6):
    define ("BUNDESLAND", "SN");
  elseif ($hq_id == 7):
    define ("BUNDESLAND", "NW");
  elseif ($hq_id == 8):
    define ("BUNDESLAND", "SN");
  elseif ($hq_id == 9):
    define ("BUNDESLAND", "BY");
  elseif ($hq_id == 10):
    define ("BUNDESLAND", "BY");
  elseif ($hq_id == 11):
    define ("BUNDESLAND", "BW");
  elseif ($hq_id == 90):
    define ("BUNDESLAND", "HB");
  endif;

  if (MASK_CR_PRICE_MODE == "1") {
    // Fuhrlohn = "38"
    // Fuhrlohn GFL = "39"
    $cr_price_readonly = "";
    if (!authCheckEmployeeRights($emp_id, "38")) : $cr_price_readonly = " readonly"; endif;
    $_cr_price_threshold_ = getParameterValue("0", "JB_CR_PRICE_THRESHOLD", "0");
    $_cr_price_block_ = getParameterValue("0", "JB_CR_PRICE_BLOCK", "0");
    $_cr_price_block_override_ = "0";
    if (authCheckEmployeeRights($emp_id, "39")) : $_cr_price_block_override_ = "1"; endif;
  }

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

//  include("../jobs/shrink.inc.php");
//  $html_code = $tpl->get();
//  echo htmlShrink($html_code, true);
elseif (!(isset($check_jb_permanent_flag) && $check_jb_permanent_flag == true)):
  $jb_markup_text = "";
  if ($jb_markup > 0)
    $jb_markup_text = " (" . str_replace(".", ",", sprintf("%01.2f", $jb_markup)) . "% Tz.)";
  if (MASK_CR_PRICE_MODE == "1") {
    if ($jb_cr_markup > 0)
      $jb_cr_markup_text = " (" . str_replace(".", ",", sprintf("%01.2f", $jb_cr_markup)) . "% Tz.)";
  }
  // Auch Treibstoffzuschlag in Prozent ermitteln
  $fuel_markup = getFuelMarkup($srvt_name, (trim($cs_id) != "" ? $cs_id : 0), $hq_id, $jb_ordertime);
  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);
  }
  $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";
  $cur_price = "nicht anwendbar";
  $cur_cr_price = "nicht anwendbar";
  if ($vht_id < 7 || getParameterValue("0", "MASK_SHOW_STANDARD_PRICE_FOR_TRUCKS", $hq_id) == "1") {
    $cur_price = str_replace(".", ",", sprintf("%01.2f", $fullPrice)) . " EUR" . $discount_sign . $jb_markup_text;
    $cur_cr_price = str_replace(".", ",", sprintf("%01.2f", $fullCrPrice)) . " EUR" . $discount_sign_cr . $jb_cr_markup_text;
//    if ($jb_cr_serviceprice > 0)
//      $cur_cr_price = $cur_cr_price . " inkl. " . str_replace(".", ",", sprintf("%01.2f", $jb_cr_serviceprice)) . " EUR Service-Fuhrlohn";
  }
  $javascript .=
    // jb_markup nur neu setzen, wenn neuer Job
//    "if (parent.job_options.jb_markup_overwrite == 1) {" .
//    "  parent.job_options.document.tourOptions.jb_markup.value = \"" . str_replace(".", ",", sprintf("%01.2f", $fuel_markup)) . "\";\n" .
    "  parent.job_options.document.tourOptions.currentTSZ.value = \"" . str_replace(".", ",", sprintf("%01.2f", $fuel_markup)) . " %\";\n" .
    "  if (parent.job_options.document.tourOptions.jb_fixprice.value != \"\") parent.job_options.checkFixprice(1);" .
//    "}\n" .
    (MASK_CR_PRICE_MODE == "1" ?
//    "if (parent.job_options.jb_cr_markup_overwrite == 1) {" .
//    "  parent.job_options.document.tourOptions.jb_cr_markup.value = \"" . str_replace(".", ",", sprintf("%01.2f", $fuel_cr_markup)) . "\";\n" .
    "  parent.job_options.document.tourOptions.currentCrTSZ.value = \"" . str_replace(".", ",", sprintf("%01.2f", $fuel_cr_markup)) . " %\";\n" .
    "  if (parent.job_options.document.tourOptions.jb_cr_price.value != \"\") parent.job_options.checkCrPrice();"
//    . "}\n"
    : "") .
    (MASK_CALCULATOR_SRV_SRC == "1" ? getCustomerServices($db, $cs_id) : "") .
    "parent.job_tour.document.tourForm.currentPrice.value = " .
      "\"" . /*"Standard Preis: " .*/ $cur_price . "\";\n" .
    (MASK_CR_PRICE_MODE == "1" ? 
      "parent.job_tour.document.tourForm.currentCrPrice.value = " .
        "\"" . $cur_cr_price . "\";\n"
    : "");
  if (MASK_CR_PRICE_MODE == "1") {
    $javascript .=
      "parent.job_tour.document.tourForm.currentCrPrice.value = " . "\"" . "\";\n";
    $javascript .=
      "parent.job_options.document.tourOptions.cr_price_text.value = " . "\"" . "\";\n";
    if (strtotime(MASK_CR_PRICE_MODE_DATE) <= strtotime($jb_ordertime)) {
      $javascript .=
        "parent.job_tour.document.tourForm.currentCrPrice.value = " .
          "\"" . $cur_cr_price . "\";\n";
      if ((($jb_fixprice != 0 && $jb_cr_price == 0) || ($jb_cr_price != 0 && $jb_markup != 0))) {
        $jb_subtotal = round((float)$jb_fixprice * (1 - ($tmp_discount_rate / 100)) * ((100-$self_service_discount)/100), 2);
        if ($jb_cr_price == 0 || $jb_cr_price == "") {
          list($cr_price, $cr_price_rate) =
            getCr_price_global($jb_subtotal, $hq_id, $cs_id, ($jb_tourname_old == "" ? $jb_ordertime : date("Y-m-d H:i:s")), $vhtSrvt_name, $vht_id);
          $cr_price_rate_text = " (./. " . str_replace(".", ",", sprintf("%01.2f", $cr_price_rate)) . "%)";
        } else {
          $cr_price = round((float)$jb_cr_price * (1 - ($tmp_discount_rate / 100)) * ((100-$self_service_discount)/100), 2);
          $cr_price_rate_text = " (BSG " . str_replace(".", ",", sprintf("%01.2f", ($jb_subtotal - $cr_price) / ($jb_subtotal != 0 ? $jb_subtotal : 1) * 100)) . "%)";
        }
        $cr_price = round($cr_price * (1 + ($jb_cr_markup / 100)), 2);
        $jb_cr_markup_text = "";
        if ($jb_cr_markup > 0)
          $jb_cr_markup_text = " mit " . str_replace(".", ",", sprintf("%01.2f", $jb_cr_markup)) . "% TSZ";
//        $javascript .= "alert('|".$jb_cr_price."|');" .
          $javascript .= 
          "parent.job_options.document.tourOptions.cr_price_text.value = " .
            "\"Frachtverg" . $jb_cr_markup_text . ": " . str_replace(".", ",", sprintf("%01.2f", $cr_price)) . " " . chr(128) . $cr_price_rate_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 .= "alert('".MASK_MARK_OLD_PRICE . "|" . $validfrom ."');";
  if (MASK_MARK_OLD_PRICE != ""):
//    $javascript .= "alert('".strtotime($validfrom) . "|" . strtotime(MASK_MARK_OLD_PRICE) ."');";
    if (strtotime($validfrom) < strtotime(MASK_MARK_OLD_PRICE) && $fullPrice > 0):
      $javascript .= "parent.job_tour.document.tourForm.currentPrice.style.backgroundColor = \"#000000\";";
    else:
      $javascript .= "parent.job_tour.document.tourForm.currentPrice.style.backgroundColor = \"" . $constBackground . "\";";
    endif;
  endif;
  $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;
  exit();
else:
  return; // exit() an dieser Stelle würde dazu führen, dass Stornieren z. B. aus der Auftragsliste nicht mehr funktioniert
endif;

if (!isset($jobMode)) $jobMode = "undefined";
if (!isset($jb_id_log)) $jb_id_log = "undefined";
writeLog_("../log/job_options_", trace_execution_time_stop() . " '../jobs/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");

?>

<html>
<head>
<title>AUFTRAGSERFASSUNG - SUBMITFRAME</title>
<script>
//Quelle: https://msdn.microsoft.com/en-us/library/cc197053%28v=vs.85%29.aspx
window.onerror=fnErrorTrap;
function fnErrorTrap(sMsg,sUrl,sLine){
//parent.job_tour.document.tourForm.
//parent.job_options.document.tourOptions.

    var tmp_jb_id = "";
    if(typeof(jb_id)!='undefined')    
      tmp_jb_id = jb_id;
    var out = '';
//    if(typeof(parent.job_options.document.tourOptions) != 'undefined') {
//      for (var i = 0; i <= parent.job_options.document.tourOptions.elements.length; i++) {
////        out += i + ": " + parent.job_options.document.tourOptions.elements[i].name + " = " + parent.job_options.document.tourOptions.elements[i].value + "\n";
//        out += parent.job_options.document.forms[0].elements[i].value + "\n";
//      }
//    }
    iframe = document.createElement("IFRAME");
    iframe.setAttribute("src", "../include/ajaxJsError.php?url="+escape(sUrl) + "&line=" + escape(sLine) + "&message=" + escape(sMsg) + "&user_agent=" + escape(navigator.userAgent) + "&jb_id=" + tmp_jb_id + "&out=" + escape(out));
    iframe.width = 1;
    iframe.height = 1;
    iframe.style.display = 'none';
    setTimeout(function(){
      document.body.appendChild(iframe);
    },10);
  return false;
}
//alürt('test');
</script>
<link rel="stylesheet" type="text/css" href="../css/phoenix.css.php">
<?php include_once ("../include/js_framework.inc.php"); ?>
<script src="../include/lib_global.10.js" type="text/javascript"></script>
<script src="../include/lib_courier.js" type="text/javascript"></script>
<script src="../include/lib_calendar.js" type="text/javascript"></script>
<script src="job_options_<?php echo $_hq_id_;?>.js" type="text/javascript"></script>
<script type="text/javascript">
<!--
var job_is_locked_unload = false;
window.addEventListener('unload', function(event) {
//  console.log('Leaving job_options, job_is_locked_unload = ' + job_is_locked_unload);
  if ("<?php echo $_jb_id_;?>" != "" && !job_is_locked_unload && "<?php echo $_jb_id_;?>" != "killMe")
    ajaxRequestGet('../include/ajaxReqJobUnlock.php', 'jb_id=' + '<?php echo $_jb_id_;?>');
});
var MASK_MAXTOUR=<?php echo $_MASK_MAXTOUR_;?>;
var MASK_MAX_TR_REMARK=<?php echo $_MASK_MAX_TR_REMARK_;?>;
var MASK_CS_PROV_DEFAULT=<?php echo $_MASK_CS_PROV_DEFAULT_;?>;
var MASK_INVOICE_SHOW_SIDS=<?php echo $_MASK_INVOICE_SHOW_SIDS_;?>;
var MASK_INVOICE_SIDS_SID="<?php echo $_MASK_INVOICE_SIDS_SID_;?>";
var MASK_INVOICE_SIDS_SID0="<?php echo $_MASK_INVOICE_SIDS_SID0_;?>";
var MASK_INVOICE_SIDS_SID1="<?php echo $_MASK_INVOICE_SIDS_SID1_;?>";
var EMAIL_CRVHSID_NO_MAIL=[<?php echo $_EMAIL_CRVHSID_NO_MAIL_;?>];
var MASK_BIKE_FILTER="<?php echo $_MASK_BIKE_FILTER_;?>";
var MASK_COMMISSION_NO_MANDATORY="<?php echo $_MASK_COMMISSION_NO_MANDATORY;?>";
var MASK_HIDE_STANDARD_PRICE_IF_KM_PRICE="<?php echo $_MASK_HIDE_STANDARD_PRICE_IF_KM_PRICE;?>";
var EU_COUNTRYCODES=[<?php echo $_EU_COUNTRYCODES_;?>];
//-->
</script>
<script src="job_edit.68.13.js" type="text/javascript"></script>
<script src="../include/key_events_content.js" language="JavaScript1.2" type="text/javascript"></script>
<script for="document" event="onkeydown()" language="JScript" type="text/jscript">
<!--
{
if(window.event.altKey&&event.keyCode>=49&&event.keyCode<=57){
actionMapEvent(window.event,event.keyCode);
}
}
//-->
</script>
<script type="text/javascript">
<!--
var isCurrentlySubmitting=false;
var job_options_isLoading=true;
var curCsc_id_payer="";
var significantPriceValues="2";
var is_afterwards=false;
var was_afterwards=false;
var fixprice_was_0=false;
var fixprice_was_zone=false;
//var bwv_alert = true;
var cur_popupWin;
function job_is_locked(job_is_locked_mode, job_is_locked_text)
{
if (job_is_locked_mode == 0) {
  job_is_locked_unload = true; // prevent unload function from calling ajaxReqJobUnlock.php
  alert("Der Auftrag wird gerade von " + job_is_locked_text + " bearbeitet!");
}
if (job_is_locked_mode == 1) {
  alert("Der Bezahler ist gesperrt!");
}
if (job_is_locked_mode == 2) {
  alert("Der Bezahler ist ausgeblendet!");
}
if (job_is_locked_mode == 3) {
  alert("Der Bezahler ist gesperrt und ausgeblendet!");
}
parent.close();
return;
}
var statusMessage="<?php echo $statusMessage;?>";
function displayStatusMessage(){
if(statusMessage!=""){
alert(statusMessage);
}
};
var hq_id="<?php echo $_hq_id_;?>";
var md_id="<?php echo $_md_id_;?>";
var cs_jbedit_cr="<?php echo $_cs_jbedit_cr_;?>";
<?php if (isset($_cs_jbedit_cr_list_)) echo $_cs_jbedit_cr_list_;?>
var cs_jbedit_cs_filter="<?php if (isset($_cs_jbedit_cs_filter_)) echo $_cs_jbedit_cs_filter_;?>";
<?php echo $_cs_jbedit_filter_list_;?>
var cur_jb_status="<?php echo $_cur_jb_status_;?>";
var cur_tr_statuses=[];
var cs_id="<?php echo $_cs_id_;?>";
var csc_id_payer_cash="<?php echo $_csc_id_payer_cash_;?>";
var cash_payer_select="<?php echo $_cash_payer_select_;?>";
<?php echo $_csc_id_extern_list_;?>
var cs_eid_list=new Array();
<?php echo $_cr_id_order_list_;?>
<?php echo $_when_;?>
var auto_refresh="<?php echo $_auto_refresh_;?>";
var hq_workmode="<?php echo $_hq_workmode_;?>";
var hq_invmode="<?php echo $_hq_invmode_;?>";
var commission_no_on="<?php echo $_commission_no_on_;?>";
var jb_id="<?php echo $_jb_id_;?>";
var prev_jb_id="<?php echo $_prev_jb_id_;?>"
var jb_copy="<?php echo $_jb_copy_;?>";
var dbhistory="<?php echo $_dbhistory_;?>";
var empModeCopyJob="<?php echo $_empModeCopyJob_;?>";
var empModeLaterJob="<?php echo $_empModeLaterJob_;?>";
var empModeLaterJobWithNormal="<?php echo $_empModeLaterJobWithNormal_;?>";
var ask_defaultpayer_change="<?php echo $_ask_defaultpayer_change_;?>";
var manual_disposition="<?php echo $_manual_disposition_;?>";
var MASK_CALCULATOR_TYPE="<?php echo $_MASK_CALCULATOR_TYPE_;?>";
var MASK_CALCULATOR_SRV="<?php echo $_MASK_CALCULATOR_SRV_;?>";
var MASK_CALC_CR_PRICE="<?php echo $_MASK_CALC_CR_PRICE_;?>";
var MASK_CR_PRICE_MODE="<?php echo $_MASK_CR_PRICE_MODE_;?>";
var MASK_CALC_SIDS="<?php echo $_MASK_CALC_SIDS_;?>";
var CSC_ID_PAYER_EXTERN="<?php echo $_CSC_ID_PAYER_EXTERN_;?>";
var MASK_JB_REPORT_BUTTON_ENABLED_PERMANENT="<?php echo $_MASK_JB_REPORT_BUTTON_ENABLED_PERMANENT_;?>";
var MASK_HIDDEN_FREETEXT="<?php echo $_MASK_HIDDEN_FREETEXT_;?>"
var discount_default=false;
var is_exported=false;
var is_b2b="<?php echo $_is_b2b_;?>";
var jb_orderer_mandatory = true;
var vht_id_old="<?php echo getFieldValueFromId('job', 'jb_id', $jb_id, 'vht_id');?>";
var cs_id_ec="<?php if (isset($_cs_id_ec_)) echo $_cs_id_ec_;?>";
var csc_id_orderer_root_ec="<?php if (isset($_csc_id_orderer_root_ec_)) echo $_csc_id_orderer_root_ec_;?>";
var csc_id_orderer_ec="<?php echo $_csc_id_orderer_ec_;?>";
var csc_id_orderer="<?php echo $_csc_id_orderer_;?>";
var jb_markup_overwrite = 1;
var jb_cr_markup_overwrite = 1;
var delete_suborder=false;
var is_non_eu_notified = <?php echo ($_jb_id_ != '' ? 'true' : 'false') ?>;
var usr_id="<?php echo $usr_id;?>";
<?php if (MASK_CR_PRICE_MODE == "1") echo "var cr_price_threshold = " . $_cr_price_threshold_ . ";\n" ?>
<?php if (MASK_CR_PRICE_MODE == "1") echo "var cr_price_block = " . $_cr_price_block_ . ";\n" ?>
<?php if (MASK_CR_PRICE_MODE == "1") echo "var cr_price_block_override = " . $_cr_price_block_override_ . ";\n" ?>

bl = "<?php echo BUNDESLAND;?>";
<?php echo $_cs_srv_list_;?>

function initForm()
{
if(typeof(parent.job_header.job_header_isLoading)=='undefined'||parent.job_header.job_header_isLoading==true||
typeof(parent.job_tour.job_tour_isLoading)=='undefined'||parent.job_tour.job_tour_isLoading== true||
typeof(parent.job_options.job_options_isLoading)=='undefined'||parent.job_options.job_options_isLoading==true)
{
self.setTimeout('initForm()',20);
return;
}
fillDateFields(1,"job_options","tourOptions","","tag","monat","jahr","stunde","minute","jb_permanent");
initFldList();
<?php echo $_javascript_;?>
parent.job_tour.document.tourForm.currentPrice.value="";
if(addressValid)
{
initJobList();
if(csc_id_orderer!=0)setJobList(0,jl_csc_id,csc_id_orderer);
setJobList(0,jl_csc_id_payer,"true");
if(typeof(parent.job_tour.document.tourForm.jb_costsplit) != 'undefined')
parent.job_tour.document.tourForm.jb_costsplit.checked=false;
if(typeof(parent.job_tour.document.tourForm.jb_cash) != 'undefined')
parent.job_tour.document.tourForm.jb_cash.checked=false;
parent.job_tour.document.tourForm.accept_all_addresses.checked=false;
parent.job_tour.document.tourForm.jb_orderer.value = "";
parent.job_tour.document.tourForm.jb_offer_mail.value = "";
parent.job_tour.document.getElementById("div_jb_offer_mail").style.display = 'none';
parent.job_tour.document.tourForm.jb_commission_no.value = "";
parent.job_options.document.tourOptions.jb_commission_no_hidden.value = "";
//parent.job_tour.document.tourForm.jb_origin[0].disabled = false;
//parent.job_tour.document.tourForm.jb_origin[2].disabled = false;
//parent.job_tour.document.tourForm.jb_origin[7].disabled = false;
//setSelectedOption("job_tour","tourForm","von_ad_country","DE");
//setSelectedOption("job_tour","tourForm","nach_ad_country","DE");
setCurTourNo(0);
moveToTour(0);
}
if(statusMessage!=""){
parent.job_tour.$('#div_distanceprice').html("");
parent.job_tour.document.tourForm.currentPrice.style.visibility = "visible";
parent.job_tour.$('#div_zoneprice').html("");
displayStatusMessage();
}else{
checkBrowser();
}
if(jb_id!="")
{
if(jb_id=="killMe")
{
parent.close();
return;
}
if(addressValid)
{
parent.job_tour.document.tourForm.duplicateJobButton.disabled=false;
parent.job_tour.document.tourForm.duplicateJobButton.className="button_enabled";
if(typeof(parent.job_tour.document.tourForm.jb_costsplit)!='undefined'){
is_afterwards=true;
parent.job_options.document.tourOptions.afterwards.disabled=true;
parent.job_options.document.tourOptions.jb_waitstorno.disabled=true;
parent.job_options.document.tourOptions.crSidList.disabled=true;
parent.job_options.document.tourOptions.cr_id_order.disabled=true;
if (cur_jb_status == 2)
{
parent.job_options.document.tourOptions.jb_status_manual.disabled=true;
parent.job_options.document.tourOptions.jb_status_manual.checked=false;
}
}
$('#multi_job_factor').hide();
$('#multi_job_all').hide();
self.setTimeout('getSavedTour('+jb_id+','+jb_copy+','+dbhistory+',false)',300);
}
} else {
  parent.job_tour.document.tourForm.jb_origin[0].checked=true;
  checkOrigin();
}
if(empModeLaterJob=="1")
{
if(typeof(parent.job_tour.document.tourForm.jb_costsplit)!='undefined'){
parent.job_options.document.tourOptions.jb_globaljob.disabled=true;
parent.job_options.document.tourOptions.jb_globaljob.checked=false;
parent.job_options.document.tourOptions.jb_status_manual.disabled=true;
parent.job_options.document.tourOptions.jb_status_manual.checked=false;
parent.job_options.document.tourOptions.afterwards.disabled=false;
parent.job_options.document.tourOptions.afterwards.checked=true;
checkAfterwards();
}
if(prev_jb_id==""){
parent.job_tour.document.tourForm.getLastJobButton.disabled=true;
parent.job_tour.document.tourForm.getLastJobButton.className="button_enabled";
}else{
parent.job_tour.document.tourForm.getLastJobButton.disabled=false;
parent.job_tour.document.tourForm.getLastJobButton.className="button_enabled";}
}else{
if(manual_disposition=="1")
{
parent.job_options.document.tourOptions.jb_status_manual.disabled=false;
if(addressValid)
parent.job_options.document.tourOptions.jb_status_manual.checked=true;
}
}
if((empModeLaterJob == "1" && MASK_HIDDEN_FREETEXT == "2") || MASK_HIDDEN_FREETEXT == "1")
  parent.job_tour.document.getElementById("div_jb_hiddenFreetextButton").style.display = "inline"; 
if(cur_jb_status == 2)
  parent.job_options.document.getElementById("div_jb_km").style.display = "inline"; 
parent.job_tour.document.tourForm.elements[von_fields[jl_tr_comp]].focus();
if (cash_payer_select=="1"&&jb_id==""&&(typeof(parent.job_tour.document.tourForm.jb_costsplit)!='undefined'))
{
parent.job_tour.document.tourForm.jb_costsplit.checked=true;
checkCostsplit(true);
}
<?php echo $_csc_id_start_code_js_;?>
}
function checkTimeFields(callerIdx)
{
var curDate=new Date();
var selHour=getSelectedNumVal(job_options,tourOptions,jb_waittime_hour);
var selMinute=getSelectedNumVal(job_options,tourOptions,jb_waittime_minute);
if(getSelectedVal(job_options,tourOptions,callerIdx)=="")
{
selHour="";
selMinute="";
}else{
if(selHour==""&&selHour.toString(10)!="0")
selHour=curDate.getHours();
if(selMinute==""&&selMinute.toString(10)!="0")
{
selMinute=curDate.getMinutes()+1;
while(selMinute%5>0)selMinute++;
if(selMinute==60)
{
selMinute=0;
if(++selHour>23)
selHour-=24;
}
}
}
setSelectedOption(job_options,tourOptions,jb_waittime_hour,selHour);
setSelectedOption(job_options,tourOptions,jb_waittime_minute,selMinute);
}
function mkTourname()
{
if(parent.job_options.document.tourOptions.jb_tourname.value!="")
parent.job_options.document.tourOptions.jb_tourname.value="";
else
parent.job_options.document.tourOptions.jb_tourname.value=parent.job_options.document.tourOptions.jb_tourname_hidden.value;
}
-->
</script>
<noscript>
<center>
<b><br>JavaScript ist nicht verf&uuml;gbar. Bitte aktivieren Sie JavaScript<br><br>
in Ihrem Browser, damit diese Seite ordnungsgem&auml;&szlig; funktioniert!</b><br><br>
</center>
</noscript>
</head>
<body onLoad="initForm()">
<table border=0 height=95% width=100% align=center cellspacing=0 cellpadding=0 vspace=0 hspace=0>
<tr>
<td width=2%>
<img src="../images/empty.gif" border=0 height=1>
</td>
<td width=18%>
<img src="../images/empty.gif" border=0 height=1>
</td>
<td width=25%>
<img src="../images/empty.gif" border=0 height=1>
</td>
<td width=10%>
<img src="../images/empty.gif" border=0 height=1>
</td>
<td width=25%>
<img src="../images/empty.gif" border=0 height=1>
</td>
<td width=18%>
<img src="../images/empty.gif" border=0 height=1>
</td>
<td width=2%>
<img src="../images/empty.gif" border=0 height=1>
</td>
</tr>
<tr>
<td>
&nbsp;
</td>
<td colspan=5 valign=top>
<table border=0 height=95% width=100% align=center cellspacing=0 cellpadding=0 vspace=0
hspace=0>
<tr>
<form name="tourOptions" action="job_options.php" method="post"
onSubmit="return checkJob()">
<td align=left valign=top width=<?php echo (MASK_CR_PRICE_MODE == "1" ? "16" : "19");?>%>
<?php echo $CUSTOMER_COURIER_DISABLED_START;?>
<div id="courierselectsingle">
Gew&uuml;nschter <b>Kurier</b>:<br>
<input name="cr_id_order" type="text" size="8" maxlength="6" class="input"
tabindex="<?php echo $_cr_id_order_tabindex_;?>" value="<?php if (isset($_cr_id_order_)) echo $_cr_id_order_;?>" onchange="checkCr_id_order()">
<input type="button" name="crSidList" value="..." tabindex="<?php echo $_crSidList_tabindex_;?>"
class="button_enabled"
title="Kurierliste (alt+<?php echo $_crSidList_accesskey_;?>)" accesskey="<?php echo $_crSidList_accesskey_;?>"
onclick="mk_cr_id_list('','')">
<?php echo $CUSTOMER_COURIER_DISABLED_END;?>
<?php echo $CUSTOMER_FILTER_DISABLED_START;?>
<input type="button" name="jb_cr_filterButton" value="Filter"
class="button_enabled"
tabindex="<?php echo $_jb_cr_filter_tabindex_;?>" title="Kurierfilter (alt+<?php echo $_jb_cr_filter_accesskey_;?>)" accesskey="<?php echo $_jb_cr_filter_accesskey_;?>" onclick="parent.frames[2].mkJb_cr_filter()">
<?php echo $CUSTOMER_FILTER_DISABLED_END;?>
<?php echo $CUSTOMER_DISABLED_START;?>
<br>
<input type="checkbox" name="jb_waitstorno" value="1" tabindex="<?php echo $_jb_waitstorno_tabindex_;?>" <?php if (isset($_jb_waitstorno_disabled_)) echo $_jb_waitstorno_disabled_;?>>
Storno wenn<br>nicht verf&uuml;gbar<br>
<br>
</div>
<div id="courierselectmultiple">
</div>
<?php echo $CUSTOMER_DISABLED_END;?>
<?php echo $WAITTIME_DISABLED_START;?>
<b>Annahme</b> bis (Uhrzeit):<br>
<select name="jb_waittime_hour" class="input" tabindex="<?php if (isset($_jb_waittime_hour_tabindex_)) echo $_jb_waittime_hour_tabindex_;?>"
onchange="checkTimeFields(12)">
<option value=""></option>
<option value="00">00</option>
<option value="01">01</option>
<option value="02">02</option>
<option value="03">03</option>
<option value="04">04</option>
<option value="05">05</option>
<option value="06">06</option>
<option value="07">07</option>
<option value="08">08</option>
<option value="09">09</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option>
<option value="17">17</option>
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
<option value="21">21</option>
<option value="22">22</option>
<option value="23">23</option>
</select>
<select name="jb_waittime_minute" class="input" tabindex="<?php if (isset($_jb_waittime_minute_tabindex_)) echo $_jb_waittime_minute_tabindex_;?>"
onchange="checkTimeFields(13)">
<option value=""></option>
<option value="00">00</option>
<option value="05">05</option>
<option value="10">10</option>
<option value="15">15</option>
<option value="20">20</option>
<option value="25">25</option>
<option value="30">30</option>
<option value="35">35</option>
<option value="40">40</option>
<option value="45">45</option>
<option value="50">50</option>
<option value="55">55</option>
</select><br>
<?php echo $WAITTIME_DISABLED_END;?>
<br>
<table border=0 align=left cellspacing=0 cellpadding=0 vspace=0 hspace=0>
<tr>
<td align=center>
Gew&uuml;nschter<br> <b>Fahrzeugtyp</b>:<br>
<select name="vht_id" class="input" tabindex="<?php echo $_vht_id_tabindex_;?>" onchange="checkWeight(1)">
<?php echo $_vht_id_options_;?>
</select>
&nbsp;<br>&nbsp;<br>
</td><td align=center>
&nbsp;<b>Treibstoff-<br>&nbsp;zuschlag (TSZ):<br></b>
&nbsp;<input name="jb_markup" type="text" size="4" maxlength="5"
class="input" tabindex="<?php echo $_jb_markup_tabindex_;?>"onchange="checkMarkup()" value="<?php if (isset($_jb_markup_)) echo $_jb_markup_;?>">&nbsp;%<br>
Standard:<input name="currentTSZ" type="text" value="" size="6" maxlength="7" class="hideRed" readonly>
</td></tr>
<tr>
<td align=center>
&nbsp;<b>Maut/Auslagen:<br></b>
&nbsp;<input name="jb_toll" type="text" size="6" maxlength="7"
class="input" tabindex="<?php echo $_jb_toll_tabindex_;?>"onchange="checkToll()" value="<?php if (isset($_jb_toll_)) echo $_jb_toll_;?>">&nbsp;&euro;
&nbsp;<br>&nbsp;<br>
</td>
<td align=center>
<br>&nbsp;<b>TSZ Frachtverg.:<br></b>
&nbsp;<input name="jb_cr_markup" type="text" size="4" maxlength="5"
class="input" tabindex="<?php echo $_jb_cr_markup_tabindex_;?>"onchange="checkMarkupCr()" value="<?php if (isset($_jb_cr_markup_)) echo $_jb_cr_markup_;?>">&nbsp;%<br>
&nbsp;Standard:<input name="currentCrTSZ" type="text" value="" size="6" maxlength="7" class="hideRed" readonly>
</td>
</tr>
</table>
</td>
<td align=left valign=top width=<?php echo (MASK_CR_PRICE_MODE == "1" ? "16" : "19");?>%>
<?php echo $CUSTOMER_DISABLED_START;?>
<?php echo $RANKING_JB2CRVH_MEASURE_DISABLED_START . "\n";?>
<b>Maximalgewicht</b> eines<br>Transportgutes in kg:<br>
<input name="jb_weight" type="text" size="5" maxlength="5" class="input"
tabindex="<?php echo $_jb_weight_tabindex_;?>" value="0" onchange="checkWeight(0)" value="<?php if (isset($_jb_weight_)) echo $_jb_weight_;?>"><br>
<i>(Maximale Ma&szlig;e ggfs. in<br>Feld Bemerkung eintragen)</i><br>
<?php echo $RANKING_JB2CRVH_MEASURE_DISABLED_END . "\n";?>
<?php echo $RANKING_JB2CRVH_MEASURE_ENABLED_START . "\n";?>
<table border=0 align=left cellspacing=0 cellpadding=0 vspace=0 hspace=0>
<tr>
<td>
<table border=0 align=left cellspacing=0 cellpadding=0 vspace=0 hspace=0>
<tr>
<td colspan=2>
<b>Maximalgewicht:</b>
<input name="jb_weight" type="text" size="2" maxlength="5" class="input"
tabindex="<?php echo $_jb_weight_tabindex_;?>" value="0" onchange="checkWeight(0)" value="<?php if (isset($_jb_weight_)) echo $_jb_weight_;?>">kg
</td>
</tr>
<tr>
<td>
<b>Länge:</b>
<input name="jb_crvh_length" type="text" size="2" maxlength="4" class="input"
tabindex="<?php echo $_jb_crvh_length_tabindex_;?>" value="0" onchange="checkDimensions(0)" value="<?php if (isset($_crvh_length_)) echo $_crvh_length_;?>">cm&nbsp;&nbsp;
<br><b>Breite:</b>
<input name="jb_crvh_width" type="text" size="2" maxlength="4" class="input"
tabindex="<?php echo $_jb_crvh_width_tabindex_;?>" value="0" onchange="checkDimensions(1)" value="<?php if (isset($_crvh_width_)) echo $_crvh_width_;?>">cm&nbsp;&nbsp;
</td>
<td>
<b>H&ouml;he:&nbsp;&nbsp;</b>
<input name="jb_crvh_height" type="text" size="2" maxlength="4" class="input"
tabindex="<?php echo $_jb_crvh_height_tabindex_;?>" value="0" onchange="checkDimensions(2)" value="<?php if (isset($_crvh_height_)) echo $_crvh_height_;?>">cm
<br><b>Pl&auml;tze:</b>
<input name="jb_crvh_position" type="text" size="2" maxlength="4" class="input"
tabindex="<?php echo $_jb_crvh_position_tabindex_;?>" value="0" onchange="checkDimensions(3)" value="<?php if (isset($_crvh_position_)) echo $_crvh_position_;?>">
</td>
</tr>
<tr>
<td colspan=2>
<?php echo $RANKING_JB2CRVH_MEASURE_ENABLED_END . "\n";?>
<br><b>Rhythmus</b> (nur Dauerauftrag):<br>
<select name="jb_permanent" class="input" tabindex="<?php echo $_jb_permanent_tabindex_;?>" onchange="checkJb_permanent(1)" disabled>
<option value="" selected="selected"></option>
<?php echo $_jb_permanent_options_;?>
</select><br>
<?php echo $RANKING_JB2CRVH_MEASURE_ENABLED_START . "\n";?>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td>
<?php echo $RANKING_JB2CRVH_MEASURE_ENABLED_END . "\n";?>
<table border=0 align=left cellspacing=0 cellpadding=0 vspace=0 hspace=0>
<tr>
<td align=center>
Mo
</td>
<td align=center>
Di
</td>
<td align=center>
Mi
</td>
<td align=center>
Do
</td>
<td align=center>
Fr
</td>
<td align=center>
Sa
</td>
<td align=center>
So
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="jb_permanent2_0" value="0" tabindex="<?php echo $_jb_permanent2_0_tabindex_;?>"
onclick="checkJb_permanent2()" disabled>
</td>
<td>
<input type="checkbox" name="jb_permanent2_1" value="1" tabindex="<?php echo $_jb_permanent2_1_tabindex_;?>"
onclick="checkJb_permanent2()" disabled>
</td>
<td>
<input type="checkbox" name="jb_permanent2_2" value="2" tabindex="<?php echo $_jb_permanent2_2_tabindex_;?>"
onclick="checkJb_permanent2()" disabled>
</td>
<td>
<input type="checkbox" name="jb_permanent2_3" value="3" tabindex="<?php echo $_jb_permanent2_3_tabindex_;?>"
onclick="checkJb_permanent2()" disabled>
</td>
<td>
<input type="checkbox" name="jb_permanent2_4" value="4" tabindex="<?php echo $_jb_permanent2_4_tabindex_;?>"
onclick="checkJb_permanent2()" disabled>
</td>
<td>
<input type="checkbox" name="jb_permanent2_5" value="5" tabindex="<?php echo $_jb_permanent2_5_tabindex_;?>"
onclick="checkJb_permanent2()" disabled>
</td>
<td>
<input type="checkbox" name="jb_permanent2_6" value="6" tabindex="<?php echo $_jb_permanent2_6_tabindex_;?>"
onclick="checkJb_permanent2()" disabled>
</td>
</tr>
</table>
<?php echo $RANKING_JB2CRVH_MEASURE_ENABLED_START . "\n";?>
</td>
</tr>
<tr>
<td>
<div id="multi_job_factor">
<br>
<select name="jb_multi_factor" class="input" tabindex="<?php echo $_jb_multi_factor_tabindex_;?>"
onchange="check_jb_multi_factor()">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
<b>Auftr&auml;ge insgesamt</b><br>
</div>
</td>
</tr>
</table>
<?php echo $RANKING_JB2CRVH_MEASURE_ENABLED_END . "\n";?>
</td>
<?php echo $CUSTOMER_DISABLED_END;?>
<td align=left valign=top width=<?php echo (MASK_CR_PRICE_MODE == "1" ? "16" : "24");?>%>
<div id="appointment"></div>
<div id="dateselect">
<b>Datum</b> (nur Vorbestellung/<br>Dauerauftrag/Nacherfassung):<br>
<?php echo $DATESELECTFIELDS_DISABLED_START;?>
<select name="tag" class="input" tabindex="<?php echo $_tag_tabindex_;?>"
onchange="fillDateFields(0, 'job_options', 'tourOptions', 'tag', 'tag', 'monat', 'jahr', 'stunde', 'minute', 'jb_permanent')">
</select>
<select name="monat" class="input" tabindex="<?php echo $_monat_tabindex_;?>"
onchange="fillDateFields(0, 'job_options', 'tourOptions', 'monat', 'tag', 'monat', 'jahr', 'stunde', 'minute', 'jb_permanent')">
</select>
<select name="jahr" class="input" tabindex="<?php echo $_jahr_tabindex_;?>"
onchange="fillDateFields(0, 'job_options', 'tourOptions', 'jahr', 'tag', 'monat', 'jahr', 'stunde', 'minute', 'jb_permanent')">
</select>
<?php echo $DATESELECTFIELDS_DISABLED_END;?>
<?php echo $DATEINPUTFIELDS_DISABLED_START;?>
<input name="tag" type="text" size="2" maxlength="2" class="input" tabindex="<?php echo $_tag_tabindex_;?>" value=""
onchange="checkStartDate('tag')">
<input name="monat" type="text" size="2" maxlength="2" class="input" tabindex="<?php echo $_monat_tabindex_;?>" value=""
onchange="checkStartDate('monat')">
<input name="jahr" type="text" size="4" maxlength="4" class="input" tabindex="<?php echo $_jahr_tabindex_;?>" value=""
onchange="checkStartDate('jahr')">
<?php echo $DATEINPUTFIELDS_DISABLED_END;?>
<input name="dayOfWeek" type="text" value="" size="11" maxlength="11"
class="hideSmall" readonly><br>
<i><a href="javascript:openCalendar();">Kalender &ouml;ffnen</a></i><br>
<br>
<b>Uhrzeit</b> (nur Vorbestellung/<br>Dauerauftrag/Nacherfassung):<br>
<?php echo $TIMESELECTFIELDS_DISABLED_START;?>
<select name="stunde" class="input" tabindex="<?php echo $_stunde_tabindex_;?>"
onchange="fillDateFields(0, 'job_options', 'tourOptions', 'stunde', 'tag', 'monat', 'jahr', 'stunde', 'minute', 'jb_permanent')">
</select>
<select name="minute" class="input" tabindex="<?php echo $_minute_tabindex_;?>"
onchange="fillDateFields(0, 'job_options', 'tourOptions', 'minute', 'tag', 'monat', 'jahr', 'stunde', 'minute', 'jb_permanent')">
</select>
<?php echo $TIMESELECTFIELDS_DISABLED_END;?>
<?php echo $TIMEINPUTFIELDS_DISABLED_START;?>
<input name="stunde" type="text" size="2" maxlength="2" class="input" tabindex="<?php echo $_stunde_tabindex_;?>" value=""
onchange="checkStartDate('stunde')">
<input name="minute" type="text" size="2" maxlength="2" class="input" tabindex="<?php echo $_minute_tabindex_;?>" value=""
onchange="checkStartDate('minute')">
<?php echo $TIMEINPUTFIELDS_DISABLED_END;?>
<?php echo $CUSTOMER_DISABLED_START;?>
<br>
<b>Enddatum</b> (nur Dauerauftrag -<br>Tag der letzten Ausf&uuml;hrung):<br>
<?php echo $CUSTOMER_DISABLED_END;?>
<?php echo $DATESELECTFIELDS_DISABLED_START;?>
<select name="endetag" class="input" tabindex="<?php echo $_endetag_tabindex_;?>"
onchange="fillDateFields(0, 'job_options', 'tourOptions', 'endetag', 'endetag', 'endemonat', 'endejahr', '', '', '')">
</select>
<select name="endemonat" class="input" tabindex="<?php echo $_endemonat_tabindex_;?>"
onchange="fillDateFields(0, 'job_options', 'tourOptions', 'endemonat', 'endetag', 'endemonat', 'endejahr', '', '', '')">
</select>
<select name="endejahr" class="input" tabindex="<?php echo $_endejahr_tabindex_;?>"
onchange="fillDateFields(0, 'job_options', 'tourOptions', 'endejahr', 'endetag', 'endemonat', 'endejahr', '', '', '')">
</select>
<?php echo $DATESELECTFIELDS_DISABLED_END;?>
<?php echo $DATEINPUTFIELDS_DISABLED_START;?>
<?php echo $CUSTOMER_DISABLED_START;?>
<input name="endetag" type="text" size="2" maxlength="2" class="input" tabindex="<?php echo $_endetag_tabindex_;?>" value=""
onchange="checkEndDate('endetag')">
<input name="endemonat" type="text" size="2" maxlength="2" class="input" tabindex="<?php echo $_endemonat_tabindex_;?>" value=""
onchange="checkEndDate('endemonat')">
<input name="endejahr" type="text" size="4" maxlength="4" class="input" tabindex="<?php echo $_endejahr_tabindex_;?>" value=""
onchange="checkEndDate('endejahr')">
<br>
<div id="multi_job_all">
<br>
<input type="checkbox" name="jb_multi" value="1" tabindex="<?php echo $_jb_multi_tabindex_;?>"
title="Multi-Auftrag" disabled>
&nbsp;<b>Alle Folgeauftr&auml;ge sofort anlegen</b><br>
</div>
<?php echo $CUSTOMER_DISABLED_END;?>
<?php echo $DATEINPUTFIELDS_DISABLED_END;?>
</div>
</td>
<td align=left valign=top width=<?php echo (MASK_CR_PRICE_MODE == "1" ? "16" : "19");?>%>
<b>gespeicherte Touren</b><br>
(kopiert die ausgew&auml;hlte<br>
Tour in dieses Formular):<br>
<select name="savedTour" class="input" tabindex="<?php echo $_savedTour_tabindex_;?>" onchange="getSavedTour(0,false,0,true)"
<?php echo $_savedTour_disabled_;?>>
<option value=""></option>
<?php echo $_savedTour_options_;?>
</select><br>
<br>
<b>Tourenname</b> (speichert die<br>
Tour nach dem Senden unter<br>
diesem Namen in der Liste):<br>
<input name="jb_tourname" type="text" size="20" maxlength="50"
class="input" tabindex="<?php echo $_jb_tourname_tabindex_;?>" value="<?php if(isset($_jb_tourname_)) echo $_jb_tourname_;?>"><br>
<input type="hidden" name="jb_tourname_hidden" value="">
<input type="checkbox" name="jb_tourname_overwrite" value="1" tabindex="<?php echo $_jb_tourname_overwrite_tabindex_;?>"
title="Gespeicherte Tour mit der aktuellen &uuml;berschreiben" onclick="mkTourname()" disabled>&nbsp;<b>Gespeicherte Tour</b><br>&uuml;berschreiben
<?php echo (MASK_CR_PRICE_MODE == "1" ? "<!--" : "");?>
<br><br>
<input type="submit" name="toursubmit" size="2" value="Senden" tabindex="<?php echo $_toursubmit_tabindex_;?>"
style="background:#00FF00; color:<?php echo $constButtonColor;?>; font-weight:bold; font-size:10pt; font-style:normal; font-family:Helvetica,Arial; "
align=left title="Auftrag senden (alt+<?php echo $_toursubmit_accesskey_;?>)" accesskey="<?php echo $_toursubmit_accesskey_;?>" class="submit" disabled>
<input name="submitMessage" type="text" value="" size="25" class="hideRed" readonly>
<input type="hidden" name="csc_id_orderer" value="<?php echo $_csc_id_orderer_ec_;?>">
</td>
<?php echo (MASK_CR_PRICE_MODE == "1" ? "-->" : "");?>
<td valign=top width=<?php echo (MASK_CR_PRICE_MODE == "1" ? "16" : "19");?>%>
<table border=0 align=left cellspacing=0 cellpadding=0 vspace=0 hspace=0>
<tr>
<?php echo $CUSTOMER_DISABLED_START;?>
<td>
<?php echo (MASK_CR_PRICE_MODE == "1" ? "<b>Auftrags-Preis</b>" : "<b>Festpreis</b>&nbsp;f&uuml;r&nbsp;den<br>gesamten&nbsp;Auftrag");?>:
</td>
<?php echo $SERVICEPRICE_DISABLED_START;?>
<td>
&nbsp;&nbsp;&nbsp;<?php echo (MASK_CR_PRICE_MODE == "1" ? "<b>Service-Preis</b>" : "zus&auml;tzliche<br>&nbsp;&nbsp;&nbsp;<b>Servicezeit</b>");?>:
</td>
<?php echo $SERVICEPRICE_DISABLED_END;?>
</tr>
<tr><td>
<input name="jb_fixprice" type="text" size="8" maxlength="9"
class="input" tabindex="<?php echo $_jb_fixprice_tabindex_;?>" onchange="parent.job_options.tourOptions.km_price_params.value='';checkFixprice(0)" value="<?php if (isset($_jb_fixprice_)) echo $_jb_fixprice_;?>">&nbsp;&euro;
<?php echo (MASK_CR_PRICE_MODE == "1" ? "<br><br>" : "");?>
</td>
<?php echo $SERVICEPRICE_DISABLED_START;?>
<td>
&nbsp;&nbsp;
<input name="jb_serviceprice" type="text" size="8" maxlength="9"
class="input" tabindex="<?php echo $_jb_serviceprice_tabindex_;?>" onchange="checkServiceprice()" value="<?php if (isset($_jb_serviceprice_)) echo $_jb_serviceprice_;?>">&nbsp;&euro;
<?php echo (MASK_CR_PRICE_MODE == "1" ? "<br><br>" : "");?>
</td>
</tr>
<?php echo (MASK_CR_PRICE_MODE == "1" ? "" : "<!--");?>
<tr>
<td>
<b>Auftrags-Frachtverg.</b>:
</td>
<?php echo $SERVICEPRICE_DISABLED_START;?>
<td>
&nbsp;&nbsp;&nbsp;<b>Service-Frachtverg.</b>:
</td>
<?php echo $SERVICEPRICE_DISABLED_END;?>
</tr>
<tr><td>
<input name="jb_cr_price" type="text" size="8" maxlength="9"
class="input" tabindex="<?php echo $_jb_cr_price_tabindex_;?>" onchange="checkCrPrice()" value="<?php if (isset($_jb_cr_price_)) echo $_jb_cr_price_;?>"<?php echo $cr_price_readonly?>>&nbsp;&euro;
<br><br>
</td>
<?php echo $SERVICEPRICE_DISABLED_START;?>
<td>
&nbsp;&nbsp;
<input name="jb_cr_serviceprice" type="text" size="8" maxlength="9"
class="input" tabindex="<?php echo $_jb_cr_serviceprice_tabindex_;?>" onchange="checkCrServiceprice()" value="<?php if (isset($_jb_serviceprice_)) echo $_jb_serviceprice_;?>"<?php echo $cr_price_readonly?>>&nbsp;&euro;
<br><br>
</td>
<?php echo $SERVICEPRICE_DISABLED_END;?>
</tr>
<?php echo (MASK_CR_PRICE_MODE == "1" ? "" : "-->");?>
</table><br clear=all>
<?php echo $DISCOUNT_DISABLED_START;?>
<table border=0 align=left cellspacing=0 cellpadding=0 vspace=0 hspace=0><tr><td>
<input type="checkbox" name="jb_discount" value="1" tabindex="<?php echo $_jb_discount_tabindex_;?>" onchange="checkFixprice(0)"
title="Kundenrabatt beim Fest- und Servicepreis ber&uuml;cksichtigen" disabled>&nbsp;<b>Rabatt</b> ber&uuml;cksichtigen
<input name="jb_discount_rate_text" type="text" value="" size="7" maxlength="7" class="hideSmall" readonly>
<input type="hidden" name="jb_discount_rate"><br>
<input name="jb_markup_text" type="text" value="" size="50" maxlength="7" class="hideSmall" readonly><br>
<?php echo (MASK_CR_PRICE_MODE != "1" ? "<!--" : "");?>
<input name="cr_price_text" type="text" value="" size="50" maxlength="7" class="hideSmall" readonly><br>
<?php echo (MASK_CR_PRICE_MODE != "1" ? "-->" : "");?>
</td><td>
</td></tr></table>
<br clear=all>
<?php echo $DISCOUNT_DISABLED_END;?>
<table border=0 align=left cellspacing=0 cellpadding=0 vspace=0 hspace=0><tr><td>
<b>Steuern</b>:
<input name="jb_sales_tax_rate" type="text" size="2" maxlength="2"
class="input" tabindex="<?php echo $_jb_sales_tax_rate_tabindex_;?>" onchange="checkFixprice(0)" value="<?php echo $_sales_tax_rate_value_;?>" readonly>&nbsp;&nbsp;
<select name="jb_sales_tax_rate_sign" class="input" tabindex="<?php echo $_jb_sales_tax_rate_sign_tabindex_;?>" onchange="checkJb_sales_tax_rate_sign(0)">
<?php echo $_jb_sales_tax_rate_sign_options_;?>
</select>
</td><td>&nbsp;
<?php echo $CALCULATOR_DISABLED_START;?>
<input type="button" name="calcButton" value="Calc"
class="button_enabled"
tabindex="<?php if (isset($_calcButton_tabindex_)) echo $_calcButton_tabindex_;?>" title="Calculator" onclick="parent.frames[2].calculator()">
<?php echo $CALCULATOR_DISABLED_END;?>
<input type="hidden" name="jb_type" value="<?php echo $_jb_type_;?>">
<input type="hidden" name="jb_id_parent" value="<?php if (isset($_jb_id_parent_)) echo $_jb_id_parent_;?>">
<?php echo (MASK_CR_PRICE_MODE == "1" ? "<!--" : "");?>
<input type="hidden" name="jb_cr_price" value="<?php if (isset($_jb_cr_price_)) echo $_jb_cr_price_;?>">
<?php echo (MASK_CR_PRICE_MODE == "1" ? "-->" : "");?>
<input type="hidden" name="tmp_add_jb_ids" value="<?php if (isset($_tmp_add_jb_ids_)) echo $_tmp_add_jb_ids_;?>">
<input type="hidden" name="tmp_add_sids" value="<?php if (isset($_tmp_add_sids_)) echo $_tmp_add_sids_;?>">
<input type="hidden" name="tmp_add_prices" value="<?php if (isset($_tmp_add_prices_)) echo $_tmp_add_prices_;?>">
<input type="hidden" name="tmp_add_srvs" value="<?php if (isset($_tmp_add_srvs_)) echo $_tmp_add_srvs_;?>">
<input type="hidden" name="tmp_add_srvts" value="<?php if (isset($_tmp_add_srvts_)) echo $_tmp_add_srvts_;?>">
<input type="hidden" name="tmp_add_mult" value="<?php if (isset($_tmp_add_mult_)) echo $_tmp_add_mult_;?>">
<input type="hidden" name="tmp_add_mult_price" value="<?php if (isset($_tmp_add_mult_price_)) echo $_tmp_add_mult_price_;?>">
<input type="hidden" name="km_price_params" value="<?php if (isset($_km_price_params_)) echo $_km_price_params_;?>">
<input type="hidden" name="jb_cashpayer_mail_hidden" value="<?php if (isset($_jb_cashpayer_mail_)) echo $_jb_cashpayer_mail_;?>">
<input type="hidden" name="jb_offer_mail_hidden" value="<?php if (isset($_jb_offer_mail_)) echo $_jb_offer_mail_;?>">
<input type="hidden" name="cs_invmail_hidden" value="<?php if (isset($_cs_invmail_hidden_)) echo $_cs_invmail_hidden_;?>">
<input type="hidden" name="jb_origin_hidden" value="<?php if (isset($_jb_origin_hidden_)) echo $_jb_origin_hidden_;?>">
<input type="hidden" name="jb_origin_other_hidden" value="<?php if (isset($_jb_origin_other_hidden_)) echo $_jb_origin_other_hidden_;?>">
<input type="hidden" name="jb_orderer_hidden" value="<?php if (isset($_jb_orderer_)) echo $_jb_orderer_;?>">
<input type="hidden" name="jb_commission_no_hidden" value="<?php if (isset($_jb_commission_no_)) echo $_jb_commission_no_;?>">
<input type="hidden" name="ask_mailrecipients" value="">
<input type="hidden" name="sendmail" value="0">
<input type="hidden" name="jb_id_permanent_pre" value="">
<input type="hidden" name="do_delete_suborder" value="">
<input type="hidden" name="cr_price_threshold_override" value="">
<input type="hidden" name="cr_price_block_override" value="">
<input type="hidden" name="self_service_discount" value="">
<input type="hidden" name="jb_id_insurance" value="">
<input type="hidden" name="special_case_ori" value="">
</td>
</tr>
</table>
<br clear=all>
<table border=0 align=left cellspacing=0 cellpadding=0 vspace=0 hspace=0><tr><td>
<span style="font-size: 4pt"><br></span>
<input type="checkbox" name="jb_insurance" value="1" tabindex="<?php echo $_jb_insurance_tabindex_;?>" onchange="checkInsurance()"
title="Höherversicherungs-Auftrag automatisch erzeugen">&nbsp;<b>Höherversicherung</b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<div id="div_insurance" style="display:none">
<b>Warenwert:</b>
<input name="jb_value_of_goods" type="text" size="8" maxlength="9"
class="inputRed" tabindex="<?php echo $_jb_value_of_goods_tabindex_;?>" onchange="checkValueOfGoods()" value="<?php if (isset($_jb_value_of_goods_)) echo $_jb_value_of_goods_;?>">&nbsp;&euro;
&nbsp;<input type="checkbox" name="special_case" value="1" tabindex="<?php echo $_special_case_tabindex_;?>"
title="Höherversicherungs-Auftrag soll manuell nachbearbeitet werden">&nbsp;<b>Sonderfall</b>
<br>
<b>Tarif:</b>
<select name="jb_insurance_rate" class="inputRed" tabindex="<?php echo $_jb_insurance_rate_tabindex_;?>" onchange="checkValueOfGoods()">
<option value="0">--- Bitte einen Tarif wählen ---</option>
<option value="1">BRD Warengruppe I (0,70&permil;)</option>
<option value="2">BRD Warengruppe II (1,75&permil;)</option>
<option value="3">Europa ohne GUS Warengr. I (0,85&permil;)</option>
<option value="4">Europa ohne GUS Warengr. II (2,00&permil;)</option>
<option value="5">PKW Botendienst BRD (0,7&permil;)</option>
</select>
</div>
<!--
<div id="div_insurance_done" style="display:none">
<input name="jb_id_insurance" type="text" value="" size="39" maxlength="39" class="hideSmall" readonly>
</div>
-->
</td></tr>
</table>
<br clear=all>&nbsp;<br>
<?php echo (MASK_CR_PRICE_MODE == "1" ? "</td><td valign=top width=16%>" : "");?>
<?php echo $CUSTOMER_DISABLED_END;?>
<input type="hidden" name="jobList" value="">
<?php echo $CUSTOMER_JB_SALES_TAX_RATE;?>
<?php echo $CUSTOMER_DISABLED_START;?>
<input type="checkbox" name="afterwards" value="1" tabindex="<?php echo $_afterwards_tabindex_;?>"
onclick="checkAfterwards()" title="Nacherfassung (alt+<?php echo $_afterwards_accesskey_;?>)"
accesskey="<?php echo $_afterwards_accesskey_;?>" <?php if (isset($_afterwards_checked_)) echo $_afterwards_checked_;?>>
<b>Nacherfassung</b><br>
<input type="checkbox" name="jb_globaljob" value="1" tabindex="<?php echo $_jb_globaljob_tabindex_;?>"
onclick="checkJb_globaljob()" title="An alle Kuriere"
<?php if (isset($_jb_globaljob_checked_)) echo $_jb_globaljob_checked_;?>>
<b>An alle Kuriere</b><br>
<input type="checkbox" name="jb_status_manual" value="1" tabindex="<?php echo $_jb_status_manual_tabindex_;?>"
title="Manuelle Disposition (alt+<?php echo $_jb_status_manual_accesskey_;?>)"
accesskey="<?php echo $_jb_status_manual_accesskey_;?>" <?php if (isset($_jb_status_manual_checked_)) echo $_jb_status_manual_checked_;?>>
<b>Manuelle Disposition</b><br>
<input type="checkbox" name="jb_incomplete" value="1" tabindex="<?php echo $_jb_incomplete_tabindex_;?>"
onclick="checkIncomplete()" title="Noch unvollst&auml;ndig (alt+<?php echo $_jb_incomplete_accesskey_;?>)"
accesskey="<?php echo $_jb_incomplete_accesskey_;?>" <?php if (isset($_jb_incomplete_checked_)) echo $_jb_incomplete_checked_;?>>
<b>Noch unvollst&auml;ndig</b><br>
<input type="checkbox" name="jb_offer" value="1" tabindex="<?php echo $_jb_offer_tabindex_;?>"
onclick="checkOffer()" title="Angebot"
<?php if (isset($_jb_incomplete_checked_)) echo $_jb_incomplete_checked_;?>>
<b>Angebot</b><br>
<div id="div_jb_bwv" style="display:none">
<input type="checkbox" name="jb_bwv" value="1" tabindex="<?php echo $_jb_bwv_tabindex_;?>"
onclick="checkBWV()" title="BWV-Auftrag"
<?php if (isset($_jb_bwv_checked_)) echo $_jb_bwv_checked_;?>>
<b>BWV-Auftrag</b><br>
</div>
<div id="div_jb_km" style="display:none">
<br>
<b>Geleistete Kilometer:</b>
<input name="jb_km" type="text" size="5" maxlength="9" class="input"
tabindex="<?php echo $_jb_km_tabindex_;?>" value="" onchange="checkKm()" value="<?php if (isset($_jb_km_)) echo $_jb_km_;?>">km
</div>
<input type="hidden" name="request_token" value="<?php echo $_request_token_;?>">
<input type="hidden" name="jb_id" value="<?php echo $_ec_jb_id_;?>">
<input type="hidden" name="hq_id" value="<?php echo $hq_id_job;?>">
<input type="hidden" name="csc_id_payer" value="">
<input type="hidden" name="comp_payer" value="">
<input type="hidden" name="payer_is_default" value="">
<input type="hidden" name="dont_change_tx" value="false">
<input type="hidden" name="jb_cash_hidden" value="false">
<input type="hidden" name="jb_freetext_1" value="">
<input type="hidden" name="jb_hiddenFreetext_1" value="">
<input type="hidden" name="jb_costsplit_hidden" value="false">
<input type="hidden" name="jb_permanent2_hidden" value="0000000">
<input type="hidden" name="jb_cr_filter" value="">
<input type="hidden" name="jb_cr_filter_opt" value="">
<input type="hidden" name="jb_status" value="">
<input type="hidden" name="accept_all_addresses" value="">
<input type="hidden" name="jb_id_org" value="">
<input type="hidden" name="jb_dispoinfo" value="">
<input type="hidden" name="jb_warnjahr" value="">
<input type="hidden" name="jb_warnmonat" value="">
<input type="hidden" name="jb_warntag" value="">
<input type="hidden" name="jb_warnstunde" value="">
<input type="hidden" name="jb_warnminute" value="">
<input type="hidden" name="jb_jam_waittime" value="">
<input type="hidden" name="cr_id_order_hidden" value="">
<input type="hidden" name="cr_id_orders" value="">
<?php echo (MASK_CR_PRICE_MODE == "1" ? "" : "<!--");?>
<br><br>
<input type="submit" name="toursubmit" size="2" value="Senden" tabindex="<?php echo $_toursubmit_tabindex_;?>"
style="background:#00FF00; color:<?php echo $constButtonColor;?>; font-weight:bold; font-size:10pt; font-style:normal; font-family:Helvetica,Arial; "
align=left title="Auftrag senden (alt+<?php echo $_toursubmit_accesskey_;?>)" accesskey="<?php echo $_toursubmit_accesskey_;?>" class="submit" disabled>
<div id="loader_active" style="display:none">
<img src="../images/ajax-loader.gif" height="16" width="16" border="0">
</div>
<div id="loader_inactive" style="display:inline">
<img src="../images/empty.gif" height="16" width="16" border="0">
</div>
<input name="submitMessage" type="text" value="" size="25" class="hideRed" readonly>
<input type="hidden" name="csc_id_orderer" value="<?php echo $_csc_id_orderer_ec_;?>">
</td>
<?php echo (MASK_CR_PRICE_MODE == "1" ? "" : "-->");?>
</td>
</tr>
</form>
</table>
</td>
<td>
&nbsp;
</td>
</tr>
<tr>
<td colspan=7>
<img src="../images/empty.gif" border=0 height=1>
</td>
</tr>
</table>
</body>
</html>
<script type="text/javascript">
<!--
job_options_isLoading=false;
//alert(
//  "parent.window.navigator.userAgent = " + parent.window.navigator.userAgent + "\n" +
//  "parent.window.visualViewport.scale = " + parent.window.visualViewport.scale + "\n" +
//  "parent.window.outerWidth = " + parent.window.outerWidth + "\n" +
//  "parent.window.innerWidth = " + parent.window.innerWidth + "\n" +
//  "zoom = " + (((parent.window.outerWidth - 10) / parent.window.innerWidth) * 100) + "\n" +
//  parent.document.body.clientWidth + "px x " + parent.document.body.clientHeight + "px" + "\n" +
//  "parent.window.devicePixelRatio = " + parent.window.devicePixelRatio + "\n" +
//  "1/parent.window.devicePixelRatio = " + (1/parent.window.devicePixelRatio) + "\n"
//  );
//if (parent.window.devicePixelRatio != 1 && parent.window.navigator.userAgent.indexOf("Firefox") != -1)
////  parent.document.body.style.zoom=1/parent.window.devicePixelRatio;
////  parent.job_header.document.body.style.zoom=1/parent.window.devicePixelRatio;
////  parent.job_tour.document.body.style.zoom=1/parent.window.devicePixelRatio;
////  parent.job_options.document.body.style.zoom=1/parent.window.devicePixelRatio;
////  parent.job_tour_list.document.body.style.zoom=1/parent.window.devicePixelRatio;
-->
</script>
