<?php
/*=======================================================================
 *
 * scan.php 
 *
 =======================================================================*/

include_once ("../include/mcglobal.inc.php");
include_once ("../include/auth.inc.php");

getSecHttpVars("1",array("f_act", "statusMessage", "deactivateMenu", "numOfStations", "trackingIDsNotFound", "f_costcenter"));

// Select user-type for mode of security check 
$userType = getFieldValueFromId("user","usr_id",$usr_id,"usr_type");
$userTypeName = getUserTypeName($userType);

// Check authentication verifying emmployee an his/her costcenter- and customer-association
if ( !( authCheckHQ($hq_id,$usr_id,$emp_id) || authCheck($hq_id,$usr_id,$emp_id,$cscIdRoot,$customerId,$cscIdActual) ) || $userTypeName == "" ) :
   die ("$PHP_SELF: Access denied!");
endif;

// Testumgebung Leipzig
if ($usr_id == 800001 || $usr_id == 834522): // admin_l oder l_zanger
  $hq_id = 99;
endif;

// Testumgebung Essen
if ($usr_id == 700001 || $usr_id == 842586): // admin_e oder staboe_test
  $hq_id = 98;
endif;

$deactivateMenuStatic = "1";

getLanguage(__FILE__);

$pageTitel = getLngt("Aufträge");
include_once ("../admin/menu.php");
include_once ("../include/html.inc.php");

getCurrentScript(__FILE__);


// Init
$jobDataSrc = array();
$jobDataTarget = array();

if ($numOfStations == "") : $numOfStations = 0; endif;

// Get POST parameter
for ($i = 0; $i < $numOfStations; $i++) :

    list ($jobDataSrc[$i]["jb_id"], $jobDataSrc[$i]["tr_sort"], $jobDataSrc[$i]["tr_hsno"], $jobDataSrc[$i]["trat_id"],
          $jobDataSrc[$i]["trat_serialno"], $jobDataSrc[$i]["ad_id"], $jobDataSrc[$i]["crvh_sid"], $jobDataSrc[$i]["csc_id"], 
          $jobDataTarget[$i]["jb_id"], $jobDataTarget[$i]["tr_sort"], $jobDataTarget[$i]["tr_hsno"], $jobDataTarget[$i]["trat_id"],
          $jobDataTarget[$i]["trat_serialno"], $jobDataTarget[$i]["ad_id"], $jobDataTarget[$i]["crvh_sid"], $jobDataTarget[$i]["csc_id"],
          $jobDataTarget[$i]["scan"]
          ) = getSecHttpVars("1",array("jobDataSrc_" . $i . "_jb_id", "jobDataSrc_" . $i . "_tr_sort", "jobDataSrc_" . $i . "_tr_hsno", "jobDataSrc_" . $i . "_trat_id",
                             "jobDataSrc_" . $i . "_trat_serialno", "jobDataSrc_" . $i . "_ad_id", "jobDataSrc_" . $i . "_crvh_sid", "jobDataSrc_" . $i . "_csc_id",
                             "jobDataTarget_" . $i . "_jb_id", "jobDataTarget_" . $i . "_tr_sort", "jobDataTarget_" . $i . "_tr_hsno", "jobDataTarget_" . $i . "_trat_id",
                             "jobDataTarget_" . $i . "_trat_serialno", "jobDataTarget_" . $i . "_ad_id", "jobDataTarget_" . $i . "_crvh_sid", "jobDataTarget_" . $i . "_csc_id",
                             "jobDataTarget_" . $i . "_scan"));
endfor;


$trSortOffset = 500;
$specialJbStatusNo = 999;
$specialJbStatusEnabled = false;
$driverPool = array();
$htmlOut = "";

$cscIdPayerArrayOfIFTMIN = array();
$cscIdPayerAssociativeArrayOfIFTMIN = array();
$jobArrayOfIFTMIN = array();
$scanFieldArray = array();
for ($i = 0; $i < $numOfStations; $i++) :
    $scanFieldArray[$jobDataSrc[$i]["jb_id"] . "_" . $jobDataSrc[$i]["tr_sort"]] = $jobDataTarget[$i]["scan"];
endfor;

// Get costcenters of all current IFTMIN orders
$sqlquery = "SELECT DISTINCT jb.csc_id_payer, csc.csc_name"
          . "  FROM phoenix.job AS jb, phoenix.costcenter AS csc"
          . "  WHERE jb.jb_status = '" . $specialJbStatusNo . "' AND"
          . "        jb.hq_id = '" . $hq_id . "' AND"
          . "        jb.csc_id_payer = csc.csc_id"
          . "  ORDER BY jb.csc_id_payer";

$result = $db->query($sqlquery);
if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());

while ($row = $result->fetch_assoc()):
      $cscIdPayerArrayOfIFTMIN[] = $row["csc_id_payer"];
      $cscIdPayerAssociativeArrayOfIFTMIN[$row["csc_id_payer"]] = $row["csc_name"];
endwhile;
$result->free();



// Store changes of the stations and vehicles (drivers)
if ($f_act == "save") :

   if ($numOfStations != "" && is_numeric($numOfStations)) :

     TA("B");

     // First step ALL involved "tr_sort" fields of the specified jobs(!) have to be updated with an offset(!)     
     for ($i = 0; $i < $numOfStations; $i++) :

         $jbIdSrc = $jobDataSrc[$i]["jb_id"];
         $trSortSrc = $jobDataSrc[$i]["tr_sort"];

         if ($jbIdSrc != "") :
            updateStmt("tour", "jb_id", $jbIdSrc, array("tr_sort", ($trSortSrc + $trSortOffset)),"tr_sort = '" . $trSortSrc . "'");
            updateStmt("tourarticle", "jb_id", $jbIdSrc, array("tr_sort", ($trSortSrc + $trSortOffset)),"tr_sort = '" . $trSortSrc . "'");
         endif;
     endfor;

     // Compare all (unique) tracking IDs and update "tr_sort" in "tour" and "tourarticle"
     // Iterate SOURCE values
     for ($i = 0; $i < $numOfStations; $i++) :

         $trackingIdSrc = $jobDataSrc[$i]["trat_serialno"];
         $jbIdSrc = $jobDataSrc[$i]["jb_id"];
         $trSortSrc = $jobDataSrc[$i]["tr_sort"];

         if ($jbIdSrc != "") :
            // Iterate TARGET values
            for ($j = 0; $j < $numOfStations; $j++) :
            
                $trackingIdTarget = $jobDataTarget[$j]["trat_serialno"];
            
                if ($trackingIdSrc == $trackingIdTarget) :   // Has to be true every time because of IFTMIN and Javascript
            
                   $jbIdTarget = $jobDataTarget[$j]["jb_id"];
                   $trSortTarget = $jobDataTarget[$j]["tr_sort"];
                   $crvhSid = $jobDataTarget[$i]["crvh_sid"];
                   
                   if ($jbIdSrc == $jbIdTarget) :   // Has to be true every time because of Javascript
            
                      // Check jb_status
                      $jbStatusSrc = getFieldValueFromId("job", "jb_id", $jbIdSrc, "jb_status");
                      $jbStatusTarget = getFieldValueFromId("job", "jb_id", $jbIdTarget, "jb_status");
            
                      if (!$specialJbStatusEnabled || ($jbStatusSrc == $specialJbStatusNo && $jbStatusTarget == $specialJbStatusNo)) :
            
                         if ($trSortSrc == $trSortTarget) :
                            updateStmt("tour", "jb_id", $jbIdSrc, array("tr_sort", $trSortSrc, "tr_cs_freetext", $crvhSid),"tr_sort = '" . ($trSortSrc + $trSortOffset) . "'");
                            updateStmt("tourarticle", "jb_id", $jbIdSrc, array("tr_sort", $trSortSrc),"tr_sort = '" . ($trSortSrc + $trSortOffset) . "'");
                         else :
                            updateStmt("tour", "jb_id", $jbIdTarget, array("tr_sort", $trSortTarget, "tr_cs_freetext", $crvhSid),"tr_sort = '" . ($trSortSrc + $trSortOffset) . "'");
                            updateStmt("tourarticle", "jb_id", $jbIdTarget, array("tr_sort", $trSortTarget),"tr_sort = '" . ($trSortSrc + $trSortOffset) . "'");
                         endif;
                      else :
                         $statusMessage = getLngt("AUFTRAGSSTATUS NICHT " . $specialJbStatusNo . "!!!");
                      endif;
                   endif;
                endif;
            endfor;
         endif;
     endfor;

     TA("C");
     TA("E");

   else :
      $statusMessage = getLngt("Es sind keine Paketnummern vorhanden!");
   endif;
endif;


// Set events for each of the packages
if ($f_act == "final_save") :

   TA("B");

   $currentTime = getDateTime("0");

   // Write events into "tourarticleprocess" for scanned packages
   for ($i = 0; $i < $numOfStations; $i++) :

       $jbIdSrc = $jobDataSrc[$i]["jb_id"];
       $trSortSrc = $jobDataSrc[$i]["tr_sort"];
       $cscIdSrc = $jobDataSrc[$i]["csc_id"];
       
       // Check for correct data to be final saved regarding the selected costcenter button
       if ($f_costcenter == $cscIdSrc) :

          if ($jbIdSrc != "") :
             if ($trSortSrc != "1") :
                // Get all tracking IDs being NOT(!) in pick up stations. Only delivery stations!
                $tmpArray = $scanFieldArray[$jbIdSrc . "_" . $trSortSrc];
                $scanField = spliti(",", $tmpArray);
                $scanFieldLen = count($scanField);
          
                // Get all "trat_id" entries and tracking IDs of the station
                $sqlquery = "SELECT trat.trat_id, trat.trat_serialno"
                          . "  FROM phoenix.tourarticle AS trat"
                          . "  WHERE trat.jb_id = '" . $jbIdSrc . "' AND"
                          . "        trat.tr_sort = '" . $trSortSrc . "'";
          
                $result = $db->query($sqlquery);
                if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
                $tratIdArray = array();
                $trackingIdArray = array();
                while ($row = $result->fetch_assoc()):
                      $tratIdArray[] = $row["trat_id"];
                      $trackingIdArray[] = $row["trat_serialno"];
                endwhile;
                $result->free();
          
                // Check for tracking ID being in scanned field
                $trackingIdArrayLen = count($trackingIdArray);
          
                for ($j = 0; $j < $trackingIdArrayLen; $j++) :
          
                    // Check for existence of a scan event "201" or "411"
                    $sqlquery = "SELECT tratp.tratp_type, tratp.tratp_state, trat.trat_id"
                              . "  FROM phoenix.tourarticle AS trat, phoenix.tourarticleprocess AS tratp"
                              . "  WHERE trat.trat_serialno = '" . $trackingIdArray[$j] . "' AND"
                              . "        trat.trat_id = tratp.trat_id AND"
                              . "        tratp.tratp_type IN ('201','411')";
          
                    $result = $db->query($sqlquery);
                    if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
                    $numberOfEventExists = "";
                    $stateOfEventExists = "0";
                    $tratIdOfEventExists = "0";
                    while ($row = $result->fetch_assoc()):
                          $numberOfEventExists = $row["tratp_type"];
                          $stateOfEventExists  = $row["tratp_state"];
                          $tratIdOfEventExists = $row["trat_id"];
                    endwhile;
                    $result->free();
          
                    if ($numberOfEventExists == "") :
                       // Event does not exist in database, find package in current scan field of the page
                       $tmpSearch = array_search($trackingIdArray[$j], $scanField);
                       if ($tmpSearch === FALSE) :
                          $eventNo = "411";
                       else :
                          $eventNo = "201";
                       endif;
                       if ($tratIdArray[$j] != "") :                    
                          // The event has to be placed to the pickup station !!!
                          $tmpTratId = getFieldValueFromClause("tourarticle","trat_id","jb_id = '" . $jbIdSrc . "' AND tr_sort = '1' AND trat_serialno = '" . $trackingIdArray[$j] . "'");
                          if ($tmpTratId == "") :
                             $tmpTratId = $tratIdArray[$j];  // Fallback if package would not be found at pick up station.
                          endif;
                          insertStmt("tourarticleprocess", array("trat_id", $tmpTratId, "tratp_type", $eventNo, "tratp_state", "1", "tratp_remark", "", "tratp_createtime", $currentTime));
                       endif;
                    else :
                       // Event does exist and if event equals "not found" then it could be changed in found in current scan field of the page and IFTSTA was not sent
                       if ($stateOfEventExists < "2" && $numberOfEventExists == "411" && $tratIdOfEventExists > "0") :
                          // Find package in current scan field of the page
                          $tmpSearch = array_search($trackingIdArray[$j], $scanField);
                          if (!($tmpSearch === FALSE)) :
                             updateStmt("tourarticleprocess", "trat_id", $tratIdOfEventExists, array("tratp_type", "201", "tratp_createtime", $currentTime), "tratp_type = '411' AND tratp_state < '2'");
                          endif;
                       endif;
                    endif;
                endfor;
             endif;
          endif;
       endif;
   endfor;

   // Write events for scanned packages (into "tourarticleprocess") being NOT in any electronic manifest
   $trackingIDsNotFoundArray = spliti(",", $trackingIDsNotFound);
   $trackingIDsNotFoundArrayLen = count($trackingIDsNotFoundArray);
   for ($i = 0; $i < $trackingIDsNotFoundArrayLen; $i++) :

       $trackingIDNotFound = $trackingIDsNotFoundArray[$i];

       // Check for existence of a scan event "412"
       $sqlquery = "SELECT trat.trat_id"
                 . "  FROM phoenix.tourarticle AS trat, phoenix.tourarticleprocess AS tratp"
                 . "  WHERE trat.trat_serialno = '" . $trackingIDNotFound . "' AND"
                 . "        trat.trat_id = tratp.trat_id AND"
                 . "        tratp.tratp_type = '412'";
       
       $result = $db->query($sqlquery);
       if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
       $tmpEventExists = false;
       while ($row = $result->fetch_assoc()):
             $tmpEventExists = true;
       endwhile;
       $result->free();

       if (!$tmpEventExists) :
          // Final check for the non-existence of the tracking no.
          if ($trackingIDNotFound != "" && !existsEntry("tourarticle",array("trat_serialno",$trackingIDNotFound))) :
          
             // It is nessessary to insert it into the "tourarticle", because the package (tracking ID) is not known and no tourarticle entry does exist.
             // We can take the first (pick up) station of each job displayed, because all of them have the same pick up address !!!
             // To simplify matters we take the first job and the first station, equals to the first entry of the list
             $jbIdSrc = $jobDataSrc["0"]["jb_id"];          
             $trSortSrc = "1";
             $eventNo = "412";
          
             if ($jbIdSrc != "") :
                insertStmt("tourarticle", array("jb_id", $jbIdSrc, "tr_sort", $trSortSrc, "trat_serialno", $trackingIDNotFound, "trat_state", "1", "trat_createtime", $currentTime));
                $tratId = getLastInsertID();
                insertStmt("tourarticleprocess", array("trat_id", $tratId, "tratp_type", $eventNo, "tratp_state", "1", "tratp_remark", "", "tratp_createtime", $currentTime));
             endif;
          endif;
       endif;
   endfor;

   // Last step is to finalize the job
   for ($i = 0; $i < $numOfStations; $i++) :

       $jbIdSrc = $jobDataSrc[$i]["jb_id"];
       $trSortSrc = $jobDataSrc[$i]["tr_sort"];
       $cscIdSrc = $jobDataSrc[$i]["csc_id"];
       
       // Check for correct data to be final saved regarding the selected costcenter button
       if ($f_costcenter == $cscIdSrc) :
          if ($jbIdSrc != "") :
             if ($trSortSrc == "1") :
                // Set jb_status
                updateStmt("job", "jb_id", $jbIdSrc, array("jb_status", "998", "hq_id", $hq_id));   // ???   , "jb_ordertime", $currentTime, "jb_taketime", $currentTime
             endif;
          endif;
       endif;
   endfor;

   TA("C");
   TA("E");
   
   $numOfStations = 0;
   // $f_costcenter = "";
   
   // Call function to finalize the job
   include_once ("../tools/finalize_job.inc.php");
   finalize_jobs();
endif;


function getCurrentJobData($jobArrayOfIFTMIN, $scanFieldArray = array(), $driverPool, $f_costcenter) {
	global $db, $PHP_SELF;
	global $hq_id;

  $numOfStations = 0;
  $htmlOut = "";

  $jobArrayOfIFTMINLen = count($jobArrayOfIFTMIN);

  if ($jobArrayOfIFTMINLen > 0) :

    $whereClauseJobs = "(" . implode(",", $jobArrayOfIFTMIN) . ")";

    // Get data from "job", "tour", "tourarticle"
    /*
    $sqlquery = "SELECT jb.jb_id, jb.cr_id, csc.csc_id, csc.csc_name,"
              . "       tr.tr_sort, tr.tr_signname, tr.tr_hsno,"
              . "       ad.ad_id, ad.ad_street, ad.ad_zipcode, ad.ad_city, ad.ad_country,"
              . "       crvh.crvh_sid"
              . "  FROM phoenix.job AS jb LEFT JOIN phoenix.couriervehicle AS crvh ON jb.cr_id = crvh.cr_id,"
              . "       phoenix.tour AS tr, phoenix.address AS ad, phoenix.costcenter AS csc"
              . "  WHERE jb.jb_id IN " . $whereClauseJobs . " AND"
              . "        jb.jb_id = tr.jb_id AND"
              . "        tr.ad_id = ad.ad_id AND"
              . "        jb.csc_id_payer = csc.csc_id"
              . "  ORDER BY jb.jb_id, tr.tr_sort";

    $sqlquery = "SELECT jb.jb_id, csc.csc_id, csc.csc_name,"
              . "       tr.tr_sort, tr.tr_signname, tr.tr_hsno, tr.tr_cs_freetext AS crvh_sid,"
              . "       ad.ad_id, ad.ad_street, ad.ad_zipcode, ad.ad_city, ad.ad_country"
              . "  FROM phoenix.job AS jb, phoenix.tour AS tr, phoenix.address AS ad, phoenix.costcenter AS csc"
              . "  WHERE jb.jb_id IN " . $whereClauseJobs . " AND"
              . "        jb.jb_id = tr.jb_id AND"
              . "        tr.ad_id = ad.ad_id AND"
              . "        jb.csc_id_payer = csc.csc_id"
              . "  ORDER BY jb.jb_id, tr.tr_sort";
    */
    $sqlquery = "SELECT jb.jb_id, csc.csc_id, csc.csc_name, tr.tr_comp, tr.tr_comp2, tr.tr_ware_from_to,"
              . "       tr.tr_sort, tr.tr_signname, tr.tr_hsno, tr.tr_cs_freetext AS crvh_sid,"
              . "       ad.ad_id, ad.ad_street, ad.ad_zipcode, ad.ad_city, ad.ad_country"
              . "  FROM phoenix.job AS jb, phoenix.tour AS tr, phoenix.address AS ad, phoenix.costcenter AS csc"
              . "  WHERE jb.jb_id IN " . $whereClauseJobs . " AND"
              . "        jb.jb_id = tr.jb_id AND"
              . "        tr.ad_id = ad.ad_id AND"
              . "        jb.csc_id_payer = csc.csc_id"
              . "  ORDER BY jb.jb_id, tr.tr_sort";

// echo $sqlquery . "<br>";
    $result = $db->query($sqlquery);
    if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());

    $htmlOut .= "<table>\n";
    $htmlOut .= "<tr>\n";
    // if ($f_costcenter == "") :
       $htmlOut .= "  <td align=\"center\"><b>" . getLngt("Kostenstelle") . "</b></td>\n";
    // endif;
    // $htmlOut .= "  <td align=\"center\"><b>" . getLngt("Auftrag") . "</b></td>\n";
    $htmlOut .= "  <td align=\"center\"><b>" . getLngt("Station") . "</b></td>\n";
    $htmlOut .= "  <td align=\"center\"><b>" . getLngt("Adresse") . "</b></td>\n";
    $htmlOut .= "  <td align=\"center\"><b>" . "&nbsp;" . "</b></td>\n";
    $htmlOut .= "  <td align=\"center\"><b>" . getLngt("Sendung") . "</b></td>\n";
    $htmlOut .= "  <td align=\"center\"><b>" . getLngt("Scan")    . "</b></td>\n";
    $htmlOut .= "  <td align=\"center\"><b>" . getLngt("Fahrer")
              . "    <input type=\"checkbox\" name=\"crvhTopDown\" value=\"0\" onfocus=\"javascript: setScanFocus();\">"
              . "  </b></td>\n";
    $htmlOut .= "  <td align=\"center\"><b>" . getLngt("Aktion")  . "</b></td>\n";
    $htmlOut .= "</tr>\n";

    $numOfStations = $result->numRows();

    $remJbId = ""; 
    $remCscId = ""; 
    $remCscName = "";
    $i = 0;
    while ($row = $result->fetch_assoc()):

          // Get the tracking IDs of the stations
          $trackingIDs = getColVectorFromDB2ArrayByClause("tourarticle", "trat_serialno", "jb_id = '" . $row["jb_id"] . "' AND tr_sort = '" . $row["tr_sort"] . "'", "", "");
          $trackingIDsLen = count($trackingIDs);
          $trackingIDsString = implode(",", $trackingIDs);

          // Check for existence of event "201" or "411"
          $existingEventNo = "";
          for ($j = 0; $j < $trackingIDsLen; $j++) :
              // Get all trat_id entries from the current tracking ID(s)
              $tratIDs = getColVectorFromDB2ArrayByClause("tourarticle", "trat_id", "trat_serialno = '" . $trackingIDs[$j] . "'", "", "");
              $tratIDsLen = count($tratIDs);
              if ($tratIDsLen > 0) :
                 $tratIDsString = implode(",", $tratIDs);
                 // Get all event entries ("201" and "411" only) from the specified trat_id entries
                 $tratTypes = getColVectorFromDB2ArrayByClause("tourarticleprocess", "tratp_type", "trat_id IN (" . $tratIDsString . ") AND tratp_type IN ('201','411')", "", "");
                 $tratTypesLen = count($tratTypes);
                 if ($tratTypesLen > 0) :
                    $existingEventNo = $tratTypes[0];
                 endif;
              endif;
          endfor;

          // Get number of stations of the job
          $numOfStationsOfCurrentJob = getCountOfTable("tour", "jb_id = '" . $row["jb_id"] . "'");

          // Driver pool
          $tmpSearch = array_search($row["crvh_sid"], $driverPool);
          if ($tmpSearch === FALSE) :
             $driverPool[] = $row["crvh_sid"];
          endif;

          if ($remJbId != "" && $remJbId != $row["jb_id"]) :
             $htmlOut .= "<tr><td colspan=\"6\" align=\"center\"><input type=\"button\" name=\"button_save_changes\" value=\"" . getLngt($remCscName . " Aufträge freigeben") . "\" onclick=\"javascript:finishFinalSave('" . $remCscId . "');\"><td><tr>";
             $htmlOut .= "<tr><td colspan=\"6\" align=\"center\"><img src=\"../images/spacer_bgcolor.jpg\" border=\"0\" height=\"20\" width=\"100%\"></td></tr>\n";
          endif;

          // If first character of "tr_comp" equals "*" then add "*" to "tr_comp2"
          $asterisk_01 = "";
          if (substr($row["tr_comp"],0,1) == "*") :
             $asterisk_01 = " [*]";
          endif;

          // FORM fields
          // Hidden (Source)
          $htmlOut .= "<input type=\"hidden\" name=\"jobDataSrc_" . $i . "_csc_id\" value=\"" . $row["csc_id"] . "\">\n";
          // $htmlOut .= "<input type=\"hidden\" name=\"jobDataSrc_" . $i . "_csc_name\" value=\"" . $row["csc_name"] . "\">\n";
          $htmlOut .= "<input type=\"hidden\" name=\"jobDataSrc_" . $i . "_csc_name\" value=\"" . $row["tr_comp2"] . $asterisk_01 . "\">\n";
          $htmlOut .= "<input type=\"hidden\" name=\"jobDataSrc_" . $i . "_jb_id\" value=\"" . $row["jb_id"] . "\">\n";
          $htmlOut .= "<input type=\"hidden\" name=\"jobDataSrc_" . $i . "_tr_sort\" value=\"" . $row["tr_sort"] . "\">\n";
          $htmlOut .= "<input type=\"hidden\" name=\"jobDataSrc_" . $i . "_ad_id\" value=\"" . $row["ad_id"] . "\">\n";
          $htmlOut .= "<input type=\"hidden\" name=\"jobDataSrc_" . $i . "_trat_id\" value=\"" . $row["trat_id"] . "\">\n";
          if ($row["tr_sort"] == "1") :
             $htmlOut .= "<input type=\"hidden\" name=\"jobDataSrc_" . $i . "_trat_serialno\" value=\"\" disabled>\n";
          else :
             $htmlOut .= "<input type=\"hidden\" name=\"jobDataSrc_" . $i . "_trat_serialno\" value=\"" . $trackingIDsString . "\">\n";
          endif;
          $htmlOut .= "<input type=\"hidden\" name=\"jobDataSrc_" . $i . "_crvh_sid\" value=\"" . $row["crvh_sid"] . "\">\n";
          // Hidden (Target)
          $htmlOut .= "<input type=\"hidden\" name=\"jobDataTarget_" . $i . "_csc_id\" value=\"" . $row["csc_id"] . "\">\n";
          $htmlOut .= "<input type=\"hidden\" name=\"jobDataTarget_" . $i . "_ad_id\" value=\"" . $row["ad_id"] . "\">\n";
          $htmlOut .= "<input type=\"hidden\" name=\"jobDataTarget_" . $i . "_trat_id\" value=\"" . $row["trat_id"] . "\">\n";
          // Displayed
          $htmlOut .= "<tr>\n";
          // if ($f_costcenter == "") :
             // $htmlOut .= "  <td><input type=\"text\" name=\"jobDataTarget_" . $i . "_csc_name\" value=\"" . $row["csc_name"] . "\" size=\"15\" onfocus=\"javascript: setScanFocus();\" readonly ></td>\n";
             $htmlOut .= "  <td>" . "<input type=\"text\" name=\"jobDataTarget_" . $i . "_csc_name\" value=\"" . $row["tr_comp2"] . $asterisk_01 . "\" size=\"15\" onfocus=\"javascript: setScanFocus();\" readonly ></td>\n";
          // endif;
          // $htmlOut .= "  <td><input type=\"text\" name=\"jobDataTarget_" . $i . "_jb_id\" value=\"" . $row["jb_id"] . "\" size=\"10\" onfocus=\"javascript: setScanFocus();\" readonly ></td>\n";
          $htmlOut .= "<input type=\"hidden\" name=\"jobDataTarget_" . $i . "_jb_id\" value=\"" . $row["jb_id"] . "\">\n";
          $htmlOut .= "  <td><input type=\"text\" name=\"jobDataTarget_" . $i . "_tr_sort\" value=\"" . $row["tr_sort"] . "\" size=\"3\" onfocus=\"javascript: setScanFocus();\" readonly ></td>\n";
          $htmlOut .= "  <td><input type=\"text\" name=\"jobDataTarget_" . $i . "_address\" value=\"" . $row["ad_zipcode"] . " " . $row["ad_city"] . ", " . $row["ad_street"] . " " . $row["tr_hsno"] . "\" size=\"50\" readonly >";
          if($row["tr_sort"] != "1"):
            $htmlOut .= "&nbsp;<a href=\"javascript:showInfo('" . $trackingIDsString . "')\"><b>?</b></a>";
          endif;
          $htmlOut .= "</td>\n";
          if ($row["tr_sort"] == "1" || $row["tr_ware_from_to"] == "1") :
             $htmlOut .= "  <td>&nbsp;</td>\n";
          else :
             $streetHttp = urlencode($row["ad_street"]);
             $zipcodeHttp = urlencode($row["ad_zipcode"]);
             $cityHttp = urlencode($row["ad_city"]);
             $hsnoHttp = urlencode($row["tr_hsno"]);
             $htmlOut .= "  <td><input type=\"button\" name=\"action_ad_search\" value=\"...\" onclick=\"searchScanAddress('" . $i . "','" . $row["ad_id"] . "','" . $streetHttp . "','" . $zipcodeHttp . "','" . $cityHttp . "','" . $row["jb_id"] . "','" . $row["tr_sort"] . "','" . $hsnoHttp . "');\"></td>\n";
          endif;
          if ($row["tr_sort"] == "1") :
             $htmlOut .= "  <td><input type=\"text\" name=\"jobDataTarget_" . $i . "_trat_serialno\" value=\"\" size=\"35\" readonly disabled ></td>\n";
             $htmlOut .= "  <td><input type=\"text\" name=\"jobDataTarget_" . $i . "_scan\" value=\"\" size=\"35\" readonly disabled ></td>\n";
          else :
             $htmlOut .= "  <td><input type=\"text\" name=\"jobDataTarget_" . $i . "_trat_serialno\" value=\"" . $trackingIDsString . "\" size=\"35\" readonly ></td>\n";

             $tmpScanValue = $scanFieldArray[$row["jb_id"] . "_" . $row["tr_sort"]];
             if ($existingEventNo == "201") :
                $tmpScanValue = $trackingIDsString;
             elseif ($existingEventNo == "411") :
                $tmpScanValue = getLngt("Sendung fehlte!");
             endif;
             $htmlOut .= "  <td><input type=\"text\" name=\"jobDataTarget_" . $i . "_scan\" value=\"" . $tmpScanValue . "\" size=\"35\" readonly ></td>\n";
          endif;
          $htmlOut .= "  <td><select name=\"jobDataTarget_" . $i . "_crvh_sid\" onChange=\"changeVehicle(this,'" . $i . "','" . $row["jb_id"] . "','" . $row["tr_sort"] . "','" . $row["crvh_sid"] . "','" . $row["csc_id"] . "');\"><option value=\"\">---</option>" . addOptionsFromTable("couriervehicle AS crvh, courier AS cr", "crvh_sid", "crvh_sid", "crvh_sid", "crvh.cr_id = cr.cr_id AND cr.hq_id = '" . ($hq_id != 99 ? ($hq_id != 98 ? $hq_id : 7) : 8) . "'", $row["crvh_sid"]) . "</select></td>\n";
          $htmlOut .= "  <td align=\"center\">\n";

          // No arrows at the first station (pick up)
          // Move down
          if ($row["tr_sort"] >= "2" && $row["tr_sort"] < $numOfStationsOfCurrentJob) :
             $htmlOut .= "    &nbsp;&nbsp;&nbsp;<a href=\"javascript:moveItem('down'," . $i . ")\">" . "<img src=\"../images/arrow_down.png\" border=\"1\" height=\"25\" width=\"10\">" . "</a>\n";
          else :
             $htmlOut .= "    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
          endif;
          // Move up
          if ($row["tr_sort"] > "2") :
             $htmlOut .= "    &nbsp;&nbsp;&nbsp;<a href=\"javascript:moveItem('up'," . $i . ")\">" . "<img src=\"../images/arrow_up.png\" border=\"1\" height=\"25\" width=\"10\">" . "</a>\n";
          else :
             $htmlOut .= "    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp";
          endif;
          
          $htmlOut .= "  </td>\n";
          $htmlOut .= "</tr>\n";
          
          $remJbId = $row["jb_id"];
          $remCscId = $row["csc_id"]; 
          $remCscName = $row["csc_name"];

          $i++;
    endwhile;
    $result->free();
    $htmlOut .= "<tr><td colspan=\"6\" align=\"center\"><input type=\"button\" name=\"button_save_changes\" value=\"" . getLngt($remCscName . " Aufträge freigeben") . "\" onclick=\"javascript:finishFinalSave('" . $remCscId . "');\"><td><tr>";
    $htmlOut .= "</table>\n";
  endif;

  return array($htmlOut, $numOfStations, $driverPool);
}


// Init current costcenter for the page if empty (Do this AFTER saving or final saving data!)
if ($f_costcenter == "") : $f_costcenter = $cscIdPayerArrayOfIFTMIN[0]; endif;

// $outCostcenters = "<b>" . getLngt("AUSWAHL:") . "</b>&nbsp;";
// $outCostcenters .= "<select name=\"f_costcenter\" onChange=\"changeCostcenter();\"><option value=\"\">---</option>" . addOptionsFromAssociativeArray($cscIdPayerAssociativeArrayOfIFTMIN, $f_costcenter) . "</select>\n";
// $outCostcenters .= "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
$outCostcenters = "";

// Get job data array of specified IFTMIN orders accorting to the selected costcenter
$whereClauseCostcenter = "";
/*
if ($f_costcenter != "" && is_numeric($f_costcenter)) :
   $whereClauseCostcenter = " AND jb.csc_id_payer = '" . $f_costcenter . "'";
endif;
*/

$sqlquery = "SELECT jb.jb_id"
          . "  FROM phoenix.job AS jb"
          . "  WHERE jb.jb_status = '" . $specialJbStatusNo . "' AND"
          . "        jb.hq_id = '" . $hq_id . "'"
          .          $whereClauseCostcenter
          . "  ORDER BY jb.jb_id";

$result = $db->query($sqlquery);
if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());

while ($row = $result->fetch_assoc()):
      $jobArrayOfIFTMIN[] = $row["jb_id"];
endwhile;
$result->free();

$tmpJobArray = getCurrentJobData($jobArrayOfIFTMIN, $scanFieldArray, $driverPool, $f_costcenter);
$htmlOut = $tmpJobArray[0];
$numOfStations = $tmpJobArray[1];
$driverPool = $tmpJobArray[2];
?>


<html>

<head>
<title><?php echo $pageTitel ?></title>

<link rel="stylesheet" type="text/css" href="../css/phoenix.css">
<style type="text/css">
  <?php include_once ("../css/navigation.css.php"); ?>
</style>

<?php include_once ("../include/js_framework.inc.php"); ?>

<script src="../include/checkFormTags.js" type="text/javascript"></script>

<script type="text/javascript">
<!--

/********************************************************************************/
// Quelle: http://9elements.com/html5demos/audio/
// Audioelement erstellen
//var ackSnd;
var hintSnd;
var warnSnd;
var soundOn = true;

try {
//  ackSnd = new Audio("");
  hintSnd = new Audio("");
  warnSnd = new Audio("");
} catch (e) {
  soundOn = false;
}

function initSounds() {
	if (soundOn) {
    // im DOM einfügen, sonst wird es nicht abgespielt
//    document.body.appendChild(ackSnd);
    document.body.appendChild(hintSnd);
    document.body.appendChild(warnSnd);

    // herausfinden welcher Medientyp abgespielt werden kann
    var canPlayType = warnSnd.canPlayType("audio/wav");
    if(canPlayType.match(/maybe|probably/i)) {
//	    ackSnd.src = 'sound/registerscan.wav';
	    hintSnd.src = 'sound/buzzer1.wav';
  	  warnSnd.src = 'sound/buzzer.wav';
    } else {
      soundOn = false;
    }
  }
//	if (soundOn) {
//		alert("Sound is on!")
//  } else {
//		alert("Sound is off!")
// 	}  
}

//function beepAck() {
//	if (soundOn)
//    ackSnd.play();
//}

function beepHint() {
	if (soundOn)
    hintSnd.play();
}

function beepWarn() {
	if (soundOn)
    warnSnd.play();
}
/********************************************************************************/

// NAVIGATION
<?php echo $jsMenuOut; ?>


var numOfStations = <?php echo $numOfStations ?>;

function setScanFocus() {
  <?php if ($usedFramework == "2") : ?>
    if ($('f_scan')) {
       $('f_scan').focus();
    }
  <?php else : ?>
    if ($('#f_scan')) {
       $('#f_scan').focus();
    }
  <?php endif; ?>
}

function executeScanCode() {
	frm = document.forms[0];
  var scan_elem = document.forms[0].f_scan;
  var scan_value = trim(scan_elem.value);

  var IDfound = false;
  var IDfoundDouble = false;

  if (scan_value != '') {
     for(var i=0; i<numOfStations; ++i) {
     	  var tratSerialno_elem = eval('frm.jobDataTarget_' + i + '_trat_serialno');
     	  var tratSerialno = tratSerialno_elem.value;
     	  var scannedIDs = eval('frm.jobDataTarget_' + i + '_scan');
     
     	  var trackingIDs = tratSerialno.split(",");
     	  trackingIDsLen = trackingIDs.length;
     
     	  for(var j=0; j<trackingIDsLen; ++j) {
     	      trackingID = trackingIDs[j];
             if (trackingID == scan_value) {

                IDfound = true;

                // Check for multiple scan
                tmpScannedIDs = scannedIDs.value;
                checkScannedIDs = tmpScannedIDs.split(",");
                checkScannedIDsLen = checkScannedIDs.length;
                IDfoundDouble = false;
                for(var j=0; j<checkScannedIDsLen; ++j) {
                	   checkScanID = checkScannedIDs[j];
                    if (checkScanID == scan_value) {
                       IDfoundDouble = true;
                    }
                }
                if (!IDfoundDouble) {
                	 if (scannedIDs.value == '<?php echo getLngt("Sendung fehlte!") ?>') {
                	 	  scannedIDs.value = '';
                	 }
             	     if (scannedIDs.value != '') {
                      scannedIDs.value = scannedIDs.value + ',';
                   }             
                	 scannedIDs.value = scannedIDs.value + scan_value;
//                   beepAck();
                }
                
             }
         }
     }
  }

  if (IDfoundDouble) {
     beepHint();
  	 alert('<?php echo getLngt("Das Paket hatten Sie schon gescanned!") ?>');
  } else {
  	 if (scan_value != '') {
  	    IDfoundDouble = false;
  	    var notFoundIDs = frm.trackingIDsNotFound.value;
        var notFoundIDsArray = notFoundIDs.split(",");
        notFoundIDsArrayLen = notFoundIDsArray.length;
        for(var j=0; j<notFoundIDsArrayLen; ++j) {
        	  notFoundID = notFoundIDsArray[j];
           if (notFoundID == scan_value) {
              IDfoundDouble = true;
           }
        }
        if (IDfoundDouble) {
           beepWarn();
  	       alert('<?php echo getLngt("Das Paket hatten Sie schon gescanned! Die Nummer befindet sich bei den nicht gefundenen Paketnummern!") ?>');
  	    }
  	 }
  }

  if (!IDfound && !IDfoundDouble && scan_value != '') {
  	 beepWarn();
  	 var parPrefix = '<?php echo getParameterValue("0", "MASK_SCAN_TRACKING_NO_PREFIX", "0");?>';
  	 /*
  	 if (!confirm('<?php echo getLngt("Haben Sie versehentlich die Rechnungsnummer gescanned?") ?> [' + scan_value + ']')) {
  	    if (frm.trackingIDsNotFound.value != '') {frm.trackingIDsNotFound.value = frm.trackingIDsNotFound.value + ','};
        frm.trackingIDsNotFound.value = frm.trackingIDsNotFound.value + scan_value;
     }
     */
  	 if (frm.trackingIDsNotFound.value != '') {frm.trackingIDsNotFound.value = frm.trackingIDsNotFound.value + ','};
     frm.trackingIDsNotFound.value = frm.trackingIDsNotFound.value + scan_value;
     if (parPrefix != '' && parPrefix == scan_value.substring(0,3)) {
        beepWarn();
        alert('<?php echo getLngt("ACHTUNG: Kein Auftrag für das Paket ") ?> [' + scan_value + ']! Bitte zur Seite legen und mit dem Lieferanten klären!');
     }
  }
  
  scan_elem.value = '';
  setScanFocus();
}

function moveItem(upOrDown, station) {		
	frm = document.forms[0];
	
	// ATTENTION: "down" is the same like "up" with changed stations
	var stationTo;
  if (upOrDown == 'up') {
  	 stationTo = station - 1;
  } else {
  	 // Switch stations to use "UP" functionality
  	 stationTo = station;
  	 station = station + 1;
  	 upOrDown = 'up';
  };

  // *** Get current contents ***
  // FROM
	var jbId = eval('frm.jobDataTarget_' + station + '_jb_id').value;
	var trSort = eval('frm.jobDataTarget_' + station + '_tr_sort').value;
	var adId = eval('frm.jobDataTarget_' + station + '_ad_id').value;
	var address = eval('frm.jobDataTarget_' + station + '_address').value;
	var tratId = eval('frm.jobDataTarget_' + station + '_trat_id').value;
	var tratSerialno = eval('frm.jobDataTarget_' + station + '_trat_serialno').value;
	var scan = eval('frm.jobDataTarget_' + station + '_scan').value;
	var crvhSid;
  var tmpCrvhSidElem = eval('frm.jobDataTarget_' + station + '_crvh_sid');
  for(var j=0;j<tmpCrvhSidElem.length;++j) {
     if (tmpCrvhSidElem.options[j].selected == true) {
        crvhSid = tmpCrvhSidElem.options[j].value;
     }
  }
  // TO
	var jbIdTo = eval('frm.jobDataTarget_' + stationTo + '_jb_id').value;
	var trSortTo = eval('frm.jobDataTarget_' + stationTo + '_tr_sort').value;
	var adIdTo = eval('frm.jobDataTarget_' + stationTo + '_ad_id').value;
	var addressTo = eval('frm.jobDataTarget_' + stationTo + '_address').value;
	var tratIdTo = eval('frm.jobDataTarget_' + stationTo + '_trat_id').value;
	var tratSerialnoTo = eval('frm.jobDataTarget_' + stationTo + '_trat_serialno').value;
	var scanTo = eval('frm.jobDataTarget_' + stationTo + '_scan').value;
	var crvhSidTo;
  var tmpCrvhSidElemTo = eval('frm.jobDataTarget_' + stationTo + '_crvh_sid');
  for(var j=0;j<tmpCrvhSidElemTo.length;++j) {
     if (tmpCrvhSidElemTo.options[j].selected == true) {
        crvhSidTo = tmpCrvhSidElemTo.options[j].value;
     }
  }

  // *** Switch contents ***
  // FROM => TO
  eval('frm.jobDataTarget_' + station + '_ad_id').value = adIdTo;
  eval('frm.jobDataTarget_' + station + '_address').value = addressTo;
  eval('frm.jobDataTarget_' + station + '_trat_id').value = tratIdTo;
  eval('frm.jobDataTarget_' + station + '_trat_serialno').value = tratSerialnoTo;
  eval('frm.jobDataTarget_' + station + '_scan').value = scanTo;
  tmpCrvhSidElem = 'jobDataTarget_' + station + '_crvh_sid';
  setSelectedValue(tmpCrvhSidElem, crvhSidTo);
  // TO => FROM
  eval('frm.jobDataTarget_' + stationTo + '_ad_id').value = adId;
  eval('frm.jobDataTarget_' + stationTo + '_address').value = address;
  eval('frm.jobDataTarget_' + stationTo + '_trat_id').value = tratId;
  eval('frm.jobDataTarget_' + stationTo + '_trat_serialno').value = tratSerialno;
  eval('frm.jobDataTarget_' + stationTo + '_scan').value = scan;
  tmpCrvhSidElemTo = 'jobDataTarget_' + stationTo + '_crvh_sid';
  setSelectedValue(tmpCrvhSidElemTo, crvhSid);
}

function execBodyOnLoad() {
<?php 
  echo $phpCurrentNavigationOnLoad;
?>
initSounds();
// initForm();
displayStatusMessage();
setScanFocus();
}

function changeVehicle(elem, station, jbId, trSort, crvhSidOld, cscId) {
	var elemLen = elem.length;
	if (document.forms[0].crvhTopDown.checked) {
	   // Selected vehicle of the current element
     for(var j=0;j<elemLen;++j) {
        if (elem.options[j].selected == true) {
           crvhSid = elem.options[j].value;
        }
     }
     // Change all following elements according to "crvhSid"
     for(var i=station;i<numOfStations;++i) {
	      tmpCrvhSidElem = 'jobDataTarget_' + i + '_crvh_sid';
	      setSelectedValue(tmpCrvhSidElem, crvhSid);
     }
	}
}

function changeVehicleOLD(elem, station, jbId, trSort, crvhSidOld, cscId) {
	var elemLen = elem.length;
	var crvhSid;
	var jbIdTarget;
	var trSortTarget;
	var cscIdTarget;
	var costcenterOk = true;
	
	// Old vehicle (Source)
	var crvhSidSource = eval('frm.jobDataSrc_' + station + '_crvh_sid').value;
	var crvhSidTargetCurrent;
	
	// Selected vehicle (Target)
  for(var j=0;j<elemLen;++j) {
     if (elem.options[j].selected == true) {
        crvhSid = elem.options[j].value;
     }
  }

  if (crvhSid != '') {
     // Check compatibility of the costcenters
     for(var i=0;i<numOfStations;++i) {     
     	  jbIdTarget = eval('frm.jobDataTarget_' + i + '_jb_id').value;
     	  trSortTarget = eval('frm.jobDataTarget_' + i + '_tr_sort').value;
     	  // Look for costcenter ID in pick up station only
        if (trSortTarget == 1) {
        	 // Get vehicle of the pickup station
     	     crvhSidTargetCurrentElem = eval('frm.jobDataTarget_' + i + '_crvh_sid');
     	     crvhSidTargetCurrentElemLen = crvhSidTargetCurrentElem.length;
           for(var j=0;j<crvhSidTargetCurrentElemLen;++j) {
              if (crvhSidTargetCurrentElem.options[j].selected == true) {
                 crvhSidTargetCurrent = crvhSidTargetCurrentElem.options[j].value;
              }
           }
           // If the target vehicle matches the selected vehicle, both costcenters have to be the same
           if (crvhSidTargetCurrent == crvhSid) {
              cscIdTarget = eval('frm.jobDataTarget_' + i + '_csc_id').value;
              if (cscIdTarget == cscId) {
                 tmpCrvhSidElem = 'jobDataTarget_' + i + '_crvh_sid';
                 setSelectedValue(tmpCrvhSidElem, crvhSid);
              } else {
              	costcenterOk = false;
              }
           }
        }
     }

     if (costcenterOk) {
     	  if (trSort == '1') {
           for(var i=0;i<numOfStations;++i) {
           	  jbIdTarget = eval('frm.jobDataTarget_' + i + '_jb_id').value;
           	  trSortTarget = eval('frm.jobDataTarget_' + i + '_tr_sort').value;
              if (jbIdTarget == jbId && trSortTarget > 1) {
           	     // Get current vehicle of the target element
           	     crvhSidTargetCurrentElem = eval('frm.jobDataTarget_' + i + '_crvh_sid');
           	     crvhSidTargetCurrentElemLen = crvhSidTargetCurrentElem.length;
                 for(var j=0;j<crvhSidTargetCurrentElemLen;++j) {
                    if (crvhSidTargetCurrentElem.options[j].selected == true) {
                       crvhSidTargetCurrent = crvhSidTargetCurrentElem.options[j].value;
                    }
                 }
	               // if (crvhSidTargetCurrent == crvhSidSource) {
	               	  tmpCrvhSidElem = 'jobDataTarget_' + i + '_crvh_sid';
	               	  setSelectedValue(tmpCrvhSidElem, crvhSid);
	               // }
	            }
           }
        }
     } else {
	      tmpCrvhSidElem = 'jobDataTarget_' + station + '_crvh_sid';
	      setSelectedValue(tmpCrvhSidElem, crvhSidOld);
     	  alert('<?php echo getLngt("Dieses Fahrerzeug können Sie derzeit nicht zuordnen, da es in einem anderen Auftrag mit einer abweichenden Kostenstelle schon zugewiesen ist!") ?>');
     }
  }
}

function finishPage(f_act) {
	document.forms[0].f_act.value = f_act;
	document.forms[0].submit();
}	

function finishSave() {
  finishPage('save');
}

function finishSaveOld() {
	var submitOk = true;

	// Get driver entries of the pickup stations
	var driverPool = new Array();	
	var crvhSid;
	var count = 0;
  for(var i=0;i<numOfStations;++i) {
  	 var tmptrSortElem = eval('frm.jobDataTarget_' + i + '_tr_sort');
  	 var tmptrSortValue = tmptrSortElem.value;
  	
  	 // Check for pick up address only
  	 if (tmptrSortValue == '1') {
  	    var tmpCrvhSidElem = eval('frm.jobDataTarget_' + i + '_crvh_sid');
        for(var j=0;j<tmpCrvhSidElem.length;++j) {
           if (tmpCrvhSidElem.options[j].selected == true) {
              driverPool[count] = tmpCrvhSidElem.options[j].value;
              count++;
           }
        }        
     }
  }
  var driverPoolLen = driverPool.length;
  
	// Check driver
	// [1.] One driver cannot have more then one tour
  var allDisjunct = true;
  for(var i=0;i<driverPoolLen;++i) {
  	 x = parseInt(i) + 1;
  	 for(var j=x;j<driverPoolLen;++j) {
  	 	  if (driverPool[i] == driverPool[j] && driverPool[i] != '' && driverPool[j] != '') {
  	 	  	 allDisjunct = false;
  	 	  	 submitOk = false;
  	 	  }
  	 }
  }
  if (!allDisjunct) {
  	 alert('<?php echo getLngt("In den Abholstationen müssen unterschiedliche Fahrer eingetragen sein") ?>');
  }

	// [2.] All driver entries being NOT the first pick up station only have to be out of the pool according to [1.]
	var currentDriver;
	var currentDriverIsOk = true;
  for(var i=0;i<numOfStations;++i) {
  	 var tmptrSortElem = eval('frm.jobDataTarget_' + i + '_tr_sort');
  	 var tmptrSortValue = tmptrSortElem.value;
  	
  	 // Check for all stations but NOT the pick up address
  	 if (tmptrSortValue != '1') {
  	 	  // Get current driver of the row
  	 	  currentDriver = '';
  	    var tmpCrvhSidElem = eval('frm.jobDataTarget_' + i + '_crvh_sid');
        for(var j=0;j<tmpCrvhSidElem.length;++j) {
           if (tmpCrvhSidElem.options[j].selected == true) {
              currentDriver = tmpCrvhSidElem.options[j].value;
           }
        }
        // Check "currentDriver" being in "driverPool"
        var tmpBool = false;
        for(var j=0;j<driverPoolLen;++j) {
           if (driverPool[j] == currentDriver) {
              tmpBool = true;
           }
        }
        // At least one occurrence is enough to abort the submit
        if (!tmpBool) {
           currentDriverIsOk = false;
           submitOk = false;        	
        }
     }
  }
  if (!currentDriverIsOk) {
  	 alert('<?php echo getLngt("Die eingetragenen Fahrer der Auslieferstationen müssen aus der Menge der eingetragenen Fahrer der Abholstationen sein!") ?>');
  }  

	if (submitOk) {
     finishPage('save');
	}
}

function finishFinalSave(cscId) {
	var submitOk = false;

  if (confirm('<?php echo getLngt("Haben Sie alle Änderungen übernommen? Diese würden ansonsten verworfen werden!") ?>')) {
	   if (confirm('<?php echo getLngt("Möchten Sie die Aufträge zur weiteren Bearbeitung finalisieren?") ?>')) {
	   	  document.forms[0].f_costcenter.value = cscId;
		    submitOk = true;
     }
  }

	if (submitOk) {
     finishPage('final_save');
	}	
}

function changeCostcenter() {
	var submitOk = false;
	// Check existence of any scanned tracking IDs
	var scannedIDexists = false;
	var scan;
	for(var i=0;i<numOfStations;++i) {
		 scan = eval('frm.jobDataTarget_' + i + '_scan').value;
		 scan = trim(scan);
		 if (scan != '') {
		 	  scannedIDexists = true;
		 }
  }
  if (scannedIDexists) {
	   if (confirm('<?php echo getLngt("Achtung! Es ist mindestens ein Barcode gescanned worden. Bei einem Kostenstellenwechsel gehen diese Informationen verloren. Möchten Sie fortfahren?") ?>')) {
        submitOk = true;
     }
  } else {
  	submitOk = true;
  }
  if (submitOk) {
	   finishPage('');
	}
}

function searchScanAddress(elemNo, adId, adStreet, adZipcode, adCity, jbId, trSort, trHsno) {
  var f_act = 'search';
  var widthPopupWin = 1200;
  var heightPopupWin = 800;
  var leftPopupWin = (screen.width / 2) - (widthPopupWin / 2) - 12;
  var topPopupWin = (screen.height / 2) - (heightPopupWin / 2) - 50;
  var popupWin;
  popupWin = window.open("../tools/ad_list2.php?f_act=" + f_act + "&elemNo=" + elemNo + "&f_ad_id=" + adId + "&f_street=" + adStreet + "&f_zipcode=" + adZipcode + "&f_city=" + adCity + "&f_jb_id=" + jbId + "&f_tr_sort=" + trSort + "&f_tr_hsno=" + trHsno, "","dependent=yes,width=" + widthPopupWin + ",height=" + heightPopupWin +",left=" + leftPopupWin + ",top=" + topPopupWin + ",scrollbars=yes");
};

function showInfo(trackingID) {
  var widthPopupWin = 315;
  /* var heightPopupWin = 275; */
  var heightPopupWin = 260;
  var leftPopupWin = (screen.width / 2) - (widthPopupWin / 2) - 12;
  var topPopupWin = (screen.height / 2) - (heightPopupWin / 2) - 50;
  var popupWin;
  popupWin = window.open("../tools/show_tracking_id_info.php?f_id=" + trackingID, "Info","dependent=yes,width=" + widthPopupWin + ",height=" + heightPopupWin +",left=" + leftPopupWin + ",top=" + topPopupWin + ",scrollbars=no");
  popupWin.focus();
};

-->
</script>


</head>

<body onLoad="execBodyOnLoad();">

<?php echo $phpMenuOut ?>
<?php echo $phpReducedMenuOut ?>
<?php echo $phpPageTitelOut ?>

<div class="maincontent" name="maincontent" id="maincontent">

  <form name="scan" action="../tools/scan.php" method="post">

    <input type="hidden" name="f_act" value="">
    <?php echo $phpCurrentNavigationInputHidden ?>
    <input type="hidden" name="deactivateMenu" value="<?php echo ec($deactivateMenu) ?>">
    <input type="hidden" name="statusMessage" value="">

    <input type="hidden" name="numOfStations" value="<?php echo $numOfStations ?>">
    <input type="hidden" name="f_costcenter" value="<?php echo $f_costcenter ?>">

    <br><br>

    <center>

  	<?php echo $outCostcenters ?>

  	<b><?php echo getLngt("BARCODE-SCAN:") ?></b>&nbsp;<input type="text" id="f_scan" name="f_scan" value="" size="20" onblur="javascript:executeScanCode();" border="2">

    <br><br>

    <?php echo $htmlOut ?>

    <br><br>

    <b><?php echo getLngt("Nicht zuzuordnende Paketnummern:") ?></b><br>
    <textarea name="trackingIDsNotFound" cols="100" rows="3" onblur="javascript:setScanFocus();"><?php echo $trackingIDsNotFound; ?></textarea>

    <br><br>

    <input type="button" name="button_save_changes" value="<?php echo getLngt("Fahrzeugänderungen übernehmen") ?>" onclick="javascript:finishSave();">
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    <!-- <input type="button" name="button_save_changes" value="<?php echo getLngt("Alle Aufträge freigeben") ?>" onclick="javascript:finishFinalSave();"> -->

    </center>

  </div>

  </form>

</div>

</body>

</html>
