<?php 
/*=======================================================================
 *
 * disposition_appointments.php
 *
 * Autor: Marc Vollmann
 *
  =======================================================================*/


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


// Check HTTP-Parameters
getSecHttpVars("1",array("f_act", "customerId", "cscIdRoot", "cscIdActual", 
                         "jbId", "csId", "ecoDayTimeArray", "ecoWeekdayArray", "ecoZipcode", "ecoNeededTimeUnits", 
                         "sortSequence", "ecoServices", "ecoWeight", "ecoPositions", "maxLimitOfRows", "deliveryTimeValue",
                         "deactivateMenu", "day_from", "month_from", "year_from", "day_to", "month_to", "year_to", 
                         "jbTimedFilter", "dateSelectionByCalendar", "futureDaysOffset"));



getLanguage(__FILE__);
$deactivateMenuStatic = "1";
include_once ("../admin/menu.php");
include_once ("../include/html.inc.php");
getCurrentScript(__FILE__);

// Check for authentication access and granted rights
$usrAccessArray["hq"] = "1"; $usrAccessArray["cs"] = "1";
// authCheckForAccess($hq_id, $usr_id, $emp_id, "1", $customerId, $cscIdRoot, $cscIdActual);
if ($userTypeName == "hq") :
   authCheckEmployeeRights($emp_id, "0", "1");
   authCheckEmployeeRights($emp_id, "4", "1");
endif;

// Init
$currentTimestamp = getDateTime("0");
$currentDay = getDateTime("3");   // "Y-m-d"
$currentTime = getDateTime("4");  // Current time ("H:i:s")
$currYear = getDateTime("year");  // Current year
$combinedJob = false;
$pageTitel = getLngt("TERMINVERGABE");
$output = "";
$errMsgArray = array();


// Get available vehicle data
$globalParArray = array($jbId, $csId, $ecoDayTimeArray, $ecoWeekdayArray, $ecoZipcode, $ecoNeededTimeUnits, $sortSequence, $ecoServices, $ecoWeight, $ecoPositions,
                        $maxLimitOfRows, $deliveryTimeValue, $deactivateMenu, $day_from, $month_from, $year_from, $day_to, $month_to, $year_to, $jbTimedFilter, 
                        $dateSelectionByCalendar, $futureDaysOffset);

$retArray = getDispositionAppointments("3", $globalParArray);

$globalParArray = $retArray[0];  // Global parameters
$tmpArray = $retArray[1];  // Available vehicle data as array OR error string

list($jbId, $csId, $ecoDayTimeArray, $ecoWeekdayArray, $ecoZipcode, $ecoNeededTimeUnits, $sortSequence, $ecoServices, $ecoWeight, $ecoPositions,
     $maxLimitOfRows, $deliveryTimeValue, $deactivateMenu, $day_from, $month_from, $year_from, $day_to, $month_to, $year_to, $jbTimedFilter, 
     $dateSelectionByCalendar, $currentTimestamp, $currentDay, $currentTime, $currYear, $combinedJob, $hourTimeUnits, $ecoDayClockTimes, 
     $jbOrdertime, $ecoCapacityMax, $ecoSummatedNeededTimeUnits,$ecoHasWholeDayRequest, $ecoSrvpId, $ecoSrvzId, $weekDayNames, $checkTotalweight, 
     $dispositionJbStatusMode, $ecoChildrenServices, $maskDisplayWholeDayAvoidingSingleDaytimes, $ecoIsInstallationJob, $ecoIsSpecialServiceJob, 
     $dispositionAllocationMode, $ecoChildrenTimeunitsArray, $jbIdChildren, $jbIdChildrenLen, $daytimeReadonlyArray) = $globalParArray;

// Check for ERRORS
if (!is_array($tmpArray)) :
   if (!(strpos($tmpArray, "ERR:ZIPCODE_NOT_IN_ANY_ZONE") === FALSE)) :
      $errMsgArray[] = getLngt("Die PLZ ist keiner Zone zugeordnet!") . " [" . $ecoZipcode . "]";
   else :
      $errMsgArray[] = getLngt("Bereichsfehler!");
   endif;
endif;
$errMsgArrayLen = count($errMsgArray);

// DEBUG (Start)
$empIdRootAdmin = getEmpIdOfRootAdmin("hq");
$debug = false;
if ($empIdRootAdmin == $emp_id || $emp_id == "15795") :
   $debug = true;
endif;
// DEBUG (END)

// Write logdata into log database for calling reservation page
if ($jbId != "") :
   $parLogCallingReservationPage = getParameterValue("0", "DISPOSITION_LOG_PAGE_CALL_ENABLED", $hq_id);
   if ($parLogCallingReservationPage == "1") :
      // ZIP = Zipcode, CJ = Combined Job, WD = Whole day request
      writeToLogDB("130",$hq_id,$jbId,$usr_id,"","",$csId,"ZIP=" . $ecoZipcode . "|ZONE=" . $ecoSrvzId . "|CJ=" . ($combinedJob ? "Y" : "N") . "|WD=" . ($ecoHasWholeDayRequest ? "Y" : "N"),"","",$emp_id);
   endif;
endif;


if ($errMsgArrayLen == 0 && $csId != "" && $ecoZipcode != "" && $ecoNeededTimeUnits != "") :

   if (is_array($tmpArray)) :
      $tmpArrayLen = count($tmpArray);

      // Get parameter for hiding rows looks like the same. They are different because of different vehicles, but one vehicle for the day and daytime shall be displayed only !!!!
      $maskDispositionMultipleRowsDisabled = getParameterValue("0", "MASK_DISPOSITION_MULTIPLE_ROWS_DISABLED", $hq_id);
      if ($maskDispositionMultipleRowsDisabled == "") : $maskDispositionMultipleRowsDisabled = getParameterValue("0", "MASK_DISPOSITION_MULTIPLE_ROWS_DISABLED", "0"); endif;

      // Get parameter for hiding special columns in appointment list
      if ($ecoHasWholeDayRequest && $maskDisplayWholeDayAvoidingSingleDaytimes == "1") :
         $maskDispositionAppointmentsEnabled = getParameterValue("0", "MASK_DISPOSITION_WHOLE_DAY_APPOINTMENTS_ENABLED", $hq_id);
         if ($maskDispositionAppointmentsEnabled == "") : $maskDispositionAppointmentsEnabled = getParameterValue("0", "MASK_DISPOSITION_WHOLE_DAY_APPOINTMENTS_ENABLED", "0"); endif;
      else :
         $maskDispositionAppointmentsEnabled = getParameterValue("0", "MASK_DISPOSITION_APPOINTMENTS_ENABLED", $hq_id);
         if ($maskDispositionAppointmentsEnabled == "") : $maskDispositionAppointmentsEnabled = getParameterValue("0", "MASK_DISPOSITION_APPOINTMENTS_ENABLED", "0"); endif;
      endif;
      if ($maskDispositionAppointmentsEnabled == "") : $maskDispositionAppointmentsEnabled = "0,1,2,3,4,5"; endif;  // Default
      $maskDisplayedArray = array();
      if ($maskDispositionAppointmentsEnabled != "") :
         $maskDisplayedArray = spliti(",", $maskDispositionAppointmentsEnabled);
      endif;
      $maskDisplayedArrayLen = count($maskDisplayedArray);

      // Get parameter for hiding daytime intervals (display whole day only) if eco (or combined job) is installation, but no special service job !!!!
      $displayStatusDaytimeForInstallations = true;
      if ($ecoIsInstallationJob && !$ecoIsSpecialServiceJob) :
         $maskDispositionDaytimeForInstallationsDisabled = getParameterValue("0", "MASK_DISPOSITION_DAYTIMES_FOR_INSTALLATIONS_DISABLED", $hq_id);
         if ($maskDispositionDaytimeForInstallationsDisabled == "") : $maskDispositionDaytimeForInstallationsDisabled = getParameterValue("0", "MASK_DISPOSITION_DAYTIMES_FOR_INSTALLATIONS_DISABLED", "0"); endif;
         if ($maskDispositionDaytimeForInstallationsDisabled == "1") :
            $displayStatusDaytimeForInstallations = false;
         endif;
      endif;

      // Get parameter for setting "whole-day"-jobs in FDS or "green banner" !!!!
      $wholeDayEcoWillBeSetInFDS = getParameterValue("0", "MASK_DISPOSITION_WHOLE_DAY_JOB_SET_IN_FDS", $hq_id);
      if ($wholeDayEcoWillBeSetInFDS == "") : $wholeDayEcoWillBeSetInFDS = getParameterValue("0", "MASK_DISPOSITION_WHOLE_DAY_JOB_SET_IN_FDS", "0"); endif;
      if ($wholeDayEcoWillBeSetInFDS == "") :  $wholeDayEcoWillBeSetInFDS = "1"; endif;  // Enabled by default, because parameter does not exist. Eco will be placed in FDS

// DEBUG (Start)
if ($debug) :
   echo "currentTimestamp : " . $currentTimestamp . "<br>";
   echo "jbId : " . $jbId . "<br>";
   echo "csId : " . $csId . "<br>";
   echo "ecoZipcode : " . $ecoZipcode . "<br>";
   echo "jbOrdertime : " . $jbOrdertime . "<br>";
   echo "jbTimedFilter : " . $jbTimedFilter . "<br>";
   echo "hourTimeUnits : " . $hourTimeUnits . "<br>";
   echo "ecoNeededTimeUnits : " . $ecoNeededTimeUnits . "<br>";
   echo "sortSequence : " . $sortSequence . "<br>";
   echo "ecoServices : " . $ecoServices . "<br>";
   echo "ecoIsInstallationJob : " . ($ecoIsInstallationJob ? "YES" : "NO") . "<br>";
   echo "ecoWeight : " . $ecoWeight . "<br>";
   echo "ecoPositions : " . $ecoPositions . "<br>";
   echo "maxLimitOfRows : " . $maxLimitOfRows . "<br>";
   echo "deliveryTimeValue : " . $deliveryTimeValue . "<br>";
   echo "ecoWeekdayArray : "; print_r($ecoWeekdayArray); echo "<br>";
   echo "ecoDayTimeArray : "; print_r($ecoDayTimeArray); echo "<br>";
   echo "daytimeReadonlyArray : "; print_r($daytimeReadonlyArray); echo "<br>";
   echo "Uhrzeitenpaare : "; print_r($ecoDayClockTimes); echo "<br>";
   echo "jbIdChildren : "; print_r($jbIdChildren); echo "<br>";
   echo "jbIdChildrenLen : " . $jbIdChildrenLen . "<br>";
   echo "ecoHasWholeDayRequest : " . ($ecoHasWholeDayRequest ? "WD YES" : "WD NO") . "<br>";
   echo "fromDateRange : " . "NOT_NEEDED_HERE" . "<br>";
   echo "toDateRange : " . "NOT_NEEDED_HERE" . "<br>";
   echo "whereClause : " . "NOT_NEEDED_HERE" . "<br>";
   echo "orderByClause : " . "NOT_NEEDED_HERE" . "<br>";
   echo "Wochentage : "; print_r($weekDayNames); echo "<br>";
   echo "checkTotalweight : " . $checkTotalweight . "<br>";
   echo "ecoSrvpId : " . $ecoSrvpId . "<br>";
   echo "ecoSrvzId : " . $ecoSrvzId . "<br>";
   if ($maskDispositionServicezoneCapacityEnabled == "1") :
      echo "Max. Kapazitäten : "; print_r($ecoCapacityMax); echo "<br>";
      echo "Akt. Kapazitäten des gesamten Tages : "; print_r($ecoCapacityOccupied); echo "<br>";
   endif;
   if ($combinedJob) :
     echo "ecoSummatedNeededTimeUnits : " . $ecoSummatedNeededTimeUnits . "<br>";
     echo "ecoChildrenServices : " . $ecoChildrenServices . "<br>";
   else :
      echo "combined_job: NO<br>";
   endif;
   echo "dispositionJbStatusMode : " . $dispositionJbStatusMode . "<br>";
   echo "maskDisplayWholeDayAvoidingSingleDaytimes : " . $maskDisplayWholeDayAvoidingSingleDaytimes . "<br>";
   echo "ecoIsSpecialServiceJob : " . $ecoIsSpecialServiceJob . "<br>";
   echo "dispositionAllocationMode : " . $dispositionAllocationMode . "<br>";
   echo "maskDispositionMultipleRowsDisabled : " . $maskDispositionMultipleRowsDisabled . "<br>";
   echo "maskDispositionAppointmentsEnabled : " . $maskDispositionAppointmentsEnabled . "<br>";
   echo "maskDispositionDaytimeForInstallationsDisabled : " . $maskDispositionDaytimeForInstallationsDisabled . "<br>";   
endif;
// DEBUG (END)

      // Headline of the list
      $outWidth = " width=\"100\" ";
      $output .= "<table>";
      $output .= "<tr>";

      for ($i = 0; $i < $maskDisplayedArrayLen; $i++) :
          if ($maskDisplayedArray[$i] == 0) :
             $output .= "<td" . $outWidth . "><b>" . getLngt("Wochentag") . "&nbsp;</b></td><td" . $outWidth . "><b>" . getLngt("Datum") . "&nbsp;</b></td>";
          endif;
          if ($maskDisplayedArray[$i] == 1) :
             $output .= "<td" . $outWidth . "><b>" . getLngt("Fahrzeug") . "&nbsp;</b></td>";  // SID
          endif;
          if ($maskDisplayedArray[$i] == 2) :
             $output .= "<td" . $outWidth . "><b>" . getLngt("Tageszeit") . "&nbsp;</b></td>";  // Namen der Tageszeiten
          endif;
          if ($maskDisplayedArray[$i] == 3) :
             $output .= "<td" . $outWidth . "><b>" . getLngt("Verf. Zeiteinheiten") . "&nbsp;</b></td>";
          endif;
          if ($maskDisplayedArray[$i] == 4) :
             $output .= "<td" . $outWidth . "><b>" . getLngt("Startzeit") . "&nbsp;</b></td>";
          endif;
          if ($maskDisplayedArray[$i] == 5) :
             $output .= "<td" . $outWidth . "><b>" . getLngt("Service") . "&nbsp;</b></td>";
          endif;
          if ($maskDisplayedArray[$i] == 6) :
             $output .= "<td" . $outWidth . "><b>" . getLngt("Tageszeiten") . "&nbsp;</b></td>";  // Nummern der Tageszeiten
          endif;
          // ....
          if ($maskDisplayedArray[$i] == 10) :
             $output .= "<td" . $outWidth . "><b>" . getLngt("Tageszeit") . "&nbsp;</b></td>";  // Uhrzeiten der Tageszeiten
          endif;
          if ($maskDisplayedArray[$i] == 11) :
             $output .= "<td" . $outWidth . "><b>" . "&nbsp;" . "&nbsp;</b></td>";  // Uhrzeiten der Tageszeiten
          endif;
      endfor;

      $output .= "</tr>";


      // Get parameter for displaying "whole day" link after "day" has changed [="0" <=> default] or after "day AND vehicle" [="1"] have changed only
      $wholeDayEcoLinkDisplayMode = getParameterValue("0", "MASK_DISPOSITION_WHOLE_DAY_JOB_DISPLAY_MODE", $hq_id);
      if ($wholeDayEcoLinkDisplayMode == "") : $wholeDayEcoLinkDisplayMode = getParameterValue("0", "MASK_DISPOSITION_WHOLE_DAY_JOB_DISPLAY_MODE", "0"); endif;
      if ($wholeDayEcoLinkDisplayMode == "") :  $wholeDayEcoLinkDisplayMode = "0"; endif;

      // Get MASK parameter for value to be inserted in attribute "colspan" for "whole-day"-jobs
      // (e.g. "5,0" <=> 5 cols before phrase "Ganztägig" and 0 cols after phrase and befor link "Reservierung")
      $wholeDayEcoColspanValues = "2,0";
      $parWholeDayEcoColspanValues = getParameterValue("0", "MASK_DISPOSITION_WHOLE_DAY_COLSPAN_VALUES", $hq_id);
      if ($parWholeDayEcoColspanValues == "") : $parWholeDayEcoColspanValues = getParameterValue("0", "MASK_DISPOSITION_WHOLE_DAY_COLSPAN_VALUES", "0"); endif;
      if ($parWholeDayEcoColspanValues != "") :  
         $wholeDayEcoColspanValues = $parWholeDayEcoColspanValues;
      endif;
      $wholeDayEcoColspanArray = spliti(",", $wholeDayEcoColspanValues);

      // Get MASK parameter for JAVASCRIPT setting for function "reserveEco" or "reserveMultiEco"
      $wholeDayEcoJsReserveParameter = getParameterValue("0", "MASK_DISPOSITION_WHOLE_DAY_JS_RESERVE_PAR", $hq_id);
      if ($wholeDayEcoJsReserveParameter == "") : $wholeDayEcoJsReserveParameter = getParameterValue("0", "MASK_DISPOSITION_WHOLE_DAY_JS_RESERVE_PAR", "0"); endif;
      if ($wholeDayEcoJsReserveParameter == "") :  $wholeDayEcoJsReserveParameter = "1"; endif;


      if ($tmpArrayLen > 0) :
         $remMasterArray = array();
         $remDay = "";
         $remDaytime = "";
         $remVehicle = "";         
         $firstRowWillBeDisplayed = true;
         $displayDayInRow = true;
         $wholeDayEcoReserveLink = "";
         $displayWholeDayLinkIfatLeastOneDaytimeLinkDoesExist = false;  // The whole day link has to appear only if at least one daytime link does exist

         for ($i = 0; $i < $tmpArrayLen; $i++) :
             $tmpArray2 = $tmpArray[$i];
             $tmpArray2Len = count($tmpArray2);

             // Get week day of the suggested date
             $weekDay = date("w", mktime(0, 0, 0, substr($tmpArray2[0],5,2), substr($tmpArray2[0],8,2), substr($tmpArray2[0],0,4)));   // 0 = Sunday, 1 = Monday, etc.
             if ($weekDay == 0) : $weekDay = "7"; endif;   // Reformat to 1 = Monday, ... , 7 = Sunday

             // Check for week day is matching the selection
             if (!(array_search($weekDay, $ecoWeekdayArray) === FALSE)) :

                if ($ecoHasWholeDayRequest && $maskDisplayWholeDayAvoidingSingleDaytimes == "1") :

                   // **** DISPLAYING WHOLE DAY LINKS ONLY ****************************************************************************************************

                   $displayDayInRow = false;
                   if ($remDay != $tmpArray2[0]) :
                      $displayDayInRow = true;
                   endif;

                   // Day changed?
                   if (true || $dispositionUniqueDisplayArray[0] == "1") :
                      $tmpCmpLeft = $remDay;
                      $tmpCmpRight = $tmpArray2[0];
                   endif;
                   // Daytime changed?
                   if ($dispositionUniqueDisplayArray[1] == "1") :
                      $tmpCmpLeft .= $remDaytime;
                      $tmpCmpRight .= $tmpArray2[6];
                   endif;
                   // Vehicle changed?
                   if ($dispositionUniqueDisplayArray[2] == "1") :
                      $tmpCmpLeft .= $remVehicle;
                      $tmpCmpRight .= $tmpArray2[7];
                   endif;

                   // if ($tmpCmpLeft != $tmpCmpRight) :
                   if (!in_array($tmpCmpRight, $remMasterArray)) :

                      $output .= "<tr>";
                      if ($displayDayInRow) :
                         $output .= "<td>" . $weekDayNames[$weekDay - 1] . "</td>";  // Name of the week day
                         $output .= "<td>" . $tmpArray2[$maskDisplayedArray[0]] . "</td>";
                      else : 
                         $output .= "<td colspan=\"2\"></td>";
                      endif;
                      for ($j = 1; $j < $maskDisplayedArrayLen; $j++) :
                          if ($maskDisplayedArray[$j] == 11) :
                             // Coloured background for service or delivery
                             $cellBgCol = "#88BB88";
                             $cellText = getLngt("LI");
                             if (((int)$tmpArray2[$maskDisplayedArray[$j]] & 2) == 2) :
                                $cellBgCol = "#55BB55";
                                $cellText = getLngt("MO");
                             endif;
                             $output .= "<td style=\"text-align:center;\">";
                             $output .= "  <table><tr><td>&nbsp;</td><td style=\"width:30px; text-align:center; background-color:" . $cellBgCol . ";\">" . $cellText . "</td><td>&nbsp;</td></tr></table>";
                             $output .= "</td>";
                          elseif ($maskDisplayedArray[$j] == 10) :
                             // if ($wholeDayEcoColspanArray[0] != "" && is_numeric($wholeDayEcoColspanArray[0]) && $wholeDayEcoColspanArray[0] > 0) :
                             //    $output .= "<td colspan=\"" . $wholeDayEcoColspanArray[0] . "\"" .  ">&nbsp;</td>";
                             // endif;
                             $output .= "<td>" . getLngt("Ganztägig") . "</td>";
                             // if ($wholeDayEcoColspanArray[1] != "" && is_numeric($wholeDayEcoColspanArray[1]) && $wholeDayEcoColspanArray[1] > 0) :
                             //    $output .= "<td colspan=\"" . $wholeDayEcoColspanArray[1] . "\"" .  ">&nbsp;</td>";
                             // endif;
                          else :
                             $output .= "<td>" . $tmpArray2[$maskDisplayedArray[$j]] . "</td>";
                          endif;
                      endfor;

                      // If the current data come from an stored job in the database then use following link to move this job on the timeline regarding the selected suggested date
                      // if ($jbId != "" && (!$ecoIsSpecialServiceJob || ($ecoIsSpecialServiceJob && ($tmpArray2[6] == "0" || $tmpArray2[6] == "1")))) :
                      if ($jbId != "") :
                         if ($combinedJob) :
                            // Set string with starttimes for ALL jobs 
                            // (e.g. 5 jobs [1001-1005] 12_03, 12_05, 13_04, 16_03, 17_01 => "1001;12;03;2014-01-17 12:30:00;2#1002;12;05;2014-01-17 12:50:00;2#1003;13;04;2014-01-17 13:40:00;3#1004;16;03;2014-01-17 16:30:00;12#1005;17;01;2014-01-17 17:10:00;3")
                            $tmpStartHour = intval($tmpArray2[8]);
                            $tmpStartHourUnit = intval($tmpArray2[9]);

                            $remNeededTimeUnits = $ecoNeededTimeUnits;  // The following job has to use the needed timeunits of the job before to get the start time !!!!

                            $combinedJobStr = $jbId . ";" .$tmpStartHour . ";" . $tmpStartHourUnit . ";" . $tmpArray2[0] . " " . $tmpArray2[4] . ":00" . ";" . $ecoNeededTimeUnits;  // Init with main job
                            for ($k = 0; $k < $jbIdChildrenLen; $k++) :
                                // Add timeunits of the job before to increase $tmpStartHour and $tmpStartHourUnit for current (child) job
                                for ($l = 0; $l < $remNeededTimeUnits; $l++) :
                                    $tmpStartHourUnit++;
                                    if ($tmpStartHourUnit == $hourTimeUnits) :
                                       $tmpStartHour++;
                                       $tmpStartHourUnit = 0;
                                    endif;
                                endfor;

                                // Get timeunits of the current (child) job
                                $tmpTimeUnitsNeeded = $ecoChildrenTimeunitsArray[$jbIdChildren[$k]];
                                if ($tmpTimeUnitsNeeded != "" && is_numeric($tmpTimeUnitsNeeded)) :
                                   $combinedJobStr .= "#" . $jbIdChildren[$k] . ";" . pad(strval($tmpStartHour),2) . ";" . pad(strval($tmpStartHourUnit),2) . ";" . $tmpArray2[0] . " " . pad(strval($tmpStartHour),2) . ":" . pad(strval(floor($tmpStartHourUnit * (60 / $hourTimeUnits))), 2) . ":00" . ";" . $tmpTimeUnitsNeeded;
                                   $remNeededTimeUnits = $tmpTimeUnitsNeeded;
                                endif;
                            endfor;

                            $ecoReserveLink = "<td>" . "<a href=\"javascript:reserveMultiEco('" . $tmpArray2[7] . "','" . $tmpArray2[0] . "','" . $combinedJobStr . "','" . $tmpArray2[10] . "','WHOLE_DAY_MAKRO');\" >" . getLngt("Reservierung") . "</a>" . "</td>";
                         else :
                            $ecoNewOrdertime = $tmpArray2[0] . " " . $tmpArray2[4] . ":00";  // Needed to set the new ordertime to the existing job
                            $ecoReserveLink = "<td>" . "<a href=\"javascript:reserveEco('" . $jbId . "','" . $tmpArray2[7] . "','" . $tmpArray2[0] . "','" . $tmpArray2[8] . "','" . $tmpArray2[9] . "','" . $ecoNeededTimeUnits . "','" . $ecoNewOrdertime . "','1','" . $tmpArray2[10] . "','WHOLE_DAY_MAKRO','1');\" >" . getLngt("Reservierung") . "</a>" . "</td>";
                         endif;

                         $tmpEcoReserveLink = str_replace("WHOLE_DAY_MAKRO", "1", $ecoReserveLink);  // Link is "whole day"
                         /*
                         if ($wholeDayEcoWillBeSetInFDS == "1") :
                            $tmpEcoReserveLink = str_replace("WHOLE_DAY_MAKRO", "0", $ecoReserveLink);  // Link is NOT "whole day"
                         else :
                            $tmpEcoReserveLink = str_replace("WHOLE_DAY_MAKRO", "1", $ecoReserveLink);  // Link is "whole day"
                         endif;
                         */
                         if ($displayStatusDaytimeForInstallations) :
                            $output .= $tmpEcoReserveLink;
                         endif;
                   
                         // Set whole day link if eco should be set on the FDS. Take care to take the earliest (daytime) interval being available.
                         if ($wholeDayEcoReserveLink == "") :
                            $tmpEcoReserveLink = str_replace("WHOLE_DAY_MAKRO", $wholeDayEcoJsReserveParameter, $ecoReserveLink);  // Link is "whole day"
                            $wholeDayEcoReserveLink = $tmpEcoReserveLink;
                         endif;
                      endif;
                      $output .= "</tr>";

                      $remDay = $tmpArray2[0];
                      $remDaytime = $tmpArray2[6];
                      $remVehicle = $tmpArray2[7];
                      
                      array_push($remMasterArray, $tmpCmpRight);
                   endif;

                else :

                   // **** STANDARD DISPLAYING ****************************************************************************************************************

                   // Display link for whole-day
                   if ($dispositionAllocationMode == "0") :
                      $displayDayInRow = false;
                   endif;
                   if ($firstRowWillBeDisplayed) :
                      $displayDayInRow = true;
                      $firstRowWillBeDisplayed = false;
                   endif;

                   if ($dispositionAllocationMode == "0") :
                      $tmpDisplayWholeDayLink = ($remDay != "" && $tmpArray2[0] != "" && $remDay != $tmpArray2[0]);  // Day changed?
                      if ($wholeDayEcoLinkDisplayMode == "1") :
                         $tmpDisplayWholeDayLink = $tmpDisplayWholeDayLink && (true);  // Vehicle or other changed....?
                      endif;
                   
                      if ($tmpDisplayWholeDayLink) :
                         if ($ecoHasWholeDayRequest) :
                            $output .= "</tr>";
                            
                            // Whole day reservation link
                            if ($displayWholeDayLinkIfatLeastOneDaytimeLinkDoesExist) :
                               $output .= "<tr>";
                               if ($wholeDayEcoColspanArray[0] != "" && is_numeric($wholeDayEcoColspanArray[0]) && $wholeDayEcoColspanArray[0] > 0) :
                                  $output .= "<td colspan=\"" . $wholeDayEcoColspanArray[0] . "\"" .  ">&nbsp;</td>";
                               endif;
                               $output .= "<td>" . getLngt("Ganztägig") . "</td>";
                               if ($wholeDayEcoColspanArray[1] != "" && is_numeric($wholeDayEcoColspanArray[1]) && $wholeDayEcoColspanArray[1] > 0) :
                                  $output .= "<td colspan=\"" . $wholeDayEcoColspanArray[1] . "\"" .  ">&nbsp;</td>";
                               endif;
                               if ($jbId != "") :
                                  if ($wholeDayEcoWillBeSetInFDS == "1" && $wholeDayEcoReserveLink != "") :
                                     $output .= $wholeDayEcoReserveLink;
                                     $wholeDayEcoReserveLink = "";
                                  else :
                                     $output .= "<td>" . "<a href=\"javascript:reserveWholeDayEcoNotForFDS('" . $jbId . "','" . $remDay . " 00:00:01" . "','1');\" >" . getLngt("Reservierung") . "</a>" . "</td>";
                                  endif;
                               endif;
                               $output .= "</tr>";
                               $displayWholeDayLinkIfatLeastOneDaytimeLinkDoesExist = false;
                            endif;
                            
                            $output .= "<tr>";
                         endif;
                         $displayDayInRow = true;
                      endif;
                   endif;

                   // Check for mode hiding the row
                   $displayRow = true;
                   if ($dispositionAllocationMode == "0") :
                      if ($maskDispositionMultipleRowsDisabled == "1") :
                         $displayRow = false;

                         // Day changed?
                         if (true || $dispositionUniqueDisplayArray[0] == "1") :
                            $tmpCmpLeft = $remDay;
                            $tmpCmpRight = $tmpArray2[0];
                         endif;
                         // Daytime changed?
                         if ($dispositionUniqueDisplayArray[1] == "1") :
                            $tmpCmpLeft .= $remDaytime;
                            $tmpCmpRight .= $tmpArray2[6];
                         endif;
                         // Vehicle changed?
                         if ($dispositionUniqueDisplayArray[2] == "1") :
                            $tmpCmpLeft .= $remVehicle;
                            $tmpCmpRight .= $tmpArray2[7];
                         endif;

                         // if ($remDay . $remDaytime != $tmpArray2[0] . $tmpArray2[6]) :                         
                         // if ($tmpCmpLeft != $tmpCmpRight) :
                         if (!in_array($tmpCmpRight, $remMasterArray)) :

                            $remDay = $tmpArray2[0];
                            $remDaytime = $tmpArray2[6];
                            $remVehicle = $tmpArray2[7];
                      
                            array_push($remMasterArray, $tmpCmpRight);
                            $displayRow = true;
                         endif;
                      endif;
                   endif;

                   // Check for servicezone capacities if enabled 
                   if ($displayRow && $maskDispositionServicezoneCapacityEnabled == "1") :
                       if ( ( ($ecoCapacityMax[$weekDay][$tmpArray2[6]] - $ecoCapacityOccupied[$weekDay][$tmpArray2[6]]) <= 0) ||
                            ( ($ecoCapacityMax[$weekDay]["999"] - $ecoCapacityOccupied[$weekDay]["999"]) <= 0)) :
                          $displayRow = false;
                       endif;
                   endif;
                   
                   if ($displayRow) :
                      $output .= "<tr>";
                      if (!(array_search(0, $maskDisplayedArray) === false)) :
                         if ($displayDayInRow) :
                            $output .= "<td>" . $weekDayNames[$weekDay - 1] . "</td>";  // Name of the week day
                            $output .= "<td>" . $tmpArray2[$maskDisplayedArray[0]] . "</td>";
                         else : 
                            $output .= "<td colspan=\"2\"></td>";
                         endif;
                      endif;
                      for ($j = 1; $j < $maskDisplayedArrayLen; $j++) :
                          if ($maskDisplayedArray[$j] == 11) :
                             // Coloured background for service or delivery
                             $cellBgCol = "#88BB88";
                             $cellText = getLngt("LI");
                             if (((int)$tmpArray2[$maskDisplayedArray[$j]] & 2) == 2) :
                                $cellBgCol = "#55BB55";
                                $cellText = getLngt("MO");
                             endif;
                             $output .= "<td style=\"text-align:center;\">";
                             $output .= "  <table><tr><td>&nbsp;</td><td style=\"width:30px; text-align:center; background-color:" . $cellBgCol . ";\">" . $cellText . "</td><td>&nbsp;</td></tr></table>";
                             $output .= "</td>";
                          else :
                             $output .= "<td>" . $tmpArray2[$maskDisplayedArray[$j]] . "</td>";
                          endif;
                      endfor;
                   
                      // If the current data come from an stored job in the database then use following link to move this job on the timeline regarding the selected suggested date
                      // if ($jbId != "" && (!$ecoIsSpecialServiceJob || ($ecoIsSpecialServiceJob && ($tmpArray2[6] == "0" || $tmpArray2[6] == "1")))) :
                      if ($jbId) :
                         if ($combinedJob) :
                            // Set string with starttimes for ALL jobs 
                            // (e.g. 5 jobs [1001-1005] 12_03, 12_05, 13_04, 16_03, 17_01 => "1001;12;03;2014-01-17 12:30:00;2#1002;12;05;2014-01-17 12:50:00;2#1003;13;04;2014-01-17 13:40:00;3#1004;16;03;2014-01-17 16:30:00;12#1005;17;01;2014-01-17 17:10:00;3")
                            $tmpStartHour = intval($tmpArray2[8]);
                            $tmpStartHourUnit = intval($tmpArray2[9]);
                   
                            $remNeededTimeUnits = $ecoNeededTimeUnits;  // The following job has to use the needed timeunits of the job before to get the start time !!!!
                   
                            $combinedJobStr = $jbId . ";" .$tmpStartHour . ";" . $tmpStartHourUnit . ";" . $tmpArray2[0] . " " . $tmpArray2[4] . ":00" . ";" . $ecoNeededTimeUnits;  // Init with main job
                            for ($k = 0; $k < $jbIdChildrenLen; $k++) :
                                // Add timeunits of the job before to increase $tmpStartHour and $tmpStartHourUnit for current (child) job
                                for ($l = 0; $l < $remNeededTimeUnits; $l++) :
                                    $tmpStartHourUnit++;
                                    if ($tmpStartHourUnit == $hourTimeUnits) :
                                       $tmpStartHour++;
                                       $tmpStartHourUnit = 0;
                                    endif;
                                endfor;
                   
                                // Get timeunits of the current (child) job
                                $tmpTimeUnitsNeeded = $ecoChildrenTimeunitsArray[$jbIdChildren[$k]];
                                if ($tmpTimeUnitsNeeded != "" && is_numeric($tmpTimeUnitsNeeded)) :
                                   $combinedJobStr .= "#" . $jbIdChildren[$k] . ";" . pad(strval($tmpStartHour),2) . ";" . pad(strval($tmpStartHourUnit),2) . ";" . $tmpArray2[0] . " " . pad(strval($tmpStartHour),2) . ":" . pad(strval(floor($tmpStartHourUnit * (60 / $hourTimeUnits))), 2) . ":00" . ";" . $tmpTimeUnitsNeeded;
                                   $remNeededTimeUnits = $tmpTimeUnitsNeeded;
                                endif;
                            endfor;
                   
                            $ecoReserveLink = "<td>" . "<a href=\"javascript:reserveMultiEco('" . $tmpArray2[7] . "','" . $tmpArray2[0] . "','" . $combinedJobStr . "','" . $tmpArray2[10] . "','WHOLE_DAY_MAKRO');\" >" . getLngt("Reservierung") . "</a>" . "</td>";
                         else :
                            $ecoNewOrdertime = $tmpArray2[0] . " " . $tmpArray2[4] . ":00";  // Needed to set the new ordertime to the existing job
                            $ecoReserveLink = "<td>" . "<a href=\"javascript:reserveEco('" . $jbId . "','" . $tmpArray2[7] . "','" . $tmpArray2[0] . "','" . $tmpArray2[8] . "','" . $tmpArray2[9] . "','" . $ecoNeededTimeUnits . "','" . $ecoNewOrdertime . "','1','" . $tmpArray2[10] . "','WHOLE_DAY_MAKRO','1');\" >" . getLngt("Reservierung") . "</a>" . "</td>";
                         endif;
                   
                         $tmpEcoReserveLink = str_replace("WHOLE_DAY_MAKRO", "0", $ecoReserveLink);  // Link is NOT "whole day"
                         if ($displayStatusDaytimeForInstallations) :
                            $output .= $tmpEcoReserveLink;
                         endif;
                   
                         // Set whole day link if eco should be set on the FDS. Take care to take the earliest (daytime) interval being available.
                         if ($wholeDayEcoReserveLink == "") :
                            $tmpEcoReserveLink = str_replace("WHOLE_DAY_MAKRO", $wholeDayEcoJsReserveParameter, $ecoReserveLink);  // Link is "whole day"
                            $wholeDayEcoReserveLink = $tmpEcoReserveLink;
                         endif;
                      endif;
                   
                      $output .= "</tr>";
                      $displayWholeDayLinkIfatLeastOneDaytimeLinkDoesExist = true;
                   endif;  // Check for $displayRow
                endif;  // Display mode "whole day only" or "standard mode"
             endif;
         endfor;

         if ($dispositionAllocationMode == "0" && $ecoHasWholeDayRequest) :
            if ($maskDisplayWholeDayAvoidingSingleDaytimes != "1") :
               // Display link for whole-day for the last day displayed in the list
               $output .= "<tr>";
               if ($wholeDayEcoColspanArray[0] != "" && is_numeric($wholeDayEcoColspanArray[0]) && $wholeDayEcoColspanArray[0] > 0) :
                  $output .= "<td colspan=\"" . $wholeDayEcoColspanArray[0] . "\"" .  ">&nbsp;</td>";
               endif;
               $output .= "<td>" . getLngt("Ganztägig") . "</td>";
               if ($wholeDayEcoColspanArray[1] != "" && is_numeric($wholeDayEcoColspanArray[1]) && $wholeDayEcoColspanArray[1] > 0) :
                  $output .= "<td colspan=\"" . $wholeDayEcoColspanArray[1] . "\"" .  ">&nbsp;</td>";
               endif;
               if ($jbId != "") :
                  if ($wholeDayEcoWillBeSetInFDS == "1" && $wholeDayEcoReserveLink != "") :                  
                     $output .= $wholeDayEcoReserveLink;
                     $wholeDayEcoReserveLink = "";
                  else :
                     $output .= "<td>" . "<a href=\"javascript:reserveWholeDayEcoNotForFDS('" . $jbId . "','" . $tmpArray2[0] . " 00:00:01" . "','1');\" >" . getLngt("Reservierung") . "</a>" . "</td>";
                  endif;
               endif;
               $output .= "</tr>";
            endif;
         endif;
      else :
         // $output .= "<tr><td>" . getLngt("In dem angegebenen Zeitraum sind keine passenden Termine verfügbar!") . "</td></tr>";
         $output .= "<tr><td>" . getLngt("Überschreitung der Zeiteinheiten - bitte kontaktieren Sie die Disposition!") . "</td></tr>";
      endif;
      $output .= "</table>";
   else :
      if ($tmpArray == "ERR:NO_ZONE") :
         $output .= "<span class=\"f12np1_red\">" . getLngt("Die PLZ des Kunden liegt außerhalb der Liefergebiete!") . "</span>";  // Error message
      else :
         $output .= "<span class=\"f12np1_red\">" . $tmpArray . "</span>";  // Error message
      endif;
   endif;
else :
   // if ($jbId == "") :
      if ($csId == "") :
         $errMsgArray[] = getLngt("Der Kunde (z.B. Markt) ist nicht spezifiziert!");
      endif;
      if ($ecoZipcode == "") :
         $errMsgArray[] = getLngt("Die PLZ wurde nicht definiert!");
      endif;
      if ($ecoNeededTimeUnits == "") :
         $errMsgArray[] = getLngt("Die benötigte Auftragsdauer wurde nicht definiert!");
      endif;
   // endif;
endif;

// Check for any error message
if (count($errMsgArray) > 0) :
   $output .= "<span class=\"f10np1_red\">" . implode("<br>", $errMsgArray) . "</span>";  // Error message
endif;


/*
Zone zipcodes IKEA Schnelsen
0 = 20253  // Kerngebiet
1 = 22946  // Sek.-gebiet Nord
2 = 21039  // Sek.-gebiet Süd
3 = 24239  // Restgebiet Nord
4 = 19273  // Restgebiet Süd

$tmpCrvhSid = getFieldValueFromId("couriervehicle", "crvh_id", $row["crvh_id"], "crvh_sid");
$tmpDaytime = getFieldValueFromClause("metatype","mt_value","mt_type = 'day_time' AND mt_objtype = 'cs' AND mt_objid = '" . $csId . "' AND mt_sort = '" . $row["vhat_daytime"] . "'");
$tmpStarttime = substr($row["vhat_starttimeunit"],0,2) . ":" . pad(strval(floor(intval(substr($row["vhat_starttimeunit"],3,2)) * (60 / $hourTimeUnits))), 2);
$retArray[] = array($row["vha_day"], $tmpCrvhSid, $tmpDaytime, $row["vhat_timeunits"], $tmpStarttime, $row["vhat_daytime"], $row["crvh_id"], substr($row["vhat_starttimeunit"],0,2), substr($row["vhat_starttimeunit"],3,2));

SELECT 
    vha.vha_day, vha.crvh_id, vhat.vhat_daytime, vhat.vhat_timeunits, vhat.vhat_starttimeunit 
  FROM 
    vehicleavailability AS vha, vehicleavailabilitytimeunits AS vhat 
  WHERE 
    vha.vha_id = vhat.vha_id AND 
    vhat.cs_id = '1' AND 
    vhat.vhat_srvz_no = '0' AND 
    vha.vha_day = '2013-08-16' AND 
    vhat.vhat_daytime = '0' AND 
    vhat.vhat_timeunits >= '7' 
  LIMIT 0,3

SELECT 
    crvh.crvh_sid, crvh.crvh_service, vha.vha_day, vhat.vhat_srvz_no, vhat.vhat_daytime, vhat.vhat_timeunits, vhat.vhat_starttimeunit 
  FROM 
    vehicleavailability AS vha, vehicleavailabilitytimeunits AS vhat , couriervehicle AS crvh
  WHERE 
    crvh.crvh_id = vha.crvh_id AND
    vha.vha_id = vhat.vha_id AND 
    vhat.cs_id = '1'
  ORDER BY crvh.crvh_sid, vha.vha_day, vhat.vhat_srvz_no, vhat.vhat_daytime
*/

// * Output only *

// Javascript-function as template only for categorie depending on date-filter (not status-filter)
$onLoadCall = "initForm();";  // displayStatusMessage();
$onLoadCall .= "calendarMonthInit('appointment', " . $year_from . ", " . $month_from . ", true);";

$js_date = "";
$js_date .= "<script src=\"../include/lib_global.js\" type=\"text/javascript\">\n";
$js_date .= "</script>\n";
$js_date .= "\n";
$js_date .= "<script type=\"text/javascript\">\n";
$js_date .= "<!--\n";
$js_date .= "FILLDATEFIELDSSTARTYEAR=" . $currYear . ";\n";
$js_date .= "function initForm() {\n";
$js_date .= "  fillDateFields(1,\"maincontent\",\"disposition\",\"\",\"day_from\",\"month_from\",\"year_from\",\"\",\"\",\"\");\n";
$js_date .= "  setDateTimeFields(\"maincontent\",\"disposition\",".$day_from.",".$month_from.",".$year_from.", \"\", \"\", \"day_from\", \"month_from\", \"year_from\", \"\", \"\", \"\");\n";
$js_date .= "  fillDateFields(1,\"maincontent\",\"disposition\", \"\", \"day_to\", \"month_to\", \"year_to\", \"\", \"\", \"\");\n";
$js_date .= "  setDateTimeFields(\"maincontent\",\"disposition\",".$day_to.",".$month_to.",".$year_to.", \"\", \"\", \"day_to\", \"month_to\", \"year_to\", \"\", \"\", \"\");\n";
$js_date .= "}\n";
$js_date .= "-->\n";
$js_date .= "</script>\n";

// Date ranges
$categoryFilter  = "von:\n";      
$categoryFilter .= "<select name=\"day_from\" class=\"f8np1\" onchange=\"fillDateFieldsCheck(0, 'maincontent', 'disposition', 'day_from', 'day_from', 'month_from', 'year_from', '', '', '', 'day_to', 'month_to', 'year_to', '', '', '')\"></select>\n";
$categoryFilter .= "<select name=\"month_from\" class=\"f8np1\" onchange=\"fillDateFieldsCheck(0, 'maincontent', 'disposition', 'month_from', 'day_from', 'month_from', 'year_from', '', '', '', 'day_to', 'month_to', 'year_to', '', '', '')\"></select>\n";
$categoryFilter .= "<select name=\"year_from\" class=\"f8np1\" onchange=\"fillDateFieldsCheck(0, 'maincontent', 'disposition', 'year_from', 'day_from', 'month_from', 'year_from', '', '', '', 'day_to', 'month_to', 'year_to', '', '', '')\"></select>\n";      
$categoryFilter .= "&nbsp;&nbsp;bis:\n";     
$categoryFilter .= "<select name=\"day_to\" class=\"f8np1\" onchange=\"fillDateFieldsCheck(0, 'maincontent', 'disposition', 'day_to', 'day_from', 'month_from', 'year_from', '', '', '', 'day_to', 'month_to', 'year_to', '', '', '')\"></select>\n";
$categoryFilter .= "<select name=\"month_to\" class=\"f8np1\" onchange=\"fillDateFieldsCheck(0, 'maincontent', 'disposition', 'month_to', 'day_from', 'month_from', 'year_from', '', '', '', 'day_to', 'month_to', 'year_to', '', '', '')\"></select>\n";
$categoryFilter .= "<select name=\"year_to\" class=\"f8np1\" onchange=\"fillDateFieldsCheck(0, 'maincontent', 'disposition', 'year_to', 'day_from', 'month_from', 'year_from', '', '', '', 'day_to', 'month_to', 'year_to', '', '', '')\"></select>\n";
?>

<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 src="../include/lib_calendar.js" type="text/javascript"></script>

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

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


function finishPage(mode) {
  var ok = true;

  if (mode == 'request') {
  	 document.forms[0].dateSelectionByCalendar.value = '';
     document.forms[0].submit();
  }

  if (mode == 'reserve') {
     document.forms[0].submit();
  }
  // document.forms[0].f_act.value='xxxx';
  // document.location.href = "disposition_appointments.php?jbId=<?php echo ec($jbId) ?>&csId=<?php echo ec($csId) ?>";  
};


function setOpenerData (day, clocktime) {
  if (opener.dispoCallback) {
     var reservationText = '';
     if (clocktime == '') {
        day = day.substr(0, 10);  // Whole-day, output day only without clock time inteval
        clocktime = '<?php echo getLngt("ganztägig") ?>';
     }
     reservationText = day.substr(8, 2) + '.' + day.substr(5, 2) + '.' + day.substr(0, 4) + '  ' + clocktime;
     opener.dispoCallback(reservationText);
  }
}

// Reserves a job on the timeline according to the choice of one of the suggested dates.
// ATTENTION: For a single job (NOT combuned eco) the parameter "lastEcoOfCombinedJob" equals '1' !!!!
// This function moves(!) an existing job on the timeline and sets a new "jb_ordertime", "cr_sid", "cr_id", etc.
function reserveEco (ecoId, crvhId, orderDay, hour, hourUnit, neededTimeslots, newOrdertime, doSubmit, clockTime, isWholeDayLink, lastEcoOfCombinedJob) {
  if (ecoId != '') {
     var alertMsg = '';
     var ecoInFDS = '0';

     // Check eco is a multiple day job. If it is NOT then ecoMultDayTimeunitsOfSelectedDay =!= 0 else ecoMultDayTimeunitsOfSelectedDay contains the timeunits of the selected day
     var ecoMultDayTimeunitsOfSelectedDay = 0;
     ajaxRequestGet('../include/ajaxReqDisposition.php', 'mode=isMultipleDayJob&jbId=' + ecoId + '&csId=<?php echo $csId ?>');
     if (isMultipleDayJob != '' && isMultipleDayJob != '0') {
     	  // Eco is multiple day job, get timeunits of the selected day
     	  // ajaxRequestGet('../include/ajaxReqDisposition.php', 'mode=getMultipleDayJobTimeunits&jbId=' + ecoId + '&csId=<?php echo $csId ?>&currDay=<?php echo $currentSelectedDay ?>');
     	  ajaxRequestGet('../include/ajaxReqDisposition.php', 'mode=getMultipleDayJobTimeunits&jbId=' + ecoId + '&csId=<?php echo $csId ?>&currDay=' + orderDay);
     	  if (jobMultipleDayTimeunitsOfSelectedDay != '' && jobMultipleDayTimeunitsOfSelectedDay != '0') {
     	  	 ecoMultDayTimeunitsOfSelectedDay = parseInt(jobMultipleDayTimeunitsOfSelectedDay);
     	  }
     }
     
     // Check the availability of the specified vehicle for the requested interval
     if (ecoMultDayTimeunitsOfSelectedDay > 0) {
        ajaxRequestGet('../include/ajaxReqDisposition.php', 'mode=checkAvailabilityCrvhMultipleDayJb&crvhId=' + crvhId + '&currDay=' + orderDay + '&hour=' + hour + '&hourUnit=' + hourUnit + '&jbId=' + ecoId + '&csId=<?php echo $csId ?>&hourTimeUnits=<?php echo $hourTimeUnits ?>');
     } else {
     	  ajaxRequestGet('../include/ajaxReqDisposition.php', 'mode=checkAvailabilityCrvhJb&crvhId=' + crvhId + '&currDay=' + orderDay + '&hour=' + hour + '&hourUnit=' + hourUnit + '&timeslots=' + neededTimeslots + '&jbId=' + ecoId + '&csId=<?php echo $csId ?>&hourTimeUnits=<?php echo $hourTimeUnits ?>');
     }

     // Check for parameter for total weight being enabled
     var capacityCheckForTotalweight = '<?php echo $checkTotalweight ?>';
     if (capacityCheckForTotalweight == '0' || capacityProblem == '') {

        // Eco has been set to the new time slot => Update "jb_ordertime"
        ajaxRequestGet('../include/ajaxReqLib.php', 'mode=100&db_table=job&db_id_field=jb_id&db_op_field=jb_ordertime&new_content=' + newOrdertime + '&search_value=' + ecoId);

        // Remove potential existing eco on timeline
        ajaxRequestGet('../include/ajaxReqDisposition.php', 'mode=removeAssocCrvhJb&jbId=' + ecoId + '&csId=<?php echo $csId ?>&hourTimeUnits=<?php echo $hourTimeUnits ?>');
        if (isRemovedFromDb == '1') {
        	 // Eco did exist in any timeline and is removed now
        	 if (lastEcoOfCombinedJob == '1') {
        	    alertMsg += '<?php echo getLngt("Der Auftrag wurde an der alten Position freigegeben.") ?> ';
        	 }
        }

        // Persistent update of the new time interval for the eco into the DB
        ajaxRequestGet('../include/ajaxReqDisposition.php', 'mode=setAssocCrvhJb&crvhId=' + crvhId + '&currDay=' + orderDay + '&hour=' + hour + '&hourUnit=' + hourUnit + '&timeslots=' + neededTimeslots + '&jbId=' + ecoId + '&csId=<?php echo $csId ?>&hourTimeUnits=<?php echo $hourTimeUnits ?>');
        if (isUpdatedInDb == '1') {
           // Check vehicle is blocked
           var jbStatus = '9';
           if ('<?php echo $dispositionJbStatusMode ?>' == '1') {
              ajaxRequestGet('../include/ajaxReqDisposition.php', 'mode=crvhIsCarrierBlocked&crvhId=' + crvhId + '&currDay=' + orderDay);
              if (retValue == '1') {
              	  jbStatus = '0';
              	  // Set "internal" courier and SID associated to the vehicle to the job
              	  ajaxRequestGet('../include/ajaxReqDisposition.php', 'mode=setCourierAndVehicleInJobByVehicle&crvhId=' + crvhId + '&jbId=' + ecoId);
              	  if (retValue != '1') {
              	     jbStatus = '9';
              	  }
              }
           }
        	 // Set job status if vehicle is blocked for carrier administration => Update "jb_status"
        	 ajaxRequestGet('../include/ajaxReqLib.php', 'mode=100&db_table=job&db_id_field=jb_id&db_op_field=jb_status&new_content=' + jbStatus + '&search_value=' + ecoId);
        	 if (lastEcoOfCombinedJob == '1') {
        	    alertMsg += '<?php echo getLngt("Die Reservierung erfolgte.") ?> ';
        	 }
        	 ecoInFDS = '1';
        } else {
           // Write log entry
           if (lastEcoOfCombinedJob == '1') {
              ajaxRequestGet('../include/ajaxReqLib.php', 'mode=300&db_id_field=129&db_op_field=jb&search_value=' + ecoId + '&id_01=CRVH_ID&value_01=' + crvhId + '&id_02=CURR_DAY&value_02=' + orderDay + '&id_03=TIMESLOTS&value_03=' + neededTimeslots + '&id_03=CS_ID&value_03=<?php echo $csId ?>');
              alertMsg += '<?php echo getLngt("Der Auftrag konnte nicht auf das gewählte Fahrzeug gebucht werden. Bitte die Seite aktualisieren!") ?> ';
           }
           doSubmit = '0';
        }

        if (alertMsg != '') {
           alert(alertMsg);
        }
        if (doSubmit == '1') {
           // Check for being a whole day link
           if (isWholeDayLink == '1') {
              clockTime = '';
           }
           setOpenerData(orderDay, clockTime);
           if (lastEcoOfCombinedJob == '1') {
              // document.forms[0].submit();
              window.close();
           }
        }        
     } else {
/*
       if (capacityProblem == '0') {
          alert('<?php echo getLngt("Der Auftrag kann dem Fahrzeug nicht zugewiesen werden!") ?>');

       } else if (capacityProblem == '1') {
       	 // Presently output for MULTIPLE DAY JOBS only !!!!
       	 if (ecoMultDayTimeunitsOfSelectedDay > 0) {
       	    alert('<?php echo getLngt("Die erforderlichen Zeiteinheiten für den mehrtägigen Auftrag stehen für das Fahrzeug leider nicht zur Verfügung!") ?>');
       	 }
       } else if (capacityProblem == '2') {
       	 alert('<?php echo getLngt("Die Nutzlast des Fahrzeugs scheint ausgereizt!") ?>');
       }
*/
     }
  }
<?php if ($combinedJob) : ?>
  return ecoInFDS;
<?php endif; ?>
}

<?php if ($combinedJob) : ?>
function reserveMultiEco (crvhId, orderDay, combinedJobString, clockTime, isWholeDayLink) {
  if (crvhId != '' && orderDay != '' && combinedJobString != '') {
     var ecoInFDS = '1';
     var alertMsg = '';
     var lastEcoOfCombinedJob;
     var jobDataString;
     var jobDataArray;

     var jobsArray = combinedJobString.split("#");
     var jobsArrayLen = jobsArray.length;
     for (i=0; i<jobsArrayLen ;++i) {
     	   if (ecoInFDS == '1') {
     	      jobDataString = jobsArray[i];
            jobDataArray = jobDataString.split(";");
            
            lastEcoOfCombinedJob = '0';
            if (i == (jobsArrayLen - 1)) {
               lastEcoOfCombinedJob = '1';
            }
            
            ecoInFDS = reserveEco(jobDataArray[0], crvhId, orderDay, jobDataArray[1], jobDataArray[2], jobDataArray[4], jobDataArray[3], '0', '', isWholeDayLink, lastEcoOfCombinedJob);
         }
     }

     if (ecoInFDS == "1") {
        // Check for being a whole day link
        if (isWholeDayLink == '1') {
           clockTime = '';
        }
        setOpenerData(orderDay, clockTime);
        // document.forms[0].submit();

        // Ok, all ecos are stored in FDS
        window.close();
     } else {
        // Rollback, remove all combined ecos from the FDS
        for (i=0; i<jobsArrayLen ;++i) {
        	  jobDataString = jobsArray[i];
            jobDataArray = jobDataString.split(";");
            ajaxRequestGet('../include/ajaxReqDisposition.php', 'mode=removeAssocCrvhJb&jbId=' + jobDataArray[0] + '&csId=<?php echo $csId ?>&hourTimeUnits=<?php echo $hourTimeUnits ?>');
        }
        // Write log entry
        ajaxRequestGet('../include/ajaxReqLib.php', 'mode=300&db_id_field=129&db_op_field=jb&search_value=' + jobDataArray[0] + '&id_01=CRVH_ID&value_01=' + crvhId + '&id_02=CURR_DAY&value_02=' + orderDay + '&id_03=TIMESLOTS&value_03=' + jobDataArray[4] + '&id_03=CS_ID&value_03=<?php echo $csId ?>&id_04=COMBINED&value_04=Y');
        alertMsg += '<?php echo getLngt("Der Auftrag konnte nicht auf das gewählte Fahrzeug gebucht werden. Bitte die Seite aktualisieren!") ?> ';
     }
     if (alertMsg != '') {
        alert(alertMsg);
     }
  }
}
<?php endif; ?>

// Reserves a job according to the choice of one of the suggested dates, but does not set it on the timeline.
function reserveWholeDayEcoNotForFDS (ecoId, newOrdertime, doSubmit) {
  if (ecoId != '') {
     var alertMsg = '';

     // Remove potential existing eco on timeline
     ajaxRequestGet('../include/ajaxReqDisposition.php', 'mode=removeAssocCrvhJb&jbId=' + ecoId + '&csId=<?php echo $csId ?>&hourTimeUnits=<?php echo $hourTimeUnits ?>');
     if (isRemovedFromDb == '1') {
     	  // Eco did exist in any timeline and is removed now
     	  // alertMsg += '<?php echo getLngt("Der Auftrag wurde an der alten Position freigegeben.") ?> ';
     }

 	   // Eco has been set to the new ordertime => Update "jb_ordertime"
     ajaxRequestGet('../include/ajaxReqLib.php', 'mode=100&db_table=job&db_id_field=jb_id&db_op_field=jb_ordertime&new_content=' + newOrdertime + '&search_value=' + ecoId);
     alertMsg += '<?php echo getLngt("Der Auftrag wurde der neuen Position zugeordnet.") ?> ';

     if (doSubmit == '1') {    //  && alertMsg != ''
        // alert(alertMsg);
        setOpenerData(newOrdertime, '');
        // document.forms[0].submit();
        window.close();
     }
  }
}

function calendarFunc(year, month, day) {
  var monthStr = String(month);
  var dayStr = String(day);
  if (month < 10)
    monthStr = '0' + monthStr;
  if (day < 10)
    dayStr = '0' + dayStr;
  document.forms[0].day_from.value = dayStr;
  document.forms[0].month_from.value = monthStr;
  document.forms[0].year_from.value = year;
  document.forms[0].day_to.value = '';
  document.forms[0].month_to.value = '';
  document.forms[0].year_to.value = '';
  document.forms[0].dateSelectionByCalendar.value = '1';
  document.forms[0].submit();
}
-->
</script>

<?php echo $js_date ?>

</head>

<body class="menu_bgcol" onLoad="<?php echo $phpCurrentNavigationOnLoad ?><?php echo $onLoadCall ?>">

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

<form name="disposition" action="../admin/disposition_appointments.php" method="post">
  <input type="hidden" name="f_act" value="">
  <input type="hidden" name="jbId" value="<?php echo ec($jbId) ?>">
  <input type="hidden" name="csId" value="<?php echo ec($csId) ?>">
  <input type="hidden" name="ecoServices" value="<?php echo ec($ecoServices) ?>">
  <input type="hidden" name="ecoZipcode" value="<?php echo ec($ecoZipcode) ?>">
  <input type="hidden" name="ecoNeededTimeUnits" value="<?php echo ec($ecoNeededTimeUnits) ?>">
  <input type="hidden" name="ecoWeight" value="<?php echo ec($ecoWeight) ?>">
  <input type="hidden" name="ecoPositions" value="<?php echo ec($ecoPositions) ?>">
  <input type="hidden" name="maxLimitOfRows" value="<?php echo ec($maxLimitOfRows) ?>">
  <input type="hidden" name="deliveryTimeValue" value="<?php echo ec($deliveryTimeValue) ?>">
  <input type="hidden" name="dateSelectionByCalendar" value="">
  <input type="hidden" name="futureDaysOffset" value="<?php echo ec($futureDaysOffset) ?>">
  <input type="hidden" name="jbTimedFilter" value="<?php echo ec($jbTimedFilter) ?>">

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

  <?php echo htmlDivLineSpacer("10px"); ?>

  <div class="f12bp1_blue">
    <?php echo $pageTitel ?>
  </div>
  
  <?php echo htmlDivLineSpacer("30px"); ?>

  <div>
    <div <?php echo setStyleHtmlDiv("250px","left"); ?>>
      <!-- Calendar -->
      <div id="appointment"></div>
      <?php echo htmlDivLineSpacer("15px"); ?>
    </div>
    
    <div>
      <!-- Date ranges -->
      <div><?php echo "<b>" . getLngt("Bevorzugter Zeitraum") . "&nbsp;:&nbsp;&nbsp;&nbsp;&nbsp;</b>" . $categoryFilter; ?></div>
      <?php echo htmlDivLineSpacer("15px"); ?>
      
      <!-- Week days -->
      <div><?php echo "<b>" . getLngt("Bevorzugte Wochentage") . "&nbsp;:&nbsp;&nbsp;&nbsp;&nbsp;</b>" . addCheckboxesFromTable("ecoWeekdayArray","metatype","mt_sort","LEFT(mt_value,2)","mt_sort","mt_type = 'cal_week_days' AND mt_objtype = '' AND mt_objid = '0'",$ecoWeekdayArray, "&nbsp;&nbsp;&nbsp;&nbsp;") ?></div>
      <?php echo htmlDivLineSpacer("15px"); ?>
      
      <!-- Day times -->
      <div><?php echo "<b>" . getLngt("Bevorzugte Tageszeit") . "&nbsp;:&nbsp;&nbsp;&nbsp;&nbsp;</b>" . addCheckboxesFromTable("ecoDayTimeArray","metatype","mt_sort","mt_value","mt_sort","mt_type = 'day_time' AND mt_objtype = 'cs' AND mt_objid = '" . $csId . "'",$ecoDayTimeArray, "&nbsp;&nbsp;&nbsp;&nbsp;", $daytimeReadonlyArray) ?></div>
      <?php echo htmlDivLineSpacer("15px"); ?>

      
      <!-- Sort sequence -->
      <?php if (false) : ?>
        <div>
        	<?php echo "<b>" . getLngt("Anzeigepriorität nach") . "&nbsp;:&nbsp;&nbsp;&nbsp;&nbsp;</b>" ?>
          <input class="f8np1" type="radio" name="sortSequence" value="0" <?php if ($sortSequence == "0") : echo "checked"; endif; ?>> <?php echo getLngt("Tagen") ?>
          <input class="f8np1" type="radio" name="sortSequence" value="1" <?php if ($sortSequence == "1") : echo "checked"; endif; ?>> <?php echo getLngt("Zeitintervallen") ?>
        </div>
        <?php echo htmlDivLineSpacer("15px"); ?>
      <?php endif; ?>
      
      <?php echo htmlDivLineSpacer("10px"); ?>
      
      <div>
        <?php echo defineButtonType10(getLngt("Anfragen"), "action_save", "finishPage('request');", "100", "left", "3"); ?>
        <?php // echo defineButtonType10(getLngt("Reservieren"), "action_close", "finishPage('reserve');", "100", "left", "3"); ?>
        <?php // echo defineButtonType10(getLngt("Schließen"), "action_close", "window.close();", "100", "left", "3"); ?>
      </div>
      <?php echo htmlDivLineSpacer("20px", "", "left"); ?>
      <!-- Show job data if current request looks for moving an existing job -->
      <?php 
        if ($jbId != "") : 
           $jbOrdertime2 = substr($jbOrdertime,8,2) . "." . substr($jbOrdertime,5,2) . "." . substr($jbOrdertime,0,4) . "." . "&nbsp;&nbsp;" . substr($jbOrdertime,11,2) . ":" . substr($jbOrdertime,14,2) . "&nbsp;" . getLngt("Uhr");
           $tmpService = implode(",", getColVectorFromDB2ArrayByClause("metatype", "mt_mapped_value", "mt_type = 'service' AND mt_objtype = '' AND mt_objid = '0' AND mt_sort IN (" . implode(",", mcConvertNum2Sel($ecoChildrenServices)) . ")", "", "mt_sort", ""));
      ?>
        <div>
        	<?php echo "<b>" . getLngt("Auftrag") . "&nbsp;:&nbsp;&nbsp;</b>" . $jbId . "&nbsp;&nbsp;&nbsp;&nbsp;[" . $jbOrdertime2 . "]" . "&nbsp;&nbsp;&nbsp;&nbsp;[" . $tmpService . "]" . "&nbsp;&nbsp;&nbsp;&nbsp;[" . $ecoSummatedNeededTimeUnits . "&nbsp;". getLngt("ZE") . "]"; ?>
        </div>  
        <?php echo htmlDivLineSpacer("20px"); ?>
      <?php 
        endif;
      ?>
    </div>
  </div>

  <!-- Suggested dates -->
  <div>
    <table>
      <tr>
        <td class="f10bp1">
        	<?php echo getLngt("Vorschläge"); ?>
        	<br><br>
        </td>      
      </tr>
      <tr>
        <td>
          <?php echo $output ?>
        </td>      
      </tr>
    </table>  
  </div>

</form>
</div>
</body>

</html>