<?php
include_once ("../include/global.inc.php");
include_once ("../include/auth.inc.php");
include_once ("../include/inc_vehicle.inc.php");
include_once ("../include/inc_job.inc.php");


// Check HTTP-Parameters
getSecHttpVars("1",array("f_act", "mode", "hourTimeUnits", "crvhId", "currDay", "hour", "hourUnit", "timeslots", "jbId", "csId", "content", "crvhSidMovedTo",
                         "value_01", "value_02", "value_03", "value_04", "value_05"));

if ($mode != "") :
   header("Content-Type: text/html; charset=ISO-8859-1\n");
endif;
                           
// echo "alert('" . $mode . " ' + '" . $hourTimeUnits . " ' + '" . $crvhId . " ' + '" . $currDay . " ' + '" . $jbId . " ');";
// ajaxRequestGet('../include/ajaxReqDisposition.php', 'mode=setAssocCrvhJb&crvhId=' + crvhId + '&hour=' + hour + '&hourUnit=' + hourUnit + '&timeslots=' + draggableTimeslots);


// Get global mode of usage
$globalParUseRelatedCustomer = getParameterValue("0", "GLOBAL_USE_RELATED_CUSTOMER", "0");
if ($globalParUseRelatedCustomer != "1") :
   include ("../include/copy_job.inc.php");
endif;


// ***********
// * ACTIONS *
// ***********

if ($mode == "setAssocCrvhJb") :

   // Make association between eco and vehicle persistent in db
   $retBool = setAssocCrvhJb($jbId, $crvhId, $csId, $currDay, $hour, $hourUnit, $timeslots, $hourTimeUnits);

   if ($retBool) :
       echo "isUpdatedInDb = '1';";
   else :
       echo "isUpdatedInDb = '0';";
   endif;


elseif ($mode == "removeAssocCrvhJb") : 

   // Removes an association between eco and any vehicle persistent in db
   $retBool = removeAssocCrvhJb($jbId, $csId, $hourTimeUnits);
   if ($retBool) :
       echo "isRemovedFromDb = '1';";
   else :
       echo "isRemovedFromDb = '0';";
   endif;


elseif ($mode == "checkAvailabilityCrvhJb") :

   // Check the availability of the specified vehicle for the requested interval
   $capacityProblem = "0";
   if ($hourTimeUnits != "" && is_numeric($hourTimeUnits) && $crvhId != "" && is_numeric($crvhId) && $currDay != "" && $hour != "" && is_numeric($hour) && 
       $hourUnit != "" && is_numeric($hourUnit) && $timeslots != "" && is_numeric($timeslots) && $jbId != "" && is_numeric($jbId)) :

       // Get first timeslot and last timeslot (interval)
       $startTimeslotToBeChecked = $currDay . '_' . pad($hour, 2) . '_' . pad($hourUnit, 2);
       $tmpHour = $hour;
       $tmpHourUnit = $hourUnit;        
       for ($i = 0; $i < $timeslots; $i++) :
           $tmpHourUnit++;
           if ($tmpHourUnit == $hourTimeUnits) :
              $tmpHour++;
              $tmpHourUnit = 0;
           endif;
       endfor;
       $endTimeslotToBeChecked = $currDay . '_' . pad($tmpHour, 2) . '_' . pad($tmpHourUnit, 2);

       $capacityProblem = checkAvailableVehicleCapacity($crvhId, $currDay, $startTimeslotToBeChecked, $endTimeslotToBeChecked, $jbId);
   endif;
   echo "capacityProblem = '" . $capacityProblem . "';";


elseif ($mode == "checkAvailabilityCrvhMultipleDayJb") :

   // Check the availability of the specified vehicle for the requested interval
   $capacityProblem = "1";
   if ($hourTimeUnits != "" && is_numeric($hourTimeUnits) && $crvhId != "" && is_numeric($crvhId) && $currDay != "" && $hour != "" && is_numeric($hour) && 
       $hourUnit != "" && is_numeric($hourUnit) && $jbId != "" && is_numeric($jbId)) :

       // Get the the number of days with their time units 
       // E.g. jb_timeunits = 116 and $csRelatedMaxTimeunitsService = 48 <=> retArray[0] = 48, retArray[1] = 48, retArray[2] = 20 (rest of example with 116)
       $daysWithJobTimeUnitsArray = getMultipleDayJobTimeUnitsPerDay($jbId, $csId);
       $daysWithJobTimeUnitsArrayLen = count($daysWithJobTimeUnitsArray);
       if ($daysWithJobTimeUnitsArrayLen > 0) :
          // Get earliest start time of the related customer
          $parCsRelatedDayStartTimeunit = getObjectBasedParameterValue("CS_DAY_TIMEUNIT_START", $csId, $hq_id);
          if ($parCsRelatedDayStartTimeunit == "") :
             // Gets the first (start)timeunit of the first daytime interval from metatype (e.g. "08_00") !!!!
             $tmpTimeIntervalArray = metatypeGetMappedValues("day_time", $hourTimeUnits, $csId, "cs", "");
             $parCsRelatedDayStartTimeunit = $tmpTimeIntervalArray[0][0];
          endif;
          if ($parCsRelatedDayStartTimeunit == "") : $parCsRelatedDayStartTimeunit = "08_00"; endif;  // Fallback

          $allDaysLocked = true;
          $dayLockedArray = array();
          $vhtDayCapacities = true;
          for ($i = 0; $i < $daysWithJobTimeUnitsArrayLen; $i++) :
              $tmpDay = getDateTime("format", array(0,0,0,substr($currDay,5,2),substr($currDay,8,2) + $i,substr($currDay,0,4)), "Y-m-d");

              // Lock vehicle for this day
              $res = updateStmt("vehicleavailability", "crvh_id", $crvhId, array("vha_lock", "1"), "vha_day = '" . $tmpDay . "' AND vha_lock = '0'");
              if ($db->affected_rows == 0) :
                 $capacityProblem = "0";
                 $allDaysLocked = false;
                 $dayLockedArray[$i] = false;
                 break;
              else :
                 $dayLockedArray[$i] = true;
              endif;
          endfor;

          // Check capacities of involved days
          if ($allDaysLocked) :
             for ($i = 0; $i < $daysWithJobTimeUnitsArrayLen; $i++) :
                 $tmpDay = getDateTime("format", array(0,0,0,substr($currDay,5,2),substr($currDay,8,2) + $i,substr($currDay,0,4)), "Y-m-d");
                 // Get first timeslot and last timeslot (interval) to check the vehicle availability
                 if ($i == 0) :
                    $startTimeslotToBeChecked = $tmpDay . '_' . pad($hour, 2) . '_' . pad($hourUnit, 2);
                    $tmpHour = $hour;
                    $tmpHourUnit = $hourUnit;
                 else :
                    $startTimeslotToBeChecked = $tmpDay . '_' . $parCsRelatedDayStartTimeunit;
                    $tmpHour = substr($parCsRelatedDayStartTimeunit,0,2);
                    $tmpHourUnit = substr($parCsRelatedDayStartTimeunit,3,2);
                 endif;
                 for ($j = 0; $j < $daysWithJobTimeUnitsArray[$i]; $j++) :
                     $tmpHourUnit++;
                     if ($tmpHourUnit == $hourTimeUnits) :
                        $tmpHour++;
                        $tmpHourUnit = 0;
                     endif;
                 endfor;
                 $endTimeslotToBeChecked = $tmpDay . '_' . pad($tmpHour, 2) . '_' . pad($tmpHourUnit, 2);
                 $capacityProblem = checkAvailableVehicleCapacity($crvhId, $tmpDay, $startTimeslotToBeChecked, $endTimeslotToBeChecked, $jbId);
                 if ($capacityProblem == "1") :  // Restriction payload check will not be achieved. (Presently...!)
                    $vhtDayCapacities = false;
                    break;
                 endif;
             endfor;
          endif;

          // Unlock 
          for ($i = 0; $i < $daysWithJobTimeUnitsArrayLen; $i++) :
              if ($dayLockedArray[$i]) :
                 $tmpDay = getDateTime("format", array(0,0,0,substr($currDay,5,2),substr($currDay,8,2) + $i,substr($currDay,0,4)), "Y-m-d");
                 updateStmt("vehicleavailability", "crvh_id", $crvhId, array("vha_lock", "0"), "vha_day = '" . $tmpDay . "'");
              endif;
          endfor;
       endif;
   endif;
   echo "capacityProblem = '" . $capacityProblem . "';";
   
   
elseif ($mode == "checkMovedJobDependingOnAnotherJob") :

   // Check the availability of the specified vehicle for the requested interval
   $timeProblem = "";
   if ($jbId != "" && is_numeric($jbId) && $currDay != "" && $hour != "" && is_numeric($hour) && $hourUnit != "" && is_numeric($hourUnit)) :

       // Start time unit of the moved job
       $jbStartTimeunitToBeChecked = $currDay . '_' . pad($hour, 2) . '_' . pad($hourUnit, 2);

       // [1] Check installation job cannot be moved in timeline before delivery job
       $jbIdParent = getFieldValueFromId("job","jb_id",$jbId,"jb_id_parent");  // Get job parent if does exist
       if ($jbIdParent != "" && is_numeric($jbIdParent)) :
          $timeProblem = $jbIdParent;

          // Get beginning timeunit of the parent job
          $jbParentStartTimeunit = getOneStmt("SELECT vhd_timeslot FROM vehicledisposition WHERE jb_id = '" . $jbIdParent . "' ORDER BY vhd_timeslot", "vhd_timeslot");

          // Compare start timeunits
          if ($jbParentStartTimeunit != "" && $jbStartTimeunitToBeChecked <= $jbParentStartTimeunit) :
             $timeProblem = -($jbIdParent);
          endif;
       endif;

       // [2] Check (delivery) job having a child job not able to be moved in timeline behind any child (installation) job
       if ($timeProblem == "" || $timeProblem == "0") :
          $jbIdChildren = getColVectorFromDB2ArrayByClause("job", "jb_id", "jb_id_parent = '" . $jbId . "'", "", "jb_id", "");
          $jbIdChildrenLen = count($jbIdChildren);
          if ($jbIdChildrenLen > 0) :             
             for ($i = 0; $i < $jbIdChildrenLen; $i++) :
                 $timeProblem = $jbIdChildren[$i];
          
                 // Get beginning timeunit of the child job
                 $jbChildStartTimeunit = getOneStmt("SELECT vhd_timeslot FROM vehicledisposition WHERE jb_id = '" . $jbIdChildren[$i] . "' ORDER BY vhd_timeslot", "vhd_timeslot");
          
                 // Compare start timeunits
                 if ($jbChildStartTimeunit != "" && $jbStartTimeunitToBeChecked >= $jbChildStartTimeunit) :
                    $timeProblem = -($jbIdChildren[$i]);
                    break;
                 endif;
             endfor;
          endif;
       endif;
   endif;
   echo "timeProblem = '" . $timeProblem . "';";


elseif ($mode == "sendCartageNote") : 

   $jsReturn = "0";
   if ($crvhId != "" && is_numeric($crvhId) && $currDay != "") :

      $currentDayTime = getDateTime("0");   // "Y-m-d H:i:s" (current timestamp)

      // Get courier ID of the current vehicle
      if ($globalParUseRelatedCustomer == "1") :
         $crvhSid = getFieldValueFromId("couriervehicle","crvh_id",$crvhId,"crvh_sid");   // Get SID, needed for "fake" courier for the vehicle !!!!
         $crId = getFieldValueFromId("courier","cr_sid",$crvhSid,"cr_id");                // Get "fake" courier ID
         $orderByClause = "";
      else :
         // "Classic" tour
         $crvhSid = "";
         $crId = "0";
         $orderByClause = "vhd_timeslot";
      endif;

      // Get all jobs associated to the current vehicle for the current day
      $jbIdArray = getColVectorFromDB2ArrayByClause("vehicledisposition", "jb_id", "crvh_id = '" . $crvhId . "' AND LEFT(vhd_timeslot, 10) = '" . $currDay . "' AND jb_id != '0'", "", $orderByClause, "DISTINCT");
      $jbIdArrayLen = count($jbIdArray);

      // Check jobs being no offers !!!!
      if ($globalParUseRelatedCustomer == "1" && $jbIdArrayLen > 0) :
         $tmpJbIdArray = getColVectorFromDB2ArrayByClause("job", "jb_id", "jb_id IN (" . implode(',', $jbIdArray) . ") AND jb_offer = '0'", "", "", "");
         $jbIdArray = $tmpJbIdArray;
         $jbIdArrayLen = count($jbIdArray);
      endif;

      if ($jbIdArrayLen > 0) :

         TA("B");

         $jsReturn = "1";
         if ($globalParUseRelatedCustomer == "1") :

            for ($i = 0; $i < $jbIdArrayLen; $i++) :

               // Update job
               // According to be TA-safe the WHERE-Clause depends on the current list the user is in
               $res = updateStmt("job", "jb_id", $jbIdArray[$i], array("cr_id", $crId, "cr_id_order", $crId, "jb_status", "1", "cr_sid", $crvhSid, "jb_taketime", $currentDayTime, "jb_globaljob", "0", "jb_autoranking", "0"), "jb_status = '9' AND jb_offer = '0'");

               if ($db->affected_rows > 0) :

                  // Insert PDA command to remove job (take cr_id/cr_id_order before changing)
                  /*
                  $currentTimePDA = getDateTime("datetime_plus_offset", array(0,0,30,0,0,0), $formatStr = "Y-m-d H:i:s");
                  if ($crIdCurrent != "" && $crIdCurrent != "0") :
                     insertPDACommand($jbHqId, $crIdCurrent, "4", "1", $f_jb_id, $currentTimePDA, "");
                  endif;
                  if ($crIdOrderCurrent != "" && $crIdOrderCurrent != "0" && $crIdOrderCurrent != $crIdCurrent) :
                     insertPDACommand($jbHqId, $crIdOrderCurrent, "4", "1", $f_jb_id, $currentTimePDA, "");
                  endif;
                  */
   
                  // Write logdata into log database
                  // writeToLogDB("x",$jbHqId,$f_jb_id,$currentSessionUsrId,$cr_id,$f_cr_sid,"","LOST_RANKING=" . ($arLooseRanking == "1" ? "YES" : "NO"));
   
                  // Update "vehicledisposition" and remove jobs
                  // updateStmt("vehicledisposition", "jb_id", $jbIdArray[$i], array("jb_id", "0"));
               else :
                  $jsReturn = "0";
                  break;
               endif;
            endfor;
         else :

            // "Classic" tour.
            $jbIdClassic = copy_jobs_cartage($jbIdArray);
            if ($jbIdClassic == "" || !is_numeric($jbIdClassic) || $jbIdClassic == 0) :
               $jsReturn = "0";
            endif;
         endif;

         if ($jsReturn == "1") :
            TA("C");
         else :
            TA("R");
         endif;
         TA("E");
      endif;
   endif;
   if ($jsReturn == "1") :
       echo "updateOK = '1';";
   else :
       echo "updateOK = '0';";
   endif;


elseif ($mode == "mailCartageNote") : 

   $jsReturn = cartageNoteSendMail($csId, $crvhId, $currDay);
   echo "mailSentOK = '" . $jsReturn . "';";


elseif ($mode == "moveCartageNote") :

   $jsReturn = "0";  // Init with "ERR: No job selected to be moved"
   if ($crvhId != "" && is_numeric($crvhId) && $crvhSidMovedTo != "" && $currDay != "" && $csId != "" && $hourTimeUnits != "") :

      // Get courier ID of the CURRENT vehicle
      $crvhSid = getFieldValueFromId("couriervehicle","crvh_id",$crvhId,"crvh_sid");  // Get SID, needed for "fake" courier for the vehicle !!!!
      $crId = getFieldValueFromId("courier","cr_sid",$crvhSid,"cr_id");               // Get "fake" courier ID

      // Get courier vehicle ID and courier ID of the TARGET vehicle
      $crvhIdMovedTo = getFieldValueFromId("couriervehicle","crvh_sid",$crvhSidMovedTo,"crvh_id");  // Get ID of the vehicle the cartage note will be moved to
      $crIdMovedTo = getFieldValueFromId("courier","cr_sid",$crvhSidMovedTo,"cr_id");               // Get "fake" courier ID

      $currentDayTime = getDateTime("0");   // "Y-m-d H:i:s" (current timestamp)

      // Get all timeslots of the CURRENT vehicle having a job at the specified day
      $currentVhdTimeslotArray = getColVectorFromDB2ArrayByClause("vehicledisposition", "vhd_timeslot", "crvh_id = '" . $crvhId . "' AND LEFT(vhd_timeslot, 10) = '" . $currDay . "' AND jb_id != '0'", "", "", "");
      $currentVhdTimeslotArrayLen = count($currentVhdTimeslotArray);

      $doContinue = false;
      if ($currentVhdTimeslotArrayLen > 0) :
         // Check timeslots have to be free for TARGET vehicle
         /*
         $currentVhdTimeslots = "'" . implode("','", $currentVhdTimeslotArray) . "'";         
         $jbIdTargetArray = getColVectorFromDB2ArrayByClause("vehicledisposition", "jb_id", "crvh_id = '" . $crvhIdMovedTo . "' AND LEFT(vhd_timeslot, 10) = '" . $currDay . "' AND jb_id != '0' AND vhd_timeslot IN (" . $currentVhdTimeslots . ")", "", "", "DISTINCT");
         $jbIdTargetArrayLen = count($jbIdTargetArray);
         if ($jbIdTargetArrayLen == 0) :
            $doContinue = true;
         endif;
         */

         // Get all timeslots of the TARGET vehicle having a job at the specified day
         $movedToVhdTimeslotArray = getColVectorFromDB2ArrayByClause("vehicledisposition", "vhd_timeslot", "crvh_id = '" . $crvhIdMovedTo . "' AND LEFT(vhd_timeslot, 10) = '" . $currDay . "' AND jb_id != '0'", "", "", "");
         // $movedToVhdTimeslotArrayLen = count($movedToVhdTimeslotArray);
         
         // Check intersection of both timeslot arrays
         $intersectTimeslotArray = array_intersect($currentVhdTimeslotArray, $movedToVhdTimeslotArray);
         $intersectTimeslotArrayLen = count($intersectTimeslotArray);
         if ($intersectTimeslotArrayLen == 0) :
            $doContinue = true;
         endif;
      endif;

      if ($doContinue) :
         // Get all jobs associated to the CURRENT vehicle for the current day
         $jbIdArray = getColVectorFromDB2ArrayByClause("vehicledisposition", "jb_id", "crvh_id = '" . $crvhId . "' AND LEFT(vhd_timeslot, 10) = '" . $currDay . "' AND jb_id != '0'", "", "", "DISTINCT");
         $jbIdArrayLen = count($jbIdArray);

         // Check jobs being no offers !!!!
         /*
         if ($jbIdArrayLen > 0) :
            $tmpJbIdArray = getColVectorFromDB2ArrayByClause("job", "jb_id", "jb_id IN (" . implode(',', $jbIdArray) . ") AND jb_offer = '0'", "", "", "");
            $jbIdArray = $tmpJbIdArray;
            $jbIdArrayLen = count($jbIdArray);
         endif;
         */

         if ($jbIdArrayLen > 0) :

            TA("B");            

            $jsReturn = "1";  // Jobs will be moved. (OK!)
            for ($i = 0; $i < $jbIdArrayLen; $i++) :

                $jbId = $jbIdArray[$i];
                $retBool = removeAssocCrvhJb($jbId, $csId, $hourTimeUnits);
                if ($retBool) :
                   $jbOrdertime = getFieldValueFromId("job","jb_id",$jbId,"jb_ordertime");
                   $hour = substr($jbOrdertime,11,2);
                   $hourUnit = pad(strval(ceil(intval(substr($jbOrdertime,14,2)) * ($hourTimeUnits / 60))), 2);
                   $jbTimeunits = getFieldValueFromId("job","jb_id",$jbId,"jb_timeunits");
                   $retBool = setAssocCrvhJb($jbId, $crvhIdMovedTo, $csId, $currDay, $hour, $hourUnit, $jbTimeunits, $hourTimeUnits);
                endif;
                              
                if (!$retBool) :
                   $jsReturn = "0";
                   break;
                endif;
            endfor;

            // Update FDS for both vehicles after all operations
            updateVehicleAvailability($crvhId, $csId, $currDay);
            updateVehicleAvailability($crvhIdMovedTo, $csId, $currDay);

            if ($jsReturn == "1") :
               TA("C");
            else :
               TA("R");
            endif;
            TA("E");
         endif;
      else :
         $jsReturn = "2";  // ERR: At least one time unit is NOT free for target vehicle
      endif;
   endif;
   echo "movementState = '" . $jsReturn . "';";


elseif ($mode == "sendSingleJob") :

   $jsReturn = "0";
   if ($jbId != "" && is_numeric($jbId)) :

      TA("B");            

      $crvhId = getOneStmt("SELECT crvh_id FROM vehicledisposition WHERE jb_id = '" . $jbId . "'", "crvh_id");
      if ($crvhId != "") :

         // Get courier ID of the current vehicle
         if ($globalParUseRelatedCustomer == "1") :
            $crvhSid = getFieldValueFromId("couriervehicle","crvh_id",$crvhId,"crvh_sid");   // Get SID, needed for "fake" courier for the vehicle !!!!
            $crId = getFieldValueFromId("courier","cr_sid",$crvhSid,"cr_id");                // Get "fake" courier ID
         else :
            // "Classic" tour
            $crvhSid = "";
            $crId = "0";
         endif;

         $currentDayTime = getDateTime("0");   // "Y-m-d H:i:s" (current timestamp)

         $jsReturn = "1";

         // Update job
         // According to be TA-safe the WHERE-Clause depends on the current list the user is in
         $res = updateStmt("job", "jb_id", $jbId, array("cr_id", $crId, "cr_id_order", $crId, "jb_status", "1", "cr_sid", $crvhSid, "jb_taketime", $currentDayTime, "jb_globaljob", "0", "jb_autoranking", "0"), "jb_status = '9' AND jb_offer = '0'");

         if ($db->affected_rows > 0) :

            // Update "vehicledisposition" and remove jobs
            // updateStmt("vehicledisposition", "jb_id", $jbId, array("jb_id", "0"));

            // Write logdata into log database
            // writeToLogDB("x",$jbHqId,$f_jb_id,$currentSessionUsrId,$cr_id,$f_cr_sid,"","LOST_RANKING=" . ($arLooseRanking == "1" ? "YES" : "NO"));
         else :
            $jsReturn = "0";
         endif;
      endif;

      TA("C");
      TA("E");
   endif;
   if ($jsReturn == "1") :
       echo "updateOK = '1';";
   else :
       echo "updateOK = '0';";
   endif;


elseif ($mode == "revokeSingleJob") :

   $jsReturn = "0";
   if ($jbId != "" && is_numeric($jbId)) :

      TA("B");            

      $jsReturn = "1";

      // Update job
      // According to be TA-safe the WHERE-Clause depends on the current list the user is in
      $res = updateStmt("job", "jb_id", $jbId, array("cr_id", "", "cr_id_order", "", "jb_status", "9", "cr_sid", "", "jb_taketime", "", "jb_globaljob", "0", "jb_autoranking", "0"), "jb_status = '1'");

      if ($db->affected_rows > 0) :

         // Write logdata into log database
         // writeToLogDB("x",$jbHqId,$f_jb_id,$currentSessionUsrId,$cr_id,$f_cr_sid,"","LOST_RANKING=" . ($arLooseRanking == "1" ? "YES" : "NO"));
      else :
         $jsReturn = "0";
      endif;

      TA("C");
      TA("E");
   endif;
   if ($jsReturn == "1") :
       echo "updateOK = '1';";
   else :
       echo "updateOK = '0';";
   endif;


elseif ($mode == "changeDateOfJob") :

   $jsReturn = "0";
   if ($jbId != "" && is_numeric($jbId) && $content != "") :

      TA("B");            

      // Update job
      // According to be TA-safe the WHERE-Clause depends on the current list the user is in
      $res = updateStmt("job", "jb_id", $jbId, array("jb_ordertime", $content), "jb_status != '2'");

      if ($db->affected_rows > 0) :

         if (existsEntry("vehicledisposition",array("jb_id",$jbId))) :
            $res = updateStmt("vehicledisposition", "jb_id", $jbId, array("jb_id", '0'), "");
            if ($db->affected_rows > 0) :
               $jsReturn = "1";

               // Write logdata into log database
               // writeToLogDB("x",$jbHqId,$f_jb_id,$currentSessionUsrId,$cr_id,$f_cr_sid,"","LOST_RANKING=" . ($arLooseRanking == "1" ? "YES" : "NO"));
            endif;
         else :
            $jsReturn = "1";

            // Write logdata into log database
            // writeToLogDB("x",$jbHqId,$f_jb_id,$currentSessionUsrId,$cr_id,$f_cr_sid,"","LOST_RANKING=" . ($arLooseRanking == "1" ? "YES" : "NO"));
         endif;
      endif;

      TA("C");
      TA("E");
   endif;
   if ($jsReturn == "1") :
       echo "updateOK = '1';";
   else :
       echo "updateOK = '0';";
   endif;


elseif ($mode == "getCrvhData") :

   $retData = "";
   if ($crvhId != "" && is_numeric($crvhId) && $currDay != "") :

      $crvhSid = getFieldValueFromId("couriervehicle", "crvh_id", $crvhId, "crvh_sid");
      $crvhTotalBusinessVolumeOfTheDay_ALL = 0;

      // Get business volume for the requested vehicle for the requested day
      // 1. Take NOT associated jobs (existing in "vehicledisposition" only)
      $jbIdArray = getColVectorFromDB2ArrayByClause("vehicledisposition", "jb_id", "crvh_id = '" . $crvhId . "' AND LEFT(vhd_timeslot, 10) = '" . $currDay . "' AND jb_id != '0'", "", "", "DISTINCT");
      $jbIdArrayLen = count($jbIdArray);
      
      $crvhTotalBusinessVolumeOfTheDay_01 = 0;
      if ($jbIdArrayLen > 0) :
         $crvhTotalBusinessVolumeOfTheDay_01 = getSumOfTable("job", "jb_totalprice", "jb_id IN (" . implode(",", $jbIdArray) . ") AND jb_status IN ('9','0')");
         $crvhTotalBusinessVolumeOfTheDay_ALL += $crvhTotalBusinessVolumeOfTheDay_01;
      endif;

      // 2. Take associated jobs
      $crvhTotalBusinessVolumeOfTheDay_02 = 0;
      if ($crvhSid != "") :
         $crvhTotalBusinessVolumeOfTheDay_02 = getSumOfTable("job", "jb_totalprice", "cr_sid = '" . $crvhSid . "' AND jb_status = '1' AND LEFT(jb_ordertime, 10) = '" . $currDay . "'");
         if ($crvhTotalBusinessVolumeOfTheDay_02 != -1) :
            $crvhTotalBusinessVolumeOfTheDay_ALL += $crvhTotalBusinessVolumeOfTheDay_02;
         endif;
      endif;

      // 3. Take finished jobs
      $crvhTotalBusinessVolumeOfTheDay_03 = 0;
      if ($crvhSid != "") :
         $crvhTotalBusinessVolumeOfTheDay_03 = getSumOfTable("job", "jb_totalprice", "cr_sid = '" . $crvhSid . "' AND jb_status = '2' AND LEFT(jb_ordertime, 10) = '" . $currDay . "' AND (isnull(jb_storno) OR jb_storno = '0' OR jb_storno = '1')");
         if ($crvhTotalBusinessVolumeOfTheDay_03 != -1) :
            $crvhTotalBusinessVolumeOfTheDay_ALL += $crvhTotalBusinessVolumeOfTheDay_03;
         endif;
      endif;

      // 4. Take total weight of the vehicle
      $crvhTotalWeightOfTheDay = 0;
      for ($i = 0; $i < $jbIdArrayLen; $i++) :
          $crvhTotalWeightOfTheDay += getTratTotalweight($jbIdArray[$i]);
      endfor;

      // 5. Take sum of packing pieces of the vehicle
      $crvhSumOfPackingPiecesOfTheDay = 0;
      for ($i = 0; $i < $jbIdArrayLen; $i++) :
          $crvhSumOfPackingPiecesOfTheDay += getTratPackingPieces($jbIdArray[$i]);
      endfor;


      // Get gross values
      $taxFactor = 1.19;
      if ($jbIdArrayLen > 0) :
         $taxFactor = getSalesTaxFactor($jbIdArray[0]);  // Get sales tax factor
      endif;
      $crvhTotalBusinessVolumeOfTheDay_01 *= $taxFactor;
      $crvhTotalBusinessVolumeOfTheDay_02 *= $taxFactor;
      $crvhTotalBusinessVolumeOfTheDay_03 *= $taxFactor;
      $crvhTotalBusinessVolumeOfTheDay_ALL *= $taxFactor;

      $retData .= "<table>";
      $retData .= "<tr><td>" . getLngt("Gesamtgewicht aller Aufträge") . "</td><td>&nbsp;:&nbsp;&nbsp;</td><td align=\"right\">" . number_format(round($crvhTotalWeightOfTheDay, 3), 3, ",", ".") . " " . getLngt("KG") . "</td></tr>";
      $retData .= "<tr><td>" . getLngt("Anzahl Packstücke aller Aufträge") . "</td><td>&nbsp;:&nbsp;&nbsp;</td><td align=\"right\">" . number_format($crvhSumOfPackingPiecesOfTheDay, 0, ",", ".") . " " . getLngt("PCS") . "</td></tr>";
      $retData .= "<tr><td>&nbsp;</td><td>&nbsp;:&nbsp;&nbsp;</td><td align=\"right\">&nbsp;</td></tr>";
      $retData .= "<tr><td>" . getLngt("Summe nicht gesendeter Aufträge") . "</td><td>&nbsp;:&nbsp;&nbsp;</td><td align=\"right\">" . number_format(round($crvhTotalBusinessVolumeOfTheDay_01, 2), 2, ",", ".") . "</td></tr>";
      $retData .= "<tr><td>" . getLngt("Summe angenommener Aufträge") . "</td><td>&nbsp;:&nbsp;&nbsp;</td><td align=\"right\">" . number_format(round($crvhTotalBusinessVolumeOfTheDay_02, 2), 2, ",", ".") . "</td></tr>";
      $retData .= "<tr><td>" . getLngt("Summe erledigter Aufträge") . "</td><td>&nbsp;:&nbsp;&nbsp;</td><td align=\"right\">" . number_format(round($crvhTotalBusinessVolumeOfTheDay_03, 2), 2, ",", ".") . "</td></tr>";
      $retData .= "<tr><td><b>" . getLngt("Summe aller Aufträge") . "</b></td><td>&nbsp;:&nbsp;&nbsp;</td><td align=\"right\"><b>" . number_format(round($crvhTotalBusinessVolumeOfTheDay_ALL, 2), 2, ",", ".") . "</b></td></tr>";
      $retData .= "</table>";
      
      $retData = my_char_conversion($retData);
   endif;
   echo "retCrvhData = '" . my_str_check_js($retData) . "';";


elseif ($mode == "getTourarticleData") :

   $retData = "";
   if ($jbId != "" && is_numeric($jbId)) :

      $retData = getOutputJobTratArticleData($jbId, "1");
      $retData = my_char_conversion($retData);
   endif;
   echo "retTratData = '" . my_str_check_js($retData) . "';";


elseif ($mode == "getJobcalculatorData") :

   $retData = "";
   if ($jbId != "" && is_numeric($jbId)) :

      $retData = getOutputJobCalculatorData ($jbId, "1");
      $retData = my_char_conversion($retData);
   endif;
   echo "retTratData = '" . my_str_check_js($retData) . "';";


elseif ($mode == "getJobContentData") :

   $retData = "";
   if ($jbId != "" && is_numeric($jbId)) :

      getDBData("job", $jbId);
      if (count($jobData["job"]) > 0) :

         $jbFreetext1 = getFieldValueFromId("job", "jb_id", $jbId, "jb_freetext_1");  // Time interval for the customer
         $jbFreetext1 = trim($jbFreetext1);
         $taxFactor = getSalesTaxFactor($jb_id);  // Get sales tax factor
         $cscIdRelated = $jobData["job"]["csc_id_related"];
         $csId = getFieldValueFromId("costcenter", "csc_id", $cscIdRelated, "cs_id");
         $ecoIdOut = getJobIdOutput($jbId, $jobData["job"]["jb_id_parent"]);
         getDBData("tour", $jbId);

         $retData .= $ecoIdOut . "<br>";
         $retData .= getJobDaytimeTimeInterval($jobData["job"]["jb_ordertime"], $jbFreetext1, $csId, "") . "<br>";
         $retData .= $jobData["tour"][2]["ad_street"] . " " . $jobData["tour"][2]["tr_hsno"] . "<br>";
         $retData .= $jobData["tour"][2]["ad_zipcode"] . " " . $jobData["tour"][2]["ad_city"] . "<br>";
         $retData .= $jobData["job"]["jb_timeunits"] . " " . getLngt("ZE") . "<br>";
         $retData .= number_format(round(($jobData["job"]["jb_totalprice"] * $taxFactor), 2), 2, ",", ".") . " &euro;";
         
         $retData = my_char_conversion($retData);
      endif;
   endif;
   echo "retData = '" . my_str_check_js($retData) . "';";
   

elseif ($mode == "crvhBlock") :

   $retBlocked = crvhBlock($crvhId, $currDay);
   echo "retValue = '" . $retBlocked . "';";


elseif ($mode == "crvhUnblock") :

   $retUnblocked = crvhUnblock($crvhId, $currDay);
   echo "retValue = '" . $retUnblocked . "';";


elseif ($mode == "crvhIsBlocked") :

   $blockedState = "0";
   $retIsBlocked = crvhIsBlocked($crvhId, $currDay, 0);
   if ($retIsBlocked) :
      $blockedState = "1";
   endif;
   echo "retValue = '" . $blockedState . "';";


elseif ($mode == "crvhIsCarrierBlocked") :

   $blockedState = "0";
   $retIsBlocked = crvhIsBlocked($crvhId, $currDay, 1);
   if ($retIsBlocked) :   
      $blockedState = "1";
   endif;
   echo "retValue = '" . $blockedState . "';";


elseif ($mode == "crvhBlockedState") :

   $retBlockedState = crvhBlockedState($crvhId, $currDay);
   echo "retBlockedState = '" . $retBlockedState . "';";


elseif ($mode == "dayBlock" || $mode == "dayUnblock") :

   $retBlockedState = "";
   if ($csId != "" && is_numeric($csId) && $currDay != "") :

      // Get all vehicles of the current customer and selected day
      $sqlquery = getStmtCustomerVehicleRelation("", $csId, $crvhWhereClauseService);
      $result = $db->query($sqlquery);
      if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
      $crvhList = array();
      while ($row = $result->fetch_assoc()):
            $crvhList[] = $row["crvh_id"];  // $row["cs_id"], $row["cs_eid"], $row["csvh_day_times"], $row["crvh_sid"], $row["csvh_relation"], $row["cmp_comp"], $row["cmp_comp2"], $row["hq_id"], $row["csvh_description"], $row["crvh_service"]
      endwhile;
      $result->free();
      $crvhListLen = count($crvhList);
      for ($i = 0; $i < $crvhListLen; $i++) :
          if ($mode == "dayBlock") :
             $retBlockedState = crvhBlock($crvhList[$i], $currDay);
          else :
             $retBlockedState = crvhUnblock($crvhList[$i], $currDay);
          endif;
      endfor;

      $gdcContent = "0";
      if ($mode == "dayBlock") :
         $gdcContent = "1";
      endif;
      if (existsEntry("genericdatacontainer",array("gdc_obj_type","vha","gdc_obj_id",$csId,"gdc_gen_fieldname","vha_day_blocked","gdc_context",$currDay))) :
         updateStmt("genericdatacontainer","gdc_obj_type","vha",array("gdc_content", $gdcContent),"gdc_obj_id = '" . $csId . "' AND gdc_gen_fieldname = 'vha_day_blocked' AND gdc_context = '" . $currDay . "'");
      else :
         insertStmt("genericdatacontainer", array("gdc_obj_type", "vha", "gdc_obj_id", $csId, "gdc_gen_fieldname", "vha_day_blocked", "gdc_content", $gdcContent, "gdc_context", $currDay));
      endif;
   endif;
   echo "retBlockedState = '" . $retBlockedState . "';";


elseif ($mode == "crvhBlockForCourierDispo") :

   $retBlocked = crvhBlockForCourierDispo($crvhId, $currDay);
   echo "retValue = '" . $retBlocked . "';";


elseif ($mode == "crvhUnblockForCourierDispo") :

   $retUnblocked = crvhUnblockForCourierDispo($crvhId, $currDay);
   echo "retValue = '" . $retUnblocked . "';";


elseif ($mode == "jobBlockForCourierDispo") :

   $retBlocked = "";
   if ($jbId != "" && is_numeric($jbId)) :
      if (existsEntry("vehicledisposition",array("jb_id",$jbId))) :
         $res = updateStmt("job", "jb_id", $jbId, array("jb_status", "0"), "jb_status = '9' AND jb_offer = '0'");
         if ($db->affected_rows > 0) :
            $retBlocked = "1";
         endif;
      endif;
   endif;
   echo "retValue = '" . $retBlocked . "';";


elseif ($mode == "jobUnblockForCourierDispo") :

   $retBlocked = "";
   if ($jbId != "" && is_numeric($jbId)) :
      if (existsEntry("vehicledisposition",array("jb_id",$jbId))) :
         $res = updateStmt("job", "jb_id", $jbId, array("jb_status", "9"), "jb_status = '0'");
         if ($db->affected_rows > 0) :
            $retBlocked = "1";
         endif;
      endif;
   endif;
   echo "retValue = '" . $retBlocked . "';";


elseif ($mode == "jobGetParent") :

   $retVal = "";
   if ($jbId != "" && is_numeric($jbId)) :
      $retVal = getFieldValueFromId("job", "jb_id", $jbId, "jb_id_parent");
   endif;
   echo "retParentId = '" . $retVal . "';";


elseif ($mode == "jobGetChild") :

   $retVal = "";
   if ($jbId != "" && is_numeric($jbId)) :
      $retVal = getFieldValueFromId("job", "jb_id_parent", $jbId, "jb_id");
   endif;
   echo "retChildId = '" . $retVal . "';";


elseif ($mode == "jobGetParentCascadeLevel") :

   $retVal = "";
   if ($jbId != "" && is_numeric($jbId)) :
      $retVal = getJobParentCascadeLevel($jbId);
   endif;
   echo "retParentCascadeLevel = '" . $retVal . "';";


elseif ($mode == "isMultipleDayJob") :

   $retVal = isMultipleDayJob($jbId);
   echo "isMultipleDayJob = '" . $retVal . "';";


elseif ($mode == "getMultipleDayJobTimeunits") :

   // Get timeslots of the job for the day selected
   $retVal = "0";
   if ($currDay != "") :
      $daysWithJobTimeUnitsArray = getMultipleDayJobTimeUnitsPerDay($jbId, $csId);
      $daysWithJobTimeUnitsArrayLen = count($daysWithJobTimeUnitsArray);
      // Iterate all involved days to get the timeslots for the selected day
      for ($d = 0; $d < $daysWithJobTimeUnitsArrayLen; $d++) :
          $tmpDay = getDateTime("format", array(0,0,0,substr($currDay,5,2),substr($currDay,8,2) + $d,substr($currDay,0,4)), "Y-m-d");
          if ($tmpDay == $currDay) :
             $retVal = $daysWithJobTimeUnitsArray[$d];
             break;
          endif;
      endfor;
   endif;
   echo "jobMultipleDayTimeunitsOfSelectedDay = '" . $retVal . "';";


elseif ($mode == "setSMSTime") :

   $retVal = "";
   if ($jbId != "" && is_numeric($jbId) && $value_01 != "" && is_numeric($value_01) && $value_02 != "" && is_numeric($value_02)) :

      $gdcContentSms = $value_01 . ":" . $value_02;  // E.g.: "hour:minute" <=> "17:30"
      if (existsEntry("genericdatacontainer",array("gdc_obj_type","jb","gdc_obj_id",$jbId,"gdc_gen_fieldname","sms_time"))) :
         updateStmt("genericdatacontainer","gdc_obj_type","jb",array("gdc_content", $gdcContentSms, "gdc_context", ""),"gdc_obj_id = '" . $jbId . "' AND gdc_gen_fieldname = 'sms_time'");
         $retVal = "1";
      else :
         insertStmt("genericdatacontainer", array("gdc_obj_type", "jb", "gdc_obj_id", $jbId, "gdc_gen_fieldname", "sms_time", "gdc_content", $gdcContentSms, "gdc_context", ""));
         $retVal = "2";
      endif;
   endif;
   echo "retVal = '" . $retVal . "';";


elseif ($mode == "removeMultipleDayJobTimeunitsFromFDS") :

   $retVal = "";
   if ($jbId != "" && is_numeric($jbId) && $currDay != "") :
      $res = updateStmt("vehicledisposition", "jb_id", $jbId, array("jb_id", "0"), "LEFT(vhd_timeslot,10) >= '" . $currDay . "'");
      if ($db->affected_rows > 0) :
         $retVal = "1";
      endif;
   endif;
   echo "retVal = '" . $retVal . "';";


elseif ($mode == "getInternalCourierByVehicle") :

   $retVal = "";
   if ($crvhId != "") :
      // Get courier ID of the current vehicle ("jb.cr_id_order" has to be set regarding the current vehicle)
      $crvhSid = getFieldValueFromId("couriervehicle","crvh_id",$crvhId,"crvh_sid");   // Get SID, needed for "fake" courier for the vehicle !!!!
      $crId = getFieldValueFromId("courier","cr_sid",$crvhSid,"cr_id");                // Get "fake" courier ID
      $retVal = $crId;
   endif;
   echo "retVal = '" . $retVal . "';";


elseif ($mode == "setCourierAndVehicleInJobByVehicle") :

   $retVal = "";
   if ($crvhId != "") :
      // Get courier ID of the current vehicle ("jb.cr_id_order" has to be set regarding the current vehicle)
      $crvhSid = getFieldValueFromId("couriervehicle","crvh_id",$crvhId,"crvh_sid");   // Get SID, needed for "fake" courier for the vehicle !!!!
      $crId = getFieldValueFromId("courier","cr_sid",$crvhSid,"cr_id");                // Get "fake" courier ID
      $res = updateStmt("job", "jb_id", $jbId, array("cr_sid", $crvhSid, "cr_id_order", $crId));
      if ($db->affected_rows > 0) :
         $retVal = "1";
      endif;
   endif;
   echo "retVal = '" . $retVal . "';";


elseif ($mode == "sortVehicleTimeline") :

   $retVal = "";
   if ($csId != "" && $crvhId != "" && $currDay != "" && is_array($content)) :
      $contentLen = count($content);
      if ($contentLen > 0) :
         // Get current job IDs (cartage note) from vehicle of the current day
         $jbIdArray = getColVectorFromDB2ArrayByClause("vehicledisposition", "jb_id", "crvh_id = '" . $crvhId . "' AND LEFT(vhd_timeslot, 10) = '" . $currDay . "' AND jb_id != '0'", "", "vhd_timeslot", "DISTINCT");
         $jbIdArrayLen = count($jbIdArray);
         if ($jbIdArrayLen == $contentLen) :
            // Get earliest start time of the related customer
            $parCsRelatedDayStartTimeunit = getObjectBasedParameterValue("CS_DAY_TIMEUNIT_START", $csId, $hq_id);
            if ($parCsRelatedDayStartTimeunit == "") :
               // Gets the first (start)timeunit of the first daytime interval from metatype (e.g. "08_00") !!!!
               $tmpTimeIntervalArray = metatypeGetMappedValues("day_time", $hourTimeUnits, $csId, "cs", "");
               $parCsRelatedDayStartTimeunit = $tmpTimeIntervalArray[0][0];
            endif;
            if ($parCsRelatedDayStartTimeunit == "") : $parCsRelatedDayStartTimeunit = "08_00"; endif;  // Fallback
            $hour = substr($parCsRelatedDayStartTimeunit,0,2);
            $hourUnit = substr($parCsRelatedDayStartTimeunit,3,2);
            // Remove all jobs from the timeline of the vehicle for the specified day
            for ($i = 0; $i < $jbIdArrayLen; $i++) :
                removeAssocCrvhJb($jbIdArray[$i], $csId, $hourTimeUnits);
            endfor;
            // Resort the jobs by new sorting list
            for ($i = 0; $i < $contentLen; $i++) :
                $sortNo = intval($content[$i]);
                $currJbId = $jbIdArray[$sortNo];
                $jbTimeUnits = getFieldValueFromId("job","jb_id",$currJbId,"jb_timeunits");

                // Set new position in FDS                
                setAssocCrvhJb($currJbId, $crvhId, $csId, $currDay, $hour, $hourUnit, $jbTimeUnits, $hourTimeUnits);

                // Set new ordertime of the current job
                $newOrdertime = $currDay . " " . pad($hour,2) . ":" . pad(($hourUnit * (60 / $hourTimeUnits)), 2) . ':00';
                updateStmt("job", "jb_id", $currJbId, array("jb_ordertime", $newOrdertime));
                
                // Compute start time for the next job
                $tmpHour = intval($hour);
                $tmpHourUnit = intval($hourUnit);
                $tmpTimeslots = 0;
                for ($j = $tmpHour; $j <= 23; $j++) :
                    for ($k = $tmpHourUnit; $k < $hourTimeUnits; $k++) :
                       if ($tmpTimeslots == $jbTimeUnits) :
                          $hour = pad($j, 2);
                          $hourUnit = pad($k, 2);
                          break 2;
                       endif;
                       $tmpTimeslots++;
                    endfor;
                    $tmpHourUnit = 0;  // Init because the daily start time e.g. could start 08:30 et al.
                endfor;
            endfor;

            // Update FDS for both vehicles after all operations
            updateVehicleAvailability($crvhId, $csId, $currDay);
         endif;
      else :
         echo "alert('" . getLngt("Achtung: Die Ursprungsliste hat sich während der Bearbeitung geändert! Der Vorgang musste leider abgebrochen werden!") . "');";
      endif;
   endif;
   // echo "isSorted = '" . $retVal . "';";
   echo "isSorted = '1';";


elseif ($mode == "sortVehicleTimelineByNewOrdertimes") :

   $retVal = "";
   if ($csId != "" && $crvhId != "" && $currDay != "" && is_array($content)) :
      $contentLen = count($content);
      if ($contentLen > 0) :
         // Get new ordertimes
         $newOrdertimeArray = spliti("_", $value_01);

         // Get current job IDs (cartage note) from vehicle of the current day
         $jbIdArray = getColVectorFromDB2ArrayByClause("vehicledisposition", "jb_id", "crvh_id = '" . $crvhId . "' AND LEFT(vhd_timeslot, 10) = '" . $currDay . "' AND jb_id != '0'", "", "vhd_timeslot", "DISTINCT");
         $jbIdArrayLen = count($jbIdArray);
         if ($jbIdArrayLen == $contentLen) :
            // Get earliest start time of the related customer
            /*
            $parCsRelatedDayStartTimeunit = getObjectBasedParameterValue("CS_DAY_TIMEUNIT_START", $csId, $hq_id);
            if ($parCsRelatedDayStartTimeunit == "") :
               // Gets the first (start)timeunit of the first daytime interval from metatype (e.g. "08_00") !!!!
               $tmpTimeIntervalArray = metatypeGetMappedValues("day_time", $hourTimeUnits, $csId, "cs", "");
               $parCsRelatedDayStartTimeunit = $tmpTimeIntervalArray[0][0];
            endif;
            if ($parCsRelatedDayStartTimeunit == "") : $parCsRelatedDayStartTimeunit = "08_00"; endif;  // Fallback
            $hour = substr($parCsRelatedDayStartTimeunit,0,2);
            $hourUnit = substr($parCsRelatedDayStartTimeunit,3,2);
            */
            // Check order times being a sequence (e.g. 15:40 cannot appear before 15:20)
            $checkSequenceOfOrdertimesIsOk = true;
            for ($i = 0; $i < $contentLen; $i++) :
                // Current job
                $sortNo = intval($content[$i]);
                $currJbId = $jbIdArray[$sortNo];
                if ($currJbId != "" && is_numeric($currJbId)) :
                   // Get new order time of the current job, find key in $newOrdertimeArray
                   $currItemKey = array_search($currJbId, $newOrdertimeArray);
                   $hour = $newOrdertimeArray[($currItemKey + 1)];
                   $hourUnit = strval(ceil(intval($newOrdertimeArray[($currItemKey + 2)]) * ($hourTimeUnits / 60)));
                   $tmpHour = intval($hour);
                   $tmpHourUnit = intval($hourUnit);
                   // Get successor job if doeas exist
                   $succI = $i + 1;
                   if ($succI < $contentLen) :
                      $succSortNo = intval($content[$succI]);
                      $succJbId = $jbIdArray[$succSortNo];
                      if ($succJbId != "" && is_numeric($succJbId)) :
                          // Get new order time of the successor job, find key in $newOrdertimeArray
                          $succItemKey = array_search($succJbId, $newOrdertimeArray);
                          $succHour = intval($newOrdertimeArray[($succItemKey + 1)]);
                          $succHourUnit = strval(ceil(intval($newOrdertimeArray[($succItemKey + 2)]) * ($hourTimeUnits / 60)));
                          $succHourUnit = intval($succHourUnit);
                          if (($succHour < $tmpHour) || ($succHour == $tmpHour && $succHourUnit <= $tmpHourUnit)) :
                             $checkSequenceOfOrdertimesIsOk = false;
                          endif;
                      endif;
                   endif;
                endif;
            endfor;

            // Insert new order times
            if ($checkSequenceOfOrdertimesIsOk) :
               // Remove all jobs from the timeline of the vehicle for the specified day
               for ($i = 0; $i < $jbIdArrayLen; $i++) :
                   removeAssocCrvhJb($jbIdArray[$i], $csId, $hourTimeUnits);
               endfor;
               // Resort the jobs by new sorting list
               for ($i = 0; $i < $contentLen; $i++) :
                   $sortNo = intval($content[$i]);
                   $currJbId = $jbIdArray[$sortNo];
                   $jbTimeUnits = getFieldValueFromId("job","jb_id",$currJbId,"jb_timeunits");
                   
                   // Get new order time of the current job, find key in $newOrdertimeArray
                   $currItemKey = array_search($currJbId, $newOrdertimeArray);
                   $hour = $newOrdertimeArray[($currItemKey + 1)];
                   $hourUnit = strval(ceil(intval($newOrdertimeArray[($currItemKey + 2)]) * ($hourTimeUnits / 60)));
               
                   // If a successor job does exist then recompute new value for the time units inserted into the FDS
                   $newFDSTimeUnitValue = $jbTimeUnits;
                   $succI = $i + 1;
                   if ($succI < $contentLen) :
                      $succSortNo = intval($content[$succI]);
                      $succJbId = $jbIdArray[$succSortNo];
                      if ($succJbId != "" && is_numeric($succJbId)) :
                         $tmpHour = intval($hour);
                         $tmpHourUnit = intval($hourUnit);
                         $succItemKey = array_search($succJbId, $newOrdertimeArray);
                         $succHour = intval($newOrdertimeArray[($succItemKey + 1)]);
                         $succHourUnit = strval(ceil(intval($newOrdertimeArray[($succItemKey + 2)]) * ($hourTimeUnits / 60)));
                         $succHourUnit = intval($succHourUnit);
                         $tmpTimeslots = 0;
                         for ($j = $tmpHour; $j <= 23; $j++) :
                             for ($k = $tmpHourUnit; $k < $hourTimeUnits; $k++) :
                                if ($tmpTimeslots == $jbTimeUnits || ($j == $succHour && $k == $succHourUnit)) :
                                   $newFDSTimeUnitValue = $tmpTimeslots;
                                   break 2;
                                endif;
                                $tmpTimeslots++;
                             endfor;
                             $tmpHourUnit = 0;  // Init because the daily start time e.g. could start 08:30 et al.
                         endfor;
                      endif;
                   endif;
               
                   // Set new position in FDS                
                   setAssocCrvhJb($currJbId, $crvhId, $csId, $currDay, $hour, $hourUnit, $newFDSTimeUnitValue, $hourTimeUnits);
               
                   // Set new ordertime of the current job
                   $newOrdertime = $currDay . " " . pad($hour,2) . ":" . pad(($hourUnit * (60 / $hourTimeUnits)), 2) . ':00';
               
                   updateStmt("job", "jb_id", $currJbId, array("jb_ordertime", $newOrdertime));
               endfor;
               
               // Update FDS for both vehicles after all operations
               updateVehicleAvailability($crvhId, $csId, $currDay);
               
               $retVal = "1";
            else :
               $retVal = "0";
            endif;
         endif;
      else :
         echo "alert('" . getLngt("Achtung: Die Ursprungsliste hat sich während der Bearbeitung geändert! Der Vorgang musste leider abgebrochen werden!") . "');";
      endif;
   endif;
   echo "isSorted = '" . $retVal . "';";
endif;
?>
