<?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("../jobs/job_courier.inc.lib.php");
include_once("../include/global.inc.php");

trace_execution_time_start();

$cr_id_order_list = "var cr_id_order_list=[";
$cr_id_order_list2 = "var cr_id_order_list2=[";
$vht_id_str_js = "var vht_id_str=new Array();\n";

$hq_workmode = getFieldValueFromId("headquarters", "hq_id", "$hq_id", "hq_workmode");
//if ($hq_workmode == "2" && $hq_id != 1):
  // Wenn jb_id gesetzt, dann kommt der Aufruf aus der Auftragsliste
  if (isset($jb_id) && $jb_id != "" && isset($zipcode) && $zipcode != ""):
    // Auftragsliste -> Kuriere sortieren
//die("\"$zipcode\", \"1111100\", $jb_id");
    $cr_id_order_list_temp_all = getCourierByRanking("$zipcode", "1111100", $jb_id);
    // Favorisierte Kuriere
    $cr_id_order_list_favoured = get_complete_courier_data($cr_id_order_list_temp_all[2]);
    // favorisierte Kuriere
    usort ($cr_id_order_list_favoured, "cmp_usort");
    if (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;
    // 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");
    if (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;
    // Kuriere im Vermittlungsbereich
    $cr_id_order_list_area = $cr_id_order_list_temp_all[3];
    if ($cr_id_order_list_area == "")
      $cr_id_order_list_area = Array();
    usort ($cr_id_order_list_area, "cmp_usort");
    if (MASK_COURIER_SORT_BY_OCCUPIED == "1"):
      if (MODE_INTERMEDIATION == 1): // Bremen
        array_unshift($cr_id_order_list_area, array("*", "<b>- im Vermittlungsbereich</b>"));
      elseif(MODE_INTERMEDIATION == 2 || MODE_INTERMEDIATION == 3): // Hamburg, Berlin
        $srvpa_name = $db->getOne(
          "SELECT srvpa.srvpa_name FROM serviceplzareamapping AS srvpam, serviceplz AS srvp, serviceplzarea AS srvpa" .
          " WHERE srvp.srvp_id = srvpam.srvp_id AND srvpam.srvpa_id = srvpa.srvpa_id AND srvp.srvp_plz = '$zipcode'");
        $srvpa_longname = $db->getOne(
          "SELECT srvpa.srvpa_longname FROM serviceplzareamapping AS srvpam, serviceplz AS srvp, serviceplzarea AS srvpa" .
          " WHERE srvp.srvp_id = srvpam.srvp_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>"));
      endif;
    else:
      if (MODE_INTERMEDIATION == 1): // Bremen
        array_unshift($cr_id_order_list_area, array("*", "<b>Kuriere im Vermittlungsbereich</b>"));
      elseif(MODE_INTERMEDIATION == 2 || MODE_INTERMEDIATION == 3): // Hamburg, Berlin
        $srvpa_name = $db->getOne(
          "SELECT srvpa.srvpa_name FROM serviceplzareamapping AS srvpam, serviceplz AS srvp, serviceplzarea AS srvpa" .
          " WHERE srvp.srvp_id = srvpam.srvp_id AND srvpam.srvpa_id = srvpa.srvpa_id AND srvp.srvp_plz = '$zipcode'");
        $srvpa_longname = $db->getOne(
          "SELECT srvpa.srvpa_longname FROM serviceplzareamapping AS srvpam, serviceplz AS srvp, serviceplzarea AS srvpa" .
          " WHERE srvp.srvp_id = srvpam.srvp_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 (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(MODE_INTERMEDIATION == 2 || MODE_INTERMEDIATION == 3): // Hamburg, Berlin
      for($i = 1; $i <= AUTORANKING_NEIGHBOUR_LEVEL; $i++):
        $cr_id_order_list_temp_all[$i] = getCourierByRanking("$zipcode", "0100100000", $jb_id, $i);
        $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 (MASK_COURIER_SORT_BY_OCCUPIED == "1"):
      if (MODE_INTERMEDIATION == 1): // Bremen
        array_unshift($cr_id_order_list_neighbourhood, array("*", "<b>- in der Nachbarschaft</b>"));
      elseif(MODE_INTERMEDIATION == 2 || MODE_INTERMEDIATION == 3): // Hamburg, Berlin
        for($i = 1; $i <= AUTORANKING_NEIGHBOUR_LEVEL; $i++):
          $srvpa_name = $db->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.srvpa_id = srvpa.srvpa_id AND srvp.srvp_plz = '$zipcode'");
          $srvpa_longname = $db->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.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 (MODE_INTERMEDIATION == 1): // Bremen
        array_unshift($cr_id_order_list_neighbourhood, array("*", "<b>Kuriere in der Nachbarschaft</b>"));
      elseif(MODE_INTERMEDIATION == 2 || MODE_INTERMEDIATION == 3): // Hamburg, Berlin
        for($i = 1; $i <= AUTORANKING_NEIGHBOUR_LEVEL; $i++):
          $srvpa_name = $db->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.srvpa_id = srvpa.srvpa_id AND srvp.srvp_plz = '$zipcode'");
          $srvpa_longname = $db->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.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 = $cr_id_order_list_temp_all[0];
    if ($cr_id_order_list_absolutely_all == "")
      $cr_id_order_list_absolutely_all = Array();
    // Die Liste aller Kuriere soll nur die enthalten, die nicht bereits in den ersten Listen enthalten sind
    if (MODE_INTERMEDIATION == 1): // Bremen
    elseif(MODE_INTERMEDIATION == 2 || MODE_INTERMEDIATION == 3): // Hamburg, Berlin
      $cr_id_order_list_neighbourhood = Array();
      for($i = 1; $i <= 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));
    usort ($cr_id_order_list_rest, "cmp_usort");
    if (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;
    $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:
    // 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_filter, crvh.crvh_sid "
      . " FROM courier AS cr, couriervehicle AS crvh, metatype AS mt, company AS cmp"
      . " WHERE "
      . "       cr.hq_id = '" . $hq_id . "'                   AND"
      . "       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";
    $res = $db->query($sqlQuery);
    $cr_id_order_list_temp = array();
    if (DB::isError($res)) reportDie ("$PHP_SELF: '$sqlQuery'" . $res->getMessage());
    while ($row = $res->fetch_assoc()):
      $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"]
      );
    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
$vehicletypes = array();
$vehicletype_ids = array();
$sqlQuery = "SELECT mt_sort, mt_value FROM metatype WHERE mt_type = 'vehicletype'";
$res = $db->query($sqlQuery);
if (DB::isError($res)) reportDie ("$PHP_SELF: '$sqlQuery': " . $res->getMessage());
while ($row = $res->fetch_assoc()):
  $vehicletypes[$row["mt_sort"]] = $row["mt_value"];
  $vehicletype_ids[$row["mt_value"]] = $row["mt_sort"];
endwhile;
$res->free();

// bei occupied Kurieren sollen die aktuellen Aufträge angezeigt werden
if (isset($jb_id) && $jb_id != "" && isset($zipcode) && $zipcode != ""):
  list($csc_id, $tr_comp, $tr_person, $ad_street, $tr_hsno,
    $ad_zipcode, $ad_city, $tr_remark, $tr_status, $tr_ware_from_to) =
    getTourData($jb_id, 1, "tour");
  if (MASK_COURIER_SORT_BY_OCCUPIED == "1"):
    array_unshift($cr_id_order_list_temp, array("*", "<tr><td align=left valign=center><B>KURIERE OHNE AUFTRAG</B><\/td><\/tr>"));
  endif;
  $cur_vht_id_job = $db->getOne("SELECT vht_id FROM job WHERE jb_id = '" . $jb_id . "'");
//  $cur_vht_id_value_job = $db->getOne("SELECT mt_value FROM metatype WHERE mt_sort = " . $cur_vht_id_job . " AND mt_type = 'vehicletype'");
  $cur_vht_id_value_job = $vehicletypes[$cur_vht_id_job];
  array_unshift($cr_id_order_list_temp, array("#", "<b>Auftrag Nr. "
    . "<a href=\\\"javascript:popupWindow('../admin/jb_detail.php?job_id=" . $jb_id . "','Auftrag','scrollbars=yes,width=800,height=500');\\\"><i>$jb_id</i></a>"
    . ", Start: " .
    "$tr_comp" . (trim($tr_person) != "" ? ", $tr_person" : "") . ", $ad_street $tr_hsno, $ad_zipcode $ad_city; Fahrzeug: $cur_vht_id_value_job</b>" .
    "<table border=0 align=center width=100% cellspacing=0 cellpadding=0 vspace=0 hspace=0>" .
    "<tr><td align=left valign=center><a href=\\\"javascript:popupWindow('../admin/push_autoranking.php?jb_id=" . $jb_id . "','Auftrag','resizable=no,scrollbars=no,width=250,height=10')\\\"><i>" . "(In automatische Vermittlung einstellen)" . "</i></a>" .
    "</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></table>"));
endif;

// Alle Kuriere finden, die KEINE newbies sind... (d.h. erster eledigter Job innerhalb von MASK_COURIER_NEWBIE_TIME Tagen in der Vergangenheit)

$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";
$res = $db->query($sqlQuery);
if (DB::isError($res)) reportDie ("$PHP_SELF: '$sqlQuery': " . $res->getMessage());
while ($row = $res->fetch_assoc()):
  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

$job_ids_sql = "";
$current_jobs = array();
$sqlQuery = "SELECT jb_id, jb_ordertime, cr_sid FROM job WHERE jb_status = 0 OR jb_status = 1 ORDER BY cr_sid, jb_id ASC";
$res = $db->query($sqlQuery);
if (DB::isError($res)) reportDie ("$PHP_SELF: '$sqlQuery': " . $res->getMessage());
while ($row = $res->fetch_assoc()):
  $current_jobs[$row["cr_sid"]][] = array($row["jb_id"], $row["jb_ordertime"]);
  if ($job_ids_sql != "")
    $job_ids_sql .= ",";
  $job_ids_sql .= "'" . $row["jb_id"] . "'";
endwhile;
$res->free();

$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";
  $res = $db->query($sqlQuery);
  if (DB::isError($res)) reportDie ("$PHP_SELF: '$sqlQuery': " . $res->getMessage());
  while ($row = $res->fetch_assoc()):
    $current_tours[$row["jb_id"]][] = array($row["tr_sort"], $row["tr_status"], $row["ad_zipcode"]);
  endwhile;
  $res->free();
endif;

// Jeden Kurier einzeln verarzten
$i1 = 0;
$i2 = 1;
$cr_id_order_list2 .= "\"*<tr><td align=left valign=center><B>KURIERE MIT AUFTRAG</B><\/td><\/tr>" . "\"";
for($i = 0; $i < count($cr_id_order_list_temp); $i++):
  if ($cr_id_order_list_temp[$i][0] != "*" && $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 = $db->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 = $res->fetch_assoc()):
    if ($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 = $db->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 =
//          $db->getOne("SELECT ad_zipcode FROM address WHERE ad_id = '" .
//            $db->getOne("SELECT ad_id FROM tour WHERE tr_sort = '" . $j . "' AND jb_id = '" . $row["jb_id"] . "'")      
//              . "'");
//        $tr_status =
//          $db->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 =
//          $db->getOne("SELECT ad_zipcode FROM address WHERE ad_id = '" .
//            $db->getOne("SELECT ad_id FROM tour WHERE tr_sort = '1' AND jb_id = '" . $row["jb_id"] . "'")      
//              . "'");
//        $ziel_plz = "";
//        if ($db->getOne("SELECT max(tr_sort) FROM tour WHERE jb_id = '" . $row["jb_id"] . "'") > 1):
//          $ziel_plz =
//            $db->getOne("SELECT ad_zipcode FROM address WHERE ad_id = '" .
//              $db->getOne("SELECT ad_id FROM tour WHERE tr_sort = '" .
//                $db->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);
          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;
        $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>";
      }
    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>";
    $leadingStr = "";
    $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 != "")):
      $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 ($newbie_cr_sids[trim($cr_id_order_list_temp[$i][0])] != 1):
      $tmp_cr_sid = "<span style=\\\"color:#9999FF\\\">" . $tmp_cr_sid . "<\/span>";
    endif;
    $tmpCourierStr =
      "\"" . $leadingStr .
      "<i><b>" . $tmp_cr_sid . "</b>, " . trim($cr_id_order_list_temp[$i][3]) .
      "<i>" . $curFilter . "</i>" . $cr_id_order_list_temp[$i][7] . "\"";

    // Wenn MASK_COURIER_SORT_BY_OCCUPIED gesetzt, dann müssen die Kuriere nach occupied-status sortiert werden
    if (MASK_COURIER_SORT_BY_OCCUPIED == "1"):
      if ($cr_is_occupied != true || !(isset($jb_id) && $jb_id != "" && isset($zipcode) && $zipcode != "")):
        if ($i1++ > 0) $cr_id_order_list .= ",\n";
        $cr_id_order_list .= /* "cr_id_order_list[" . $i1++ . "] = " . */ $tmpCourierStr;
      else:
        if ($i2++ > 0) $cr_id_order_list2 .= ",\n";
        $cr_id_order_list2 .= /* "cr_id_order_list2[" . $i2++ . "] = " . */ $tmpCourierStr;
      endif;
    else:
      if ($i1++ > 0) $cr_id_order_list .= ",\n";
      $cr_id_order_list .= /* "cr_id_order_list[" . $i1++ . "] = " . */ $tmpCourierStr;
    endif;
    // Abgleich der Fahrzeugtypen Kurier/Auftrag
    $vht_id_str = "";
//    $cur_vht_id_job = $db->getOne("SELECT vht_id FROM job WHERE jb_id = '" . $jb_id . "'");
//    $cur_vht_id_value_job = $db->getOne("SELECT mt_value FROM metatype WHERE mt_sort = " . $cur_vht_id_job . " AND mt_type = 'vehicletype'");
//    $cur_vht_id_courier = $db->getOne("SELECT mt_sort FROM metatype WHERE mt_value = '" . $cr_id_order_list_temp[$i][3] . "' AND mt_type = 'vehicletype'");    
    $cur_vht_id_courier = $vehicletype_ids[$cr_id_order_list_temp[$i][3]];
    if ($cur_vht_id_job > $cur_vht_id_courier)
      $vht_id_str = "\\n\\nACHTUNG: Fahrzeug passt nicht! (Angefordert: " . $cur_vht_id_value_job . ", zuweisen: " . $cr_id_order_list_temp[$i][3] . ")";
    if ($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] . ")";
    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 (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><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 ($hq_workmode != "2" || $hq_id == 1):
//  $hq_distancecalc = getFieldValueFromId("headquarters", "hq_id", "$hq_id", "hq_distancecalc");
//  if ($hq_workmode == "1" && $hq_distancecalc == "1"):
//    $res = $db->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 = $db->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 = $res->fetch_assoc()):
//    // 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 = $db->query($query);
//      if (DB::isError($res_geo))
//        reportDie ("$PHP_SELF: '$query': " . $res_geo->getMessage());
//      while ($row = $res_geo->fetch_assoc()):
//        $plz_geo_list[$row["srvp_plz"]] = array($row["srvp_latitude"] , $row["srvp_longitude"]);
//      endwhile;
//      $res_geo->free();
//    }
//  endif;

endif;

$cr_id_order_list .= "];\n";
$cr_id_order_list2 .= "];\n";

if (isset($jb_id) && $jb_id != "" && isset($zipcode) && $zipcode != ""):
  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 = $jb_id, couriers: " . count($cr_id_order_list_temp) . ", vehicletype: $cur_vht_id_value_job" . ", \$usr_id = $usr_id");
endif;
//// Gesperrte / gewünschte Kuriere der Kunden
//$res = $db->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 = $res->fetch_assoc()):
//  $customercourier_list .= "customercourier_list[" . $i++ . "] = " .
//     "new Array(" . $row["cs_id"] . ", " . $row["cr_id"] . ", " . $row["cscr_relation"] . ");\n";
//endwhile;
//$res->free();

?>
