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

include_once("../include/caglobal.inc.php");
include_once("../include/global.inc.php");
include_once("../include/auth.inc.php");
$phpVersion = substr(phpversion(), 0, 3); // Mail von I.K. am 06.01. -> Merkwürdige Fehlermeldung in check_jb_permanent_multi_202201.log: $phpVersion scheint nicht definiert?
if ($phpVersion < "8.0"):
  if ($phpVersion >= "7.0"):
    require_once("../PEAR/HTML/Template/IT.php");
  else:
   require_once("HTML/IT.php");
  endif;
endif;

// Decision to use the archive or normal tables
list ($dbhistory) = getHttpVars(array("dbhistory"));
getDBNames($dbhistory);
if (!isset($dbh_jb) || $dbh_jb == "")
  $dbh_jb = "job";
if (!isset($dbh_tr) || $dbh_tr == "")
  $dbh_tr = "tour";

// Name der Tabellen
if (!(isset($_copy_jobs_flag) && $_copy_jobs_flag == true) || (isset($jb_storno) && $jb_storno > 0) ||
  (isset($_copy_jobs_flag_ori) && $_copy_jobs_flag_ori == true)):
  $_job_table = $dbh_jb;
  $_tour_table = $dbh_tr;
else:
  $_job_table = "job_backup";
  $_tour_table = "tour_backup";
endif;

// Job-ID des Auftrags ist Parameter
// checken, ob jb_id schon definiert (gesetzt, wenn von "check_jb_permanent.php" aufgerufen)
if (!(isset($check_jb_permanent_flag) && $check_jb_permanent_flag == true))
  list ($jb_id, $cr_sid_none, $consider_manual_disp, $jb_copy, $no_dates) = getHttpVars(array("jb_id", "cr_sid", "consider_manual_disp", "jb_copy", "no_dates"));
if ($jb_id == "") reportDie ("$PHP_SELF: Parameter 'jb_id' fehlt!", false);

// gespeicherte Job-Daten holen
list($hq_id, $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_id_copy_permanent,
  $jb_sales_tax_rate, $jb_sales_tax_rate_sign, $jp_permenddat, $jb_cr_filter, $jb_cr_filter_opt,
  $jb_locktime, $jb_lockuser, $jb_status, $cr_id_permanent, $jb_incomplete, $jb_id_parent, $jb_export_time, $jb_freetext_2, $jb_dispoinfo, $jb_warningtime, $jb_offer, $jb_origin, $jb_orderer, $jb_commission_no, $jb_createtime) = // $jb_status wird bei der nachträglichen Änderung einer Tour benötigt
  getFieldsValueFromId($_job_table, "jb_id", $jb_id,
    array("hq_id", "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_subprice", "csc_id_payer", "csc_id_payer_cash",
      "jb_type", "jb_globaljob", "jb_freetext_1", "jb_payment", "jb_permanent2", "jb_id_copy_permanent",
      "jb_sales_tax_rate", "jb_sales_tax_rate_sign", "jp_permenddat", "jb_cr_filter", "jb_cr_filter_opt",
      "jb_locktime", "jb_lockuser", "jb_status", "cr_id_permanent", "jb_incomplete", "jb_id_parent", "jb_export_time", "jb_freetext_2", "jb_dispoinfo", "jb_warningtime", "jb_offer", "jb_origin", "jb_orderer", "jb_commission_no", "jb_createtime"));
if (isset($no_dates) && $no_dates == "true")
  $jb_orderer = "";
if (isset($_get_tr_commission_no) && $_get_tr_commission_no != true)
  $jb_commission_no = "";
if (MASK_CR_PRICE_MODE == "1") {
  $jb_cr_serviceprice = $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'");
  // 23.01.2024: Wenn Dauerauftragsfortsetzung, dann manuelle TSZ-Sätze ignorieren  (d.h. nur laden, wenn keine Dauerauftragsfortsetzung)
  if (!(isset($check_jb_permanent_flag) && $check_jb_permanent_flag == true && getParameterValue("0", "MASK_CHECK_MARKUP_PERMANENT", $hq_id) == "1")):
    $jb_cr_markup = $db->getOne("SELECT jbprc_price FROM jobprice WHERE jb_id = " . $jb_id . " AND mt_sort = 9");
    $jb_markup = $db->getOne("SELECT jbprc_price FROM jobprice WHERE jb_id = " . $jb_id . " AND mt_sort = 8");
  endif;
}
$jb_km = $db->getOne("SELECT jbprc_price FROM jobprice WHERE jb_id = " . $jb_id . " AND mt_sort = 11 AND (TRIM(jbprc_remark) = 'm' OR TRIM(jbprc_remark) = 'M')");
$jb_price_km = $db->getOne("SELECT jbprc_price FROM jobprice WHERE jb_id = " . $jb_id . " AND mt_sort = 15");
$jb_toll = $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 = $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'");
$jb_bwv = $db->getOne("SELECT gdc_content FROM genericdatacontainer WHERE gdc_obj_type = 'jb' AND gdc_obj_id = " . $jb_id . " AND gdc_gen_fieldname = 'jb_bwv'");
$jb_id_insurance = $db->getOne("SELECT gdc_content FROM genericdatacontainer WHERE gdc_obj_type = 'jb' AND gdc_obj_id = " . $jb_id . " AND gdc_gen_fieldname = 'jb_id_insurance'");
$jb_value_of_goods = "";
$jb_insurance_rate = "0";
$special_case = 0;
if ($jb_id_insurance != "") {
  $jb_id_insurance_gdc_context = explode("|", $db->getOne("SELECT gdc_context FROM genericdatacontainer WHERE gdc_obj_type = 'jb' AND gdc_obj_id = " . $jb_id . " AND gdc_gen_fieldname = 'jb_id_insurance'"));
  $jb_value_of_goods = $jb_id_insurance_gdc_context[0];
  $jb_insurance_rate = $jb_id_insurance_gdc_context[1];
  $special_case = $jb_id_insurance_gdc_context[2];
}
$special_case_ori = $special_case;
$job_is_exported = (trim($jb_export_time) != "" ? true : false);
$self_service_discount = $db->getOne("SELECT jbprc_price FROM jobprice WHERE jb_id = " . $jb_id . " AND mt_sort = 13");
$jb_hiddenFreetext_1 = $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 = $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 = $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_cashpayer_mail_status = $db->getOne("SELECT gdc_context FROM genericdatacontainer WHERE gdc_obj_type = 'jb' AND gdc_obj_id = " . $jb_id . " AND gdc_gen_fieldname = 'jb_cashpayer_mail'");
$jb_job_jam = $db->getOne("SELECT gdc_content FROM genericdatacontainer WHERE gdc_obj_type = 'jb' AND gdc_obj_id = " . $jb_id . " AND gdc_gen_fieldname = 'jb_job_jam'");
$jb_jam_waittime = "";
if (trim($jb_job_jam) != ""):
  if ($jb_reserv == 1):
    $tmpCsIdPayer = getFieldValueFromId("costcenter", "csc_id", $csc_id_payer, "cs_id");
    $jb_jam_waittime = $db->getOne("SELECT cs_jb_jam_waittime_minutes from customer WHERE cs_id = " . $tmpCsIdPayer);
    if ($jb_jam_waittime == 0):
      $jb_jam_waittime = getParameterValue("0", "CS_JB_JAM_WAITTIME_AD_HOC_DEFAULT", "0"); endif;
  else:
    $jb_jam_waittime = (strtotime($jb_job_jam) - strtotime($jb_ordertime)) / 60;
  endif;
endif;

// Wenn Dauerauftrag dann den ersten Vorgänger finden, der nicht temporär geändert worden ist und als Vorlage für einen Fortsetzungsauftrag
// gilt, sollte dieser Auftrag temporär geändert werden
// Dies aber natürlich nur dann, wenn der Auftrag in die Maske geladen wird und nicht dann, wenn gerade ein Dauerauftrag neu eingestellt wird
$jb_id_permanent_pre2 = "";
if (!(isset($check_jb_permanent_flag) && $check_jb_permanent_flag == true)):
  if ($jb_permanent != "0" && $jb_id_copy_permanent == "" && getParameterValue("0", "MASK_ASK_PERMANENT", $hq_id) == "1") {
    $jb_id_permanent_pre2 = $db->getOne("SELECT jb_id FROM job WHERE jb_id_copy_permanent = " . $jb_id);
    if ($jb_id_permanent_pre2 != "") { // es gibt einen Vorgänger; hier schauen, ob der nicht temporär geändert worden war und einen anderen Vorgänger hatte
      $gdc_content = $db->getOne("SELECT gdc_content FROM genericdatacontainer WHERE gdc_obj_type = 'jb' AND gdc_obj_id = " . $jb_id_permanent_pre2 . " AND gdc_gen_fieldname = 'jb_id_permanent_pre'");
      if ($gdc_content != "")
        $jb_id_permanent_pre2 = $gdc_content;
    }
  }
endif;

$today = getdate();
// Prüfen, ob Datensatz gesperrt bzw. neue Sperre setzen
if (!(isset($_copy_jobs_flag) && $_copy_jobs_flag == true) && !(isset($check_jb_permanent_flag) && $check_jb_permanent_flag == true)):
  $job_is_locked = false;
  $job_is_locked_mode = 0;
  $job_is_locked_text = "";
  $locktime = date("Y-m-d H:i:s");
  if ($jb_locktime != "" && $jb_locktime != "0000-00-00 00:00:00" && $jb_lockuser != $usr_id):
//echo "'$jb_lockuser' == '$usr_id'";
    // Datensatz ist gesperrt; überprüfen, ob Sperrzeit bereits abgelaufen
    $jb_locktime_arr = getValsFromDate($jb_locktime);
    $locktime_expired = date("Y-m-d H:i:s",
      mktime((int) $jb_locktime_arr[3], (int) $jb_locktime_arr[4] + (int) MASK_LOCKTIME_TIMEOUT, (int) $jb_locktime_arr[5], (int) $jb_locktime_arr[1], (int) $jb_locktime_arr[2], $jb_locktime_arr[0]));
    if ($locktime <= $locktime_expired):
      // Timeout noch nicht abgelaufen: Datensatz ist gesperrt
      $job_is_locked = true;
      $job_is_locked_text = "";
      $tmpUserNames = getFieldsValueFromId("user", "usr_id", $jb_lockuser, array("usr_firstname","usr_name"));
      $job_is_locked_text = $tmpUserNames[0] . " " . $tmpUserNames[1];
    endif;
  endif;
  if ($job_is_locked != true):
    // Datensatz ist noch nicht gespert, jetzt aber für anderweitige Benutzer sperren
    updateStmt("job", "jb_id", $jb_id, array("jb_locktime", $locktime, "jb_lockuser", $usr_id));
  endif;

  if (!$job_is_locked && $csc_id_payer != CSC_ID_PAYER_CASH && isset($jb_copy) && $jb_copy == "true"):
    $tmpCsIdPayer = getFieldValueFromId("costcenter", "csc_id", $csc_id_payer, "cs_id");
    $tmpCmpIdPayer = getFieldValueFromId("customer", "cs_id", $tmpCsIdPayer, "cmp_id");
    $tmpCmpPayerFields = getFieldsValueFromId("company", "cmp_id", $tmpCmpIdPayer, array("cmp_authenticated","cmp_visible"));
    if ($tmpCmpPayerFields[0] == "0" || $tmpCmpPayerFields[1] == "0") : 
       $job_is_locked = true;
       if ($tmpCmpPayerFields[0] == "0") : $job_is_locked_mode = 1; endif;
       if ($tmpCmpPayerFields[1] == "0") : $job_is_locked_mode = 2; endif;
       if ($tmpCmpPayerFields[0] == "0" && $tmpCmpPayerFields[1] == "0") : $job_is_locked_mode = 3; endif;
    endif;
  $fileHandle = @fopen("../log/get_saved_tour_" . $today['year'] . sprintf("%02d", $today['mon']) . ".log", 'a');
  @fwrite($fileHandle, "[" . date("Y-m-d H:i:s") . "] \$jb_id = " . $jb_id . ", \$csc_id_payer = " . $csc_id_payer . ", \$usr_id = " . $usr_id . ", \$tmpCmpIdPayer = " . $tmpCmpIdPayer . ", \$tmpCmpPayerFields = " . json_encode($tmpCmpPayerFields) . ", \$job_is_locked = " . $job_is_locked . ", \$job_is_locked_mode = " . $job_is_locked_mode . "\n");
  @fclose($fileHandle);

  endif;
endif;

if ($jb_weight == "") $jb_weight = "0";
if ($jb_crvh_length == "") $jb_crvh_length = "0";
if ($jb_crvh_width == "") $jb_crvh_width = "0";
if ($jb_crvh_height == "") $jb_crvh_height = "0";
if ($jb_crvh_position == "") $jb_crvh_position = "0";
//if ($jb_payment == 0) $jb_payment = "";
if ($jb_fixprice == 0) $jb_fixprice = "";
//if ($jb_markup == 0) $jb_markup = "";
if ($jb_serviceprice == 0) $jb_serviceprice = "";
if ($jb_cr_price == 0) $jb_cr_price = "";
if ($jb_fixprice != 0 && $jb_fixprice != "")
  $jb_fixprice = str_replace(".", ",", sprintf("%01.2f", $jb_fixprice));
if (isset($jb_markup) && $jb_markup != 0 && $jb_markup != "")
  $jb_markup = str_replace(".", ",", sprintf("%01.2f", $jb_markup));
if ($jb_toll != "")
  $jb_toll = str_replace(".", ",", sprintf("%01.2f", $jb_toll));
if ($jb_serviceprice != 0 && $jb_serviceprice != "")
  $jb_serviceprice = str_replace(".", ",", sprintf("%01.2f", $jb_serviceprice));
if ($jb_cr_price != 0 && $jb_cr_price != "")
  $jb_cr_price = str_replace(".", ",", sprintf("%01.2f", $jb_cr_price));
if (MASK_CR_PRICE_MODE == "1") {
  if ($jb_cr_serviceprice != "")
    $jb_cr_serviceprice = str_replace(".", ",", sprintf("%01.2f", $jb_cr_serviceprice));
  if (isset($jb_cr_markup) && $jb_cr_markup != "") {
    $jb_cr_markup = str_replace(".", ",", sprintf("%01.2f", $jb_cr_markup));
//  } else {
//    $jb_cr_markup = $jb_markup;
  }
}
if ($jb_km != "")
  $jb_km = str_replace(".", ",", sprintf("%01.3f", $jb_km));
while (substr($jb_km, -1) == "0")
  $jb_km = substr($jb_km, 0, -1);
if (substr($jb_km, -1) == ",")
  $jb_km = substr($jb_km, 0, -1);

if (isset($csc_id_order))
  if ($csc_id_order == 0)
    $csc_id_order = "";
if ($jb_waittime != "")
  list($jb_waittime_jahr, $jb_waittime_monat, $jb_waittime_tag,
    $jb_waittime_hour, $jb_waittime_minute) = getValsFromDate($jb_waittime);
else
  $jahr = $monat = $tag = $stunde = $minute = "";

$was_afterwards = job_was_afterwards($jb_id);
if ((!isset($no_dates) || $no_dates != "true") && ($jb_reserv == 1 || $jb_permanent != 0 || $was_afterwards)):
  list($jahr, $monat, $tag, $stunde, $minute) = getValsFromDate($jb_ordertime);
  list($endejahr, $endemonat, $endetag, $dummy1, $dummy2) = getValsFromDate($jp_permenddat);
else:
  $jahr = $monat = $tag = $stunde = $minute = "";
  $endejahr = $endemonat = $endetag = "";
  $jb_id_permanent_pre2 = ""; // temporäre Änderungen in Tour-Konserven ergeben beim Aufruf der Konserve keinen Sinn mehr (siehe Mail aus Dresden am 16.02.2023)
endif;
if ($jb_warningtime != "0000-00-00 00:00:00" && $jb_warningtime != ""):
  list($jb_warnjahr, $jb_warnmonat, $jb_warntag, $jb_warnstunde, $jb_warnminute) = getValsFromDate($jb_warningtime);  
else:
  $jb_warnjahr = $jb_warnmonat = $jb_warntag = $jb_warnstunde = $jb_warnminute = "";
endif;

// Unteraufträge holen
list ($tmp_add_jb_ids, $tmp_add_sids, $tmp_add_prices) = getJobChildren($jb_id, $dbh_jb, (isset($no_dates) ? $no_dates : false));
$delete_suborder = false;
if ($tmp_add_jb_ids != "" AND $db->getOne("SELECT job.jb_id" .
  " FROM costcenter, customer, job" .
  " WHERE jb_id = " . $jb_id .
  " AND job.csc_id_payer = costcenter.csc_id AND costcenter.cs_id = customer.cs_id AND cs_eid IN (" . getParameterValue("0", "JB_CR_PRICE_MINIMUM", "0") . ")" .
  " AND csc_name = '- Ad hoc Pkw bis XL-Bus'" .
  " AND jb_finishtime > '2020-08-10' AND jb_status = 2" .
  " AND jb_storno IS NULL" .
  " AND jb_export_time IS NULL") == $jb_id)
  $delete_suborder = true;

// Sondervereinbarungen holen
list ($tmp_add_srvs, $tmp_add_srvts, $tmp_add_mult, $tmp_add_mult_price) = explode(chr(0xB2), $jb_freetext_2); //chr(0xB2) = "²"; "²" führt zu Problemen, wenn da eine ungewollte Konvertierung zwischenkommt

// Zoneneinträge holen
$km_price_params = "";
$sqlquery = "SELECT trs_srv_name FROM tourservice WHERE trs_srvt_name = 'z' AND jb_id = " . $jb_id;
$res = $db->query($sqlquery);
if (DB::isError($res)) reportDie ("$PHP_SELF: '$sqlquery': " . $res->getMessage());
while ($row = ($phpVersion >= "8.0" ? $res->fetch_assoc() : $res->fetchRow())):
  $km_price_params .= ($km_price_params != "" ? " + " : "") . $row['trs_srv_name'];
endwhile;
$res->free();

// Km-Preis Parameter holen
$javascript_zone = "";
if ($km_price_params != "") {
//  $tr_mediationarea_names = "";
//  $sqlquery = "SELECT tr_mediationarea_name FROM tour WHERE jb_id = " . $jb_id;
//  $res = $db->query($sqlquery);
//  if (DB::isError($res)) reportDie ("$PHP_SELF: '$sqlquery': " . $res->getMessage());
//  while ($row = ($phpVersion >= "8.0" ? $res->fetch_assoc() : $res->fetchRow())):
//    $tr_mediationarea_names .= ($tr_mediationarea_names != "" ? "," : "") . $row['tr_mediationarea_name'];
//  endwhile;
//  $res->free();
  $minimum_price_name = $db->getOne("SELECT trs_srvt_name FROM tourservice WHERE trs_srv_name = 'Fixpreis' AND trs_srvt_name LIKE '[M] Mindestpreis%' AND jb_id = " . $jb_id);
//  $km_price_params = "|" . $km_price_params . "||zone|" . $tr_mediationarea_names . "|" . ($minimum_price_name != "" ? $minimum_price_name : "");
  $km_price_params = $jb_price_km . "|" . $km_price_params . "||zone||" . ($minimum_price_name != "" ? $minimum_price_name : "");
  $javascript_zone = "opener.parent.job_options.fixprice_was_zone = true;\n";
  if (isset($no_dates) && $no_dates == "true") {
    $jb_fixprice = "";
    $jb_cr_price = "";
  }
} else {
  $km_price_params = $db->getOne("SELECT trs_srvt_name FROM tourservice WHERE trs_srv_name = 'Fixpreis' AND jb_id = " . $jb_id);
}

//$cr_sid = "";
//if ($cr_id_order != "")
//  $cr_sid = $db->getOne(
//    "SELECT crvh_sid FROM courier_vehicle WHERE cr_id = '$cr_id_order'");
////    "SELECT crvh_sid FROM courier_vehicle WHERE cr_id = '$cr_id_order' AND hq_id = '$hq_id'");
if (isset($emp_id) && getParameterValue($emp_id, "MODE_COPY_JOB") == "1" && $cr_sid != "0")
  $cr_sid_none = $cr_sid;

// Javascript-Funktionen im temporären Fenster ändern die Werte im Eingabeformular
// Job-Tour Frame
$jb_sales_tax_rate_sign = $db->getOne("SELECT tx_id FROM tax WHERE tx_sign = '$jb_sales_tax_rate_sign'");
$jb_sales_tax_rate = "voll";
if ($jb_sales_tax_rate_sign == "0")
  $jb_sales_tax_rate = "ohne";

$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 ($jb_cr_filter == $mandatory_filtersArr[$i])
      $jb_cr_filter = "";
    $jb_cr_filter = str_replace("," . $mandatory_filtersArr[$i] . ",", ",", $jb_cr_filter);
    $jb_cr_filter = str_replace($mandatory_filtersArr[$i] . ",", "", $jb_cr_filter);
    $jb_cr_filter = str_replace("," . $mandatory_filtersArr[$i], "", $jb_cr_filter);
  endfor;
endif;
//echo $jb_cr_filter . "<br>\n"; die();

$javascript = "opener.parent.job_options.bwv_alert = false;\n" . setJavascriptOpenerFormVals("job_options", "tourOptions",
  array("cr_id_order" => (isset($cr_sid_none) && $cr_sid_none == "none" ? "" : $cr_sid), "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, "savedTour" => "", "jb_fixprice" => $jb_fixprice, "jb_markup" => (isset($jb_markup) ? $jb_markup : ""), "jb_cr_markup" => (isset($jb_cr_markup) ? $jb_cr_markup : ""), "jb_toll" => $jb_toll,
    "jb_id_insurance" => $jb_id_insurance, "jb_serviceprice" => $jb_serviceprice, "jb_cr_price" => $jb_cr_price,
    "jb_tourname_hidden" => my_str_check(getFieldValueFromId($_job_table, "jb_id", $jb_id, "jb_tourname")),
    "jb_freetext_1" => my_str_check($jb_freetext_1), "jb_hiddenFreetext_1" => my_str_check($jb_hiddenFreetext_1), "jb_cr_filter" => $jb_cr_filter,
    "jb_dispoinfo" => my_str_check($jb_dispoinfo),
    "jb_warnjahr" => $jb_warnjahr, "jb_warnmonat" => $jb_warnmonat, "jb_warntag" => $jb_warntag, "jb_warnstunde" => $jb_warnstunde,
    "jb_warnminute" => $jb_warnminute,
    "jb_cr_filter_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,
    "dont_change_tx" => "true",
    "jb_id_parent" => $jb_id_parent, "jb_type" => $jb_type,
    "tmp_add_jb_ids" => $tmp_add_jb_ids, "tmp_add_sids" => $tmp_add_sids, "tmp_add_prices" => $tmp_add_prices,
    "tmp_add_srvs" => my_str_check($tmp_add_srvs), "tmp_add_srvts" => my_str_check($tmp_add_srvts), "tmp_add_mult" => $tmp_add_mult, "tmp_add_mult_price" => $tmp_add_mult_price,
    "km_price_params" => $km_price_params, "jb_id_permanent_pre" => $jb_id_permanent_pre2, "jb_km" => $jb_km, "self_service_discount" => $self_service_discount
  )
);

if (MASK_CR_PRICE_MODE == "1") {
  $javascript .= setJavascriptOpenerFormVals("job_options", "tourOptions", array("jb_cr_serviceprice" => $jb_cr_serviceprice));
}

$javascript .=
  "opener.checkJb_permanent(0);\n" .
  "opener.setDateTimeFields(\"job_options\", \"tourOptions\", \"$tag\", \"$monat\", \"$jahr\", \"$stunde\", \"$minute\", \"tag\", \"monat\", \"jahr\", \"stunde\", \"minute\", \"jb_permanent\");\n" .
  "opener.setDateTimeFields(\"job_options\", \"tourOptions\", \"$endetag\", \"$endemonat\", \"$endejahr\", \"\", \"\", \"endetag\", \"endemonat\", \"endejahr\", \"\", \"\", \"\");\n" .
//  "opener.setDateTimeFields(\"job_options\", \"tourOptions\", \"$warntag\", \"$warnmonat\", \"$warnjahr\", \"\", \"\", \"warntag\", \"warnmonat\", \"warnjahr\", \"\", \"\", \"\");\n" .
  "if (typeof(opener.parent.job_options.document.tourOptions.endetag) != 'undefined')\n" .
  "  opener.setDateTimeFields(\"job_options\", \"tourOptions\", \"$endetag\", \"$endemonat\", \"$endejahr\", \"\", \"\", \"endetag\", \"endemonat\", \"endejahr\", \"\", \"\", \"\");\n" .
  "if(typeof(opener.parent.job_tour.document.tourForm.jb_freetextButton) != 'undefined') {" .
  "  if (\"" . my_str_check($jb_freetext_1) . "\" == \"\")\n" .
  "    opener.parent.job_tour.document.tourForm.jb_freetextButton.value = \"Text\";\n" .
  "  else\n" .
  "    opener.parent.job_tour.document.tourForm.jb_freetextButton.value = \"Text*\"\n;" .
  "}" .
  "  if (\"" . my_str_check($jb_hiddenFreetext_1) . "\" == \"\") {\n" .
  "    opener.parent.job_tour.document.tourForm.jb_hiddenFreetextButton.value = \"Text nur Rg\";\n" .
  "  } else {\n" .
  "    opener.parent.job_tour.document.tourForm.jb_hiddenFreetextButton.value = \"Text nur Rg*\"}\n;" .
  "  if (\"" . my_str_check($jb_dispoinfo) . "\" == \"\" && (\"" . $jb_warningtime. "\" == \"0000-00-00 00:00:00\" || \"" . $jb_warningtime . "\" == \"\")) {\n" .
  "    opener.parent.job_tour.document.tourForm.jb_dispoInfoButton.value = \"Dispo Info\";\n" .
  "  } else {\n" .
  "    opener.parent.job_tour.document.tourForm.jb_dispoInfoButton.value = \"Dispo Info*\"};\n" .
  "  if (typeof(opener.parent.job_tour.document.tourForm.jb_cashpayer_mail) != 'undefined') {\n" .
  "    opener.parent.job_tour.document.tourForm.jb_cashpayer_mail.value = \"" . $jb_cashpayer_mail . "\";}\n" .
  "  if (typeof(opener.parent.job_tour.document.tourForm.jb_offer_mail) != 'undefined') {\n" .
  "    opener.parent.job_tour.document.tourForm.jb_offer_mail.value = \"" . $jb_offer_mail . "\";}\n" .
  "  if (typeof(opener.parent.job_tour.document.tourForm.jb_orderer) != 'undefined') {\n" .
  "    opener.parent.job_tour.document.tourForm.jb_orderer.value = \"" . $jb_orderer . "\";}\n" .
  "  opener.parent.job_options.jb_orderer_mandatory = " . ((isset($no_dates) && $no_dates == "true") || strtotime($jb_createtime) > strtotime("2025-09-16 18:39:00") ? "true" : "false") . ";\n" .
//"alert(\"$jb_cashpayer_mail\");\n";
$javascript .= setJavascriptOpenerFormVals("job_options", "tourOptions",
  array(
    "jb_orderer_hidden" => $jb_orderer
  )
);

if ($jb_cashpayer_mail_status == "MAIL_SENT" || $jb_cashpayer_mail_status == "MAIL_NOT_SENT")
  $javascript .=
    "  opener.parent.job_tour.document.tourForm.jb_cashpayer_mail.disabled = true;\n";
else
  $javascript .= setJavascriptOpenerFormVals("job_options", "tourOptions",
    array(
      "jb_cashpayer_mail_hidden" => $jb_cashpayer_mail
    )
  );
if ($jb_cashpayer_mail_status == "MAIL_NOT_SENT")
  $javascript .=
    "  opener.parent.job_tour.document.tourForm.jb_cashpayer_mail.style.backgroundColor = '#FF2222';\n";

$javascript .= setJavascriptOpenerFormVals("job_options", "tourOptions",
  array(
    "jb_offer_mail_hidden" => $jb_offer_mail
  )
);

if (MASK_WAITTIME_ENABLED == "1"):
  $javascript .= setJavascriptOpenerFormVals("job_options", "tourOptions",
    array(
      "jb_waittime_hour" => $jb_waittime_hour, "jb_waittime_minute" => $jb_waittime_minute
   )
 );
endif;

if ($jb_origin != 0) {
  $jb_origin_pos = array(1 => 0, 2 => 2, 3 => 4, 4 => 6, 5 => 1, 6 => 7, 7 => 3, 8 => 5);

  $javascript .=
    "  opener.parent.job_tour.document.tourForm.jb_origin[". ($jb_origin_pos[$jb_origin]) ."].checked = true;\n";
  if ($jb_origin == 3 || $jb_origin == 4 || $jb_origin == 5 || $jb_origin == 7 || $jb_origin == 8) {
    $javascript .=
      "  opener.parent.job_tour.document.tourForm.jb_origin[" . $jb_origin_pos[1] . "].disabled = true;\n" .
      "  opener.parent.job_tour.document.tourForm.jb_origin[" . $jb_origin_pos[2] . "].disabled = true;\n" .
      "  opener.parent.job_tour.document.tourForm.jb_origin[" . $jb_origin_pos[6] . "].disabled = true;\n";
  }
  if ($jb_origin_other != "")
    $javascript .=
      "  opener.parent.job_tour.document.tourForm.jb_origin_other.value = '" . $jb_origin_other . "';\n";
  $javascript .=
    "opener.checkOrigin();\n";
}
if ($jb_bwv == "1") {
  $javascript .=
    "  opener.parent.job_options.document.tourOptions.jb_bwv.checked = true;\n";
}

// Job-Options Frame initialisieren
$javascript .=
  setJavascriptOpenerDisabled("job_options", "tourOptions", "jb_tourname_overwrite",
    ((trim(getFieldValueFromId($_job_table, "jb_id", $jb_id, "jb_tourname")) != "") ? "false" : "true")) .
  setJavascriptOpenerChecked("job_options", "tourOptions", "jb_waitstorno",
    (($jb_waitstorno != "1") ? "false" : "true")) .
  setJavascriptOpenerDisabled("job_options", "tourOptions", "jb_permanent",
    (($jb_reserv == 1 || $jb_permanent != "") ? "false" : "true")) .
  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")) .
//  setJavascriptOpenerChecked("job_options", "tourOptions", "jb_type",
//    (($jb_type != "1") ? "false" : "true")) .
  setJavascriptOpenerChecked("job_options", "tourOptions", "jb_globaljob",
    (($jb_globaljob != "1") ? "false" : "true")) .
  "if (opener.parent.job_options.document.tourOptions.jb_globaljob.disabled == true)\n" .
  "  opener.parent.job_options.document.tourOptions.jb_globaljob.checked = false;\n" .
  "opener.checkJb_permanent2();\n" .
  "opener.initJobList();\n" .
  "opener.checkCr_id_order();\n" .
  "opener.checkFixprice(2);\n" .
  (isset($no_dates) && $no_dates == "true" ? "opener.checkJb_sales_tax_rate_sign(0);\n" : "");

$i = 1;
$payer_found = false;
$jobList = "";
$cur_tr_statuses = "";
do {
  // gespeicherte Tour-Daten holen
  if (existsEntry($_tour_table, array("jb_id", $jb_id, "tr_sort", $i))):
    $tourFound = 1;
    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, $dbh_tr);

    // 17.02.2026: Bei Konserven und Daueraufträgen soll die erste Ko.-Nr. als $jb_commission_no übernommen werden wenn vorhanden und letztere leer
    if (((isset($no_dates) && $no_dates == "true") || $_get_tr_commission_no == true) && $jb_commission_no == "" && my_str_check($tr_commission_no) != "" && $i == 1)
      $jb_commission_no = my_str_check($tr_commission_no);
    $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')");
    $arr_tour = $db->getOne("SELECT gdc_content FROM genericdatacontainer WHERE gdc_obj_type = 'tr' AND gdc_gen_fieldname = 'arr_tour' AND gdc_obj_id = " . $tr_id);
//    $cur_tr_statuses .= ",[" . $tr_id . "," . $tr_status . "]\n";
    $cur_tr_statuses .= ",[" . $tr_id . "," . (trim($arr_tour) != "" ? 1 : 0) . "]\n";
    $tr_tracking = "";
    $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);
    if ($gdc_content != "") {
      $gdc_content_arr = explode("|", $gdc_content);
      $tr_tracking = $gdc_content_arr[0];
	}
    $is_payer = (($csc_id_payer == $csc_id && $csc_id_payer != CSC_ID_PAYER_CASH) || ($csc_id_payer_cash == $csc_id && $jb_payment == 2)) ? "true" : "false";
    if (MASK_CR_PRICE_MODE == "1" && $is_payer == "true" && $csc_id_payer == CSC_ID_PAYER_CASH)
      $is_payer = !(strpos($tr_remark, "*** Bitte im Auftrag STADTBOTE Bar ") === FALSE) ? "true" : "false";
//    if ($is_payer == "true"): die(strpos($tr_remark, "*** Bitte im Auftrag STADTBOTE Bar ") . ", tr_sort=" . $i . ", \$csc_id_payer=" . $csc_id_payer . ", \$csc_id=" . $csc_id . ", \$csc_id_payer_cash=" . $csc_id_payer_cash . ", CSC_ID_PAYER_CASH=" . CSC_ID_PAYER_CASH); endif;
//$javascript .= 
//"alert($i + \",\" + '$is_payer' + \",\" + $csc_id + \",\" + $csc_id_payer + \",\" + $csc_id_payer_cash);";
    if (!(strpos($tr_remark, "~~~\\n") === false)):
$fileHandle = @fopen("../log/get_saved_tour_" . $today['year'] . sprintf("%02d", $today['mon']) . ".log", 'a');
@fwrite($fileHandle, "[" . date("Y-m-d H:i:s") . "] [\$tr_remark = " . $tr_remark . "] . \n");
      $filters_text = strstr($tr_remark, "~~~\\n");
@fwrite($fileHandle, "[" . date("Y-m-d H:i:s") . "] [\$filters_text = " . $filters_text . "] . \n");
      $filters_text = substr($filters_text, 0, strpos($filters_text, "~~~\\n", 5) + strlen("~~~\\n"));
@fwrite($fileHandle, "[" . date("Y-m-d H:i:s") . "] [\$filters_text = " . $filters_text . "] . \n");
      if ($filters_text == "~~~\\n") {
        $filters_text = strstr($tr_remark, "~~~\\n");
@fwrite($fileHandle, "[" . date("Y-m-d H:i:s") . "] [\$filters_text = " . $filters_text . "] . \n");
        $filters_text = substr($filters_text, 0, strpos($filters_text, "~~~", 3) + strlen("~~~"));
@fwrite($fileHandle, "[" . date("Y-m-d H:i:s") . "] [\$filters_text = " . $filters_text . "] . \n");
      }
      $tr_remark = str_replace($filters_text, "", $tr_remark);
@fwrite($fileHandle, "[" . date("Y-m-d H:i:s") . "] [\$tr_remark = " . $tr_remark . "] . \n");
@fclose($fileHandle);
    endif;
    $javascript .= setJavascriptOpenerJobList($i - 1,
      array(JL_CSC_ID => $csc_id, JL_TR_COMP => $tr_comp, JL_TR_PERSON => $tr_person,
        JL_AD_STREET => $ad_street, JL_TR_HSNO => $tr_hsno, JL_AD_COUNTRY => $ad_country, JL_AD_ZIPCODE => $ad_zipcode,
        JL_AD_CITY => $ad_city, JL_TR_REMARK => $tr_remark, JL_CSC_ID_PAYER => $is_payer,
        JL_TR_COMMISSION_NO => my_str_check($tr_commission_no),
        JL_TR_TRACKING => my_str_check($tr_tracking),
        JL_TR_MEDIATIONAREA_ID => $tr_mediationarea_id,
        JL_TR_WARE_TO => ($tr_ware_from_to == 1 || $tr_ware_from_to == 3 ? "true" : "false"),
        JL_TR_WARE_FROM => ($tr_ware_from_to == 2 || $tr_ware_from_to == 3 ? "true" : "false"),
        JL_TR_PHOTO => ($tr_photo != "" ? "true" : "false")));
    if (!isset($no_dates) || $no_dates != "true"):
      $javascript .= setJavascriptOpenerJobList($i - 1, array(JL_TR_ID => $tr_id));
    endif;
    if ($is_payer == "true"): $payer_found = true; endif;
    // wenn von "check_jb_permanent.php" aufgerufen, muss joblist-Array aufgebaut werden
    if (isset($check_jb_permanent_flag) && $check_jb_permanent_flag == true):
      setJobList($i, JL_CSC_ID, $csc_id);
      setJobList($i, JL_TR_COMP, $tr_comp);
      setJobList($i, JL_TR_PERSON, $tr_person);
      setJobList($i, JL_AD_STREET, $ad_street);
      setJobList($i, JL_TR_HSNO, $tr_hsno);
      setJobList($i, JL_AD_COUNTRY, $ad_country);
      setJobList($i, JL_AD_ZIPCODE, $ad_zipcode);
      setJobList($i, JL_AD_CITY, $ad_city);
      setJobList($i, JL_TR_REMARK, $tr_remark);
      setJobList($i, JL_TR_PHOTO, ($tr_photo != "" ? "true" : "false"));
//echo "tr_commission_no: " . "'$_tr_commission_no'" . "<br>";
      if ($_get_tr_commission_no == true):
        setJobList($i, JL_TR_COMMISSION_NO, my_str_check($tr_commission_no));
      else:
        setJobList($i, JL_TR_COMMISSION_NO, "");
      endif;
      setJobList($i, JL_TR_TRACKING, my_str_check($tr_tracking));
      setJobList($i, JL_HIDE_TR_REMARK, "true");
      setJobList($i, JL_TR_WARE_FROM, ($tr_ware_from_to == 2 || $tr_ware_from_to == 3 ? "true" : "false"));
      setJobList($i, JL_TR_WARE_TO, ($tr_ware_from_to == 1 || $tr_ware_from_to == 3 ? "true" : "false"));
      setJobList($i, JL_CSC_ID_PAYER, $is_payer);
      if (defined('JL_MEDIATIONAREA_ID'))
        setJobList($i, JL_MEDIATIONAREA_ID, $tr_mediationarea_id);
      if ($jb_payment == 0):
        $jb_costsplit = "false";
        $jb_cash = "false";
      endif;
      if ($jb_payment == 1):
        $jb_costsplit = "true";
        $jb_cash = "false";
      endif;
      if ($jb_payment == 2):
        $jb_costsplit = "false";
        $jb_cash = "true";
      endif;
      if ($javascript_zone != ""):
        $jb_fixprice = 0;
        $jb_cr_price = 0;
      endif;
    else:
      $javascript .= javascriptAdd_cs_eid($csc_id, "opener.");
    endif;
  else:
    $tourFound = 0;
  endif;
  $i++;
} while ($tourFound == 1);
if (isset($check_jb_permanent_flag) && $check_jb_permanent_flag == true):
  $fileHandle = @fopen("../log/get_saved_tour_" . $today['year'] . sprintf("%02d", $today['mon']) . ".log", 'a');
  @fwrite($fileHandle, "JL_CSC_ID="                   . JL_CSC_ID . "\n");
  @fwrite($fileHandle, "JL_TR_COMP="                  . JL_TR_COMP . "\n");
  @fwrite($fileHandle, "JL_TR_PERSON="                . JL_TR_PERSON . "\n");
  @fwrite($fileHandle, "JL_AD_STREET="                . JL_AD_STREET . "\n");
  @fwrite($fileHandle, "JL_TR_HSNO="                  . JL_TR_HSNO . "\n");
  @fwrite($fileHandle, "JL_AD_COUNTRY="               . JL_AD_COUNTRY . "\n");
  @fwrite($fileHandle, "JL_AD_ZIPCODE="               . JL_AD_ZIPCODE . "\n");
  @fwrite($fileHandle, "JL_AD_CITY="                  . JL_AD_CITY . "\n");
  @fwrite($fileHandle, "JL_TR_REMARK="                . JL_TR_REMARK . "\n");
  @fwrite($fileHandle, "JL_TR_PHOTO="                 . JL_TR_PHOTO . "\n");
  @fwrite($fileHandle, "JL_TR_COMMISSION_NO="         . JL_TR_COMMISSION_NO . "\n");
  @fwrite($fileHandle, "JL_HIDE_TR_REMARK="           . JL_HIDE_TR_REMARK . "\n");
  @fwrite($fileHandle, "JL_TR_WARE_FROM="             . JL_TR_WARE_FROM . "\n");
  @fwrite($fileHandle, "JL_TR_WARE_TO="               . JL_TR_WARE_TO . "\n");
  @fwrite($fileHandle, "JL_CSC_ID_PAYER="             . JL_CSC_ID_PAYER . "\n");
  @fwrite($fileHandle, "JL_TR_MEDIATIONAREA_ID="      . JL_TR_MEDIATIONAREA_ID . "\n");
  @fwrite($fileHandle, "JL_TR_ID="                    . JL_TR_ID . "\n");
  @fwrite($fileHandle, "[" . date("Y-m-d H:i:s") . "] \$jb_id = " . $jb_id . ", \$jobList = " . $jobList . "\n");
  @fclose($fileHandle);
endif;
$javascript .= 
  "if (typeof(opener.parent.job_tour.document.tourForm.jb_commission_no) != 'undefined') {\n" .
  "  opener.parent.job_tour.document.tourForm.jb_commission_no.value = \"" . $jb_commission_no . "\";\n" .
  "  opener.check_jb_commission_no();\n" . 
  "}\n";
setJavascriptOpenerFormVals("job_options", "tourOptions",
  array(
    "jb_commission_no_hidden" => $jb_commission_no
  )
);

// möglichen Kostensplit beachten
/* für Zentrale Hansetrans: Barzahlung */
if ($jb_payment == 1 || ($jb_payment == 0 && MASK_CASH_PAYER_SELECT == "1"))
  $javascript .=
    "opener.parent.job_tour.document.tourForm.jb_costsplit.checked = true;\n" .
    "opener.checkCostsplit();\n";
// Kostenteilung, Barzahlungsarie berücksichtigen

$comp_payer = "";
if ($csc_id_payer != -1 && $csc_id_payer != 0 && (CSC_ID_PAYER_CASH != "" && $csc_id_payer != CSC_ID_PAYER_CASH)):
  // wenn der Payer nicht in der Joblist gefunden wurde und
  // csc_id_payer weder Kostenteilung noch Barzahlung enthält
  // dann ist der Zahler in csc_id_payer der Drittzahler!!!
  // Da muss nun auch noch ein Name gefunden werden.
  if (!$payer_found):
    $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_payer'");
    $comp_payer = my_str_check_js($comp_payer);
    $javascript .=
      "opener.setCsc_id_payer('$csc_id_payer', '$comp_payer');\n";
    $javascript .= javascriptAdd_cs_eid($csc_id_payer, "opener.");
  endif;
endif;

$javascript .=
  "opener.jobList_ori = opener.parent.job_options.document.tourOptions.jobList.value;\n" .
  "opener.jb_fixprice_ori = opener.parent.job_options.document.tourOptions.jb_fixprice.value;\n" .
  "opener.jb_serviceprice_ori = opener.parent.job_options.document.tourOptions.jb_serviceprice.value;\n" .
  "opener.jb_markup_ori = opener.parent.job_options.document.tourOptions.jb_markup.value;\n" .
  "opener.jb_ordertime_ori = '$jahr-$monat-$tag $stunde:$minute';\n" .
  "opener.curCsc_id_payer_ori = " . $csc_id_payer . ";\n" .
  "opener.cur_tr_statuses = [" . substr($cur_tr_statuses, 1) . "];\n";
// Statusmail bei Auftragsänderung?
$mail_recipients = "";
// if (!(isset($_copy_jobs_flag) && $_copy_jobs_flag == true) && $no_dates != "true" && $jb_status == 2 && !($db->getOne("SELECT jb_storno FROM job WHERE jb_id = " . $jb_id) > 0)):
// if (!(isset($_copy_jobs_flag) && $_copy_jobs_flag == true) && $no_dates != "true" && ($jb_status == 2 || $jb_status == 1) && !($db->getOne("SELECT jb_storno FROM job WHERE jb_id = " . $jb_id) > 0)):
if (!(isset($_copy_jobs_flag) && $_copy_jobs_flag == true) && $no_dates != "true" && !($db->getOne("SELECT jb_storno FROM job WHERE jb_id = " . $jb_id) > 0)):
//  $cs_id = getFieldValueFromId("costcenter", "csc_id", ($csc_id_payer == CSC_ID_PAYER_CASH ? $csc_id_payer_cash : $csc_id_payer), "cs_id");
//  $cs_jbstatusmail_fields = getFieldValueFromId("customer", "cs_id", $cs_id, "cs_jbstatusmail_fields");
//
//  $empIdActCC24State = false; 
//  $empHqList = getParameterValue("0", "HEADQUARTERS_MULTIPLE_ACCESS_EMPLOYEES", "0") . "|300001";
//  if ($empHqList != "") {
//    $empIdActCC24State = isInParameterString($emp_id, $empHqList);
//  }
//
//  if ((substr($cs_jbstatusmail_fields, 3, 1) == "1" && (getParameterValue("0", "MASK_IGNORE_JBSTATUSMAIL2CSC", $hq_id) == "0" || $empIdActCC24State)) ||
//    (getParameterValue("0", "MASK_IGNORE_JBSTATUSMAIL2CSC", $hq_id) != "0" && (getParameterValue($emp_id, "MODE_LATER_JOB") != "0" || $vht_id >= 7 /* Immer Status-Mails bei LKWs */ || getParameterValue("0", "MASK_IGNORE_JBSTATUSMAIL2CSC", $hq_id) == "2"))):
//    $sqlquery = "SELECT usr.usr_email, cs.cs_jbstatusmail, cscad.cscad_email"
//              . " FROM costcenter AS csc, customer AS cs, costcenteraddress AS cscad, employee AS emp, user AS usr"
//              . " WHERE csc.csc_id = " . ($csc_id_payer == CSC_ID_PAYER_CASH ? $csc_id_payer_cash : $csc_id_payer) . " AND"
//              . "       csc.cs_id = cs.cs_id                                   AND"
//              . "       cs.cs_admin = emp.emp_id                               AND"
//              . "       emp.usr_id = usr.usr_id                                AND"
//              . "       csc.csc_id = cscad.csc_id                              AND"
//              . "       cscad.adt_id = '2'";
//  //echo $sqlquery . "<br>\n";
//    $fileHandle = @fopen("../log/get_saved_tour_" . $today['year'] . sprintf("%02d", $today['mon']) . ".log", 'a');
//    @fwrite($fileHandle, "[" . date("Y-m-d H:i:s") . "] \$jb_id = $jb_id [" . $sqlquery . "] . \n");
//    @fclose($fileHandle);
//    $result = $db->query($sqlquery);
//    if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
//     while ($row = ($phpVersion >= "8.0" ? $result->fetch_assoc() : $result->fetchRow())):
//      $ask_for_statusmail =
//        (getParameterValue("0", "MASK_IGNORE_JBSTATUSMAIL2CSC", $hq_id) == "0" || $empIdActCC24State) ||
//        ((getParameterValue("0", "MASK_IGNORE_JBSTATUSMAIL2CSC", $hq_id) != "0" && (getParameterValue($emp_id, "MODE_LATER_JOB") == "1" || $vht_id >= 7 || getParameterValue("0", "MASK_IGNORE_JBSTATUSMAIL2CSC", $hq_id) == "2"))
//          && ($row["cs_jbstatusmail"] == "1" || (substr($cs_jbstatusmail_fields, 3, 1) == "1"))
//        );
//      if (trim($row["usr_email"]) != "" && $ask_for_statusmail)
//        $mail_recipients = trim($row["usr_email"]);
//      if (trim($row["cscad_email"]) != "" && $ask_for_statusmail)
//        $mail_recipients = trim($row["cscad_email"]);
//    endwhile;
//    $result->free();
//  //  $javascript .= "opener.ask_mailrecipients = '" . $mail_recipients . "';\n";
//    $javascript .= setJavascriptOpenerFormVals("job_options", "tourOptions", array("ask_mailrecipients" => $mail_recipients));

// Ist in ajaxReqJobs ausgelagert worden, deshalb hier eine "1"
    $javascript .= setJavascriptOpenerFormVals("job_options", "tourOptions", array("ask_mailrecipients" => "1"));

//  //die($mail_recipients);
//    $fileHandle = @fopen("../log/get_saved_tour_" . $today['year'] . sprintf("%02d", $today['mon']) . ".log", 'a');
//    @fwrite($fileHandle, "[" . date("Y-m-d H:i:s") . "] [" . $mail_recipients . "] \n");
//    @fclose($fileHandle);
//  endif;
endif;

// 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 < opener.parent.job_options.cfl.length; i++)\n" .
  "  opener.parent.job_options.cfl[i][3] = 0;\n" .
  "var filterStr = \"Filter\";";
// Alle Kurierfilter neu setzen
for ($i = 0; $i <= count($jb_cr_filter_list); $i++)
{
  if (isset($jb_cr_filter_list[$i]))
    $javascript .=
      "for (var i = 0; i < opener.parent.job_options.cfl.length; i++)\n" .
      "{\n" .
      "  if (opener.parent.job_options.cfl[i][0] == \"" . trim($jb_cr_filter_list[$i]) . "\")\n" .
      "  {\n" .
      "    opener.parent.job_options.cfl[i][3] = 1;\n" .
      "    filterStr = \"Filter*\";" .
      "    break;\n" .
      "  }\n" .
      "}\n";
}

$javascript .=
"if (typeof(opener.parent.job_options.document.tourOptions.jb_cr_filterButton) != 'undefined')\n {" .  
  "opener.parent.job_options.document.tourOptions.jb_cr_filterButton.value = filterStr;\n" .
"}";

// Wenn Barzahlung, dann Checkbox ankreuzen
if ($jb_payment == 2)
  $javascript .=
   "opener.parent.job_tour.document.tourForm.jb_cash.checked = true;\n" .
   "opener.checkCash();\n";
else
  $javascript .=
   "opener.parent.job_tour.document.tourForm.jb_cash.checked = false;\n" .
   "opener.checkCash();\n";

$waittimefiels = "";
if (MASK_WAITTIME_ENABLED == "1"):
  $waittimefiels =
    "opener.parent.job_options.document.tourOptions.jb_waittime_hour.disabled = false;\n" .
    "opener.parent.job_options.document.tourOptions.jb_waittime_minute.disabled = false;\n";
endif;

// Wenn der Originalaufrag einen Festpreis hatte und ein Discount berücksichtigt wurde,
// dann muss die entsprechende Checkbox gesetzt sein!
  $javascript .=
    "opener.parent.job_options.discount_default = true;\n";
$javascript .= $javascript_zone;
$jb_discount = 0;
$jb_discount_rate = 0;
if (($jb_fixprice != "0" && $jb_fixprice != "") || ($jb_serviceprice != "0" && $jb_serviceprice != "")):
  $granted_discount = $db->getOne("SELECT trs_discount FROM tourservice WHERE jb_id = '$jb_id' AND (trs_srv_name = 'Fixpreis' OR trs_srv_name = 'Servicepreis') AND trs_discount != 0");
  if ($granted_discount != 0 && $granted_discount != ""):
//    $javascript .=
//      "opener.parent.job_options.document.tourOptions.jb_discount.disabled = false;\n" .
//      "opener.parent.job_options.document.tourOptions.jb_discount.checked = true;\n";
    $jb_discount = 1;
    $jb_discount_rate = $granted_discount;
  else:
    $javascript .=
      "opener.parent.job_options.discount_default = false;\n";
    // für check_jb_permanent
  endif;
else:
// Hansetrans legt oft Touren an, die erst nachträglich bearbeitet werden. Diese haben bei der Anlage erst mal einen
// Festpreis "0", so dass der der Default-Discount beim Nachbearbeiten verschwindet. Daher wird sich gemerkt, ob der
// ursprüngliche Auftrag einen Nullpreis hatte, so dass in diesem Fall der Auftrag wieder wie ein neuer behandelt wird und
// der Default-Discount zur Anwendung kommt
  $javascript .= 
    "opener.parent.job_options.fixprice_was_0 = true;\n";
endif;

$javascript .= 
  "opener.parent.job_options.delete_suborder = " . ($delete_suborder ? "true" : "false") . ";\n" .
  "opener.parent.job_options.is_exported = " . ($job_is_exported ? "true" : "false") . ";\n" .
  "opener.parent.job_options.was_afterwards = " . ($was_afterwards ? "true" : "false") . ";\n" .
  "opener.checkCalculator();\n";

$javascript .=
  "opener.parent.job_options.document.tourOptions.tag.disabled = false;\n" .
  "opener.parent.job_options.document.tourOptions.monat.disabled = false;\n" .
  "opener.parent.job_options.document.tourOptions.jahr.disabled = false;\n" .
  "opener.parent.job_options.document.tourOptions.stunde.disabled = false;\n" .
  "opener.parent.job_options.document.tourOptions.minute.disabled = false;\n" .
  "opener.parent.job_options.document.tourOptions.jb_permanent.disabled = false;\n" .
  $waittimefiels .
//  "opener.parent.job_options.document.tourOptions.jb_globaljob.checked = false;\n" .
//  "opener.parent.job_options.document.tourOptions.jb_globaljob.disabled = false;\n" .
//  "opener.parent.job_options.document.tourOptions.jb_status_manual.disabled = false;\n" .
  ((isset($consider_manual_disp) && $consider_manual_disp == 1 && MASK_MANUAL_DISPOSITION == "1")
    ? "opener.parent.job_options.document.tourOptions.jb_status_manual.checked = true;\n"
    : "opener.parent.job_options.document.tourOptions.jb_status_manual.checked = false;\n") .
  "opener.checkAfterwards();\n" .
  ($jb_incomplete == 1
  ? "opener.parent.job_options.document.tourOptions.jb_incomplete.checked = true;\n"
  : "opener.parent.job_options.document.tourOptions.jb_incomplete.checked = false;\n") .
//  "opener.parent.job_options.document.tourOptions.crSidList.disabled = false;\n" .
//  "opener.parent.job_options.document.tourOptions.cr_id_order.disabled = false;\n" .
//  "opener.parent.job_options.document.tourOptions.jb_waitstorno.disabled = false;\n" .
//"alert(\"$jb_incomplete\");\n" .
  ($jb_offer == 1
  ? "opener.parent.job_options.document.tourOptions.jb_offer.disabled = false;\n" .
    "opener.parent.job_options.document.tourOptions.jb_offer.checked = true;\n" .
    "opener.checkOffer();\n"
  : "opener.parent.job_options.document.tourOptions.jb_offer.disabled = " . ((trim(getFieldValueFromId($_job_table, "jb_id", $jb_id, "jb_tourname")) != "") ? "false" : "true") . ";\n" .
    "opener.parent.job_options.document.tourOptions.jb_offer.checked = false;\n"
  ) .
  "opener.parent.job_options.document.tourOptions.jb_jam_waittime.value = '" . $jb_jam_waittime . "';\n" .
  "opener.parent.job_options.document.tourOptions.jb_value_of_goods.value = '" . $jb_value_of_goods . "';\n" .
  "opener.document.getElementsByName('jb_insurance_rate')[0].selectedIndex = '" . $jb_insurance_rate . "';\n" .
  "opener.parent.job_options.document.tourOptions.special_case_ori.value = '" . $special_case_ori . "';\n" .
//  "opener.parent.job_options.document.tourOptions.jb_id_insurance.value = 'in Auftrag Nr. " . $jb_id_insurance . " (Warenwert " . $jb_value_of_goods . " EUR)';\n" .
//  ($jb_id_insurance != "" ? "opener.\$('#div_insurance_done').show(); opener.parent.job_options.document.tourOptions.jb_insurance.checked = true;"
//    . " opener.parent.job_options.document.tourOptions.jb_insurance.disabled = true;\n" : "opener.\$('#div_insurance_done').hide();\n") .
  ($jb_id_insurance != "" ? "opener.parent.job_options.document.tourOptions.jb_insurance.checked = true; "
   . ($special_case == 1 ? "opener.parent.job_options.document.tourOptions.special_case.checked = true; " : "")  
   . "opener.\$('#div_insurance').show();\n" : "") .
  "opener.resetSignificantPriceValues();\n" .
//  "opener.writeJob();\n" .
  "var curTourNo = 0;\n" .  
  (isset($job_is_locked) && $job_is_locked ? "opener.parent.job_options.setTimeout('job_is_locked(" . $job_is_locked_mode . ", \\'" . $job_is_locked_text . "\\')', 100);\n" : "") .
  (isset($jb_copy) && $jb_copy == "true" ? "opener.parent.job_options.setTimeout('duplicateJob(true)', 100);\n" : "")
    . javascriptOpenerRefreshAndClose();

//
// checken ob von "check_jb_permanent.php" aufgerufen
// wenn ja, dann keine HTML-Ausgabe
//
if (!(isset($check_jb_permanent_flag) && $check_jb_permanent_flag == true)):
// Inhalt des temporären Fensters erzeugen und ausgeben
//  if ($phpVersion >= "7.0"):
//    $tpl = new HTML_Template_IT();
//  else:
//    $tpl = new IntegratedTemplate();
//  endif;
//  $tpl->loadTemplatefile(GETDATAHTMLTPL, true, true);
//  $tpl->setCurrentBlock("javascript");
//  $tpl->setVariable("_javascript_", $javascript);
//  $tpl->parseCurrentBlock("javascript");
//  $tpl->show();
$output = file_get_contents(GETDATAHTMLTPL);
$output = str_replace("{_javascript_}", $javascript, $output);
echo $output;
endif;

// Für 'check_jb_permanent.php' muss jb_freetext (und 'jb_dispoinfo' für Stornos) clean sein!
$jb_freetext_1 = my_str_check($jb_freetext_1);
$jb_hiddenFreetext_1 = my_str_check($jb_hiddenFreetext_1);
$jb_dispoinfo = my_str_check($jb_dispoinfo);

?>
