<?php
/*=======================================================================
 *
 * job_courier.inc.php
 *
 * Autor: Carsten Annacker
 *
 =======================================================================*/

// Die Kuriernummern werden in ein JavaScript-Array geschrieben,
// damit die Gültigkeit schon online geprüft werden kann
// Es stehen normalerweise alle Kuriere zur Verfügung (Wunschkurier);
// wenn allerdings hq.hq_workmode == "1" (Disposition erwünscht),
// dann nur eingeschränkte Auswahl (sortiert nach angemeldetem PLZ-Bereich,
// Ranking nach Anmeldezeit, nur angemeldete Kuriere)
include_once("../include/auth.inc.php");
include_once("../include/ranking.inc.php");
include_once("../include/caglobal.inc.php");
include_once("../include/global.inc.php");
include_once("../include/services_func.inc.php");
include_once("../jobs/job_courier.inc.lib.php");
include_once("../jobs/job_courier.inc.newbies.php");
include_once("../locating/xServer.inc.php");
include_once("../include/inc_autoranking.inc.php"); // for getPDALocatingStatus() only

trace_execution_time_start();

$cr_id_order_list0 = "";
$cr_id_order_list02 = "";
$cr_id_order_list = "";
$cr_id_order_list2 = "var cr_id_order_list2=[";
$vht_id_str_js = "var vht_id_str=new Array();\n";
$companyIds_js = "var companyIds=[";
$cr_id_order_list_blocked_js = "var cr_id_order_list_blocked=[ ";

//getDb2Connection();     // Try to connect request server because of performance
getDb3Connection();     // special connection for courier-list
$db2 = $db3;

$jb_longhaul = 0;
$ori_zipcode = "";
if(isset($jb_id) && $jb_id != "")
  $jb_longhaul = $db->getOne("SELECT jb_longhaul FROM job WHERE jb_id = " . $jb_id);
  $ori_zipcode = $zipcode;
if ($jb_longhaul == 1) {
//  if (!authCheckEmployeeRights($emp_id, "44")) : die("Das Recht \"BWV-Aufträge\" ist bei Ihnen nicht gesetzt!"); endif;

  // Die Koordinaten der Home-Zipcodes eintragen
  $sqlQuery = "SELECT cr_id, cr_homezipcode, cr_gps_long_home, cr_gps_lat_home, cr_desiredzipcode, ad_zipcode FROM courier, company, address WHERE cr_available = 1 AND courier.cmp_id = company.cmp_id AND company.ad_id = address.ad_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())):
    $tmp_cur_cr_homezipcode = $row["cr_desiredzipcode"];
    if (trim($tmp_cur_cr_homezipcode) == "")
      $tmp_cur_cr_homezipcode = $row["cr_homezipcode"];
    if (trim($tmp_cur_cr_homezipcode) == "")
      $tmp_cur_cr_homezipcode = $row["ad_zipcode"];
    $tmp_home_coords = get_coords("DE", $tmp_cur_cr_homezipcode, ".", ".", ".", true);
    if ($tmp_home_coords[0] != $row["cr_gps_lat_home"] || $tmp_home_coords[1] != $row["cr_gps_long_home"]) {
      writeLog_("../log/job_courier_cur_", "cr_id = " . $row["cr_id"] . ", cr_gps_lat_home = " . $tmp_home_coords[0] . ", cr_gps_long_home = " . $tmp_home_coords[1]);
      updateStmt("courier", "cr_id", $row["cr_id"], array("cr_gps_lat_home", $tmp_home_coords[0], "cr_gps_long_home", $tmp_home_coords[1], "cr_modify", "cr_modify"));
    }
  endwhile;
  $res->free();

  // Die Kuriere finden, deren aktulle Position im Umkreis um die Start-Adresse liegt
  $ad_id = $db->getOne("SELECT ad_id FROM tour WHERE jb_id = " . $jb_id . " AND tr_sort = 1");
  $tr_hsno = $db->getOne("SELECT tr_hsno FROM tour WHERE jb_id = " . $jb_id . " AND tr_sort = 1");
  list($ad_country, $ad_zipcode, $ad_city, $ad_street) =
    getFieldsValueFromId("address", "ad_id", $ad_id, array("ad_country", "ad_zipcode", "ad_city", "ad_street"));
  $zipcodeArr = get_coords($ad_country, $ad_zipcode, $ad_city, $ad_street, $tr_hsno);
  $zipcode = $zipcodeArr[0] . "," . $zipcodeArr[1];

  // Auch die Kuriere finden, deren Heimat-PLZ im Umkreis um die Zieladresse liegt
  $tr_sort_end = $db->getOne("SELECT MAX(tr_sort) FROM tour WHERE jb_id = " . $jb_id);
  $ad_id_end = $db->getOne("SELECT ad_id FROM tour WHERE jb_id = " . $jb_id . " AND tr_sort = " . $tr_sort_end);
  $tr_hsno_end = $db->getOne("SELECT tr_hsno FROM tour WHERE jb_id = " . $jb_id . " AND tr_sort = " . $tr_sort_end);
  list($ad_country_end, $ad_zipcode_end, $ad_city_end, $ad_street_end) =
    getFieldsValueFromId("address", "ad_id", $ad_id_end, array("ad_country", "ad_zipcode", "ad_city", "ad_street"));
  $zipcodeArrEnd = get_coords($ad_country_end, $ad_zipcode_end, $ad_city_end, $ad_street_end, $tr_hsno_end);
  $zipcode_home = $zipcodeArr[0] . "," . $zipcodeArr[1] . "," . $zipcodeArrEnd[0] . "," . $zipcodeArrEnd[1];

  $cr_id_order_list2 = "";
}

// hq_id aus dem job holen
if (isset($jb_id) && $jb_id != ""):
  $hq_id = getFieldValueFromId("job", "jb_id", "$jb_id", "hq_id");
  if ($jb_longhaul == 1)
    $hq_id_dispo = getFieldValueFromId("job", "jb_id", "$jb_id", "hq_id_dispo");
endif;
if (!defined("CONST_MASK_COURIER_SORT_BY_OCCUPIED"))
  define ("CONST_MASK_COURIER_SORT_BY_OCCUPIED", getParameterValue("0", "MASK_COURIER_SORT_BY_OCCUPIED", $hq_id));
if (!defined("CONST_MODE_INTERMEDIATION"))
  define ("CONST_MODE_INTERMEDIATION", getParameterValue("0", "MODE_INTERMEDIATION", $hq_id));
if (!defined("CONST_AUTORANKING_NEIGHBOUR_LEVEL"))
  define ("CONST_AUTORANKING_NEIGHBOUR_LEVEL", getParameterValue("0", "AUTORANKING_NEIGHBOUR_LEVEL", $hq_id));
if (!defined("CONST_RANKING_JB2CRVH_MEASURE"))
  define ("CONST_RANKING_JB2CRVH_MEASURE", getParameterValue("0", "RANKING_JB2CRVH_MEASURE", $hq_id));
if (!defined("CONST_RANKING_RADIUS_KM"))
  define ("CONST_RANKING_RADIUS_KM", getParameterValue("0", "RANKING_RADIUS_KM", $hq_id));
//define ("CONST_RANKING_RADIUS_KM", 320);

$hq_workmode = getFieldValueFromId("headquarters", "hq_id", "$hq_id", "hq_workmode");
//if ($hq_workmode == "2" && $hq_id != 1):
  $userType = (isset($usr_id) && trim($usr_id != "")? getFieldValueFromId("user", "usr_id", $usr_id, "usr_type") : 1);
  // Wenn jb_id gesetzt, dann kommt der Aufruf aus der Auftragsliste
  if (isset($jb_id) && $jb_id != "" && isset($zipcode) && $zipcode != "" && $userType == 1):
    // Auftragsliste -> Kuriere sortieren
//die("\"$zipcode\", \"1111100\", $jb_id");
if (!(isset($jb_id) && $jb_id != "" && isset($zipcode) && $zipcode != "" && $userType == 1)):
  writeLog_("../log/job_courier_", "vor getCourierByRanking");
endif;
$ranking_radius_km = 0;
do {
    if ($jb_longhaul == 1) {
      $ranking_radius_km += CONST_RANKING_RADIUS_KM;
	}
    writeLog_("../log/job_courier_cur_", "getCourierByRanking(" . $zipcode . ", 111110001, " . $jb_id . ", " . $hq_id_string . ", " . $ranking_radius_km . ")");
    $cr_id_order_list_temp_all = getCourierByRanking("$zipcode", "111110001", $jb_id, "", $hq_id_string, $ranking_radius_km);
    if ($jb_longhaul == 1) {
      writeLog_("../log/job_courier_cur_", var_export($cr_id_order_list_temp_all[2], true));
      writeLog_("../log/job_courier_cur_", var_export($cr_id_order_list_temp_all[3], true));
      writeLog_("../log/job_courier_cur_", "getCourierByRanking(" . $zipcode_home . ", 111110001, " . $jb_id . ", " . $hq_id_string . ", " . $ranking_radius_km . ")");
      $cr_id_order_list_temp_all_home = getCourierByRanking("$zipcode_home", "111110001", $jb_id, "", $hq_id_string, $ranking_radius_km);
      writeLog_("../log/job_courier_cur_", var_export($cr_id_order_list_temp_all_home[2], true));
      writeLog_("../log/job_courier_cur_", var_export($cr_id_order_list_temp_all_home[3], true));
    }
} while ($jb_longhaul == 1 && count($cr_id_order_list_temp_all_home[2]) == 0 && count($cr_id_order_list_temp_all[2]) == 0 && count($cr_id_order_list_temp_all_home[3]) == 0 && count($cr_id_order_list_temp_all[3]) == 0 && $ranking_radius_km <= CONST_RANKING_RADIUS_KM * 12);

if (!(isset($jb_id) && $jb_id != "" && isset($zipcode) && $zipcode != "" && $userType == 1)):
  writeLog_("../log/job_courier_", "nach getCourierByRanking");
endif;
if ($jb_longhaul == 1) {
  $cr_id_order_list_temp_all_home[2] = my_array_diff ($cr_id_order_list_temp_all_home[2], $cr_id_order_list_temp_all[2]);
  writeLog_("../log/job_courier_cur_", "\$cr_id_order_list_temp_all_home[2] = " . var_export($cr_id_order_list_temp_all_home[2], true));
  $cr_id_order_list_temp_all[2] = array_merge($cr_id_order_list_temp_all[2], $cr_id_order_list_temp_all_home[2]);
}
    // Favorisierte Kuriere
    $cr_id_order_list_favoured = get_complete_courier_data($cr_id_order_list_temp_all[2]);
//    // favorisierte Kuriere
//    if ($jb_longhaul == 1)
//      $cr_id_order_list_favoured = get_longhaul_courier_data($cr_id_order_list_favoured, $ad_zipcode, $ad_city, $ad_street, $tr_hsno);
    if ($jb_longhaul != 1)
      usort ($cr_id_order_list_favoured, "cmp_usort");
    if ($jb_longhaul == 1):
      array_unshift($cr_id_order_list_favoured, array("*", "&nbsp;</td><td align=center><a href=\\\"javascript:reloadMe(1)\\\"><b>Frachtvergütung</b></a></td><td align=center><a href=\\\"javascript:reloadMe(2)\\\"><b>Anfahrt min.</b></a></td><td align=center><a href=\\\"javascript:reloadMe(3)\\\"><b>KM zur Start-PLZ</b></a></td><td align=center><a href=\\\"javascript:reloadMe(4)\\\"><b>Standort</b></a></td><td align=center><a href=\\\"javascript:reloadMe(5)\\\"><b>Heimat-PLZ</b></a></td><td align=center><a href=\\\"javascript:reloadMe(6)\\\"><b>Rundkilometer</b></a></td><td align=center><a href=\\\"javascript:reloadMe(7)\\\"><b>Fahrzeug</b></a>"));
    endif;
    if (CONST_MASK_COURIER_SORT_BY_OCCUPIED == "1"):
      array_unshift($cr_id_order_list_favoured, array("*", "<b>- bevorzugte</b>"));
    else:
      array_unshift($cr_id_order_list_favoured, array("*", "<b>Bevorzugte Kuriere</b>"));
    endif;

if ($jb_longhaul == 1) {
  $cr_id_order_list_temp_all_home[1] = my_array_diff ($cr_id_order_list_temp_all_home[1], $cr_id_order_list_temp_all[1]);
  writeLog_("../log/job_courier_cur_", "\$cr_id_order_list_temp_all_home[1] = " . var_export($cr_id_order_list_temp_all_home[1], true));
  $cr_id_order_list_temp_all[1] = array_merge($cr_id_order_list_temp_all[1], $cr_id_order_list_temp_all_home[1]);
}
    // geblockte Kuriere
    $cr_id_order_list_blocked = get_complete_courier_data($cr_id_order_list_temp_all[1]);
    usort ($cr_id_order_list_blocked, "cmp_usort");
    foreach($cr_id_order_list_blocked as $cr_id_order_blocked) {
      $cr_id_order_list_blocked_js .= "'" . trim($cr_id_order_blocked[1]) . "',";
    }
    if (CONST_MASK_COURIER_SORT_BY_OCCUPIED == "1"):
      array_unshift($cr_id_order_list_blocked, array("*", "<b>- gesperrte</b>"));
    else:
      array_unshift($cr_id_order_list_blocked, array("*", "<b>Gesperrte Kuriere</b>"));
    endif;

if ($jb_longhaul == 1) {
  $cr_id_order_list_temp_all_home[3] = my_array_diff ($cr_id_order_list_temp_all_home[3], $cr_id_order_list_temp_all[3]);
  writeLog_("../log/job_courier_cur_", "\$cr_id_order_list_temp_all_home[3] = " . var_export($cr_id_order_list_temp_all_home[3], true));
  $cr_id_order_list_temp_all[3] = array_merge($cr_id_order_list_temp_all[3], $cr_id_order_list_temp_all_home[3]);
}
    // Kuriere im Vermittlungsbereich
    $cr_id_order_list_area = $cr_id_order_list_temp_all[3];
    // Nur hier (und in den favorisierten natürlich) können bei $jb_longhaul = 1 Einträge sein
    if ($jb_longhaul == 1) {
      $cr_id_order_list_area = my_array_diff ($cr_id_order_list_area, $cr_id_order_list_favoured);
//      $cr_id_order_list_area = get_longhaul_courier_data($cr_id_order_list_area, $ad_zipcode, $ad_city, $ad_street, $tr_hsno);
    }
    if ($cr_id_order_list_area == "")
      $cr_id_order_list_area = Array();
    if ($jb_longhaul != 1)
      usort ($cr_id_order_list_area, "cmp_usort");
    if ($jb_longhaul == 1):
      array_unshift($cr_id_order_list_area, array("*", "&nbsp;</td><td align=center><a href=\\\"javascript:reloadMe(1)\\\"><b>Frachtvergütung</b></a></td><td align=center><a href=\\\"javascript:reloadMe(2)\\\"><b>Anfahrt min.</b></a></td><td align=center><a href=\\\"javascript:reloadMe(3)\\\"><b>KM zur Start-PLZ</b></a></td><td align=center><a href=\\\"javascript:reloadMe(4)\\\"><b>Standort</b></a></td><td align=center><a href=\\\"javascript:reloadMe(5)\\\"><b>Heimat-PLZ</b></a></td><td align=center><a href=\\\"javascript:reloadMe(6)\\\"><b>Rundkilometer</b></a></td><td align=center><a href=\\\"javascript:reloadMe(7)\\\"><b>Fahrzeug</b></a>"));
//      array_unshift($cr_id_order_list_blocked, array("*", "&nbsp;</td><td align=center><b>Fahrzeug</b></td><td align=center><b>Anfahrt min.</b></td><td align=center><b>KM zur Start-PLZ</b></td><td align=center><b>Standort</b></td><td align=center><b>Heimat-PLZ</b></td><td align=center><b>Rundkilometer</b></td><td align=center><b>Frachtvergütung</b>"));
    endif;
    if (CONST_MASK_COURIER_SORT_BY_OCCUPIED == "1"):
      if (CONST_MODE_INTERMEDIATION == 1 && $jb_longhaul != 1): // Bremen
        array_unshift($cr_id_order_list_area, array("*", "<b>- im Vermittlungsbereich</b>"));
      elseif((CONST_MODE_INTERMEDIATION == 2 || CONST_MODE_INTERMEDIATION == 3) && $jb_longhaul != 1): // Hamburg, Berlin
        $srvpa_name = $db2->getOne(
          "SELECT srvpa.srvpa_name FROM serviceplzareamapping AS srvpam, serviceplz AS srvp, serviceplzarea AS srvpa" .
          " WHERE srvp.srvp_id = srvpam.srvp_id AND srvpa.hq_id = '$hq_id' AND srvpam.srvpa_id = srvpa.srvpa_id AND srvp.srvp_plz = '$zipcode'");
        $srvpa_longname = $db2->getOne(
          "SELECT srvpa.srvpa_longname FROM serviceplzareamapping AS srvpam, serviceplz AS srvp, serviceplzarea AS srvpa" .
          " WHERE srvp.srvp_id = srvpam.srvp_id AND srvpa.hq_id = '$hq_id' AND srvpam.srvpa_id = srvpa.srvpa_id AND srvp.srvp_plz = '$zipcode'");
        array_unshift($cr_id_order_list_area, array("*", "<b>- im Vermittlungsbereich $srvpa_name (" . $srvpa_longname . ")</b>"));
      elseif($jb_longhaul == 1):
        array_unshift($cr_id_order_list_area, array("*", "<b>- restliche verf&uuml;gbare</b>"));
      endif;
    else:
      if (CONST_MODE_INTERMEDIATION == 1 && $jb_longhaul != 1): // Bremen
        array_unshift($cr_id_order_list_area, array("*", "<b>Kuriere im Vermittlungsbereich</b>"));
      elseif((CONST_MODE_INTERMEDIATION == 2 || CONST_MODE_INTERMEDIATION == 3) && $jb_longhaul != 1): // Hamburg, Berlin
        $srvpa_name = $db2->getOne(
          "SELECT srvpa.srvpa_name FROM serviceplzareamapping AS srvpam, serviceplz AS srvp, serviceplzarea AS srvpa" .
          " WHERE srvp.srvp_id = srvpam.srvp_id AND srvpna.hq_id = '$hq_id' AND srvpa.hq_id = '$hq_id' AND srvpam.srvpa_id = srvpa.srvpa_id AND srvp.srvp_plz = '$zipcode'");
        $srvpa_longname = $db2->getOne(
          "SELECT srvpa.srvpa_longname FROM serviceplzareamapping AS srvpam, serviceplz AS srvp, serviceplzarea AS srvpa" .
          " WHERE srvp.srvp_id = srvpam.srvp_id AND srvpna.hq_id = '$hq_id' AND srvpa.hq_id = '$hq_id' AND srvpam.srvpa_id = srvpa.srvpa_id AND srvp.srvp_plz = '$zipcode'");
        array_unshift($cr_id_order_list_area, array("*", "<b>Kuriere im Vermittlungsbereich $srvpa_name (" . $srvpa_longname . ")</b>"));
      endif;
    endif;
    // Kuriere in der Vermittlungsbereich-Nachbarschaft
    if (CONST_MODE_INTERMEDIATION == 1): // Bremen
      $cr_id_order_list_neighbourhood = $cr_id_order_list_temp_all[4];
      if ($cr_id_order_list_neighbourhood == "")
        $cr_id_order_list_neighbourhood = Array();
      usort ($cr_id_order_list_neighbourhood, "cmp_usort");
    elseif(CONST_MODE_INTERMEDIATION == 2 || CONST_MODE_INTERMEDIATION == 3): // Hamburg, Berlin
      for($i = 1; $i <= CONST_AUTORANKING_NEIGHBOUR_LEVEL; $i++):
        $cr_id_order_list_temp_all[$i] = getCourierByRanking("$zipcode", "010010001", $jb_id, $i, $hq_id);
        $cr_id_order_list_neighbourhoods[$i] = $cr_id_order_list_temp_all[$i][4];
        if ($cr_id_order_list_neighbourhoods[$i] == "")
          $cr_id_order_list_neighbourhoods[$i] = Array();
        usort ($cr_id_order_list_neighbourhoods[$i], "cmp_usort");
      endfor;
    endif;
    if (CONST_MASK_COURIER_SORT_BY_OCCUPIED == "1"):
      if (CONST_MODE_INTERMEDIATION == 1 && $jb_longhaul != 1): // Bremen
        array_unshift($cr_id_order_list_neighbourhood, array("*", "<b>- in der Nachbarschaft</b>"));
      elseif((CONST_MODE_INTERMEDIATION == 2 || CONST_MODE_INTERMEDIATION == 3)  && $jb_longhaul != 1): // Hamburg, Berlin
        for($i = 1; $i <= CONST_AUTORANKING_NEIGHBOUR_LEVEL; $i++):
          $srvpa_name = $db2->getOne(
            "SELECT srvpa.srvpa_name FROM serviceplzneighbourarea AS srvpna, serviceplz AS srvp, serviceplzarea AS srvpa" .
            " WHERE srvpna.srvpna_sort = $i AND srvp.srvp_id = srvpna.srvp_id AND srvpna.hq_id = '$hq_id' AND srvpa.hq_id = '$hq_id' AND srvpna.srvpa_id = srvpa.srvpa_id AND srvp.srvp_plz = '$zipcode'");
          $srvpa_longname = $db2->getOne(
            "SELECT srvpa.srvpa_longname FROM serviceplzneighbourarea AS srvpna, serviceplz AS srvp, serviceplzarea AS srvpa" .
            " WHERE srvpna.srvpna_sort = $i AND srvp.srvp_id = srvpna.srvp_id AND srvpna.hq_id = '$hq_id' AND srvpa.hq_id = '$hq_id' AND srvpna.srvpa_id = srvpa.srvpa_id AND srvp.srvp_plz = '$zipcode'");
          array_unshift($cr_id_order_list_neighbourhoods[$i], array("*", "<b>- in der Nachbarschaft $srvpa_name (" . $srvpa_longname . ")</b>"));
        endfor;
      endif;
    else:
      if (CONST_MODE_INTERMEDIATION == 1 && $jb_longhaul != 1): // Bremen
        array_unshift($cr_id_order_list_neighbourhood, array("*", "<b>Kuriere in der Nachbarschaft</b>"));
      elseif((CONST_MODE_INTERMEDIATION == 2 || CONST_MODE_INTERMEDIATION == 3) && $jb_longhaul != 1): // Hamburg, Berlin
        for($i = 1; $i <= CONST_AUTORANKING_NEIGHBOUR_LEVEL; $i++):
          $srvpa_name = $db2->getOne(
            "SELECT srvpa.srvpa_name FROM serviceplzneighbourarea AS srvpna, serviceplz AS srvp, serviceplzarea AS srvpa" .
            " WHERE srvpna.srvpna_sort = $i AND srvp.srvp_id = srvpna.srvp_id AND srvpna.hq_id = '$hq_id' AND srvpa.hq_id = '$hq_id' AND srvpna.srvpa_id = srvpa.srvpa_id AND srvp.srvp_plz = '$zipcode'");
          $srvpa_longname = $db2->getOne(
            "SELECT srvpa.srvpa_longname FROM serviceplzneighbourarea AS srvpna, serviceplz AS srvp, serviceplzarea AS srvpa" .
            " WHERE srvpna.srvpna_sort = $i AND srvp.srvp_id = srvpna.srvp_id AND srvpna.hq_id = '$hq_id' AND srvpa.hq_id = '$hq_id' AND srvpna.srvpa_id = srvpa.srvpa_id AND srvp.srvp_plz = '$zipcode'");
          array_unshift($cr_id_order_list_neighbourhoods[$i], array("*", "<b>- in der Nachbarschaft $srvpa_name (" . $srvpa_longname . ")</b>"));
        endfor;
      endif;
    endif;
     // Alle Kuriere
    $cr_id_order_list_absolutely_all = Array();
    // Neu ab 24.05.2020: Filter checkNationality ($jbId, $objId, $objType = "cr")
    if (isset($jb_id) && $jb_id != ""):
      for($i = 0; $i < count($cr_id_order_list_temp_all[0]); $i++):
        if (checkNationality ($jb_id, $cr_id_order_list_temp_all[0][$i][0])):
          $cr_id_order_list_absolutely_all[] = $cr_id_order_list_temp_all[0][$i];
//          writeLog_("../log/job_courier_cur_", "checkNationality (" . $jb_id . ", " . $cr_id_order_list_temp_all[0][$i][0] . ") results to true");
        else:
          $cr_id_order_list_blocked[] = $cr_id_order_list_temp_all[0][$i];
          $cr_id_order_list_blocked_js .= "'" . trim($cr_id_order_list_temp_all[0][$i][1]) . "',";
          writeLog_("../log/job_courier_cur_", "checkNationality (" . $jb_id . ", " . $cr_id_order_list_temp_all[0][$i][0] . ") results to false");
        endif;
      endfor;
    endif;
    // Die Liste aller Kuriere soll nur die enthalten, die nicht bereits in den ersten Listen enthalten sind
    if (CONST_MODE_INTERMEDIATION == 1): // Bremen
    elseif(CONST_MODE_INTERMEDIATION == 2 || CONST_MODE_INTERMEDIATION == 3): // Hamburg, Berlin
      $cr_id_order_list_neighbourhood = Array();
      for($i = 1; $i <= CONST_AUTORANKING_NEIGHBOUR_LEVEL; $i++):
        $cr_id_order_list_neighbourhood = array_merge($cr_id_order_list_neighbourhood, $cr_id_order_list_neighbourhoods[$i]);
      endfor;
//print_r($cr_id_order_list_neighbourhoods[1]);
//echo "1";
//print_r($cr_id_order_list_neighbourhoods[2]);
//echo "2";
//print_r($cr_id_order_list_neighbourhoods[3]);
//echo "3";
//print_r($cr_id_order_list_neighbourhood);
//reportDie ();
    endif;
    $cr_id_order_list_rest = my_array_diff ($cr_id_order_list_absolutely_all, array_merge($cr_id_order_list_favoured, $cr_id_order_list_area, $cr_id_order_list_neighbourhood, $cr_id_order_list_blocked));
    // $cr_id_order_list_rest ist bei jb_longhaul == 1 immer leer
    usort ($cr_id_order_list_rest, "cmp_usort");
    if (CONST_MASK_COURIER_SORT_BY_OCCUPIED == "1"):
      array_unshift($cr_id_order_list_rest, array("*", "<b>- restliche verf&uuml;gbare</b>"));
    else:
      array_unshift($cr_id_order_list_rest, array("*", "<b>Anderweitige verf&uuml;gbare Kuriere</b>"));
    endif;
    if ($jb_longhaul != 1) {
	  $cr_id_order_list_temp = array_merge ($cr_id_order_list_favoured, $cr_id_order_list_area, $cr_id_order_list_neighbourhood, $cr_id_order_list_rest, $cr_id_order_list_blocked);
    } else {
	  $cr_id_order_list_temp = array_merge ($cr_id_order_list_favoured, $cr_id_order_list_area, $cr_id_order_list_blocked);
    }
  else:
    // Auftragserfassung -> alle Kuriere (auch unangemeldet wg. Auftragsnacherfassung)
    $sqlQuery =
      "SELECT cr.cr_id, cr.cr_eid, mt.mt_value, cr.cr_locationzipcode, cr.cr_availabletime, crvh.crvh_payload, crvh.crvh_filter, crvh.crvh_sid, crvh.crvh_height, crvh.crvh_width, crvh.crvh_length, crvh.crvh_position"
      . " FROM courier AS cr, couriervehicle AS crvh, metatype AS mt, company AS cmp"
      . " WHERE "
//      . "       cr.hq_id = '" . $hq_id . "'                   AND" // BWV: Kuriere  über alle Niederlassungen sind zugelassen
      . "       crvh.crvh_sid != ''                             AND"
      . "       cr.cmp_id = cmp.cmp_id                        AND"
      . "       cmp.cmp_authenticated = '1'                   AND"
      . "       cr.cr_id = crvh.cr_id                         AND" // Quickhack wg. Fehler in der Kurierverwaltung!!!
//      . "       cr.cr_sid = crvh.crvh_sid                     AND"
      . "       crvh.vht_id = mt.mt_sort                      AND"
      . "       mt.mt_type = 'vehicletype'                       "
      . " ORDER BY crvh.crvh_sid";
//if (!(isset($jb_id) && $jb_id != "" && isset($zipcode) && $zipcode != "" && $userType == 1)):
//  writeLog_("../log/job_courier_", "[" . $sqlQuery . "]");
//endif;

    if ($userType != 1):
      $sqlQuery = "
        SELECT cr.cr_id, cr.cr_eid, mt.mt_value, cr.cr_locationzipcode, cr.cr_availabletime, crvh.crvh_payload, crvh.crvh_filter, crvh.crvh_sid, crvh.crvh_height, crvh.crvh_width, crvh.crvh_length, crvh.crvh_position
        FROM employee AS emp, costcenter AS csc, customer AS cs, customercourier AS cscr, courier AS cr, couriervehicle AS crvh, metatype AS mt, company AS cmp
        WHERE emp.usr_id = " . $usr_id . " AND emp.csc_id = csc.csc_id AND csc.cs_id = cs.cs_id AND cs.cs_id = cscr.cs_id AND cr.cr_id = cscr.cr_id AND cscr.cscr_relation = 1
        AND crvh.crvh_sid != '' AND cr.cmp_id = cmp.cmp_id AND cmp.cmp_authenticated = '1' AND cr.cr_id = crvh.cr_id AND crvh.vht_id = mt.mt_sort AND mt.mt_type = 'vehicletype'
      ";
    endif;

    $res = $db2->query($sqlQuery);
    $cr_id_order_list_temp = array();
    if (DB::isError($res)) reportDie ("$PHP_SELF: '$sqlQuery'" . $res->getMessage());
    while ($row = ($phpVersion >= "8.0" ? $res->fetch_assoc() : $res->fetchRow())):
      $cr_id_order_list_temp[] = array(
        $row["cr_id"],
        $row["crvh_sid"],
        $row["cr_eid"],
        $row["mt_value"],
        $row["cr_locationzipcode"],
        $row["cr_availabletime"],
        $row["crvh_filter"],
        $row["crvh_payload"],
        $row["crvh_height"],
        $row["crvh_width"],
        $row["crvh_length"],
        $row["crvh_position"]
      );
    endwhile;
    $res->free();
    // Spezieller Verbuchungskurier von Hansetrans
//    $cr_id_order_list_temp[] = array(87, "1888", 283128, "", "", "", "");
  endif;

//// Die Fahrzeugtabelle laden, damit nicht für jeden Kurier das Fahrzeug einzeln aus der DB geladen werden muss
// ab 01.12.2010 ausgelagert
//$vehicletypes = array();
//$vehicletype_ids = array();
//$sqlQuery = "SELECT mt_sort, mt_value FROM metatype WHERE mt_type = 'vehicletype'";
//$res = $db2->query($sqlQuery);
//if (DB::isError($res)) reportDie ("$PHP_SELF: '$sqlQuery': " . $res->getMessage());
//while ($row = ($phpVersion >= "8.0" ? $res->fetch_assoc() : $res->fetchRow())):
//  $vehicletypes[$row["mt_sort"]] = $row["mt_value"];
//  $vehicletype_ids[$row["mt_value"]] = $row["mt_sort"];
//endwhile;
//$res->free();
$vehicletype_ids = array(
  '---' => 0,
  'Fahrrad' => 1,
  'PKW' => 2,
  'Kombi' => 3,
  'Kastenwagen' => 4,
  'Bus' => 5,
  'Großer Bus' => 6,
  'LKW' => 7,
  'LKW 12 To.' => 11,
  'Service' => 999);

// bei occupied Kurieren sollen die aktuellen Aufträge angezeigt werden
if (isset($jb_id) && $jb_id != "" && isset($zipcode) && $zipcode != ""):
$cur_jb_cr_filter_opt = ""; // Optionale Filter werden zukünftig nicht mehr berücksichtigt
list($cur_jb_weight, $cur_jb_height, $cur_jb_width, $cur_jb_length, $cur_jb_position, $cur_jb_ordertime, $cur_jb_reserv, $cur_jb_permanent, $cur_vht_id_job, $cur_jb_totalprice, $cur_jb_payment, $cur_jb_cr_filter,/* $cur_jb_cr_filter_opt,*/ $cur_jb_tourdata, $cur_cr_sid, $cur_csc_id_payer, $cur_csc_id_payer_cash) =
  getFieldsValueFromId("job", "jb_id", $jb_id,
    array("jb_weight", "jb_crvh_height", "jb_crvh_width", "jb_crvh_length", "jb_crvh_position",
      "jb_ordertime", "jb_reserv", "jb_permanent", "vht_id", "jb_totalprice", "jb_payment", "jb_cr_filter",/* "jb_cr_filter_opt",*/ "jb_tourdata", "cr_sid", "csc_id_payer", "csc_id_payer_cash"));
  if ($jb_longhaul == 1) {
    $jb_km_unrounded = $db->getOne("SELECT jbprc_price FROM jobprice WHERE jb_id = " . $jb_id . " AND mt_sort = 11");
    $jb_km = round($jb_km_unrounded, 2);
  }
  $cur_vht_id_value_job = $vehicletypes[$cur_vht_id_job];
  $cur_vht_id_str = ($jb_longhaul != 1 ? " </b>Fahrzeug:<b> " : "") . $cur_vht_id_value_job;
  $cur_jb_totalprice_str = ($jb_longhaul != 1 ? "</b>, Preis:<b> " : "") . str_replace(".", ",", sprintf("%01.2f", $cur_jb_totalprice)) . " EUR";
  if ($cur_jb_payment == 2)
    $cur_jb_totalprice_str .= " (BAR)";
  if ($jb_longhaul != 1) {
    $cur_jb_reserv_str = "";
    if ($cur_jb_reserv == 1) {
      $cur_jb_ordertime_vals = getValsFromDate($cur_jb_ordertime);
      $cur_jb_reserv_str = "</b>, bestellt für<b> ";
      $today = getdate();
      if ($today['mon'] != $cur_jb_ordertime_vals[1] || $today['mday'] != $cur_jb_ordertime_vals[2])
        $cur_jb_reserv_str .= sprintf("%02d", $cur_jb_ordertime_vals[2]) . "." . sprintf("%02d", $cur_jb_ordertime_vals[1]) . "., ";
      $cur_jb_reserv_str .= sprintf("%02d", $cur_jb_ordertime_vals[3]) . ":" . sprintf("%02d", $cur_jb_ordertime_vals[4]) . " UHR";
      if ($cur_jb_permanent >= 1)
        $cur_jb_reserv_str .= " (Dauerauf.)";
    }
  }
  $cur_jb_cr_filter_str = "";
  if ($cur_jb_cr_filter != "") {
    $tmp_cur_jb_cr_filter = $cur_jb_cr_filter;
    $mandatory_filters = trim(getParameterValue("0", "MASK_MANDATORY_FILTERS", $hq_id));
    if ($mandatory_filters != ''):
      $mandatory_filtersArr = explode(",", $mandatory_filters);
      for ($i = 0; $i < count($mandatory_filtersArr); $i++):
        if ($tmp_cur_jb_cr_filter == $mandatory_filtersArr[$i])
          $tmp_cur_jb_cr_filter = "";
        $tmp_cur_jb_cr_filter = str_replace("," . $mandatory_filtersArr[$i] . ",", ",", $tmp_cur_jb_cr_filter);
        $tmp_cur_jb_cr_filter = str_replace($mandatory_filtersArr[$i] . ",", "", $tmp_cur_jb_cr_filter);
        $tmp_cur_jb_cr_filter = str_replace("," . $mandatory_filtersArr[$i], "", $tmp_cur_jb_cr_filter);
      endfor;
    endif;
    if (trim($tmp_cur_jb_cr_filter) != "")
      $cur_jb_cr_filter_str = "</b>, Filter:<b> " . $tmp_cur_jb_cr_filter;
  }
  $cur_jb_cr_filter_opt_str = "";
  if ($cur_jb_cr_filter_opt != "")
    $cur_jb_cr_filter_opt_str = "</b>, opt. Filter:<b> " . $cur_jb_cr_filter_opt;
//  if ($jb_longhaul != 1) {
    $cur_jb_weight_str = "";
    if ($cur_jb_weight > 0)
      $cur_jb_weight_str = "</b>, Gewicht:<b> " . $cur_jb_weight . " kg";
    if ($cur_jb_height > 0)
      $cur_jb_weight_str .= "</b>, Höhe:<b> " . $cur_jb_height . " cm";
    if ($cur_jb_width > 0)
      $cur_jb_weight_str .= "</b>, Breite:<b> " . $cur_jb_width . " cm";
    if ($cur_jb_length > 0)
      $cur_jb_weight_str .= "</b>, L&auml;nge:<b> " . $cur_jb_length . " cm";
    if ($cur_jb_position > 0)
      $cur_jb_weight_str .= "</b>, Stellpl&auml;tze:<b> " . $cur_jb_position;
//  }
  // Etappenliste in "Kurzform"
  list($csc_id, $tr_comp, $tr_person, $ad_street, $tr_hsno,
    $ad_zipcode, $ad_city, $tr_remark, $tr_status, $tr_ware_from_to, $tr_status, $tr_sign, $tr_signname, $tr_finishtime, $tr_id) =
    getTourData($jb_id, 1, "tour");
  $cur_jb_tour_data_split = !isset($cur_jb_tour_data) || $cur_jb_tour_data == "" ? "" : split("|", $cur_jb_tour_data);
  $cur_jb_tour_data_plzs = $cur_jb_tour_data_split == "" ? "" : split(",", $cur_jb_tour_data_split[0]);
  $cur_jb_tour_data_orte = $cur_jb_tour_data_split == "" ? "" : split(",", $cur_jb_tour_data_split[1]);
    // Alte Touren (Daueraufträge etc. haben noch keinen Eintrag in jb_tour_data;
    // deshalb zur Sicherheit checken, ob noch mehr Etappen vorhanden
  $cur_max_tour = 1;
  $via_str = "";
  $t_ad_zipcode = "";
  $t_ad_city = "";
  while (existsEntry("tour", array("jb_id", $jb_id, "tr_sort", $cur_max_tour + 1)))
  {
    if (++$cur_max_tour > 3)
      $via_str .= $jb_longhaul != 1 ? ", " : "<br>";
    if ($cur_max_tour > 2)
      $via_str .= $jb_longhaul != 1 ? $t_ad_zipcode . " " . $t_ad_city : $t_ad_street . " " . $t_tr_hsno . ", " . $t_ad_zipcode . " " . $t_ad_city;
    list($t_csc_id, $t_tr_comp, $t_tr_person, $t_ad_street, $t_tr_hsno,
      $t_ad_zipcode, $t_ad_city, $t_tr_remark, $t_tr_status, $t_tr_ware_from_to, $t_tr_status, $t_tr_sign, $t_tr_signname, $t_tr_finishtime) =
      getTourData($jb_id, $cur_max_tour, "tour");
  }
  if ($jb_longhaul != 1 && $via_str != "")
    $via_str = " (via " . $via_str . ")";
  if (CONST_MASK_COURIER_SORT_BY_OCCUPIED == "1" && $userType == 1 && $jb_longhaul != 1):
    array_unshift($cr_id_order_list_temp, array("*", "<tr><td align=left valign=center colspan=10><B>KURIERE OHNE AUFTRAG</B><\/td><\/tr>"));
  endif;
//  $reset_cr_availabletime_checked = "checked";
  $reset_cr_availabletime_checked = "";
  $reset_cr_availabletime_disabled = "";
  if (trim($cur_cr_sid) == ""):
    $cur_cr_sid = "???";
    $reset_cr_availabletime_checked = ""; 
    $reset_cr_availabletime_disabled = "disabled";
  endif;
  $cur_cs_id = getFieldValueFromId("costcenter", "csc_id", ($cur_csc_id_payer == CSC_ID_PAYER_CASH ? $cur_csc_id_payer_cash : $cur_csc_id_payer), "cs_id");
  if ($jb_longhaul == 1) {
    $cur_cmp_id = getFieldValueFromId("customer", "cs_id", $cur_cs_id , "cmp_id");
    list($cur_cmp_comp, $cur_cmp_comp2) =
      getFieldsValueFromId("company", "cmp_id", $cur_cmp_id,
        array("cmp_comp", "cmp_comp2"));
    $cur_cmp_str = $cur_cmp_comp . " " . $cur_cmp_comp2;
  }
  $ignore_fav_only_checkbox = "";
  if (existsEntry("customer", array("cs_id", $cur_cs_id, "cs_cr_fav_only", 1)))
    $ignore_fav_only_checkbox = ",<br> <input type=\\\"checkbox\\\" name=\\\"ignore_fav_only\\\" value=\\\"1\\\" " .
      (existsEntry("genericdatacontainer", array("gdc_obj_type", "jb", "gdc_obj_id", $jb_id, "gdc_gen_fieldname", "jb_ignore_fav_only", "gdc_content", "1")) ? "checked" : "") .
      ">ignoriere \\\"Nur Anforderungen\\\"";
  array_unshift($cr_id_order_list_temp, array("#",
    ($jb_longhaul != 1 ? "Auftrag Nr. <b>" : "<table border=0><tr><td align=center><b>Auftragsnummer</b></td><td align=center><b>Fahrzeug</b></td><td align=center><b>Filter</b></td><td align=center><b>Kunde</b></td><td align=center><b>Start</b></td><td align=center><b>via</b></td><td align=center><b>Ziel</b></td><td align=center><b>Referenzkilometer</b></td><td align=center><b>Preis</b></td></tr><tr><td align=center valign=top>&nbsp;"
    ) .  "<a href=\\\"javascript:popupWindow('../" . ($userType == 1 ? "admin" : "customer") . "/jb_detail.php?job_id=" . $jb_id . "','Auftrag','scrollbars=yes,width=800,height=500');\\\"><i>$jb_id</i></a></b>" .
    ($jb_longhaul != 1
      ? ",<b>" . $cur_vht_id_str . $cur_jb_totalprice_str . $cur_jb_reserv_str . $cur_jb_cr_filter_str . $cur_jb_cr_filter_opt_str . $cur_jb_weight_str
      : "&nbsp;</td><td align=center valign=top>&nbsp;" . $cur_vht_id_str .
        "&nbsp;</td><td align=center valign=top>&nbsp;" . $cur_jb_cr_filter_str . $cur_jb_cr_filter_opt_str .
        "&nbsp;</td><td align=center valign=top>&nbsp;" . $cur_cmp_str .
        "&nbsp;</td><td align=center valign=top>&nbsp;" . "$ad_street $tr_hsno, $ad_zipcode $ad_city" .
        "&nbsp;</td><td align=center valign=top>&nbsp;" . $via_str .
        "&nbsp;</td><td align=center valign=top>&nbsp;" . "$t_ad_street $t_tr_hsno, $t_ad_zipcode $t_ad_city" . 
        "&nbsp;</td><td align=center valign=top>&nbsp;" . str_replace(".", ",", sprintf("%01.2f", $jb_km)) .
        "&nbsp;</td><td align=center valign=top>&nbsp;" . $cur_jb_totalprice_str .
        "&nbsp;</td></tr></table>"
    ) .
    ($jb_longhaul != 1 ?
      "<br></b>Start: <b>" .
      "$ad_zipcode $ad_city, $ad_street $tr_hsno, " . " $tr_comp" . (trim($tr_person) != "" ? ", $tr_person" : "") .
      "</b>" .
      ($cur_max_tour > 1 ?
        "<br>Ziel:&nbsp;&nbsp; <b>" .
      "$t_ad_zipcode $t_ad_city, $t_ad_street $t_tr_hsno, " . " $t_tr_comp" . (trim($t_tr_person) != "" ? ", $t_tr_person" : "") . $via_str .
        "</b>" : "") : ""
    ) .
   ($userType == 1 ?
    "<table border=0 align=center width=100% cellspacing=0 cellpadding=0 vspace=0 hspace=0><form name=\\\"reset_cr_availabletime_form\\\"><tr>" .
    ($jb_longhaul != 1 ?
      "<td align=left valign=center>(<a href=\\\"javascript:push_autoranking('../admin/push_autoranking.php?jb_id=" . $jb_id . "','Auftrag','resizable=no,scrollbars=no,width=250,height=10')\\\"><i>" . "In automatische Vermittlung einstellen" .
      "</i></a>" . $ignore_fav_only_checkbox . ")" .
      "</td><td align=center valign=center>" : "<td align=left valign=center>") .
      "(<a href=\\\"javascript:push_autoranking('../admin/push_manual.php?jb_id=" . $jb_id . "','Auftrag','resizable=no,scrollbars=no,width=250,height=10')\\\"><i>" . "In manuelle Vermittlung einstellen" .
      "</i></a>)</td><td align=center valign=center>" .
    "<input type=\\\"checkbox\\\" name=\\\"reset_cr_availabletime\\\" value=\\\"1\\\" " . $reset_cr_availabletime_checked . $reset_cr_availabletime_disabled . ">Freimeldezeit von " . $cur_cr_sid . " aktualisieren bei Neuvergabe" . 
    "<input type=\\\"hidden\\\" name=\\\"cur_cr_sid\\\" value=\\\"" . $cur_cr_sid . "\\\">" . 
    "</td><td align=right valign=center>" .
    // Uhrzeit/Aktualisieren
    "Stand: <span style=\\\"color:red\\\">" . date("H:i:s") . "</span> Uhr" .
    "<i><a href=\\\"javascript:reloadMe()\\\">&nbsp;(Aktualisieren)</a></i></td></tr></form></table>" : "")));
endif;

// Alle Kuriere finden, die diesen Auftrag schonmal hatten

$revoked_cr_sids = array();
if (isset($jb_id) && $jb_id != ""):
  $sqlQuery = "SELECT cr_id FROM autoranking WHERE jb_id = '$jb_id'";
//  if (!(isset($jb_id) && $jb_id != "" && isset($zipcode) && $zipcode != "" && $userType == 1)):
//    writeLog_("../log/job_courier_cur_", "[" . $sqlQuery . "]");
//  endif;
  $res = $db2->query($sqlQuery);
  if (DB::isError($res)) reportDie ("$PHP_SELF: '$sqlQuery': " . $res->getMessage());
  while ($row = ($phpVersion >= "8.0" ? $res->fetch_assoc() : $res->fetchRow())):
    $revoked_cr_sids[$row["cr_id"]] = 1;
  endwhile;
  $res->free();
endif;

// Alle Kuriere finden, die KEINE newbies sind... (d.h. erster eledigter Job innerhalb von MASK_COURIER_NEWBIE_TIME Tagen in der Vergangenheit)
// ab 01.12.2010 ausgelagert
//$newbie_date = getdate(mktime(0, 0, 0, date("m"), date("d") - MASK_COURIER_NEWBIE_TIME, date("Y")));
//$newbie_date_sql = $newbie_date['year'] . "-" . sprintf("%02d", $newbie_date['mon']) . "-" . sprintf("%02d", $newbie_date['mday']) . " 23:59:59";
//$newbie_cr_sids = array();
////$sqlQuery = "SELECT cr_id, MIN(jb_ordertime) AS min_jb_ordertime FROM job WHERE jb_status = 2 AND cr_id IS NOT NULL AND cr_id != '' GROUP BY cr_id ORDER BY min_jb_ordertime ASC";
//$sqlQuery = "SELECT DISTINCT cr_id FROM job WHERE jb_status = 2 AND jb_ordertime > '$newbie_date_sql'";
//if (isset($jb_id) && $jb_id != "" && isset($zipcode) && $zipcode != "" && $userType == 1):
//  writeLog_("../log/job_courier_cur_", "$sqlQuery");
//else:
//  writeLog_("../log/job_courier_", "$sqlQuery");
//endif;
//$res = $db2->query($sqlQuery);
//if (DB::isError($res)) reportDie ("$PHP_SELF: '$sqlQuery': " . $res->getMessage());
//while ($row = ($phpVersion >= "8.0" ? $res->fetch_assoc() : $res->fetchRow())):
////  if ($row["min_jb_ordertime"] < $newbie_date_sql)
//    $newbie_cr_sids[$row["cr_id"]] = 1;
////  else
////    break;
//endwhile;
//$res->free();

// Alle laufenden Aufträge laden, damit nicht für jeden Kurier die DB einzeln abgefrägt werden muss

if (isset($jb_id) && $jb_id != "" && isset($zipcode) && $zipcode != "" && $userType == 1):
  writeLog_("../log/job_courier_cur_", "..." . trace_execution_time_stop() . " (" . (isset($jb_id) ? $jb_id : "") . ") nach revoked_cr_sids");
else:
  writeLog_("../log/job_courier_", "..." . trace_execution_time_stop() . " (" . (isset($jb_id) ? $jb_id : "") . ") nach revoked_cr_sids");
endif;

$job_ids_sql = "";
$current_jobs = array();
if ($userType == 1):
  //$sqlQuery = "SELECT jb_id, jb_ordertime, cr_sid, jb_longhaul, hq_id FROM job WHERE jb_status = 0 OR jb_status = 1 ORDER BY cr_sid, jb_id ASC";
  $sqlQuery = "SELECT job.jb_id, jb_ordertime, cr_sid, jb_longhaul, hq_id, jb_tourdata, tr_status FROM job LEFT JOIN tour ON job.jb_id = tour.jb_id WHERE (jb_status = 0 OR jb_status = 1) AND tr_sort = 1 ORDER BY jb_id ASC";
//  if (!(isset($jb_id) && $jb_id != "" && isset($zipcode) && $zipcode != "")):
//    writeLog_("../log/job_courier_", "[" . $sqlQuery . "]");
//  endif;
  $res = $db2->query($sqlQuery);
  if (DB::isError($res)) reportDie ("$PHP_SELF: '$sqlQuery': " . $res->getMessage());
  while ($row = ($phpVersion >= "8.0" ? $res->fetch_assoc() : $res->fetchRow())):
    $current_jobs[$row["cr_sid"]][] = array($row["jb_id"], $row["jb_ordertime"], $row["jb_longhaul"], $row["hq_id"], $row["jb_tourdata"], $row["tr_status"]);
    if ($job_ids_sql != "")
      $job_ids_sql .= ",";
    $job_ids_sql .= "'" . $row["jb_id"] . "'";
  endwhile;
  $res->free();
endif;

if (isset($jb_id) && $jb_id != "" && isset($zipcode) && $zipcode != "" && $userType == 1):
  writeLog_("../log/job_courier_cur_",  "..." . trace_execution_time_stop() . " ($jb_id) nach current_jobs");
else:
  writeLog_("../log/job_courier_",  "..." . trace_execution_time_stop() . " ($jb_id) nach current_jobs");
endif;

$current_tours = array();
if ($job_ids_sql != ""):
  $sqlQuery = "SELECT tour.jb_id, tour.tr_sort, tour.tr_status, address.ad_zipcode FROM tour, address WHERE tour.jb_id IN ($job_ids_sql) AND tour.ad_id = address.ad_id ORDER BY tour.jb_id, tour.tr_sort ASC";
//if (!(isset($jb_id) && $jb_id != "" && isset($zipcode) && $zipcode != "" && $userType == 1)):
//  writeLog_("../log/job_courier_", "[" . $sqlQuery . "]");
//endif;
  $res = $db2->query($sqlQuery);
  if (DB::isError($res)) reportDie ("$PHP_SELF: '$sqlQuery': " . $res->getMessage());
  while ($row = ($phpVersion >= "8.0" ? $res->fetch_assoc() : $res->fetchRow())):
    $current_tours[$row["jb_id"]][] = array($row["tr_sort"], $row["tr_status"], $row["ad_zipcode"]);
  endwhile;
  $res->free();
endif;

if (isset($jb_id) && $jb_id != "" && isset($zipcode) && $zipcode != "" && $userType == 1):
  writeLog_("../log/job_courier_cur_",  "..." . trace_execution_time_stop() . " ($jb_id) nach current_tours");
else:
  writeLog_("../log/job_courier_",  "..." . trace_execution_time_stop() . " ($jb_id) nach current_tours");
endif;

// Im Falle eines Auftrages mit Maßbeschränkungen die Maße der Fahrzeuge holen
$current_measures = array();
if (CONST_RANKING_JB2CRVH_MEASURE == "1" && isset($cur_jb_weight_str) && $cur_jb_weight_str != ""):
  $sqlQuery =
    "SELECT cr.cr_id, crvh.crvh_payload, crvh.crvh_sid, crvh.crvh_height, crvh.crvh_width, crvh.crvh_length, crvh.crvh_position"
      . " FROM courier AS cr, couriervehicle AS crvh"
      . " WHERE "
      . "   cr.hq_id = '" . $hq_id . "' AND"
      . "   crvh.crvh_sid != '' AND"
      . "   cr.cr_id = crvh.cr_id"
      . " ORDER BY crvh.crvh_sid";
//if (!(isset($jb_id) && $jb_id != "" && isset($zipcode) && $zipcode != "" && $userType == 1)):
//  writeLog_("../log/job_courier_cur_", "[" . $sqlQuery . "]");
//endif;
  $res = $db2->query($sqlQuery);
  if (DB::isError($res)) reportDie ("$PHP_SELF: '$sqlQuery'" . $res->getMessage());
  while ($row = ($phpVersion >= "8.0" ? $res->fetch_assoc() : $res->fetchRow())):
/*
    if (trim($row["crvh_payload"]) == "")
      $row["crvh_payload"] = 0;
    if (trim($row["crvh_height"]) == "")
      $row["crvh_height"] = 0;
    if (trim($row["crvh_width"]) == "")
      $row["crvh_width"] = 0;
    if (trim($row["crvh_length"]) == "")
      $row["crvh_length"] = 0;
    if (trim($row["crvh_position"]) == "")
      $row["crvh_position"] = 0;
*/
    $current_measures[$row["crvh_sid"]] = array(
      $row["crvh_payload"],
      $row["crvh_height"],
      $row["crvh_width"],
      $row["crvh_length"],
      $row["crvh_position"]
    );
  endwhile;
  $res->free();
endif;

//if (isset($jb_id) && $jb_id != "" && isset($zipcode) && $zipcode != "" && $userType == 1):
//  writeLog_("../log/job_courier_cur_",  "..." . trace_execution_time_stop() . "($jb_id) nach current_measures");
//else:
//  writeLog_("../log/job_courier_",  "..." . trace_execution_time_stop() . "($jb_id) nach current_measures");
//endif;

// Die verschlüsselten cmp_ids für die Fahreransicht holen
//$companyIds = array();
//$sqlquery =
//  "SELECT cmp.cmp_id, cr.cr_sid"
//  . " FROM company AS cmp, courier AS cr"
//  . " WHERE "
//  . "   cmp.cmp_id = cr.cmp_id AND"
//  . "   cr.hq_id = '" . $hq_id . "' AND"
//  . "   cr.cr_sid != '' AND NOT (cr.cr_sid IS NULL)";
$sqlquery =
  "SELECT cr.cr_id, crvh.crvh_id, crvh.crvh_sid"
  . " FROM courier AS cr, couriervehicle AS crvh"
  . " WHERE "
  . "   crvh.crvh_sid = cr.cr_sid AND"
  . "   cr.hq_id = '" . $hq_id . "' AND"
  . "   cr.cr_sid != '' AND NOT (cr.cr_sid IS NULL)";
//if (!(isset($jb_id) && $jb_id != "" && isset($zipcode) && $zipcode != "" && $userType == 1)):
//  writeLog_("../log/job_courier_", "[" . $sqlQuery . "]");
//endif;
$res = $db2->query($sqlquery);
if (DB::isError($res)) reportDie ("$PHP_SELF: '$sqlquery'" . $res->getMessage());
$i = 0;
while ($row = ($phpVersion >= "8.0" ? $res->fetch_assoc() : $res->fetchRow())):
  $companyIds[$row["crvh_sid"]] = "courierId=" . ec($row["cr_id"]) . "&" . "f_crvh_id=" . ec($row["crvh_id"]);
endwhile;
$res->free();

//if (isset($jb_id) && $jb_id != "" && isset($zipcode) && $zipcode != "" && $userType == 1):
//  writeLog_("../log/job_courier_cur_",  "..." . trace_execution_time_stop() . " ($jb_id) nach $companyIds");
//else:
//  writeLog_("../log/job_courier_",  "..." . trace_execution_time_stop() . " ($jb_id) nach $companyIds");
//endif;

// Jeden Kurier einzeln verarzten
$i01 = 1;
$i1 = 0;
$i02 = 1;
$i2 = 1;
$i3 = 0;
if ($jb_longhaul != 1) {
  $cr_id_order_list0 .= "\"*<tr><td align=left valign=center colspan=10><B>Bevorzugte Kuriere ohne Auftrag</B><\/td><\/tr>" . "\"";
  $cr_id_order_list02 .= "\"*<tr><td align=left valign=center colspan=10><B>Bevorzugte Kuriere mit Auftrag</B><\/td><\/tr>" . "\"";
  $cr_id_order_list2 .= "\"*<tr><td align=left valign=center colspan=10><B>KURIERE MIT AUFTRAG</B><\/td><\/tr>" . "\"";
} else {
  $cr_id_order_list0 .= "\"*<tr><td align=left valign=center colspan=10><b>- bevorzugte</b><\/td><\/tr>" . "\"";
  $cr_id_order_list02 .= "\"*<tr><td align=left valign=center colspan=10><b>- bevorzugte</b><\/td><\/tr>" . "\"";
}
//print_r($cr_id_order_list_temp); die();
if ($jb_longhaul == 1)
  writeLog_("../log/job_courier_cur_", "\$cr_id_order_list_temp2 = " . var_export($cr_id_order_list_temp, true));
$tmp_job_line = "";
if ($cr_id_order_list_temp[0][0] == "#"):
  $tmp_job_line = "#" . $cr_id_order_list_temp[0][1];
  array_shift($cr_id_order_list_temp);
endif;
if ($jb_longhaul == 1)
  writeLog_("../log/job_courier_cur_", "\$cr_id_order_list_temp2 = " . var_export($cr_id_order_list_temp, true));
$is_bevorzugt = false;
if ($jb_longhaul == 1)
  writeLog_("../log/job_courier_cur_", "\$tmp_job_line = " . $tmp_job_line);
$min_jb_cr_price = 0;
$jb_cr_price_tmp = "";
for($i = 0; $i < count($cr_id_order_list_temp); $i++):
  if ($cr_id_order_list_temp[$i][0] == "*"):
    $is_bevorzugt = strpos($cr_id_order_list_temp[$i][1], "bevorzugte") !== false;
  endif;
  if ($cr_id_order_list_temp[$i][0] != "*" && $cr_id_order_list_temp[$i][0] != "#"):
    list($dummy_year, $dummy_month, $dummy_day, $hours, $minutes) =
      getValsFromDate(trim($cr_id_order_list_temp[$i][5]));
    // courierfilter
//    $curFilter = substr(trim($cr_id_order_list_temp[$i][6]), 1, strlen(trim($cr_id_order_list_temp[$i][6])) - 2);
//    if ($curFilter != "")
//      $curFilter = "&nbsp;(" . $curFilter . ")";
    // find jobs of occupied couriers
//    if ($cr_id_order_list_temp[$i][7] == 1):
//    $sqlQuery =
//      "SELECT jb_id, jb_ordertime FROM job WHERE cr_sid = '" . $cr_id_order_list_temp[$i][1] . "' AND (jb_status = 0 OR jb_status = 1 AND (jb_globaljob IS NULL OR jb_globaljob = 0)) ORDER BY jb_id ASC";
//    $sqlQuery =
//      "SELECT jb_id, jb_ordertime FROM job WHERE cr_sid = '" . $cr_id_order_list_temp[$i][1] . "' AND (jb_status = 0 OR jb_status = 1) ORDER BY jb_id ASC";
//    $res = $db2->query($sqlQuery);
//    if (DB::isError($res)) reportDie ("$PHP_SELF: '$sqlQuery'" . $res->getMessage());
    $cr_id_order_list_temp[$i][7] = "";
    $cr_is_occupied = false;
//    while ($row = ($phpVersion >= "8.0" ? $res->fetch_assoc() : $res->fetchRow())):
    if (isset($current_jobs[$cr_id_order_list_temp[$i][1]]) && $current_jobs[$cr_id_order_list_temp[$i][1]] != ""):
      foreach($current_jobs[$cr_id_order_list_temp[$i][1]] as $current_job) {
      $plz_str = "";
//      $max_tr_sort = $db2->getOne("SELECT max(tr_sort) FROM tour WHERE jb_id = '" . $row["jb_id"] . "'");
//echo  "Honk: " . $row["jb_id"] . $max_tr_sort . "<br>\n";
//      for ($j = 1; $j <= $max_tr_sort; $j++):
      if ($current_tours[$current_job[0]] != ""):
        foreach($current_tours[$current_job[0]] as $current_tour) {
//        $ad_zipcode =
//          $db2->getOne("SELECT ad_zipcode FROM address WHERE ad_id = '" .
//            $db2->getOne("SELECT ad_id FROM tour WHERE tr_sort = '" . $j . "' AND jb_id = '" . $row["jb_id"] . "'")
//              . "'");
//        $tr_status =
//          $db2->getOne("SELECT tr_status FROM tour WHERE tr_sort = '" . $j . "' AND jb_id = '" . $row["jb_id"] . "'");
          $cur_zipcode = ($current_tour[1] == "1" ? "<span style=\\\"color:red\\\">" . $current_tour[2] . "</span>" : $current_tour[2]);
          $plz_str .= ($plz_str == "" ? $cur_zipcode : "-&gt;" . $cur_zipcode);
//echo "i:$i<br>\n";
//echo $plz_str;
          }
        endif;
//        endfor;
//        $start_plz =
//          $db2->getOne("SELECT ad_zipcode FROM address WHERE ad_id = '" .
//            $db2->getOne("SELECT ad_id FROM tour WHERE tr_sort = '1' AND jb_id = '" . $row["jb_id"] . "'")
//              . "'");
//        $ziel_plz = "";
//        if ($db2->getOne("SELECT max(tr_sort) FROM tour WHERE jb_id = '" . $row["jb_id"] . "'") > 1):
//          $ziel_plz =
//            $db2->getOne("SELECT ad_zipcode FROM address WHERE ad_id = '" .
//              $db2->getOne("SELECT ad_id FROM tour WHERE tr_sort = '" .
//                $db2->getOne("SELECT max(tr_sort) FROM tour WHERE jb_id = '" . $row["jb_id"] . "'") .
//                  "' AND jb_id = '" . $row["jb_id"] . "'") . "'");
//        endif;
        if ($plz_str != "")
          $plz_str = "&nbsp;(" . $plz_str . ")";
        $curFilter = "";
        $jb_ordertimeStr = "";
//        $jb_ordertime_vals = getValsFromDate($row["jb_ordertime"]);
        $jb_ordertime_vals = getValsFromDate($current_job[1]);
        $today = getdate();
        if ($today['mon'] != $jb_ordertime_vals[1] || $today['mday']  != $jb_ordertime_vals[2]):
          // Kurier hat Auftrag für nachfolgenden Tag aufgenommen, d.h. er gilt nicht als besetzt
          $jb_ordertimeStr = " <span style=\\\"color:green\\\">(" . sprintf("%02d", $jb_ordertime_vals[2]) . "." . sprintf("%02d", $jb_ordertime_vals[1])
            . "., " . sprintf("%02d", $jb_ordertime_vals[3]) . ":" . sprintf("%02d", $jb_ordertime_vals[4]) . ")</span>";
        else:
          // Kurier hat Auftrag für heutigen Tag aufgenommen, gilt erstmal als besetzt
          $row = array();
//          $row["jb_id"] = $current_job[0];
//          $row["jb_ordertime"] = $current_job[1];
//          $job_is_occupied = checkCrIsOccupied($row);
          $job_is_occupied = false;
          if (isset($jb_id) && $jb_id != "")
            $job_is_occupied = checkCrIsOccupied($current_job[0], $jb_id);
          if ($job_is_occupied && $jb_longhaul == 1) {
		    $jb_id_occupied = $current_job[0];
            $plz_string_occupied = $plz_str;
            $cur_zipcode_occupied = $cur_zipcode;
		  }
          if (!$cr_is_occupied)
            $cr_is_occupied = $job_is_occupied;
          // prüfen, ob Auftragsdatum heute in der Zukunft liegt
          if (($jb_ordertime_vals[3] > $today['hours']) || ($jb_ordertime_vals[3] == $today['hours'] && $jb_ordertime_vals[4] > $today['minutes'])):
            // prüfen, ob Vorlaufzeit schon erreicht
            if (!$job_is_occupied):
              $jb_ordertimeStr = " <span style=\\\"color:green\\\">(" . sprintf("%02d", $jb_ordertime_vals[3]) . ":" . sprintf("%02d", $jb_ordertime_vals[4]) . ")</span>";
            endif;
          endif;
        endif;
        if ($cr_id_order_list_temp[$i][7] == ""):
          $cr_id_order_list_temp[$i][7] = "<\/a>, <span style=\\\"color:red\\\">aktueller&nbsp;Auftrag:</span>&nbsp;";
        else:
          $cr_id_order_list_temp[$i][7] .= ", &nbsp;";
        endif;
        // Bei Ferntouren wird der Auftrag anders angezeigt!!!
        if ($current_job[2] != 1):
          $cr_id_order_list_temp[$i][7] .=
            "<a href=\\\"javascript:popupWindow('../admin/jb_detail.php?job_id=" . $current_job[0] . "','Auftrag','scrollbars=yes,width=800,height=500');\\\"><i>" . $current_job[0] . $plz_str . $jb_ordertimeStr . "</i></a>";
        else:
          $hq_name = $db2->getOne("SELECT hq_name FROM headquarters WHERE hq_id = '" . $current_job[3] . "'");
          // bei Ferntouren entscheidet das Mandantenrecht, ob der Auftrag bearbeitet werden kann
          $showLink = false;
          if (authCheckEmployeeRights($emp_id, "10")): $showLink = true; endif;
          $cr_id_order_list_temp[$i][7] .=
            "[FT $hq_name] " .
            ($showLink ? "<a href=\\\"javascript:popupWindow('../admin/jb_detail.php?job_id=" . $current_job[0] . "','Auftrag','scrollbars=yes,width=800,height=500');\\\">" : "") .
            "<i>" . $current_job[0] . $plz_str . $jb_ordertimeStr . "</i>" .
            ($showLink ? "</a>" : "");
        endif;
      }
    endif;
//    endwhile;
//    $res->free();
//    else:
//      $cr_id_order_list_temp[$i][7] = "";
//    endif;
    $plzString = trim($cr_id_order_list_temp[$i][4]);
    if ($plzString == "")
      $plzString = "00000";

//    if ($hq_id == 3)
//      $plzString .= " " . getAreaName($cr_id_order_list_temp[$i][4], 1);

    if ($cr_is_occupied):
      $plzString = "<span style=\\\"color:red\\\">" . $plzString . "</span>";
      $is_occupied[$cr_id_order_list_temp[$i][1]] = 1;
    endif;
    if ($jb_longhaul != 1) {
      $leadingStr = "&nbsp;" . $plzString . ",&nbsp;"  . $hours . ":" . $minutes . "&nbsp;-&nbsp;";
      if (trim($hours) == "")
        $hours = "00";
      if (trim($minutes) == "")
        $minutes = "00";
      // Auftragserfassung: Zusätzlich Datum anzeigen, wenn nicht heute
      if (!(isset($jb_id) && $jb_id != "" && isset($zipcode) && $zipcode != "" && $userType == 1)):
        $leadingStr = "&nbsp;" . $plzString . ",<span style=\\\"color:red\\\">&nbsp;"  . $hours . ":" . $minutes . " (" . sprintf("%02d", $dummy_day) . "." . sprintf("%02d", $dummy_month) . ".)</span>" . "&nbsp;-&nbsp;";
        if ($today['mday'] == $dummy_day && $today['mon'] == $dummy_month && $today['year'] == $dummy_year)
          $leadingStr = "&nbsp;" . $plzString . ",&nbsp;"  . $hours . ":" . $minutes . " (" . sprintf("%02d", $dummy_day) . "." . sprintf("%02d", $dummy_month) . ".)" . "&nbsp;-&nbsp;";
      endif;
    }
    $tmp_cr_sid = trim($cr_id_order_list_temp[$i][1]);
//if (!(isset($jb_id) && $jb_id != "" && isset($zipcode) && $zipcode != "" && $userType == 1)):
//  writeLog_("../log/job_courier_", "\$tmp_cr_sid = " . $tmp_cr_sid);
//endif;
    $jb2crvh_measure_str = "";
    $ranking_jb2crvh_measure_str = "";
    $jb2crvh_measure_weight_str = "";
    $jb2crvh_measure_height_str = "";
    $jb2crvh_measure_width_str = "";
    $jb2crvh_measure_length_str = "";
    $jb2crvh_measure_position_str = "";
    if (CONST_RANKING_JB2CRVH_MEASURE == "1" && isset($cur_jb_weight_str) && $cur_jb_weight_str != ""):
      $jb2crvh_measure_weight_str = $current_measures[$tmp_cr_sid][0] . "kg";
      $jb2crvh_measure_height_str .= "H:" . $current_measures[$tmp_cr_sid][1];
      $jb2crvh_measure_width_str .= "B:" . $current_measures[$tmp_cr_sid][2];
      $jb2crvh_measure_length_str .= "L:" . $current_measures[$tmp_cr_sid][3];
      $jb2crvh_measure_position_str .= "P:" . $current_measures[$tmp_cr_sid][4];
      if ($current_measures[$tmp_cr_sid][0] < $cur_jb_weight):
        $ranking_jb2crvh_measure_str = trim("\\\\\ ") . "nGewicht: " . $current_measures[$tmp_cr_sid][0] . " kg sind weniger als gefordert " . $cur_jb_weight . " kg";
        $jb2crvh_measure_weight_str = "<span style=\\\"color:#FF0000\\\">" . $jb2crvh_measure_weight_str . "<\/span>";
      endif;
      if ($jb2crvh_measure_weight_str != "")
        $jb2crvh_measure_weight_str = ", " . $jb2crvh_measure_weight_str;
      if ($current_measures[$tmp_cr_sid][3] < $cur_jb_length):
        $ranking_jb2crvh_measure_str .= trim("\\\\\ ") . "nLänge: " . $current_measures[$tmp_cr_sid][3] . " cm sind weniger als gefordert " . $cur_jb_length . " cm";
        $jb2crvh_measure_length_str = "<span style=\\\"color:#FF0000\\\">" . $jb2crvh_measure_length_str . "<\/span>";
      endif;
      if ($jb2crvh_measure_length_str != "")
        $jb2crvh_measure_length_str = ",&nbsp;" . $jb2crvh_measure_length_str;
      if ($current_measures[$tmp_cr_sid][2] < $cur_jb_width):
        $ranking_jb2crvh_measure_str .= trim("\\\\\ ") . "nBreite: " . $current_measures[$tmp_cr_sid][2] . " cm sind weniger als gefordert " . $cur_jb_width . " cm";
        $jb2crvh_measure_width_str = "<span style=\\\"color:#FF0000\\\">" . $jb2crvh_measure_width_str . "<\/span>";
      endif;
      if ($jb2crvh_measure_width_str != "")
        $jb2crvh_measure_width_str = ",&nbsp;" . $jb2crvh_measure_width_str;
      if ($current_measures[$tmp_cr_sid][1] < $cur_jb_height):
        $ranking_jb2crvh_measure_str .= trim("\\\\\ ") . "nHöhe: " . $current_measures[$tmp_cr_sid][1] . " cm sind weniger als gefordert " . $cur_jb_height . " cm";
        $jb2crvh_measure_height_str = "<span style=\\\"color:#FF0000\\\">" . $jb2crvh_measure_height_str . "<\/span>";
      endif;
      if ($jb2crvh_measure_height_str != "")
        $jb2crvh_measure_height_str = ",&nbsp;" . $jb2crvh_measure_height_str;
      if ($current_measures[$tmp_cr_sid][4] < $cur_jb_position):
        $ranking_jb2crvh_measure_str .= trim("\\\\\ ") . "nStellplätze: " . $current_measures[$tmp_cr_sid][4] . " ist/sind weniger als gefordert " . $cur_jb_position;
        $jb2crvh_measure_position_str = "<span style=\\\"color:#FF0000\\\">" . $jb2crvh_measure_position_str . "<\/span>";
      endif;
      if ($jb2crvh_measure_position_str != "")
        $jb2crvh_measure_position_str = ",&nbsp;" . $jb2crvh_measure_position_str;
      $jb2crvh_measure_str = $jb2crvh_measure_weight_str . $jb2crvh_measure_length_str . $jb2crvh_measure_width_str . $jb2crvh_measure_height_str . $jb2crvh_measure_position_str;
      if ($jb2crvh_measure_str != "")
        $jb2crvh_measure_str = " (" . substr($jb2crvh_measure_str, 2) . ")";
    endif;
    $tmpCompanyIdStr = "";
    if (isset($companyIds[$tmp_cr_sid]))
      $tmpCompanyIdStr = 
        "\"" . $companyIds[$tmp_cr_sid] . "\"";    
    
    if (isset($revoked_cr_sids[trim($cr_id_order_list_temp[$i][0])]) && $revoked_cr_sids[trim($cr_id_order_list_temp[$i][0])] == 1):
      $tmp_cr_sid = "<span style=\\\"color:#FF0000\\\">" . $tmp_cr_sid . "<\/span>";
    elseif (isset($newbie_cr_sids[trim($cr_id_order_list_temp[$i][0])]) && $newbie_cr_sids[trim($cr_id_order_list_temp[$i][0])] != 1):
      $tmp_cr_sid = "<span style=\\\"color:#9999FF\\\">" . $tmp_cr_sid . "<\/span>";
    endif;

    if ($jb_longhaul != 1) {
      $tmpCourierStr =
        "\"" . $leadingStr .
        "<i><b>" . $tmp_cr_sid . "</b>, " . trim($cr_id_order_list_temp[$i][3]) . $jb2crvh_measure_str .
        "<i>" . (isset($curFilter) ? $curFilter : "") . "</i>" . $cr_id_order_list_temp[$i][7] . "\"";
    } else {
      $is_blocked = false;
      foreach($cr_id_order_list_blocked as $cr_id_blocked) {
        if ($cr_id_blocked[0] == $cr_id_order_list_temp[$i][0]) {
          $is_blocked = true;
          break;
        }
      }
      if (!$is_blocked) {
        $is_desiredzipcode = true;
        list($cur_cr_homezipcode) =
          getFieldsValueFromId("courier", "cr_id", $cr_id_order_list_temp[$i][0], array("cr_desiredzipcode"));
        if (trim($cur_cr_homezipcode) == "") {
          list($cur_cr_homezipcode) =
            getFieldsValueFromId("courier", "cr_id", $cr_id_order_list_temp[$i][0], array("cr_homezipcode"));
          $is_desiredzipcode = false;
        }
        if (trim($cur_cr_homezipcode) == "")
          $cur_cr_homezipcode = $db2->getOne("SELECT ad_zipcode FROM courier, company, address WHERE courier.cmp_id = company.cmp_id AND company.ad_id = address.ad_id AND cr_id = " . $cr_id_order_list_temp[$i][0]);
////echo $cur_cr_homezipcode . "<br>";
//        $home_coords = get_coords("DE", $cur_cr_homezipcode, ".", ".", ".", true);
////print_r($home_coords) . "<br><br>";
        // $ad_country ist noch nicht sauber!
//        $cr_gps_lat = $cr_id_order_list_temp[$i][9];
//        $cr_gps_long = $cr_id_order_list_temp[$i][10];
        $home_coords =
          getFieldsValueFromId("courier", "cr_id", $cr_id_order_list_temp[$i][0], array("cr_gps_lat_home", "cr_gps_long_home"));
        list($cr_gps_long, $cr_gps_lat) =
          getFieldsValueFromId("courier", "cr_id", $cr_id_order_list_temp[$i][0], array("cr_gps_long", "cr_gps_lat"));
        if (!$cr_is_occupied) {
          $starting_gps_lat = $cr_gps_lat;
          $starting_gps_long = $cr_gps_long;
//          $dest_coords = $zipcodeArr;
          $force_date = '0000-00-00 00:00:00';
writeLog_("../log/job_courier_cur_", "get_distance_google(array($cr_gps_lat, $cr_gps_long), array(" . $zipcodeArr[0] . ", " . $zipcodeArr[1] . "), $force_date, \"km\", true)");
          $starting_sec = get_distance_google(array($cr_gps_lat, $cr_gps_long), $zipcodeArr, $force_date, "km", true);
          $starting_min = round($starting_sec / 60);
writeLog_("../log/job_courier_cur_", "\$starting_sec = $starting_sec, \$starting_min = $starting_min");
writeLog_("../log/job_courier_cur_", "get_distance_google(array($cr_gps_lat, $cr_gps_long), array(" . $zipcodeArr[0] . ", " . $zipcodeArr[1] . "), $force_date, \"km\")");
          $starting_m = get_distance_google(array($cr_gps_lat, $cr_gps_long), $zipcodeArr, $force_date, "km");
          $starting_km = round($starting_m / 1000);
writeLog_("../log/job_courier_cur_", "\$starting_km = $starting_km");
          $ending_m = get_distance_google($home_coords, $zipcodeArrEnd, $force_date, "km");
          $ending_km = round($ending_m / 1000);
writeLog_("../log/job_courier_cur_", "\$ending_km = $ending_km");
        } else {
          $ad_id_jb_id_occupied_end = $db->getOne("SELECT ad_id FROM tour WHERE jb_id = " . $jb_id_occupied . " AND tr_sort = " . count($current_tours[$jb_id_occupied]));
          $tr_hsno_jb_id_occupied_end = $db->getOne("SELECT tr_hsno FROM tour WHERE jb_id = " . $jb_id_occupied . " AND tr_sort = " . count($current_tours[$jb_id_occupied]));
          list($ad_country_jb_id_occupied_end, $ad_zipcode_jb_id_occupied_end, $ad_city_jb_id_occupied_end, $ad_street_jb_id_occupied_end) =
            getFieldsValueFromId("address", "ad_id", $ad_id_jb_id_occupied_end, array("ad_country", "ad_zipcode", "ad_city", "ad_street"));
          $coords_jb_id_occupied_end = get_coords($ad_country_jb_id_occupied_end, $ad_zipcode_jb_id_occupied_end, $ad_city_jb_id_occupied_end, $ad_street_jb_id_occupied_end, $tr_hsno_jb_id_occupied_end);
          $starting_gps_lat = $coords_jb_id_occupied_end[0];
          $starting_gps_long = $coords_jb_id_occupied_end[1];
		}
//        $starting_min = $cr_id_order_list_temp[$i][11];
//        $starting_m = $cr_id_order_list_temp[$i][12];
//        $starting_km = round($starting_m / 1000);
//writeLog_("../log/job_courier_cur_", $tmp_cr_sid . ", " . $cr_gps_lat . ", " . $cr_gps_long);
        $current_locationArr = get_address($cr_gps_lat, $cr_gps_long);
        $current_location = (($current_locationArr[1] != "DE" && $current_locationArr[1] != "D") ? $current_locationArr[1] . "-" : "") . $current_locationArr[2] . " " . $current_locationArr[3] . ", " . $current_locationArr[4] . " " . $current_locationArr[5];
writeLog_("../log/job_courier_cur_", "get_job_distance($jb_id, \"km\", 0, $starting_gps_lat, $starting_gps_long, " . $home_coords[0] . ", " . $home_coords[1] . ")");
        $round_kms = get_job_distance($jb_id, "km", 0, $starting_gps_lat, $starting_gps_long, $home_coords[0], $home_coords[1]);
        $round_km = round($round_kms[0]);
writeLog_("../log/job_courier_cur_", "\$round_km = $round_km");
//        $jb_cr_price = $db2->getOne("SELECT jb_cr_price FROM job WHERE jb_id = " . $jb_id);
        $jbprc_cr_subtotal = (float) $db->getOne("SELECT jbprc_price FROM jobprice WHERE jb_id = " . $jb_id . " AND mt_sort = 10");
        $jb_cr_serviceprice = (float) $db->getOne("SELECT jbprc_price FROM jobprice WHERE jb_id = " . $jb_id . " AND mt_sort = 3");
        $jbprc_cr_subtotal -= $jb_cr_serviceprice;
        list($jb_cr_price, $jb_cr_price_sub, $cr_price_longhaul_rund, $cr_price_longhaul_last, $jb_cr_price_one_way, $jb_cr_price_one_way_sub, $basic_cr_price, $cr_price_per_km_rund, $cr_price_per_km_last, $cr_fuel_markup) =
          get_cr_price_longhaul($cr_id_order_list_temp[$i][0], $cur_cs_id, $cur_vht_id_job, $jb_km, $round_km, $starting_m, $jb_km_unrounded, $cur_jb_ordertime, $hq_id_dispo, $jbprc_cr_subtotal);
        if (getParameterValue("0", "BWV_CR_PRICE_RETOUR", "0") != "1") {
          $jb_cr_price_one_way = $jb_cr_price;
          $jb_cr_price_one_way_sub = $jb_cr_price_sub;
        }
        if ($jb_cr_price_tmp == "")
          $jb_cr_price_tmp = date("Y-m-d H:i:s") . "\n";
        $jb_cr_price_tmp .=
          "\$cr_id=" . $cr_id_order_list_temp[$i][0] . "|" .
          "\$cr_sid=" . trim($cr_id_order_list_temp[$i][1]) . "|" .
          "\$cr_vehicle=" . $cr_id_order_list_temp[$i][3] . "|" .
          "\$cr_is_occupied=" . $cr_is_occupied . "|" .
          (!$cr_is_occupied ? "\$starting_min=" . $starting_min : "\$jb_id_occupied=" . $jb_id_occupied) . "|" .
          (!$cr_is_occupied ? "\$starting_km=" . $starting_km : "\$cur_zipcode_occupied=" . $cur_zipcode_occupied) . "|" .
          (!$cr_is_occupied ? "\$ending_km=" . $ending_km . "|" : "") .
          "\$cr_gps_lat=" . $cr_gps_lat . "|" .
          "\$cr_gps_long=" . $cr_gps_long . "|" .
          "\$current_location=" . $current_location . "|" .
          "\$cr_homezipcode=" . $cur_cr_homezipcode . "|" .
          "\$is_desiredzipcode=" . $is_desiredzipcode . "|" .
          "\$home_gps_lat=" . $home_coords[0] . "|" .
          "\$home_gps_long=" . $home_coords[1] . "|" .
          "\$round_km=" . $round_km . "|" .
          "\$jb_cr_price=" . $jb_cr_price . "|" .
          "\$starting_gps_lat=" . $starting_gps_lat . "|" .
          "\$starting_gps_long=" . $starting_gps_long . "|" .
//          "\$hq_id=" . $hq_id . "|" .
//          "\$cs_id=" . $cur_cs_id . "|" .
//          "\$vht_id_job=" . $cur_vht_id_job . "|" .
//          "\$jb_km=" . $jb_km . "|" .
          "\$starting_m=" . (!$cr_is_occupied ? $starting_m : 0) . "|" .
//          "\$jb_km_unrounded=" . $jb_km_unrounded . "|" .
//          "\$cur_jb_ordertime=" . $cur_jb_ordertime . "|" .
          "\$jb_cr_price_sub=" . $jb_cr_price_sub . "|" .
          "\$cr_price_longhaul_rund=" . $cr_price_longhaul_rund . "|" .
          "\$cr_price_longhaul_last=" . $cr_price_longhaul_last . "|" .
          "\$jb_cr_price_one_way=" . $jb_cr_price_one_way . "|" .
          "\$basic_cr_price=" . $basic_cr_price . "|" .
          "\$cr_price_per_km_rund=" . $cr_price_per_km_rund . "|" .
          "\$cr_price_per_km_last=" . $cr_price_per_km_last . "|" .
          "\$cr_fuel_markup=" . $cr_fuel_markup .
          "`\n";
        $jb_cr_price_text = mk_jb_cr_price_text(
          array(
            "\$cr_sid" => trim($cr_id_order_list_temp[$i][1]),
            "\$cr_vehicle" => $cr_id_order_list_temp[$i][3],
            "\$current_location" => $current_location,
            "\$cr_gps_lat" => $cr_gps_lat,
            "\$cr_gps_long" => $cr_gps_long,
            "\$cr_is_occupied" => $cr_is_occupied,
            "\$starting_min" => $starting_min,
            "\$jb_id_occupied" => isset($jb_id_occupied) ? $jb_id_occupied : "",
            "\$starting_km" => $starting_km,
            "\$ending_km" => isset($ending_km) ? $ending_km : "",
            "\$cur_zipcode_occupied" => isset($cur_zipcode_occupied) ? $cur_zipcode_occupied : "",
            "\$cr_homezipcode" => $cur_cr_homezipcode,
            "\$is_desiredzipcode" => $is_desiredzipcode,
            "\$home_gps_lat" => $home_coords[0],
            "\$home_gps_long" => $home_coords[1],
            "\$jb_cr_price" => $jb_cr_price,
            "\$cr_fuel_markup" => $cr_fuel_markup,
            "\$basic_cr_price" => $basic_cr_price,
            "\$starting_m" => $starting_m,
            "\$cr_price_per_km_rund" => $cr_price_per_km_rund,
            "\$jb_cr_price_one_way" => $jb_cr_price_one_way,
            "\$round_km" => $round_km,
            "\$cr_price_per_km_rund" => $cr_price_per_km_rund,
            "\$basic_cr_price" => $basic_cr_price,
            "\$cr_price_longhaul_rund" => $cr_price_longhaul_rund,
            "\$cr_price_per_km_last" => $cr_price_per_km_last,
            "\$cr_price_longhaul_last" => $cr_price_longhaul_last),
          $jb_id, date("Y-m-d H:i:s"), $jb_km_unrounded);
        if ($min_jb_cr_price == 0 || $jb_cr_price < $min_jb_cr_price)
          $min_jb_cr_price = $jb_cr_price;
        if ($is_desiredzipcode)
          $cur_cr_homezipcode = "<i>" . $cur_cr_homezipcode . "</i>";
        $tmpCourierStr =
          "\"" . "&nbsp;<i><b>" . $tmp_cr_sid . "</b> " . "&nbsp;</td>" .
          "<td align=center valign=top> <div title=\\\"" . str_replace("\n", "\\n", $jb_cr_price_text) . "\\\">" . str_replace(".", ",", sprintf("%01.2f", $jb_cr_price)) . "</div>" .
          "<td align=center valign=top>" . (!$cr_is_occupied ? $starting_min : $cur_zipcode_occupied) . "</td>" . 
          "<td align=center valign=top>" . (!$cr_is_occupied ? $starting_km : "<a href=\\\"javascript:popupWindow('../admin/jb_detail.php?job_id=" . $jb_id_occupied . "','Auftrag','scrollbars=yes,width=800,height=500');\\\"><i>" . $plz_string_occupied . "</i></a>") . "</td>" .
          "<td align=center valign=top>" . $current_location . "</td>" .
          "<td align=center valign=top>" . $cur_cr_homezipcode . "</td>" .
          "<td align=center valign=top>" . $round_km . "</td>" .
          "<td align=center valign=top>" . trim($cr_id_order_list_temp[$i][3]) . $jb2crvh_measure_str . "</td>" .
          "<input type=\\\"hidden\\\" name=\\\"vht_id_" . $i . "\\\" value=\\\"" . $vehicletype_ids[$cr_id_order_list_temp[$i][3]] . "\\\"></td>" .
          "<input type=\\\"hidden\\\" name=\\\"jb_cr_price_one_way_" . $i . "\\\" value=\\\"" . $jb_cr_price_one_way . "\\\">" .
          "<input type=\\\"hidden\\\" name=\\\"jb_cr_price_one_way_sub_" . $i . "\\\" value=\\\"" . $jb_cr_price_one_way_sub . "\\\">" .
          "<input type=\\\"hidden\\\" name=\\\"cr_fuel_markup_" . $i . "\\\" value=\\\"" . $cr_fuel_markup . "\\\">" .
          "</td><td>&nbsp;\"";
//          "|" . $cr_id_order_list_temp[$i][7] . "\"";
//      $tmpCourierStr =
//        "\"" . trim($cr_id_order_list_temp[$i][3]) .
//        "" . "Anfahrt min." . 
//        "" . "KM zur Start-PLZ" .
//        "" . "Standort" .
//        "" . "Heimat-PLZ" .
//        "" . "Rundkilometer" .
//        "" . "Fuhrlohn" . "\"";
//        "" . $cr_id_order_list_temp[$i][7] . "\"";
//$tmp_cr_sid .$jb2crvh_measure_str . $curFilter
      } else {
        $tmpCourierStr =
          "\"" . "&nbsp;<i><b>" . $tmp_cr_sid . "</b> " . "&nbsp;</td><td align=center valign=top>" . trim($cr_id_order_list_temp[$i][3]) . "</td>" .
          "<td align=center valign=top>" . "&nbsp;" . "</td>" . 
          "<td align=center valign=top>" . "&nbsp;" . "</td>" .
          "<td align=center valign=top>" . "&nbsp;" . "</td>" .
          "<td align=center valign=top>" . "&nbsp;" . "</td>" .
          "<td align=center valign=top>" . "&nbsp;" . "</td>" .
          "<td align=center valign=top>" . "&nbsp;" . "</td><td>&nbsp;\"";
	  }
    }
// BWV:
// Kuriere ohne Auftrag
// Fahrzeug		Anfahrt min.	KM zur Start-PLZ	Standort	Heimat-PLZ	Rundkilometer	Fuhrlohn
// Kuriere mit Auftrag
// Fahrzeug		Ziel-PLZ		aktuelle Tour		Standort	Heimat-PLZ	Rundkilometer	Fuhrlohn

    // Wenn CONST_MASK_COURIER_SORT_BY_OCCUPIED gesetzt, dann müssen die Kuriere nach occupied-status sortiert werden
    if (CONST_MASK_COURIER_SORT_BY_OCCUPIED == "1"):
      if ($cr_is_occupied != true || !(isset($jb_id) && $jb_id != "" && isset($zipcode) && $zipcode != "" && $userType == 1)):
        if ($is_bevorzugt):
          if ($i01++ > 0) $cr_id_order_list0 .= ",\n"; if ($i3++ > 0) $companyIds_js .= ",\n";
          $cr_id_order_list0 .= /* "cr_id_order_list0[" . $i01++ . "] = " . */ $tmpCourierStr;
          $companyIds_js .= $tmpCompanyIdStr;
        else:
          if ($i1++ > 0) $cr_id_order_list .= ",\n"; if ($i3++ > 0) $companyIds_js .= ",\n";
          $cr_id_order_list .= /* "cr_id_order_list[" . $i1++ . "] = " . */ $tmpCourierStr;
          $companyIds_js .= $tmpCompanyIdStr;
        endif;
      else:
        if ($is_bevorzugt):
          if ($i02++ > 0) $cr_id_order_list02 .= ",\n"; if ($i3++ > 0) $companyIds_js .= ",\n";
          $cr_id_order_list02 .= /* "cr_id_order_list92[" . $i02++ . "] = " . */ $tmpCourierStr;
          $companyIds_js .= $tmpCompanyIdStr;
        else:
          if ($i2++ > 0) $cr_id_order_list2 .= ",\n"; if ($i3++ > 0) $companyIds_js .= ",\n";
          $cr_id_order_list2 .= /* "cr_id_order_list2[" . $i2++ . "] = " . */ $tmpCourierStr;
          $companyIds_js .= $tmpCompanyIdStr;
        endif;
      endif;
    else:
      if ($i1++ > 0) $cr_id_order_list .= ",\n"; if ($i3++ > 0) $companyIds_js .= ",\n";
      $cr_id_order_list .= /* "cr_id_order_list[" . $i1++ . "] = " . */ $tmpCourierStr;
      $companyIds_js .= $tmpCompanyIdStr;
    endif;
    // Abgleich der Fahrzeugtypen Kurier/Auftrag
    $vht_id_str = "";
    if (isset($jb_id) && $jb_id != "") {
//      $assignStatusGPS = "";
      $locatingStateArray = array("","0","0");
      $locatingStatus = 0;
      if (getPDALocatingStatus($hq_id) == "1" && is_numeric($cr_id_order_list_temp[$i][4])) :
        $locatingStateArray = checkLocatingState($cr_id_order_list_temp[$i][0]);
        if ($locatingStateArray[3] == "9") :
//          $doAssignRegardingLocating = false;  // Locating disabled by courier
          $vht_id_str .=  "\\\\n" . "\\\\n" . "ACHTUNG: GPS auf dem Gerät ist deaktiviert, eine Überprüfung der Freimeldung ist nicht möglich!";
        elseif ($locatingStateArray[0] == "0" || $locatingStateArray[0] == "") :
          // Coordinates do exist => check for ranking zipcode of the courier
//          writeLog_("../log/job_courier_cur_", "checkRanking(" . $cr_id_order_list_temp[$i][0]. ", " .$locatingStateArray[1]. ", " .$locatingStateArray[2]. ", " .$locatingStateArray[3]. ", " .$locatingStateArray[4]. ", " .$locatingStateArray[5]. ", " .$jb_id. ", " .$hq_id. ", " .$cr_id_order_list_temp[$i][1]. ", " .$ori_zipcode . ", false)");
          $locatingStatus = checkRanking($cr_id_order_list_temp[$i][0], $locatingStateArray[1], $locatingStateArray[2], $locatingStateArray[3], $locatingStateArray[4], $locatingStateArray[5], $jb_id, $hq_id, $cr_id_order_list_temp[$i][1], $ori_zipcode, false);
          if ($locatingStatus == "1") :
//             $doAssignRegardingLocating = false;
            $vht_id_str .=  "\\\\n" . "\\\\n" . "ACHTUNG: Die Freimeldung des Kuriers in " . $db->getOne("SELECT cr_locationzipcode FROM courier WHERE cr_id = " . $cr_id_order_list_temp[$i][0]) . " war laut Ortung fehlerhaft, er befindet sich in " . findZipcodeArea($locatingStateArray[1], $locatingStateArray[2]) . ".";
          endif;
          if ($locatingStatus == "") : $locatingStatus = "1"; endif;
        else:
//          $assignStatusGPS = "|LOCOLD=YES";
          $vht_id_str .=  "\\\\n" . "\\\\n" . "ACHTUNG: Die Freimeldung des Kuriers in " . $db->getOne("SELECT cr_locationzipcode FROM courier WHERE cr_id = " . $cr_id_order_list_temp[$i][0]) . " lässt sich nicht überprüfen, da die letzte Ortung veraltet ist (" . findZipcodeArea($locatingStateArray[1], $locatingStateArray[2]) . " am " . str_replace("&nbsp;", " um ", my_datum_zeit_format_datetime($locatingStateArray[4])) . " Uhr).";
        endif;
      endif;
//      writeLog_("../log/job_courier_cur_", getPDALocatingStatus($hq_id) . ": " . $cr_id_order_list_temp[$i][1]. ", " . $locatingStatus . ", " . $locatingStateArray[0]);
//      if ($vht_id_str != ""):
//        writeLog_("../log/job_courier_cur_", "locating check: " . $jb_id . ", " . $cr_id_order_list_temp[$i][1] . ", " . $vht_id_str);
////        writeLog_("../log/job_courier_cur_", var_export($cr_id_order_list_temp[$i], true));
////        $vht_id_str = "";
//      endif;
      if (!check_third_country($jb_id, $cr_id_order_list_temp[$i][0])) {
      $vht_id_str = "\\\\n" . "\\\\n" . "*** Dieses Fahrzeug darf aufgrund der fehlenden EG-Lizenz und des zulässigen Gesamtgewichts nicht für Auslandseinsätze verplant werden. ***";
//      $cur_vht_id_job = $db2->getOne("SELECT vht_id FROM job WHERE jb_id = '" . $jb_id . "'");
//      $cur_vht_id_value_job = $db2->getOne("SELECT mt_value FROM metatype WHERE mt_sort = " . $cur_vht_id_job . " AND mt_type = 'vehicletype'");
//      $cur_vht_id_courier = $db2->getOne("SELECT mt_sort FROM metatype WHERE mt_value = '" . $cr_id_order_list_temp[$i][3] . "' AND mt_type = 'vehicletype'");
        writeLog_("../log/job_courier_cur_", "check_third_country (" . $jb_id . ", " . $cr_id_order_list_temp[$i][0] . ") results to false");
      }
    }
    $cur_vht_id_courier = $vehicletype_ids[$cr_id_order_list_temp[$i][3]];
//writeLog_("../log/job_courier_cur_", "\$vehicletype_ids = " . json_encode($vehicletype_ids));
    if (isset($cur_vht_id_job) && $cur_vht_id_job > $cur_vht_id_courier) {
      $vht_id_str .=  "\\\\n" . "\\\\n" . "ACHTUNG: Fahrzeug passt nicht! (Angefordert: " . $cur_vht_id_value_job . ", zuweisen: " . $cr_id_order_list_temp[$i][3] . ")";
//writeLog_("../log/job_courier_cur_", "\$cur_vht_id_job = $cur_vht_id_job, \$cur_vht_id_courier = $cur_vht_id_courier (\$vehicletype_ids[$cr_id_order_list_temp[$i][3]] = " . $vehicletype_ids[$cr_id_order_list_temp[$i][3]] . "), \$cur_vht_id_value_job = $cur_vht_id_value_job, \$missing_filters = " . $missing_filters);
    } elseif (isset($cur_vht_id_job) && $cur_vht_id_job < $cur_vht_id_courier) {
      $vht_id_str .=  "\\\\n" . "\\\\n" . "(Fahrzeug angefordert: " . $cur_vht_id_value_job . ", zuweisen: " . $cr_id_order_list_temp[$i][3] . ")";
    }
    $cr_id_order_list_temp[$i][6] = str_replace(',,', ',', str_replace(',,,', ',,', $cr_id_order_list_temp[$i][6] . "," . $db->getOne("SELECT cr_filter FROM courier WHERE cr_id = " . $cr_id_order_list_temp[$i][0])));

    $mandatory_filters = trim(getParameterValue("0", "MASK_MANDATORY_FILTERS", $hq_id));
    if ($mandatory_filters != ''):
      $mandatory_filtersArr = explode(",", $mandatory_filters);
      $mandatory_filters_text = $db->getOne("SELECT par_text FROM parameter WHERE hq_id = " . $hq_id . " AND par_key = 'MASK_MANDATORY_FILTERS'");
      $mandatory_filters_textArr = explode(",", $mandatory_filters_text);
    endif;

    $missing_filters = "";
    $warning_text = "Filterbedingung nicht erfüllt!";
    if (isset($cur_jb_cr_filter) && trim($cur_jb_cr_filter) != "") {
      $tmpArray = split(",", $cur_jb_cr_filter);
      for ($ii = 0; $ii < count($tmpArray); $ii++):
        if ((strpos ($cr_id_order_list_temp[$i][6], trim($tmpArray[$ii])) === false)) {
          $missing_filters .= ", " . trim($tmpArray[$ii]);
          if (!($key = array_search(trim($tmpArray[$ii]), $mandatory_filtersArr) === false))
            $warning_text = $mandatory_filters_textArr[$key];
        }
      endfor;
    }
//    writeLog_("../log/job_courier_cur_", "\$cur_jb_cr_filter = $cur_jb_cr_filter, \$missing_filters = " . $missing_filters);
    if (isset($cur_jb_cr_filter_opt) && trim($cur_jb_cr_filter_opt) != "") {
      $tmpArray = split(",", $cur_jb_cr_filter_opt);
      for ($ii = 0; $ii < count($tmpArray); $ii++):
        if ((strpos ($cr_id_order_list_temp[$i][6], trim($tmpArray[$ii])) === false))
          $missing_filters .= ", " . trim($tmpArray[$ii]) . " opt.";
      endfor;
    }

    if ($missing_filters != "")
      $vht_id_str .= trim("\\\\\ ") . trim("n\\\\\ ") . "nACHTUNG: " . $warning_text . " (" . substr($missing_filters, 2) . ")";

    if ($ranking_jb2crvh_measure_str != "")
      $vht_id_str .= trim("\\\\\ ") . trim("n\\\\\ ") . "nACHTUNG: Fahrzeugmaße passen nicht! " . trim("\\\\\ ") . trim("n") . $ranking_jb2crvh_measure_str;
    if ($vht_id_str != "")
//      $vht_id_str_js .= "vht_id_str[] = " . "new Array(\"" . $cr_id_order_list_temp[$i][1] . "\", \"" . $vht_id_str . "\");\n";
//    else
//      $vht_id_str_js .= "vht_id_str[] = " . "new Array(\"" . $cr_id_order_list_temp[$i][1] . "\", \"\");\n";
      $vht_id_str_js .= "vht_id_str[\"" . $cr_id_order_list_temp[$i][1] . "\"] = \"" . $vht_id_str . "\";\n";
    else
      $vht_id_str_js .= "vht_id_str[\"" . $cr_id_order_list_temp[$i][1] . "\"] = \"\";\n";
  else:
    if ($i1++ > 0) $cr_id_order_list .= ",\n";
    $cr_id_order_list .= "\"" . trim($cr_id_order_list_temp[$i][0]) . trim($cr_id_order_list_temp[$i][1]) . "\"";
    if (CONST_MASK_COURIER_SORT_BY_OCCUPIED == "1" && $cr_id_order_list_temp[$i][0] != "#" && trim($cr_id_order_list_temp[$i][1]) != "<tr><td align=left valign=center colspan=10><B>KURIERE OHNE AUFTRAG</B><\/td><\/tr>"):
      if ($i2++ > 0) $cr_id_order_list2 .= ",\n";
      $cr_id_order_list2 .= "\"" . trim($cr_id_order_list_temp[$i][0]) . trim($cr_id_order_list_temp[$i][1]) . "\"";
    endif;
  endif;
endfor;

if ($jb_longhaul == 1) {
  writeLog_("../log/job_courier_cur_", "\$cr_id_order_list_temp3 = " . var_export($cr_id_order_list_temp, true));
  writeLog_("../log/job_courier_cur_", "\$jb_cr_price_tmp = " . $jb_cr_price_tmp);
}

if ($jb_cr_price_tmp != "") {
  deleteStmt("genericdatacontainer", "gdc_obj_type = 'jb' AND gdc_obj_id = " . $jb_id . " AND gdc_gen_fieldname = 'jb_cr_price_tmp'");
  insertStmt("genericdatacontainer", array("gdc_obj_type", "jb", "gdc_obj_id", $jb_id, "gdc_gen_fieldname", "jb_cr_price_tmp", "gdc_content", $jb_cr_price_tmp, "gdc_context", ""));
}
if ($jb_longhaul == 1) {
  writeLog_("../log/job_courier_cur_", "\$min_jb_cr_price = " . $min_jb_cr_price);
  writeLog_("../log/job_courier_cur_", "\$cr_id_order_list = " . $cr_id_order_list);
}
$cr_id_order_list = str_replace("<td align=center valign=top>" . str_replace(".", ",", sprintf("%01.2f", $min_jb_cr_price)) . "<input type=\\\"hidden\\\" name=\\\"jb_cr_price_one_way_",
 "<td align=center valign=top>" . "<span style=\\\"color:red\\\">" . str_replace(".", ",", sprintf("%01.2f", $min_jb_cr_price)) . "</span>" . "<input type=\\\"hidden\\\" name=\\\"jb_cr_price_one_way_",
  $cr_id_order_list);
if ($jb_longhaul == 1)
  writeLog_("../log/job_courier_cur_", "\$cr_id_order_list = " . $cr_id_order_list);
$cr_id_order_list2 = str_replace("<td align=center valign=top>" . str_replace(".", ",", sprintf("%01.2f", $min_jb_cr_price)) . "<input type=\\\"hidden\\\" name=\\\"jb_cr_price_one_way_",
 "<td align=center valign=top>" . "<span style=\\\"color:red\\\">" . str_replace(".", ",", sprintf("%01.2f", $min_jb_cr_price)) . "</span>" . "<input type=\\\"hidden\\\" name=\\\"jb_cr_price_one_way_",
  $cr_id_order_list2);

if ($hq_workmode != "2" || $hq_id == 1):
//  $hq_distancecalc = getFieldValueFromId("headquarters", "hq_id", "$hq_id", "hq_distancecalc");
//  if ($hq_workmode == "1" && $hq_distancecalc == "1"):
//    $res = $db2->query("SELECT cr.cr_sid, cr.cr_locationzipcode, cr.cr_availabletime, srvp.srvp_latitude, srvp.srvp_longitude, cr.cr_occupied, mt.mt_value" .
//      " FROM courier AS cr, serviceplz AS srvp, couriervehicle AS crvh, metatype AS mt" .
//      " WHERE cr.hq_id = '$hq_id' AND" .
//      "       cr.cr_locationzipcode = srvp.srvp_plz AND" .
//      "       cr.cr_available = 1 AND" .
//      "       cr.cr_id = crvh.cr_id              AND" .
//      "       cr.cr_sid = crvh.crvh_sid          AND" .
//      "       crvh.vht_id = mt.mt_sort           AND" .
//      "       mt.mt_type = 'vehicletype'            " .
//     " ORDER BY cr.cr_locationzipcode ASC, cr.cr_availabletime ASC");
//  elseif ($hq_workmode == "1" || $hq_workmode == "0" || $hq_id == 1):
//    $res = $db2->query("SELECT cr.cr_sid, cr.cr_locationzipcode, cr.cr_availabletime, cr.cr_occupied, mt.mt_value" .
//      " FROM courier AS cr, couriervehicle AS crvh, metatype AS mt" .
//      " WHERE cr.hq_id = '$hq_id' AND" .
//      "       cr.cr_available = 1 AND" .
//      "       cr.cr_id = crvh.cr_id              AND" .
//      "       cr.cr_sid = crvh.crvh_sid          AND" .
//      "       crvh.vht_id = mt.mt_sort           AND" .
//      "       mt.mt_type = 'vehicletype'            " .
//      " ORDER BY cr.cr_locationzipcode ASC, cr.cr_availabletime ASC");
//  endif;
//  if (DB::isError($res))
//    reportDie ("$PHP_SELF: 'SELECT cr_sid ...' :" . $res->getMessage());
//  $plz_geo_list = array();
//  $i = 0;
//  while ($row = ($phpVersion >= "8.0" ? $res->fetch_assoc() : $res->fetchRow())):
//    // Kuriere einsammeln
//    if ($hq_workmode == "1" || $hq_id == 1):
//      list($dummy_year, $dummy_month, $dummy_day, $hours, $minutes) =
//        getValsFromDate($row["cr_availabletime"]);
//      $cr_occupied_sign = ($row["cr_occupied"] > 0) ? "*" : "";
//      $cr_id_order_list .= "cr_id_order_list[" . $i++ . "] = \"" . trim($row["cr_sid"]) . "&nbsp;-&nbsp;" . trim($row["mt_value"]) .
//        $cr_occupied_sign . "&nbsp;(" . trim($row["cr_locationzipcode"]) . ",&nbsp;" . $hours . ":" . $minutes . ")\";\n";
//      // Liste der Koordinaten (nur wenn hq_distancecalc = 1)
//      if ($hq_distancecalc == "1"):
//        $plz_geo_list[$row["cr_locationzipcode"]] = array($row["srvp_latitude"] , $row["srvp_longitude"]);
//        // save courier-zipcodes for search of surrounding zipcodes below
//        // we want to avoid duplicate querys for duplicate courier-zipcodes
//      endif;
//    else:
//      $cr_id_order_list .= "cr_id_order_list[" . $i++ . "] = \"" . trim($row["cr_sid"]) . "\";\n";
//    endif;
//  endwhile;
//  $res->free();

//  /** Searches for valid PLZs, that are in a specified radius around the PLZ of each courier.
//    Nur wenn hq_workmode = 1 und hq_distancecalc = 1//    *///  if ($hq_workmode == "1" && $hq_distancecalc == "1"):
//    $plz_key_list = array_keys($plz_geo_list);
//    foreach($plz_key_list as $zipcode)
//    {
//      $query = "SELECT srvp_plz, srvp_latitude, srvp_longitude" .//        " FROM serviceplz WHERE srvp_valid = 1 AND " .
//        "(ACOS((SIN(" . deg2rad($plz_geo_list[$zipcode][0]) . ")*SIN(RADIANS(srvp_latitude))) + " .//        "(COS(" . deg2rad($plz_geo_list[$zipcode][0]) . ")*COS(RADIANS(srvp_latitude))*COS(RADIANS(srvp_longitude)-" .
//        deg2rad($plz_geo_list[$zipcode][1]) . "))) * " . GEO_EARTH_RADIUS . ") < " . MAXIMUM_SEARCH_RADIUS;
//      $res_geo = $db2->query($query);
//      if (DB::isError($res_geo))
//        reportDie ("$PHP_SELF: '$query': " . $res_geo->getMessage());
//      while ($row = ($phpVersion >= "8.0" ? $res_geo->fetch_assoc() : $res_geo->fetchRow())):
//        $plz_geo_list[$row["srvp_plz"]] = array($row["srvp_latitude"] , $row["srvp_longitude"]);
//      endwhile;
//      $res_geo->free();
//    }
//  endif;

endif;

if ($tmp_job_line != "")
  $tmp_job_line = "\"" . $tmp_job_line . "\"" . ",\n";
$cr_id_order_list = str_replace("\"" . "*<b>- bevorzugte</b>" . "\",\n", "", $cr_id_order_list);
$cr_id_order_list2 = str_replace("\"" . "*<b>- bevorzugte</b>" . "\",\n", "", $cr_id_order_list2);
if ($jb_longhaul == 1)
  $cr_id_order_list2 = str_replace("Anfahrt min.", "Ziel PLZ", str_replace("KM zur Start-PLZ", "aktuelle Tour", $cr_id_order_list2));
if ($jb_longhaul != 1) {
  $cr_id_order_list = "var cr_id_order_list=[" . $tmp_job_line . $cr_id_order_list0 . ",\n" . $cr_id_order_list02 . ",\n" . $cr_id_order_list . "];\n";
  $cr_id_order_list2 .= "];\n";
} else {
  $cr_id_order_list = "var cr_id_order_list=[" . $tmp_job_line . "\"*<tr><td align=left valign=center colspan=10><B>KURIERE OHNE AUFTRAG</B><\/td><\/tr>" . "\""  . ",\n" . $cr_id_order_list0 . ",\n" . $cr_id_order_list . "];\n";
  $cr_id_order_list2 = "var cr_id_order_list2=[" . "\"*<tr><td align=left valign=center colspan=10><B>KURIERE MIT AUFTRAG</B><\/td><\/tr>" . "\""  . ",\n" . $cr_id_order_list02 . $cr_id_order_list2 . "];\n";
}

//echo $cr_id_order_list;
//echo $cr_id_order_list2;
//die();

$companyIds_js .= "];\n";
$cr_id_order_list_blocked_js = substr($cr_id_order_list_blocked_js, 0, -1) . "];\n";

if (isset($jb_id) && $jb_id != "" && isset($zipcode) && $zipcode != "" && $userType == 1):
  writeLog_("../log/job_courier_cur_", trace_execution_time_stop() . " job_courier.inc.php executed: \$jb_id = $jb_id, couriers: " . count($cr_id_order_list_temp) . ", vehicletype: $cur_vht_id_value_job" . ", \$usr_id = $usr_id");
else:
  writeLog_("../log/job_courier_", trace_execution_time_stop() . " job_courier.inc.php executed: \$jb_id = " . (isset($jb_id) ? $jb_id : "") . ", couriers: " . count($cr_id_order_list_temp) . ", vehicletype: " . (isset($cur_vht_id_value_job) ? $cur_vht_id_value_job : "") . ", \$usr_id = $usr_id");
endif;
//// Gesperrte / gewünschte Kuriere der Kunden
//$res = $db2->query("SELECT cs_id, cr_id, cscr_relation FROM customercourier ORDER BY cr_id");
//if (DB::isError($res))
//  reportDie ("$PHP_SELF: 'SELECT cs_id, cr_id, cscr_relation FROM customercourier ORDER BY cr_id': " . $res->getMessage());
//$customercourier_list = "var customercourier_list = new Array();\n";
//$i = 0;
//while ($row = ($phpVersion >= "8.0" ? $res->fetch_assoc() : $res->fetchRow())):
//  $customercourier_list .= "customercourier_list[" . $i++ . "] = " .
//     "new Array(" . $row["cs_id"] . ", " . $row["cr_id"] . ", " . $row["cscr_relation"] . ");\n";
//endwhile;
//$res->free();

?>
