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

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


getSecHttpVars("1", array("f_act", "statusMessage", "f_cmp_authenticated", "deactivateMenu", "f_hq_id", "grpId", "csId", "currDay", "f_servicezone", "f_services",
                          "selDay", "selMonth", "selYear", "f_eco_show_all", "restrictedAccess", "search_item", "dateSelectionByCalendar", "timeLineScalingFactor",
                          "f_actionObjType", "f_actionObjId", "f_actionID", "f_filter_cr", "f_day_time_hour_from_new", "f_day_time_minute_from_new"));


getLanguage(__FILE__);

$deactivateMenuStatic = "1";
$pageTitel = getLngt("DISPOSITION");
include_once ("../admin/menu.php");
include_once ("../include/html.inc.php");
include_once ("../include/inc_filters.inc.php");
include_once ("../include/inc_vehicle.inc.php");
include_once ("../include/inc_group.inc.php");
getCurrentScript(__FILE__);

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

// Check for authentication access and granted rights
$usrAccessArray["hq"] = "1";
$usrAccessArray["cr"] = "1";
$accessOK = authCheckForAccess($hq_id, $usr_id, $emp_id, "", $customerId, $cscIdRoot, $cscIdActual);

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

// **** HEADQUARTERS CONFIGURATION ****
$empHasAccess_27 = true;
$empHasAccess_28 = false;
if ($userTypeName == "hq") :
   $empHasAccess_27 = authCheckEmployeeRights($emp_id, "27");
   $empHasAccess_28 = authCheckEmployeeRights($emp_id, "28");
endif;
$parRestrictedAccessClauseJob = "";
$parRestrictedAccessClauseVehicle = "";
if (!$empHasAccess_27 && !$empHasAccess_28) :
   gotoReferer("1"); 
endif;
if (!$empHasAccess_27 && $empHasAccess_28) :
   $doGotoReferer = true;
   // Check restricted access, regarding a segment of source code getting out of the database used as where clause for jobs and vehicles !!!!
   if ($empHasAccess_28) :
      $parRestrictedAccessClauseJob = getParameterValue("0", "DISPOSITION_RESTRICTED_ACCESS_CLAUSE_JOB", "0");
      $parRestrictedAccessClauseVehicle = getParameterValue("0", "DISPOSITION_RESTRICTED_ACCESS_CLAUSE_VEHICLE", "0");
      if ($parRestrictedAccessClauseJob != "" && $parRestrictedAccessClauseVehicle != "") :
         $parRestrictedAccessClauseJob = " " . $parRestrictedAccessClauseJob . " ";
         $parRestrictedAccessClauseVehicle = " " . $parRestrictedAccessClauseVehicle . " ";
         $doGotoReferer = false;
      endif;
   endif;
   if ($doGotoReferer) :
      gotoReferer("1"); 
   endif;
endif;

// **** COURIER CONFIGURATION ****
if ($userTypeName == "cr") :
   // Get courier data logged in
   $crIdLoggedIn = getFieldValueFromId("courier","usr_id",$usr_id,"cr_id");
   $crHasDispoRights = getFieldValueFromId("courier","cr_id",$crIdLoggedIn,"cr_disposition");
   if ($crHasDispoRights != "1") :
      gotoReferer("1");
   endif;
   // * Get related customer of the courier logged in *
   // Get all vehicles of the courier
   $crvhIdOfCrLoggedInArray = getColVectorFromDB2ArrayByClause("couriervehicle", "crvh_id", "cr_id = '" . $crIdLoggedIn . "'", "", "", "");
   $crvhIdOfCrLoggedInArrayLen = count($crvhIdOfCrLoggedInArray);
   if ($crvhIdOfCrLoggedInArrayLen > 0) :
      // Get the customers associated to the vehicles
      $csIdArray = getColVectorFromDB2ArrayByClause("customervehicle", "cs_id", "crvh_id IN (" . implode(",", $crvhIdOfCrLoggedInArray) . ")", "", "cs_id", "DISTINCT");
      if ($csId == "") :
         $csId = $csIdArray[0];
         $csGroup = getFieldValueFromId("customer","cs_id",$csId,"cs_group");
         $csGroupArray = spliti(",", $csGroup);
         $grpId = $csGroupArray[1];
      endif;
   endif;
   // Job restrictions for courier logged in (either jb.cr_id is set for taken and finished jobs OR jb.cr_id_order is set AND job is in FDS for the courier)
   // if ($parRestrictedAccessClauseJob != "") : $parRestrictedAccessClauseJob .= " AND "; endif;
   $parRestrictedAccessClauseJob .= " (jb.cr_id = '" . $crIdLoggedIn . "' OR (jb.jb_status = '0' AND (NOT ISNULL(jb.cr_id_order) AND jb.cr_id_order != '0') AND EXISTS (SELECT * FROM vehicledisposition AS vhd, couriervehicle AS crvh WHERE vhd.jb_id = jb.jb_id AND vhd.crvh_id = crvh.crvh_id AND crvh.cr_id = '" . $crIdLoggedIn . "'))) AND ";
   // Vehicle restrictions for courier logged in
   if ($parRestrictedAccessClauseVehicle != "") : $parRestrictedAccessClauseVehicle .= " AND "; endif;
   $parRestrictedAccessClauseVehicle .= " crvh.cr_id = '" . $crIdLoggedIn . "' ";
endif;


// Get global mode of usage
$globalParUseRelatedCustomer = getParameterValue("0", "GLOBAL_USE_RELATED_CUSTOMER", "0");

// Global scaling factorfor output
if ($timeLineScalingFactor == "" || !is_numeric($timeLineScalingFactor)) : 
   $timeLineScalingFactor = 2;
   $parMaskDispositionScalingFactorDefault = getParameterValue("0", "MASK_DISPOSITION_SCALING_FACTOR_DEFAULT", $f_hq_id);
   if ($parMaskDispositionScalingFactorDefault == "") :
      $parMaskDispositionScalingFactorDefault = getParameterValue("0", "MASK_DISPOSITION_SCALING_FACTOR_DEFAULT", "0");
   endif;
   if ($parMaskDispositionScalingFactorDefault != "" && is_numeric($parMaskDispositionScalingFactorDefault) && $parMaskDispositionScalingFactorDefault >= 1 && $parMaskDispositionScalingFactorDefault <= 9) :
      $timeLineScalingFactor = $parMaskDispositionScalingFactorDefault;
   endif;
endif;

// Mandator filter
if ($f_hq_id == "") : $f_hq_id = $hq_id; endif;


// Get parameter for displaying eco ID in drag bar
$parMaskDispositionItemShowDragbarEcoId = getParameterValue("0", "MASK_DISPOSITION_ITEM_DRAGBAR_SHOW_JB_ID", $f_hq_id);
if ($parMaskDispositionItemShowDragbarEcoId == "") :
   $parMaskDispositionItemShowDragbarEcoId = getParameterValue("0", "MASK_DISPOSITION_ITEM_DRAGBAR_SHOW_JB_ID", "0");
endif;

// Get all types of service being a kind of DELIVERY, e.g. "Aufmaß" (service & 4 == 4) will be an installation in every case (service & 2 == 0)
$parDeliveryServices = getObjectBasedParameterValue("DISPOSITION_DELIVERYSERVICES", $csId, $f_hq_id);
$parDeliveryServiceArray = spliti(",", $parDeliveryServices);
$parDeliveryServiceArrayLen = count($parDeliveryServiceArray);

// Get all types of service being a kind of INSTALLATION, e.g. "Küche" (service & 16 == 16) will be an installation in every case (service & 2 == 2)
$parInstallationServices = getObjectBasedParameterValue("DISPOSITION_INSTALLATIONSERVICES", $csId, $f_hq_id);
$parInstallationServiceArray = spliti(",", $parInstallationServices);
$parInstallationServiceArrayLen = count($parInstallationServiceArray);

// Get service colors
$parServiceColours = getObjectBasedParameterValue("MASK_DISPOSITION_SERVICECOLOURS", $csId, $f_hq_id);
$serviceColourArray = array();
if ($parServiceColours != "") :
   $serviceColourArray = getKeyValueArrayFromString($parServiceColours);
endif;
$serviceColourArrayLen = count($serviceColourArray);

// Get parameter for called function for generating cartage note
$parMaskDispositionFunctionnameCartageNote = getParameterValue("0", "MASK_DISPOSITION_FUNCTIONNAME_CARTAGE_NOTE", $f_hq_id);
if ($parMaskDispositionFunctionnameCartageNote == "") :
   $parMaskDispositionFunctionnameCartageNote = getParameterValue("0", "MASK_DISPOSITION_FUNCTIONNAME_CARTAGE_NOTE", "0");
   if ($parMaskDispositionFunctionnameCartageNote == "") :
      $parMaskDispositionFunctionnameCartageNote = "getCartageNote";
   endif;
endif;

// Get parameter for displaying clock times on timeline
$parMaskDispositionHideHoursOnTimeline = getParameterValue("0", "MASK_DISPOSITION_TIMELINE_HOURS_HIDE", $f_hq_id);
if ($parMaskDispositionHideHoursOnTimeline == "") : $parMaskDispositionHideHoursOnTimeline = getParameterValue("0", "MASK_DISPOSITION_TIMELINE_HOURS_HIDE", "0"); endif;

// Get parameter for dropping objects on past time slots
$parMaskDispositionEnableDroppingOnPastTimeslots = getParameterValue("0", "MASK_DISPOSITION_TIMELINE_ENABLE_DROPPING_ON_PAST_TIMESLOTS", $f_hq_id);
if ($parMaskDispositionEnableDroppingOnPastTimeslots == "") : $parMaskDispositionEnableDroppingOnPastTimeslots = getParameterValue("0", "MASK_DISPOSITION_TIMELINE_ENABLE_DROPPING_ON_PAST_TIMESLOTS", "0"); endif;

// Check search item
$idSearchArray = array();
$search_type = "";
if ($search_item != "") :
   if ($globalParUseRelatedCustomer != "1" && is_numeric($search_item)) :
      $searchJbOrdertime = getFieldValueFromClause("job","jb_ordertime","jb_id = '" . $search_item . "' AND hq_id = '" . $hq_id . "'");
      if ($searchJbOrdertime != "") :
         array_push($idSearchArray, $search_item);
         $selDay = substr($searchJbOrdertime,8,2);
         $selMonth = substr($searchJbOrdertime,5,2);
         $selYear = substr($searchJbOrdertime,0,4);
         $search_type = "jb";
      endif;
   else :
      $idSearchArray = searchJobs($search_item);
      $idSearchArrayLen = count($idSearchArray);
      if ($idSearchArrayLen > 0) :
         // Search day to be displayed for the first job only
         $searchJbOrdertime = getFieldValueFromClause("job","jb_ordertime","jb_id = '" . $idSearchArray[0] . "' AND hq_id = '" . $hq_id . "'");
         if ($searchJbOrdertime != "") :
            $selDay = substr($searchJbOrdertime,8,2);
            $selMonth = substr($searchJbOrdertime,5,2);
            $selYear = substr($searchJbOrdertime,0,4);
            $search_type = "jb";
         endif;
      endif;
      // Check for eco
      /*
      $remSearchItem = $search_item;
      if (substr($search_item,-2) == "/1") : 
         $search_item = substr($search_item,0,-2);
      endif;
      if (substr($search_item,-2) == "/2") : 
         $search_item = substr($search_item,0,-2);
         if (is_numeric($search_item)) :
            $search_item = getFieldValueFromId("job", "jb_id_parent", $search_item, "jb_id");
         endif;
      endif;
      if ($search_item == "") :
         $search_item = getFieldValueFromId("tour", "tr_commission_no", $remSearchItem, "jb_id");
      endif;
      if ($search_item == "") :
         $search_item = getFieldValueFromClause("genericdatacontainer","gdc_obj_id","gdc_obj_type = 'jb' AND gdc_gen_fieldname = 'info_0' AND gdc_content = '" . $remSearchItem . "'");
      endif;
      if ($search_item != "" && is_numeric($search_item)) :
         $searchJbOrdertime = getFieldValueFromClause("job","jb_ordertime","jb_id = '" . $search_item . "' AND hq_id = '" . $hq_id . "'");
         if ($searchJbOrdertime != "") :
            $selDay = substr($searchJbOrdertime,8,2);
            $selMonth = substr($searchJbOrdertime,5,2);
            $selYear = substr($searchJbOrdertime,0,4);
            $search_type = "jb";
         endif;
      endif;
      */
   endif;
endif;


// Selected day
$currentDayTime = getDateTime("0");   // "Y-m-d H:i:s" (current timestamp)
$currYear = getDateTime("year");
$currentDay = getDateTime("3");   // "Y-m-d" (today)
$currentTime = getDateTime("4");  // Current time ("H:i:s")
if ($selDay == "" || $selMonth == "" || $selYear == "") : 
    // Initialize date-ranges to the current date
    $selDay = getDateTime("day");
    $selMonth = getDateTime("month");
    $selYear = $currYear;
endif;
$currentSelectedDay = $selYear . "-" . pad($selMonth,2) . "-" . pad($selDay,2);
// $dayBeforeCurrentSelectedDay = date("Y-m-d", mktime(0,0,0,$selMonth, $selDay - 1, $selYear));
$currentDayNumOfTheWeek = date("w", mktime(0, 0, 0, $selMonth, $selDay, $selYear));   // 0 = Sunday, 1 = Monday, etc.
if ($currentDayNumOfTheWeek == 0) : $currentDayNumOfTheWeek = "7"; endif;          // Reformat to 1 = Monday, ... , 7 = Sunday
$calWeekDays = getColVectorFromDB2Array("metatype","mt_type","cal_week_days","mt_value","mt_sort");
$fromDateRange = $selYear . "-" . pad($selMonth,2) . "-" . pad($selDay,2) . " 00:00:00";
$toDateRange = $selYear . "-" . pad($selMonth,2) . "-" . pad($selDay,2) . " 23:59:59";

// Hours per day
// $hours = getParameterValue("0", "DISPOSITION_HOURS", $hq_id);
// if ($hours == "" || !is_numeric($hours)) :
   $hours = getParameterValue("0", "DISPOSITION_HOURS", "0");
   if ($hours == "" || !is_numeric($hours)) :
      $hours = 23;
   endif;
// endif;

// Time units of a hour (e.g. 12 units per 5 minutes <=> 6 units per 10 minutes <=> one hour)
// $hourTimeUnits = getParameterValue("0", "DISPOSITION_HOUR_TIME_UNITS", $hq_id);
// if ($hourTimeUnits == "" || !is_numeric($hourTimeUnits)) :
   $hourTimeUnits = getParameterValue("0", "DISPOSITION_HOUR_TIME_UNITS", "0");
   if ($hourTimeUnits == "" || !is_numeric($hourTimeUnits)) :
      $hourTimeUnits = 6;
   endif;
// endif;


// Get mask configuration for the current employee logged in regarding to the group and customer setting in employee master data
if ($userTypeName == "hq") :
   $parMaskDispositionGroup = $grpId;
   $parMaskDispositionCustomer = $csId;
   if ($grpId == "" || $csId == "") :
      $parMaskDispositionGroup = getParameterValue($emp_id, "MASK_DISPOSITION_INIT_GROUP", $hq_id);
      $parMaskDispositionCustomer = getParameterValue($emp_id, "MASK_DISPOSITION_INIT_CS", $hq_id);
      // Check for "init customer" is in "init group"
      $tmpGrpArray = spliti(",", $parMaskDispositionGroup);
      $tmpCsGroupArray = getGroupMemberIDs($tmpGrpArray, "cs", array($f_hq_id));
      if (array_search($parMaskDispositionCustomer, $tmpCsGroupArray) === FALSE) :
         $parMaskDispositionCustomer = "";
      endif;
      if ($parMaskDispositionGroup != "" && $parMaskDispositionGroup != "0" && $parMaskDispositionCustomer != "" && $parMaskDispositionCustomer != "0") :
         $grpId = $parMaskDispositionGroup;
         $csId = $parMaskDispositionCustomer;
      endif;
   endif;
endif;

// Get maximum of defined time units (in metatype) of the customer
// E.g.: Three daytime intervals (08:00 - 12:00, 12:00 - 16:00, 16:00 - 21:00), take the min and max values (08:00 - 21:00) and compute number of time units between (78)
// $numOfTimeUnitsOfTheSelectedDay = getNumOfTimeUnitsBetweenInterval($csId, "", $hourTimeUnits);

// Array for the elements of the time line for each vehicle (coordinates of the top-left-corner, state of occupation, etc)
// Daily view: $masterArray[crvh_id][hour(00..23)][time_unit(0..6|12|...)] = array("occupation_state(0..1)", "coordinate_top(0..y)", "coordinate_left(0..x)")
$masterArray = array();

// Get array of weekdays
$weekDays = getColVectorFromDB2ArrayByClause("metatype", "mt_sort", "mt_type = 'cal_week_days'", "", "mt_sort", "");
$weekDayNames = getColVectorFromDB2ArrayByClause("metatype", "mt_value", "mt_type = 'cal_week_days'", "", "mt_sort", "");
$weekDaysLen = count($weekDays);

// Get array of day times by default
if ($csId != "") :
   $dayTimes = getColVectorFromDB2ArrayByClause("metatype", "mt_sort", "mt_type = 'day_time' AND mt_objtype = 'cs' AND mt_objid = '" . $csId . "'", "", "mt_sort", "");
   $dayTimeNames = getColVectorFromDB2ArrayByClause("metatype", "mt_value", "mt_type = 'day_time' AND mt_objtype = 'cs' AND mt_objid = '" . $csId . "'", "", "mt_sort", "");
   $dayTimeMappedValues = getColVectorFromDB2ArrayByClause("metatype", "mt_mapped_value", "mt_type = 'day_time' AND mt_objtype = 'cs' AND mt_objid = '" . $csId . "'", "", "mt_sort", "");
else :
   $dayTimes = array();
//    $dayTimes = getColVectorFromDB2ArrayByClause("metatype", "mt_sort", "mt_type = 'day_time'", "", "mt_sort", "");
//    $dayTimeNames = getColVectorFromDB2ArrayByClause("metatype", "mt_value", "mt_type = 'day_time'", "", "mt_sort", "");
//    $dayTimeMappedValues = getColVectorFromDB2ArrayByClause("metatype", "mt_mapped_value", "mt_type = 'day_time'", "", "mt_sort", "");
endif;
$dayTimesLen = count($dayTimes);

// Daily working range of the related customer (e.g. 07:00 - 21:00 => array("07", "00", "21", "00"))
$dispositionStartHourOffset = getParameterValue("0", "DISPOSITION_START_HOUR_OFFSET", $hq_id);
if ($dispositionStartHourOffset == "" || !is_numeric($dispositionStartHourOffset)) : $dispositionStartHourOffset = getParameterValue("0", "DISPOSITION_START_HOUR_OFFSET", "0"); endif;
if ($dispositionStartHourOffset == "" || !is_numeric($dispositionStartHourOffset)) : $dispositionStartHourOffset = 0; endif;
$dispositionEndHourOffset = getParameterValue("0", "DISPOSITION_END_HOUR_OFFSET", $hq_id);
if ($dispositionEndHourOffset == "" || !is_numeric($dispositionEndHourOffset)) : $dispositionEndHourOffset = getParameterValue("0", "DISPOSITION_END_HOUR_OFFSET", "0"); endif;
if ($dispositionEndHourOffset == "" || !is_numeric($dispositionEndHourOffset)) : $dispositionEndHourOffset = 0; endif;
$csRelatedDayTimeRange = array(0,0,0,0);
if ($dayTimesLen > 0) :
   $tmpVal = intval(substr($dayTimeMappedValues[0],0,2));
   if ($tmpVal != "" && is_numeric($tmpVal)) :
      $csRelatedDayTimeRange[0] = $tmpVal + $dispositionStartHourOffset;
   endif;
   $tmpVal = intval(substr($dayTimeMappedValues[0],3,2));
   if ($tmpVal != "" && is_numeric($tmpVal)) :
      $csRelatedDayTimeRange[1] = $tmpVal;
   endif;
   $tmpVal = intval(substr($dayTimeMappedValues[($dayTimesLen - 1)],8,2));
   if ($tmpVal != "" && is_numeric($tmpVal)) :
      $csRelatedDayTimeRange[2] = $tmpVal + $dispositionEndHourOffset;
   endif;
   $tmpVal = intval(substr($dayTimeMappedValues[($dayTimesLen - 1)],11,2));
   if ($tmpVal != "" && is_numeric($tmpVal)) :
      $csRelatedDayTimeRange[3] = $tmpVal;
   endif;
endif;


// Init service array if it is empty (no service selected). Get all services from "metatype" and init the service array with all of them
if ($f_services == "" || count($f_services) == 0) :
   // DISABLED, because the meaning "Mindestens die selektierte Dienstleistung"
   // $f_services = getColVectorFromDB2ArrayByClause("metatype", "mt_sort", "mt_type = 'service' AND mt_objtype = '' AND mt_objid = '0'", "", "mt_sort", "");
   $f_services = array();
endif;
$numOfAllServices = getCountOfTable("metatype", "mt_type = 'service' AND mt_objtype = '' AND mt_objid = '0'");  // Number of ALL services
$numOfRequestedServices = count($f_services);                                                                   // Number of services set in the mask by the user
$ecoWhereClauseService = "";
$crvhWhereClauseService = "";
if ($numOfRequestedServices != 0 && $numOfAllServices != $numOfRequestedServices) :
   $serviceValue = mcConvertSel2Num($f_services);
   $ecoWhereClauseService = " (jb.jb_service & " . $serviceValue . " = " . $serviceValue . ") ";    // Set filter for eco WHERE clause
   $crvhWhereClauseService = " (crvh.crvh_service & " . $serviceValue . " = " . $serviceValue . ") ";    // Set filter for vehicle WHERE clause
endif;

// Check for excluded vehicles (e.g. "booking vehicles") being displayed
$crvhWhereClauseExcludesVehicles = " crvh.crvh_vhd_disabled = '0' ";
$dispositionDisplayExcludedVehicles = getParameterValue("0", "DISPOSITION_SHOW_EXCLUDED_VEHICLES", $hq_id);
if ($dispositionDisplayExcludedVehicles == "") : $dispositionDisplayExcludedVehicles = getParameterValue("0", "DISPOSITION_SHOW_EXCLUDED_VEHICLES", "0"); endif;
if ($dispositionDisplayExcludedVehicles == "1") :
   $crvhWhereClauseExcludesVehicles = "";
endif;
if ($crvhWhereClauseExcludesVehicles != "") :
   if ($crvhWhereClauseService != "") : $crvhWhereClauseService .= " AND "; endif;
   $crvhWhereClauseService .= $crvhWhereClauseExcludesVehicles;
endif;


// Check for payload capacity of the vehicles
$checkTotalweight = "0";
$dispositionCheckingForTotalweightDisabled = getParameterValue("0", "DISPOSITION_CHECK_TOTALWEIGHT_ENABLED", $hq_id);
if ($dispositionCheckingForTotalweightDisabled == "") : $dispositionCheckingForTotalweightDisabled = getParameterValue("0", "DISPOSITION_CHECK_TOTALWEIGHT_ENABLED", "0"); endif;
if ($dispositionCheckingForTotalweightDisabled == "1") :
   $checkTotalweight = "1";
endif;

// Check for activated checkbox "all [ECO] jobs"
$dispositionEcoContainerDisplayAllJobsPermanently = getParameterValue("0", "DISPOSITION_ECO_CONTAINER_DISPLAY_ALL_JOBS_PERMANENTLY", $hq_id);
if ($dispositionEcoContainerDisplayAllJobsPermanently == "") : $dispositionEcoContainerDisplayAllJobsPermanently = getParameterValue("0", "DISPOSITION_ECO_CONTAINER_DISPLAY_ALL_JOBS_PERMANENTLY", "0"); endif;
if ($dispositionEcoContainerDisplayAllJobsPermanently == "1") :
   $f_eco_show_all = "1";
endif;


// ********************
// * Get the vehicles *
// ********************

// **************************************
// Check restricted access clause
if ($parRestrictedAccessClauseVehicle != "") :
   if ($crvhWhereClauseService != "") : $crvhWhereClauseService .= " AND "; endif;
   $crvhWhereClauseService .= $parRestrictedAccessClauseVehicle;
endif;
if ($userTypeName == "hq" && $f_filter_cr != "") :
   if ($crvhWhereClauseService != "") : $crvhWhereClauseService .= " AND "; endif;
   $crvhWhereClauseService .= " cr.cr_id = '" . $f_filter_cr . "' ";
endif;
// **************************************
$crList = array();
$crvhList = array();
if ($userTypeName == "hq" && $csId != "") :
   $sqlquery = getStmtCustomerVehicleRelation("", $csId, $crvhWhereClauseService, "crvh.crvh_sid");
// echo $sqlquery . "<br>";
   $result = $db->query($sqlquery);
   if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
   while ($row = $result->fetch_assoc()):
         $crvhList[] = array($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"], $row["cr_id"]);

         // Get all couriers associated to the selected related customer
         $crList[$row["cr_id"]] = $row["usr_name"] . ", " . $row["usr_firstname"];
   endwhile;
   $result->free();
elseif ($userTypeName == "cr") :
   $sqlquery = "SELECT crvh.crvh_id, crvh.crvh_sid, cmp.cmp_comp, cmp.cmp_comp2, cr.hq_id, crvh.crvh_service, cr.cr_id"
             . " FROM couriervehicle AS crvh, courier AS cr, company AS cmp"
             . " WHERE cr.cr_id_parent = '" . $crIdLoggedIn . "' AND cr.cr_sid = crvh.crvh_sid AND crvh.crvh_modify_status != '3' AND cr.cmp_id = cmp.cmp_id"
             . " ORDER BY crvh.crvh_sid";
// echo $sqlquery . "<br>";
   $result = $db->query($sqlquery);
   if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
   while ($row = $result->fetch_assoc()):
         $crvhList[] = array($row["crvh_id"], "", "", "", $row["crvh_sid"], "", $row["cmp_comp"], $row["cmp_comp2"], $row["hq_id"], "", $row["crvh_service"], $row["cr_id"]);
   endwhile;
   $result->free();
endif;
$crvhListLen = count($crvhList);

// Check for each vehicle displayed the existence of entries in "vehicledisposition", "vehicleavailability" and "vehicleavailabilitytimeunits".
// If it does not exist then generate it to handle the drag and dropping the jobs etc.
// Generate structure for "today" or future days only!
if ($currentSelectedDay >= $currentDay) :
   if ($csId != "" && $csId > "0") :
      for ($v = 0; $v < $crvhListLen; $v++) :
          $crvhId = $crvhList[$v][0];
          if (!existsEntry("vehicledisposition",array("crvh_id",$crvhId,"LEFT(vhd_timeslot, 10)",$currentSelectedDay))) :
             // Generate all new timeslot entries for the vehicle for the specified day
             generatePersistentTimeslots($crvhId, $currentSelectedDay, $hourTimeUnits, $csId);
          endif;
      endfor;
   endif;
endif;

// Check restrictions on the timeline of the current day of the vehicle regarding the daytimes and the selected special zone
// At least one of the daytimes the vehicle has to drive for the customer on the specified day and therefore the vehicle has to be displayed in the disposition list
if ($userTypeName == "hq") :
   if ($crvhListLen > 0 && $f_servicezone != "" && $f_servicezone != "ALL") :
      $crvhListTmp = $crvhList;  // Copy to temp
      $crvhListTmpLen = count($crvhListTmp);
      $crvhList = array();       // Reset original
      for ($v = 0; $v < $crvhListTmpLen; $v++) :
          $crvhId  = $crvhListTmp[$v][0];
          $removeVehicleRegardingZone = true;
          $tmpDaytimeZoneArray = getDaytimeAvailabilityOfVehicle($crvhId, $currentDayNumOfTheWeek, $csId, "1");  // $tmpDaytimeZoneArray[daytime] = zone
          // Iterate given daytimes (got from customer !!!!)
          for ($i = 0; $i < $dayTimesLen; $i++) :
              if ($tmpDaytimeZoneArray[$i] == "" || $tmpDaytimeZoneArray[$i] == $f_servicezone) :
                 $removeVehicleRegardingZone = false;   // Zone matched or one of the daytimes contains "All zones" for the vehicle for the specified day. => Display vehicle
              endif;
          endfor;
          // Remove vehicle out of the list
          if (!$removeVehicleRegardingZone) :
             $crvhList[] = $crvhListTmp[$v];
          endif;
      endfor;
      $crvhListLen = count($crvhList);
   endif;
endif;

// Check for mode the vehicle is blocked for courier disposition. Display for courier only if it is blocked !!!!
if ($userTypeName == "cr") :
   $crvhListTmp = $crvhList;  // Copy to temp
   $crvhListTmpLen = count($crvhListTmp);
   $crvhList = array();       // Reset original
   for ($v = 0; $v < $crvhListTmpLen; $v++) :
       $crvhId  = $crvhListTmp[$v][0];
       $removeVehicleRegardingCourierDisposition = false;
       $crvhBlockedState = crvhBlockedState($crvhId, $currentSelectedDay);
       if (($crvhBlockedState & 2) != 2) :
          $removeVehicleRegardingCourierDisposition = true;
       endif;
       // Remove vehicle out of the list
       if (!$removeVehicleRegardingCourierDisposition) :
          $crvhList[] = $crvhListTmp[$v];
       endif;
   endfor;
   $crvhListLen = count($crvhList);
endif;



// ********************
// * Disposition menu *
// ********************

$outputMenu = "";

// DIV to hide vehicle timelines by scrolling
$outputMenu .= "<div id=\"layer_div\" style=\"position:fixed; top:0px; left:0px; width:100%; height:120px; z-index:6; background-color: " . $constBackground . ";\"></div>\n";

$outputMenu .= "<div id=\"disposition_menu\" style=\"position:fixed; top:0px; left:0px; width:100%; height:30px; z-index:9; background-color: " . $constBackground . ";\"\">\n";
$outputMenu .= "<b>" . $pageTitel . "</b>" . "&nbsp;&nbsp;|&nbsp;&nbsp;";

if ($userTypeName == "hq") :
   // Customer selection
   $outputMenu .= "<select class=\"f8np1\" name=\"csId\" id=\"csId\" onChange=\"finishPage('');\">\n";
   $outputMenu .= "  <option value=\"\"" . ($parMaskDispositionCustomer == "" ? "selected" : "") . ">" . getLngt("----") . "</option>\n";
   // Get customers associated to the selected group only
   $parMaskCmpFieldDisplayed = getParameterValue("0", "MASK_DISPOSITION_CMP_FIELD_DISPLAYED", $hq_id);
   if ($parMaskCmpFieldDisplayed == "") : $parMaskCmpFieldDisplayed = getParameterValue("0", "MASK_DISPOSITION_CMP_FIELD_DISPLAYED", "0"); endif;
   $outputMenu .=    addOptionsFromTable("customer AS cs, company AS cmp","cs.cs_id","cmp.cmp_comp" . $parMaskCmpFieldDisplayed,"cmp.cmp_comp" . $parMaskCmpFieldDisplayed,"cs.hq_id IN " . getSQLMandatorArray(array($f_hq_id)) . " AND cmp.cmp_id = cs.cmp_id AND cmp.cmp_comp != 'EXTERN' AND cs.cs_id_parent != '0' AND NOT isnull(cs.cs_id_parent) AND cs.cs_group LIKE '%," . $parMaskDispositionGroup . ",%'",$parMaskDispositionCustomer);
   $outputMenu .= "</select>";
   $outputMenu .= "&nbsp;&nbsp;";
   $outputMenu .= "<input type=\"button\" name=\"call_menuselection\" id=\"call_menuselection\" title=\"menuselection\" value=\"" . getLngt("...") . "\" onClick=\"callMenuSelection();\">";
   $outputMenu .= "&nbsp;|&nbsp;";
   // Servicezone selection
   if ($f_servicezone == "") :
      $parMaskFirstZoneSelected = getParameterValue("0", "MASK_DISPOSITION_FIRST_ZONE_SELECTED", $hq_id);
      if ($parMaskFirstZoneSelected == "") : $parMaskFirstZoneSelected = getParameterValue("0", "MASK_DISPOSITION_FIRST_ZONE_SELECTED", "0"); endif;
      if ($parMaskFirstZoneSelected == "1") :
         $f_servicezone = getOneStmt("SELECT srvz_no FROM servicezone WHERE cs_id = '" . $csId . "' ORDER BY srvz_no LIMIT 0,1", "srvz_no");
      endif;
   endif;
   // $outputMenu .= getLngt("Zone") . ":&nbsp;";
   $outputMenu .= "<select class=\"f8np1\" name=\"f_servicezone\" id=\"f_servicezone\" onChange=\"finishPage('');\">";
   if ($parMaskDispositionCustomer == "") :
      $outputMenu .= "  <option value=\"\" " . ($f_servicezone == "" ? "selected" : "") . ">" . getLngt("Keine Einschränkung") . "</option>";
   else :
      $outputMenu .= "  <option value=\"ALL\" " . ($f_servicezone == "ALL" ? "selected" : "") . ">" . getLngt("Keine Einschränkung") . "</option>";
   endif;
   $outputMenu .=    addOptionsFromTable("servicezone", "srvz_no", "srvz_name", "srvz_no", "cs_id = '" . $csId . "'", $f_servicezone , "");
   $outputMenu .= "</select>";
   $outputMenu .= "&nbsp;|&nbsp;";
   $outputMenu .= "<input type=\"checkbox\" name=\"f_eco_show_all\" value=\"1\" " . ($f_eco_show_all == "1" ? "checked" : "") . " tabindex=\"\" onChange=\"finishPage('');\">&nbsp;" . getLngt("Alle Aufträge");
   $outputMenu .= "&nbsp;|&nbsp;";
endif;
// Selection of a specific day
$currentFrameName = "";
// $outputMenu .= getLngt("Datum") . ":&nbsp;";
$outputMenu .= "<select name=\"selDay\" class=\"f8np1\" onchange=\"fillDateFields(0, '" . $currentFrameName . "', 'history', 'selDay', 'selDay', 'selMonth', 'selYear', '', '', '')\"></select>\n";
$outputMenu .= "<select name=\"selMonth\" class=\"f8np1\" onchange=\"fillDateFields(0, '" . $currentFrameName . "', 'history', 'selMonth', 'selDay', 'selMonth', 'selYear', '', '', '')\"></select>\n";
$outputMenu .= "<select name=\"selYear\" class=\"f8np1\" onchange=\"fillDateFields(0, '" . $currentFrameName . "', 'history', 'selYear', 'selDay', 'selMonth', 'selYear', '', '', '')\"></select>\n";
$outputMenu .= "&nbsp;(" . substr($calWeekDays[$currentDayNumOfTheWeek - 1], 0, 2) . ".)";
// $outputMenu .= $currentSelectedDay . "&nbsp;(" . substr($calWeekDays[$currentDayNumOfTheWeek - 1], 0, 2) . ".)";  // " . $currentDayNumOfTheWeek . "&nbsp;
$outputMenu .= "&nbsp;";
$outputMenu .= "<input type=\"button\" name=\"call_calendar\" id=\"call_calendar\" title=\"...\" value=\"...\" onClick=\"callCalendar();\">";
$outputMenu .= "&nbsp;|&nbsp;";
// Refresh button
// $outputMenu .= defineButtonType08(getLngt("Refresh"), "action_refresh", "finishPage();", "100", "", "");
$outputMenu .= "<input type=\"submit\" name=\"refresh\" id=\"refresh\" value=\"" . getLngt("Refresh") . "\">";
   $outputMenu .= "&nbsp;|&nbsp;";
   // Search eco
   $outputMenu .= "<input type=\"text\" name=\"search_item\" id=\"eco_search\" value=\"\" size=\"6\">" . "&nbsp;";
if ($userTypeName == "hq") :
   $outputMenu .= "&nbsp;|&nbsp;";
   // Services checkboxes
   $outputMenu .= "<input type=\"button\" name=\"call_servicefilter\" id=\"call_servicefilter\" title=\"servicefilter\" value=\"" . getLngt("Service-Filter") . "\" onClick=\"callServiceFilter();\">";
   $outputMenu .= "&nbsp;|&nbsp;";
   // Check day is blocked
   $gdcSelectedDayIsBlocked = getFieldValueFromClause("genericdatacontainer", "gdc_content", "gdc_obj_type = 'vha' AND gdc_obj_id = '" . $csId . "' AND gdc_gen_fieldname = 'vha_day_blocked' AND gdc_context = '" . $currentSelectedDay . "'");
   if ($gdcSelectedDayIsBlocked == "1") :
      $outputMenu .= "<input type=\"button\" name=\"call_day_unblock\" id=\"call_day_unblock\" title=\"call_day_unblock\" value=\"" . getLngt("Tag freigeben") . "\" onClick=\"callCheckDayBlocked('0');\">";
   else :
      $outputMenu .= "<input type=\"button\" name=\"call_day_block\" id=\"call_day_block\" title=\"call_day_block\" value=\"" . getLngt("Tag blockieren") . "\" onClick=\"callCheckDayBlocked('1');\">";
   endif;
   $outputMenu .= "&nbsp;|&nbsp;";
   // Selection of couriers to filter vehicles
   $outputMenu .= "<select class=\"f8np1\" name=\"f_filter_cr\" id=\"f_filter_cr\" onChange=\"finishPage('');\">";
   $outputMenu .= "  <option value=\"\" " . ($f_filter_cr == "" ? "selected" : "") . ">" . getLngt("Alle Fahrzeuge") . "</option>";
   $outputMenu .=    addOptionsFromAssociativeArray($crList, $f_filter_cr, "", "", "");
   $outputMenu .= "</select>";
   $outputMenu .= "&nbsp;|&nbsp;";
endif;
$outputMenu .= getLngt("x");
$outputMenu .= "<select class=\"f8np1\" name=\"timeLineScalingFactor\" id=\"timeLineScalingFactor\" onChange=\"finishPage('');\">";
$outputMenu .=    addOptionsFromRange(1,9,$timeLineScalingFactor,"");
$outputMenu .= "</select>";
$outputMenu .= "</div>\n";



// *********************************************************************
// * INIT output parameter for ECO CONTAINER and for VEHICLE TIMELINES *
// *********************************************************************

// * ECO *
$posTop = 30;
$ecoWidth = 130;
$ecoDragBarWidth = 12;
$ecoWidthContainer = 150;
$ecoArrayMaxLen = 100;  // Max. displayed ecos in container
$outputEcoJS = "var ecoArray = new Array(" . $ecoArrayMaxLen . ");\n";
$outputEcoJS .= "var ecoTextDefaultArray = new Array();\n";
$outputCrvhEcoJS = "var crvhEco = new Array();\n";
$outputEco = "";

// * Vehicle timelines *
$vhtPosTop = 130;
$vhtPosLeft = 130;
$timeLineHeight = 15;
$vhtHeight = 110;

// * Timeline parameters *
$hourWidthDefault = 66;
$hourWidth = ($hourWidthDefault * $timeLineScalingFactor);
$timeUnitWidth = round(($hourWidth / $hourTimeUnits), 0);

// * Working time and offset horizontal offset for timeline output *
$hoursLowerRange = max(0, $csRelatedDayTimeRange[0]);
$hoursUpperRange = min($hours, $csRelatedDayTimeRange[2]);
$hourHorizontalOffset = -($csRelatedDayTimeRange[0] * $hourWidth);  // E.g. starttime 07:00 => "negative" offset = (7 * $hourWidth)

$outputVehicle = "";
$outputMasterJS = "var masterArray = new Array(" . $crvhListLen . ");\n";


// *****************
// * Container eco *
// *****************

// Select ecos NOT being associated to ANY vehicle for the selected day only
$whereClause = "";

$whereClauseCs = "";
if ($csId != "") : $whereClauseCs .= " csc.cs_id = '" . $csId . "' AND"; endif;
// Check for displaying ALL related customers if all jobs of all zones shall be displayed on ECO container
if ($f_eco_show_all == "1") :
   $dispositionEcoContainerDisplayAllCsRelated = getParameterValue("0", "DISPOSITION_ECO_CONTAINER_ALL_CS_RELATED", $hq_id);
   if ($dispositionEcoContainerDisplayAllCsRelated == "") : $dispositionEcoContainerDisplayAllCsRelated = getParameterValue("0", "DISPOSITION_ECO_CONTAINER_ALL_CS_RELATED", "0"); endif;
   if ($dispositionEcoContainerDisplayAllCsRelated == "1") :
      $whereClauseCs = " jb.hq_id = '" . $hq_id . "' AND";  // Overwrite filter for current related customer
   endif;
endif;
$whereClause .= $whereClauseCs;


if ($f_eco_show_all != "1" && $f_servicezone != "" && $f_servicezone != "ALL") :
   $srvzId = getFieldValueFromClause("servicezone","srvz_id","srvz_no = '" . $f_servicezone . "' AND cs_id = '" . $csId . "'");
   // $whereClause .= " AND jb.jb_mediationarea_id = '" . $srvzId . "'";
   $whereClause .= " jb.jb_mediationarea_id = '" . $srvzId . "' AND";
endif;

// **************************************
// Check restricted access clause
if ($parRestrictedAccessClauseJob != "") :
   // if ($whereClause != "") : $whereClause .= " AND "; endif;
   $whereClause .= $parRestrictedAccessClauseJob . " ";
endif;
// **************************************

// If "system customer mode" then exclude NOT hidden jobs <=> show hidden jobs (regarding job list) only
$whereClauseHidden = "";
if ($globalParUseRelatedCustomer != "1") :
   $whereClauseHidden = " gdc4.gdc_content = '1' AND ";
endif;

// Output eco container
$ecoArray = array();
if ($userTypeName == "hq") :

   // Check for offers being displayed on eco container
   $whereClauseOffers = " jb.jb_offer = '0' AND ";
   $dispositionEcoContainerOffersEnabled = getParameterValue("0", "DISPOSITION_ECO_CONTAINER_OFFERS", "0");
   if ($dispositionEcoContainerOffersEnabled == "1") : $whereClauseOffers = ""; endif;
   $whereClause .= $whereClauseOffers;

   // Exclude NOT hidden jobs
   $whereClause .= $whereClauseHidden;

   // Get jobs for eco container
   $ecoArray = getVehicleJobList("", $currentSelectedDay, $timeUnitWidth, "3", $whereClause);
   $ecoArrayLen = count($ecoArray);

   $outputEco .= "<div id=\"eco_container\" style=\"position: fixed; top:30px; left:0px; width:100%; height:70px; padding: 0px; margin: 0px; z-index:7; background-color:#449944;\"></div>\n";
   // Associate ecos to container array
   for ($i = 0; $i < $ecoArrayLen; $i++) :

        if ($search_type == "jb" && in_array($ecoArray[$i]["jb_id"], $idSearchArray)) :
           $ecoBgCol = "background-color: #BB5555;";
        else :
           if ($ecoArray[$i]["jb_offer"] == "1") :
              $ecoBgCol = "background-color: #A349A4;";
           elseif ($globalParUseRelatedCustomer != "1" && $ecoArray[$i]["jb_is_operative"] != "") :
              $ecoBgCol = "background-color: #A349A4;";
           elseif ($ecoArray[$i]["gdc1_content"] == "1") :
              $ecoBgCol = "background-color: #FF8000;";
              if ($ecoArray[$i]["jb_totalprice"] == 0 && $ecoArray[$i]["jb_cr_price"] == 0) :
                 $ecoBgCol = "background-color: #CC8000;";
              endif;
           else :
              $ecoBgCol = getDispositionStandardColours($ecoArray[$i]["jb_service"]);  // Standard colours
           endif;
        endif;
        // Check output of the eco ID
        $ecoIdOut = getJobIdOutput($ecoArray[$i]["jb_id"], $ecoArray[$i]["jb_id_parent"]);

        // Output on drag bar
        $ecoIdDragBarOut = "";
        $ecoIdOutPrefix = "";
        if ($parMaskDispositionItemShowDragbarEcoId == "1") :
           $ecoIdDragBarOut = getJobIdDragBarOutput($ecoIdOut, -2);
           if ($ecoArray[$i]["jb_is_installation"] == "1") :
              $ecoIdOutPrefix = getJobIdDragBarOutput("M", "", "|");
           else :
              $ecoIdOutPrefix = getJobIdDragBarOutput("L", "", "|");
           endif;
        endif;

        $posLeft = ($i * $ecoWidthContainer);
        $outputEco .= "  <div id=\"eco_1_" . $ecoArray[$i]["jb_id"] . "\" class=\"eco_1\" style=\"position: fixed; top:" . $posTop . "px; left:" . $posLeft . "px; z-index:8;\" timeslots=\"" . $ecoArray[$i]["jb_timeunits"] . "\" is_installation=\"" . $ecoArray[$i]["jb_is_installation"] . "\">" . $ecoIdDragBarOut . "</div>\n";
        $outputEco .= "  <div id=\"eco_2_" . $ecoArray[$i]["jb_id"] . "\" class=\"eco_2\" style=\"position: fixed; top:30px; width:" . $ecoWidth . "; left:" . ($posLeft + $ecoDragBarWidth) . "px; z-index:7; " . $ecoBgCol . "\" onClick=\"selAction('jb', '" . $ecoArray[$i]["jb_id"] . "', '" . getLngt("Auftrag") . " " . $ecoIdOut . "','" . $ecoArray[$i]["eco_body_full"] . "','" . $ecoArray[$i]["eco_url_list"] . "')\"><b>" . $ecoIdOutPrefix . $ecoIdOut . "</b><br>" . $ecoArray[$i]["eco_body"] . "</div>\n";
   
        $outputEcoJS .= "ecoArray[" . $i . "] = new Array(" . $ecoArray[$i]["jb_id"] . "," . $posLeft . "," . $posTop . ");\n";
        $outputEcoJS .= "ecoTextDefaultArray[" . $ecoArray[$i]["jb_id"] . "] = '" . $ecoIdOut . "<br>" . $ecoArray[$i]["eco_body_default"] . "';\n";
   endfor;
   // Fill up the container array with empty elements but with positions
   for ($i = $ecoArrayLen; $i < $ecoArrayMaxLen; $i++) :
       $posLeft = ($i * $ecoWidthContainer);
       $outputEcoJS .= "ecoArray[" . $i . "] = new Array(''," . $posLeft . "," . $posTop . ");\n";
   endfor;
endif;


// **********************************************
// * Vehicles with timeline and associated jobs *
// **********************************************

function displayEcos ($mode = "0", $jbStatus) {
  global $vhtEcoArray, $csId, $currentSelectedDay, $search_type, $idSearchArray, $timeUnitWidth, $ecoDragBarWidth;
  global $masterArray, $crvhId, $timeLineScalingFactor, $outputEco, $outputEcoJS, $outputCrvhEcoJS, $globalParUseRelatedCustomer;

  $vhtEcoArrayLen = count($vhtEcoArray);
  for ($i = 0; $i < $vhtEcoArrayLen; $i++) :

      $ecoId             = $vhtEcoArray[$i]["jb_id"];
      $ecoIdParent       = $vhtEcoArray[$i]["jb_id_parent"];
      $ecoTimeslots      = $vhtEcoArray[$i]["jb_timeunits"];
      // $ecoParentLevel    = $vhtEcoArray[$i]["jb_parent_level"];
      $ecoService        = $vhtEcoArray[$i]["jb_service"];
      $ecoTotalprice     = $vhtEcoArray[$i]["jb_totalprice"];
      $ecoCrPrice        = $vhtEcoArray[$i]["jb_cr_price"];
      $ecoOffer          = $vhtEcoArray[$i]["jb_offer"];
      $ecoIsInstallation = $vhtEcoArray[$i]["jb_is_installation"];
      $ecoOrdertime      = $vhtEcoArray[$i]["jb_ordertime"];
      $ecoOrderDate      = substr($vhtEcoArray[$i]["jb_ordertime"],0,10);
      $ecoIsService      = $vhtEcoArray[$i]["gdc1_content"];
      $ecoIsOperative    = $vhtEcoArray[$i]["jb_is_operative"];
      $ecoHidden         = $vhtEcoArray[$i]["jb_hide"];
      $ecoBodyDefault    = $vhtEcoArray[$i]["eco_body_default"];
      $ecoBody           = $vhtEcoArray[$i]["eco_body"];
      $ecoBodyFull       = $vhtEcoArray[$i]["eco_body_full"];
      $ecoUrlList = my_str_check_js("?maskNumOfWins=1&jb_status=" . $jbStatus . "&day_from=$selDay&month_from=$selMonth&year_from=$selYear&day_to=$selDay&month_to=$selMonth&year_to=$selYear");
      if ($ecoId != "") :  // HAS TO EXIST !!!!
         // Check eco is multiple day job
         $ecoIsMultipleDayJob = false;
         if (isMultipleDayJob($ecoId, $csId) == "1") :
            $ecoIsMultipleDayJob = true;
         endif;
         // Get start time unit of the eco to compute the position
         if ($ecoIsMultipleDayJob) :
            $startTimeOfEco = getMinOfField("vehicledisposition", "vhd_timeslot", "jb_id = '" . $ecoId . "' AND LEFT(vhd_timeslot,10) = '" . $currentSelectedDay . "'");
            // Overwrite timeslots of the job with timeslots of the current day
            $ecoTimeslots = getCountOfTable("vehicledisposition", "jb_id = '" . $ecoId . "' AND LEFT(vhd_timeslot,10) = '" . $currentSelectedDay . "'");
         else :
            $startTimeOfEco = getMinOfField("vehicledisposition", "vhd_timeslot", "jb_id = '" . $ecoId . "'");
         endif;
         if ($startTimeOfEco != "") :  // HAS TO EXIST !!!!
            // Get position (top, left) from the hour and the hour time unit
            $tmpEcoStartHour = intval(substr($startTimeOfEco, 11, 2));
            $tmpEcoStartTimeUnit = intval(substr($startTimeOfEco, 14, 2));
            $tmpEcoPosLeft = $masterArray[$crvhId][$tmpEcoStartHour][$tmpEcoStartTimeUnit][1];
            $tmpEcoPosTop = $masterArray[$crvhId][$tmpEcoStartHour][$tmpEcoStartTimeUnit][2];
            if ($mode == "0") :
               $tmpEcoWidth = ($ecoTimeslots - 1) * $timeUnitWidth;
            else :
               $tmpEcoWidth = $ecoTimeslots * $timeUnitWidth;
            endif;

            $ecoBgCol = "";
            if ($search_type == "jb" && in_array($ecoId, $idSearchArray)) :
               $ecoBgCol = "background-color: #BB5555;";
            else :
               if ($mode == "0") :
                  if ($ecoOffer == "1") :
                     $ecoBgCol = "background-color: #A349A4;";
                  elseif ($globalParUseRelatedCustomer != "1" && $ecoIsOperative != "") :
                     $ecoBgCol = "background-color: #A349A4;";
                  elseif ($ecoIsService == "1") :
                     $ecoBgCol = "background-color: #FF8000;";
                     if ($ecoTotalprice == 0 && $ecoCrPrice == 0) :
                        $ecoBgCol = "background-color: #CC8000;";
                     endif;
                  else :
                     $ecoBgCol = getDispositionStandardColours($ecoService);  // Standard colours
                  endif;
               elseif ($mode == "1") :
                  $ecoBgCol = " background-color: #BBBBBB; ";
               endif;
            endif;
            // Check output of the eco ID
            $ecoIdOut = getJobIdOutput($ecoId, $ecoIdParent);
            // $newStrLen = floor((($ecoTimeslots - 1) * $timeUnitWidth) / 7);
            $newStrLen = floor(((($ecoTimeslots - 1) * $timeUnitWidth) * $timeLineScalingFactor) / 7);

            // Output on drag bar AND prefix of eco ID
            $ecoIdDragBarOut = "";
            $ecoIdOutPrefix = "";
            if ($mode == "0" && $parMaskDispositionItemShowDragbarEcoId == "1") :
               $ecoIdDragBarOut = getJobIdDragBarOutput($ecoIdOut, -2);
               if ($ecoIsInstallation == "1") :
                  $ecoIdOutPrefix = getJobIdDragBarOutput("M", "", "|");
               else :
                  $ecoIdOutPrefix = getJobIdDragBarOutput("L", "", "|");
               endif;
               $newStrLen -= 2;
               if ($newStrLen < 0) : $newStrLen = 2; endif;
            elseif ($mode == "1" || $mode == "2") :
               if ($ecoIsInstallation == "1") :
                  $ecoIdOutPrefix = getLngt("M|");
               else :
                  $ecoIdOutPrefix = getLngt("L|");
               endif;
            endif;
            // $ecoIdOutItem = substr($ecoIdOut,0,$newStrLen);
            $ecoIdOutItem = substr($ecoIdOutPrefix . $ecoIdOut,0,$newStrLen);

            // Handle "MULTIPLE DAY ECO"
            $showDragItem = true;
            $tmpEcoPosLeftOffset = $ecoDragBarWidth;
            if ($ecoIsMultipleDayJob) :
               $tmpEcoWidth = ($ecoTimeslots - 1) * $timeUnitWidth;
            
               // Set parameter for output
               if ($ecoOrderDate != $currentSelectedDay || $mode != "0") :
                  // Get earliest start time of the related customer
                  $showDragItem = false;
                  $tmpEcoWidth += $timeUnitWidth;
                  if ($ecoOrderDate != $currentSelectedDay) :
                     $tmpEcoPosLeftOffset = 0;
                  endif;
               endif;
            
               // Reformat output
               $ecoBodyArray = spliti("<br>",$ecoBody);
               $ecoBodyArrayLen = count($ecoBodyArray);
               for ($c = 0; $c < $ecoBodyArrayLen; $c++) :
                    $ecoBodyArray[$c] = substr($ecoBodyArray[$c],0,$newStrLen);
               endfor;
               $ecoBody = implode("<br>",$ecoBodyArray);
            endif;


            // Add difference of the part of ONE timeunit because width of the drag bar could be smaller than a single time unit
            if ($mode == "0") :
               $tmpEcoWidth += ($timeUnitWidth - $ecoDragBarWidth);
            endif;

            if ($mode == "0") :
               if ($showDragItem) :
                  $outputEco .= "  <div id=\"eco_1_" . $ecoId . "\" class=\"eco_1\" style=\"position: absolute; top:" . $tmpEcoPosTop . "px; left:" . $tmpEcoPosLeft . "px; z-index:5;\" timeslots=\"" . $ecoTimeslots . "\" is_installation=\"" . $ecoIsInstallation . "\" >" . $ecoIdDragBarOut . "</div>\n";
               endif;
               $outputEco .= "  <div id=\"eco_2_" . $ecoId . "\" class=\"eco_2\" style=\"position: absolute; top:" . $tmpEcoPosTop . "px; left:" . ($tmpEcoPosLeft + $tmpEcoPosLeftOffset) . "px; z-index:4; width:" . $tmpEcoWidth . "px; " . $ecoBgCol . "\" onClick=\"selAction('jb', '" . $ecoId . "', '" . getLngt("Auftrag") . " " . $ecoIdOut . "','" . $ecoBodyFull . "','" . $ecoUrlList . "')\"><b>" . $ecoIdOutItem . "</b><br>" . $ecoBody .  "</div>\n";
            elseif ($mode == "1") :
               $outputEco .= "  <div id=\"eco_x_" . $ecoId . "\" class=\"eco_x\" style=\"position: absolute; top:" . $tmpEcoPosTop . "px; left:" . $tmpEcoPosLeft . "px; width:" . $tmpEcoWidth . "px;" . $ecoBgCol . "\" onClick=\"selAction('jb', '" . $ecoId . "', '" . getLngt("Auftrag") . " " . $ecoIdOut . "','" . $ecoBodyFull . "','" . $ecoUrlList . "')\"><b>" . $ecoIdOutItem . "</b><br>" . $ecoBody .  "</div>\n";   
            elseif ($mode == "2") :
               $outputEco .= "  <div id=\"eco_y_" . $ecoId . "\" class=\"eco_y\" style=\"position: absolute; top:" . $tmpEcoPosTop . "px; left:" . $tmpEcoPosLeft . "px; width:" . $tmpEcoWidth . "px;" . $ecoBgCol . "\" onClick=\"selAction('jb', '" . $ecoId . "', '" . getLngt("Auftrag") . " " . $ecoIdOut . "','" . $ecoBodyFull . "','" . $ecoUrlList . "')\"><b>" . $ecoIdOutItem . "</b><br>" . $ecoBody .  "</div>\n";
            endif;

            // Set JS array
            $outputEcoJS .= "ecoTextDefaultArray[" . $ecoId . "] = '" . $ecoIdOut . "<br>" . $ecoBodyDefault . "';\n";
            $outputCrvhEcoJS .= "crvhEco[" . $crvhId . "][" . $i . "] = '" . $ecoId . "';\n";
         endif;
      endif;
  endfor;
}


// Get blocked vehicles of the selected day
$crvhBlockedArray = getColVectorFromDB2ArrayByClause("vehicleavailability", "vha_blocked", "vha_day = '" . $currentSelectedDay . "' AND vha_blocked > '0'", "crvh_id", "", "");

for ($v = 0; $v < $crvhListLen; $v++) :

    $crvhId      = $crvhList[$v][0];
    $crvhSid     = $crvhList[$v][4];
    $crvhServices = "";
    if ($crvhList[$v][10] != "" && $crvhList[$v][10] != "0") :
       $crvhServices = implode(",", getColVectorFromDB2ArrayByClause("metatype", "mt_mapped_value", "mt_type = 'service' AND mt_objtype = '' AND mt_objid = '0' AND mt_sort IN (" . implode(",", mcConvertNum2Sel($crvhList[$v][10])) . ") AND mt_sort != '1'", "", "mt_sort", ""));
    endif;

    $outputMasterJS .= "masterArray[" . $crvhId . "] = new Array(" . $hoursUpperRange . ");\n";
    $outputCrvhEcoJS .= "crvhEco[" . $crvhId . "] = new Array();\n";
    
    // Check availibility of the current vehicle regarding the daytime
    $vehicleAvailableArray = array();  // Init NO availibility of the selected day
    if ($userTypeName == "cr") :
       // Iterate ALL given daytimes
       for ($i = 0; $i < $dayTimesLen; $i++) :
           // All vehicles of the carrier are available in all zones AND all daytimes !!!!
           $vehicleAvailableArray[] = array(substr($dayTimeMappedValues[$i],0,2), substr($dayTimeMappedValues[$i],3,2), substr($dayTimeMappedValues[$i],8,2), substr($dayTimeMappedValues[$i],11,2));
       endfor;
    else :
       // $userTypeName == "hq" !!!!
       if ($f_servicezone != "" && $f_servicezone != "ALL") :
          $tmpDaytimeZoneArray = getDaytimeAvailabilityOfVehicle($crvhId, $currentDayNumOfTheWeek, $csId, "1");  // $tmpDaytimeZoneArray[daytime] = zone
          // Iterate given daytimes (got from customer !!!!)
          for ($i = 0; $i < $dayTimesLen; $i++) :
              if ($tmpDaytimeZoneArray[$i] == "" || $tmpDaytimeZoneArray[$i] == $f_servicezone) :
                 // Vehicle is available in all zones OR in the selected zone for this daytime on the selected day. Extend availibility interval array for this daytime
                 $vehicleAvailableArray[] = array(substr($dayTimeMappedValues[$i],0,2), substr($dayTimeMappedValues[$i],3,2), substr($dayTimeMappedValues[$i],8,2), substr($dayTimeMappedValues[$i],11,2));
              endif;
          endfor;
       endif;
    endif;
    $vehicleAvailableArrayLen = count($vehicleAvailableArray);

    // Timeline
    for ($i = $hoursLowerRange; $i <= $hoursUpperRange; $i++) :
        $outputVehicle .= "<div id=\"hour_" . pad($i, 2) . "\" style=\"position:absolute; top:" . (($v * $vhtHeight) + $vhtPosTop) . "px; left:" . (($i * $hourWidth) + $vhtPosLeft + $hourHorizontalOffset) . "px; width:" . (($i * $hourWidth) + $vhtPosLeft) . "px; height:" . $timeLineHeight . "px; z-index:1;\">" . ($parMaskDispositionHideHoursOnTimeline != "1" ? pad($i, 2) : "  ") . "</div>\n";
    endfor;

    $posTop = (($v * $vhtHeight) + $vhtPosTop + $timeLineHeight);

    // Check for vehicle being blocked for the selected day
    $crvhBgCol = "#AADDAA;";
    if ($userTypeName == "hq") :
       $blockedState = $crvhBlockedArray[$crvhId];  // Represents vha.vha_blocked
       if ($blockedState == "") : 
          $blockedState = 0; 
       endif;
       if (($blockedState & 1) == 1) :  // Blocked by headquarters disposition
          $crvhBgCol = "#FF6A6A;";
       endif;
       if (($blockedState & 2) == 2) :  // Blocked for courier disposition, overrules the state above
          $crvhBgCol = "#BBBBBB;";
       endif;
    endif;
    // Vehicle information(s)
    $outputVehicle .= "<div id=\"" . $crvhId . "\" style=\"position:absolute; top:" . $posTop . "px; left:0px; width:" . $vhtPosLeft . "px; height:70px; z-index:1; background-color:" . $crvhBgCol . ";\" onClick=\"selAction('crvh', '" . $crvhId . "', '" . getLngt("Fahrzeug") . " " . $crvhSid . "','','')\">" . "<br>&nbsp;<b>" . $crvhSid . "</b>" . "<br>&nbsp;" . "<span class=\"f7np1\">[" . $crvhServices . "]</span></div>\n";

    // Display time units
    $count = 0;
    for ($i = $hoursLowerRange; $i <= $hoursUpperRange; $i++) :
        $changeCol = true;
        $outputMasterJS .= "masterArray[" . $crvhId . "][" . $i . "] = new Array(" . $hourTimeUnits . ");\n";

        for ($j = 0; $j < $hourTimeUnits; $j++) :
           $tmpCol = "#BBBBBB";
           if ($changeCol) : 
              $tmpCol = "#000000";
              $changeCol = false;
           endif;

           $posLeft = (($count * $timeUnitWidth) + $vhtPosLeft);

           // Check for current timeslot being activated for dropping or not. Therefore iterate all available intervals
           $tmpTimeUnitsToMinutes = $j * (60 / $hourTimeUnits);
           $tmpCrvhTimeSlot = pad($i, 2) . pad($tmpTimeUnitsToMinutes, 2);
           $timeSlotClass = "time_slot_deactivated";
           $timeSlotBgCol = "#DDDDDD";

           // Activate droppable timeslots for future days or for today with timeslot > current time
           if ($parMaskDispositionEnableDroppingOnPastTimeslots == "1" ||
               ($userTypeName == "hq" && ($currentSelectedDay > $currentDay || ($currentSelectedDay == $currentDay && $currentTime <= pad($i, 2) . ":" . $tmpTimeUnitsToMinutes . ":00"))) ||
               ($userTypeName == "cr" && $currentSelectedDay >= $currentDay) ) :
              for ($k = 0; $k < $vehicleAvailableArrayLen; $k++) :
                  $tmpTimeFrom = $vehicleAvailableArray[$k][0] . $vehicleAvailableArray[$k][1];
                  $tmpTimeTo = $vehicleAvailableArray[$k][2] . $vehicleAvailableArray[$k][3];
                  if ($tmpTimeFrom <= $tmpCrvhTimeSlot && $tmpCrvhTimeSlot < $tmpTimeTo) :
                     $timeSlotClass = "time_slot";
                     $timeSlotBgCol = "#AADDAA";
                     break;
                  endif;
              endfor;
           endif;

           // Init master array
           $masterArray[$crvhId][$i][$j] = array("0", $posLeft, $posTop);
           $outputMasterJS .= "masterArray[" . $crvhId . "][" . $i . "][" . $j . "] = new Array(0," . $posLeft . "," . $posTop . ");\n";

           // Output droppable timeline elements
           $outputVehicle .= "<div id=\"" . $crvhId . "_" . $i . "_" . $j . "\" class=\"" . $timeSlotClass . "\" style=\"position:absolute; top:" . $posTop . "px; left:" . $posLeft . "px; width:" . ($timeUnitWidth - 0) . "px; height:70px; z-index:2;\">";
           $outputVehicle .= "  <div style=\"float:left; width:1px; height:100%; background-color:" . $tmpCol . ";\"></div>\n";
           $outputVehicle .= "  <div style=\"width:" . ($timeUnitWidth - 1) . "px; height:100%; background-color:" . $timeSlotBgCol . ";\"></div>\n";
           $outputVehicle .= "</div>\n";

           $count++;
        endfor;
    endfor;


    // Get all ecos associated to the current vehicle for the specified day
    $vhtEcoArray = array();
    if ($userTypeName == "hq") :
       $vhtEcoArray = getVehicleJobList($crvhId, $currentSelectedDay, $timeUnitWidth, "0", " jb.jb_status = '9' AND " . $whereClauseHidden);  // Headquarter view with jobs can be disposed
    endif;
    if ($userTypeName == "cr") :
       $vhtEcoArray = getVehicleJobList($crvhId, $currentSelectedDay, $timeUnitWidth, "0", $parRestrictedAccessClauseJob . " jb.jb_timeunits > '0' AND " . $whereClauseHidden);
    endif;
    displayEcos("0", "9");


    // All jobs disposed by the courier by the current vehicle for the specified day
    if ($userTypeName == "hq") :
       $vhtEcoArray = getVehicleJobList($crvhId, $currentSelectedDay, $timeUnitWidth, "0", $parRestrictedAccessClauseJob . " jb.jb_status = '0' AND " . $whereClauseHidden);
       displayEcos("1", "1");
    endif;

    // All jobs taken by the current vehicle for the specified day
    $vhtEcoArray = getVehicleJobList($crvhId, $currentSelectedDay, $timeUnitWidth, "1", $parRestrictedAccessClauseJob . $whereClauseHidden);
    // Add taken multiple day jobs to be displayed
    if (true) :
       $tmpEcoArray = $vhtEcoArray;
       $tmpEcoArrayLen = count($tmpEcoArray);
       $vhtMultiDayEcoArray = getVehicleJobList($crvhId, $currentSelectedDay, $timeUnitWidth, "0", " jb.jb_status = '1' AND " . $whereClauseHidden);
       $vhtMultiDayEcoArrayLen = count($vhtMultiDayEcoArray);
       for ($i = 0; $i < $vhtMultiDayEcoArrayLen; $i++) :
           for ($j = 0; $j < $tmpEcoArrayLen; $j++) :
               $tmpEcoIdFound = false;
               if ($vhtMultiDayEcoArray[$i]["jb_id"] == $tmpEcoArray[$j]["jb_id"]) :
                  $tmpEcoIdFound = true;
                  break 1;
               endif;
           endfor;
           if (!$tmpEcoIdFound) :
              $nextElemPos = count($vhtEcoArray);
              $vhtEcoArray[$nextElemPos] = $vhtMultiDayEcoArray[$i];
              // Get time units of the added job
              $vhtEcoArray[$nextElemPos]["jb_timeunits"] = getCountOfTable("vehicledisposition", "jb_id = '" . $vhtMultiDayEcoArray[$i]["jb_id"] . "' AND LEFT(vhd_timeslot,10) = '" . $currentSelectedDay . "'");
       
              // Get ordertime of added taken multi day job from vehicledisposition !!!!       
              $startTimeOfEco = getMinOfField("vehicledisposition", "vhd_timeslot", "jb_id = '" . $vhtMultiDayEcoArray[$i]["jb_id"] . "' AND LEFT(vhd_timeslot,10) = '" . $currentSelectedDay . "'");
              if ($startTimeOfEco != "") :
                 $vhtEcoArray[$nextElemPos]["jb_ordertime"] = substr($startTimeOfEco,0,10) . " " . substr($startTimeOfEco,11,2) . ":" . pad(strval(floor(intval(substr($startTimeOfEco,14,2)) * (60 / $hourTimeUnits))),2) . ":00";
              endif;
       
              // Reformat output
              $ecoBodyArray = spliti("<br>",$vhtEcoArray[$nextElemPos]["eco_body"]);
              $ecoBodyArrayLen = count($ecoBodyArray);
              for ($c = 0; $c < $ecoBodyArrayLen; $c++) :
                   $ecoBodyArray[$c] = substr($ecoBodyArray[$c],0,$vhtEcoArray[$nextElemPos]["jb_timeunits"]);
              endfor;
              $vhtEcoArray[$nextElemPos]["eco_body"] = implode("<br>",$ecoBodyArray);
              $vhtEcoArray[$nextElemPos]["added_taken_job_from_day_before"] = "1";
           endif;
       endfor;
    endif;
    displayEcos("2", "1");

    // All done jobs by the current vehicle for the specified day
    $vhtEcoArray = getVehicleJobList($crvhId, $currentSelectedDay, $timeUnitWidth, "2", $parRestrictedAccessClauseJob . $whereClauseHidden);
    $vhtEcoArrayLen = count($vhtEcoArray);
    for ($i = 0; $i < $vhtEcoArrayLen; $i++) :
    
        $ecoId             = $vhtEcoArray[$i]["jb_id"];
        $ecoIdParent       = $vhtEcoArray[$i]["jb_id_parent"];
        $ecoService        = $vhtEcoArray[$i]["jb_service"];
        $ecoIsInstallation = $vhtEcoArray[$i]["jb_is_installation"];
        $ecoOrdertime      = $vhtEcoArray[$i]["jb_ordertime"];
        $ecoTimeslots      = $vhtEcoArray[$i]["jb_timeunits"];
        $ecoBodyDefault    = $vhtEcoArray[$i]["eco_body_default"];
        $ecoBody           = $vhtEcoArray[$i]["eco_body"];
        $ecoBodyFull       = $vhtEcoArray[$i]["eco_body_full"];
        $ecoUrlList = my_str_check_js("?maskNumOfWins=1&jb_status=2&day_from=$selDay&month_from=$selMonth&year_from=$selYear&day_to=$selDay&month_to=$selMonth&year_to=$selYear");
        if ($ecoId != "") :  // HAS TO EXIST !!!!
           // Get position (top, left) from the hour and the hour time unit
           $tmpEcoStartHour = intval(substr($ecoOrdertime, 11, 2));
           $tmpEcoStartMinute = intval(substr($ecoOrdertime, 14, 2));
           // $tmpEcoStartTimeUnit = pad($tmpEcoStartHour,2) . "_" . pad(strval(ceil(intval($tmpEcoStartMinute) * ($hourTimeUnits / 60))), 2);
           $tmpEcoStartTimeUnit = strval(ceil(intval($tmpEcoStartMinute) * ($hourTimeUnits / 60)));
           $tmpEcoPosLeft = $masterArray[$crvhId][$tmpEcoStartHour][$tmpEcoStartTimeUnit][1];
           $tmpEcoPosTop = $masterArray[$crvhId][$tmpEcoStartHour][$tmpEcoStartTimeUnit][2];
           $tmpEcoWidth = $ecoTimeslots * $timeUnitWidth;
           $ecoBgCol = "";
           if ($search_type == "jb" && in_array($ecoId, $idSearchArray)) :
              $ecoBgCol = " background-color: #BB5555; ";
           endif;
           // Check output of the eco ID
           $ecoIdOut = getJobIdOutput($ecoId, $ecoIdParent);

           if ($ecoIsInstallation == "1") :
              $ecoIdOutPrefix = getLngt("M|");
           else :
              $ecoIdOutPrefix = getLngt("L|");
           endif;

           // Resize output
           $newStrLen = floor(((($ecoTimeslots - 1) * $timeUnitWidth) * $timeLineScalingFactor) / 7);
           $ecoIdOutItem = substr($ecoIdOutPrefix . $ecoIdOut,0,$newStrLen);

           $outputEco .= "  <div id=\"eco_z_" . $ecoId . "\" class=\"eco_z\" style=\"position: absolute; top:" . $tmpEcoPosTop . "px; left:" . $tmpEcoPosLeft . "px; width:" . $tmpEcoWidth . "px;" . $ecoBgCol . "\" onClick=\"selAction('jb', '" . $ecoId . "', '" . getLngt("Auftrag") . " " . $ecoIdOut . "','" . $ecoBodyFull . "','" . $ecoUrlList . "')\"><b>" . $ecoIdOutItem . "</b><br>" . $ecoBody .  "</div>\n";

           // Set JS array
           $outputEcoJS .= "ecoTextDefaultArray[" . $ecoId . "] = '" . $ecoIdOut . "<br>" . $ecoBodyDefault . "';\n";
        endif;
    endfor;
endfor;


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

// Selection of hour and minute
$outputDayTimes = "<select class=\"f8np1\" name=\"f_day_time_hour_from_new\">" . addOptionsFromRange("0", "23", "", "1", "2", "0") . "</select>&nbsp;\n";
$outputDayTimes .= "<select class=\"f8np1\" name=\"f_day_time_minute_from_new\">" . addOptionsFromRange("0", "59", "", "1", "2", "0") . "</select>\n";
$outputDayTimes = my_str_check_js($outputDayTimes);

// For output only! 
$jsExecBodyOnLoadArray = array("0","0","0","0","0");   // If one component is set to "1" then execute a special JS function according to "body onLoad"

// Resets the parameters selected and set by each context menu
function resetActionParameters () {
	global $f_actionObjType, $f_actionObjId, $f_actionID;
	$f_actionObjType = "";
	$f_actionObjId = "";
	$f_actionID = "";
}

// ***************************************************
// * Process specified action for a specified object *
// ***************************************************
// if ($f_act == "processAction") :
   if ($f_actionObjType != "" && $f_actionObjId != "" && $f_actionID != "") :
      
      if ($f_actionObjType = "crvh") :
         if ($f_actionID == "101") :
            // Get position on map
            // ...
         elseif ($f_actionID == "102") :
            // Get delivery run sheet
            // getLogData("log.logo_id = '1000' AND log.id_01 = '" . $f_actionObjId . "'");
            // getSuHistoryData("0", "AND stk.stk_pre_id = '" . $rootStockSU . "' AND atih.atih_serialno = '" . $f_actionObjId . "'");
            if ($f_act == "processAction") :
               $maskDisplay01Switch = "0";
               $maskDisplay02Switch = "0";
               $maskDisplay03Switch = "0";
               $maskDisplay04Switch = "1";
               $maskDisplay05Switch = "0";
               $maskDisplay06Switch = "0";
               $maskDisplay07Switch = "0";
            endif;
         elseif ($f_actionID == "103") :
            // Get service jobs
            $f_jb_filter_2 = $f_actionObjId;  // Set filter for service jobs regarding the serialnumber of the service unit
            // getServiceJoblist();           // Will be called later including this filter !!!
            if ($f_act == "processAction") :
               $maskDisplay01Switch = "0";
               $maskDisplay02Switch = "0";
               $maskDisplay03Switch = "1";
               $maskDisplay04Switch = "0";
               $maskDisplay05Switch = "0";
               $maskDisplay06Switch = "0";
               $maskDisplay07Switch = "0";
            endif;
            resetActionParameters();
         elseif ($f_actionID == "104") :
            // getSuMessageData($f_actionObjId);
            if ($f_act == "processAction") :
               $maskDisplay01Switch = "0";
               $maskDisplay02Switch = "0";
               $maskDisplay03Switch = "0";
               $maskDisplay04Switch = "0";
               $maskDisplay05Switch = "1";
               $maskDisplay06Switch = "0";
               $maskDisplay07Switch = "0";
            endif;
         elseif ($f_actionID == "105") :
            // Set form fields for the administration
            // $f_su_admin_filter_1 = $f_actionObjId;  // Set filter for administration of the service unit
            $jsExecBodyOnLoadArray[2] = "1";        // Set service unit form data according to $f_actionObjId
            if ($f_act == "processAction") :
               $jsExecBodyOnLoadArray[0] = "1";   // Set form by "body onLoad"
               $maskDisplay01Switch = "0";
               $maskDisplay02Switch = "0";
               $maskDisplay03Switch = "0";
               $maskDisplay04Switch = "0";
               $maskDisplay05Switch = "0";
               $maskDisplay06Switch = "1";
               $maskDisplay07Switch = "0";
            endif;
            resetActionParameters();
         endif;
      endif;
   endif;

// Check 
$parMaskDispositionCheckDeliveryBeforeService = getParameterValue("0", "MASK_DISPOSITION_CHECK_DELIVERY_BEFORE_SERVICE_DISABLED", $f_hq_id);
if ($parMaskDispositionCheckDeliveryBeforeService == "") :
   $parMaskDispositionCheckDeliveryBeforeService = getParameterValue("0", "MASK_DISPOSITION_CHECK_DELIVERY_BEFORE_SERVICE_DISABLED", "0");
endif;

// Calendar
$parMaskDispositionCalenderSubmitDisabled = getParameterValue("0", "MASK_DISPOSITION_CALENDER_SUBMIT_DISABLED", $f_hq_id);
if ($parMaskDispositionCalenderSubmitDisabled == "") :
   $parMaskDispositionCalenderSubmitDisabled = getParameterValue("0", "MASK_DISPOSITION_CALENDER_SUBMIT_DISABLED", "0");
endif;
?>


<?php if (!$isFirefox) : ?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
       "../include/strict.dtd">
<?php endif; ?>

<html>

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

<link rel="stylesheet" type="text/css" href="../css/reset.css">
<link rel="stylesheet" type="text/css" href="../css/phoenix.css">
<style type="text/css">
  <?php include_once ("../css/navigation.css.php"); ?>
  .eco_1 {width: <?php echo $ecoDragBarWidth ?>px; height: 70px; background-color: #888888;}
  .eco_2 {height: 70px; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 7pt; font-weight: normal;}
  .eco_x {width: 130px; height: 70px; background-color: #BBBBBB; z-index:4; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 7pt; font-weight: normal; border-left:2px solid black;}
  .eco_y {width: 130px; height: 70px; background-color: #88BBBB; z-index:4; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 7pt; font-weight: normal; border-left:2px solid black;}
  .eco_z {width: 130px; height: 70px; background-color: #FFFF22; z-index:4; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 7pt; font-weight: normal; border-left:2px solid black;}
</style>

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

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

// ...

<?php echo $jsOut ?>


// Definition of the JS eco array as pendant to the PHP eco array
<?php echo $outputEcoJS ?>

// Array for vehicle-eco-relation
<?php echo $outputCrvhEcoJS ?>

// Definition of the JS master array as pendant to the PHP master array
<?php echo $outputMasterJS ?>


// Global JS parameters
var hourWidth = <?php echo $hourWidth ?>;
var hours = <?php echo $hoursUpperRange ?>;
var hourTimeUnits = <?php echo $hourTimeUnits ?>;
var timeUnitWidth = <?php echo $timeUnitWidth ?>;
var hourHorizontalOffset = <?php echo $hourHorizontalOffset ?>;
var ecoDragBarWidth = <?php echo $ecoDragBarWidth ?>;
var timeLineScalingFactor = <?php echo $timeLineScalingFactor ?>;

var globalStartPosLeftOfElemDragged = 0;
var globalStartPosTopOfElemDragged = 0;
var globalElemDraggedZIndex = 10;

FILLDATEFIELDSSTARTYEAR=<?php echo ($currYear - 1) ?>;

// Selection of a specific day
function initForm() {
  fillDateFields(1,"<?php echo $currentFrameName ?>","vehicledisposition","","selDay","selMonth","selYear","","","");
  setDateTimeFields("<?php echo $currentFrameName ?>","vehicledisposition",<?php echo $selDay ?>,<?php echo $selMonth ?>,<?php echo $selYear ?>, "", "", "selDay", "selMonth", "selYear", "", "", "");
};

// Reset the length of text of the element regarding the timeslots
function resizeEcoContent(ecoId, elemWidth) {
	var htmlStr = '';
	if (ecoId != '' && elemWidth != '') {
	   htmlStr = ecoTextDefaultArray[ecoId];  // Initial javascript data
     // Get refreshed eco data for displaying the content
     /*
     ajaxRequestGet('../include/ajaxReqDisposition.php', 'mode=getJobContentData&jbId=' + ecoId);
     if (retData != '') {
     	  htmlStr = retData;
     } else {
     	  htmlStr = ecoTextDefaultArray[ecoId];  // Fallback with initial javascript data
     }
     htmlStr = htmlStr.replace(/&euro;/g, "€");
     htmlStr = htmlStr.replace(/&auml;/g, "ä");
     htmlStr = htmlStr.replace(/&ouml;/g, "ö");
     htmlStr = htmlStr.replace(/&uuml;/g, "ü");
     htmlStr = htmlStr.replace(/&Auml;/g, "Ä");
     htmlStr = htmlStr.replace(/&Ouml;/g, "Ö");
     htmlStr = htmlStr.replace(/&Uuml;/g, "Ü");
     htmlStr = htmlStr.replace(/&szlig;/g, "ß");
     htmlStr = htmlStr.replace(/&aring;/g, "å");
     htmlStr = htmlStr.replace(/&Aring;/g, "Å");
     htmlStr = htmlStr.replace(/&Eacute;/g, "É");
     */
     var lineArray = htmlStr.split("<br>");
     var lineArrayLen = lineArray.length;
     htmlStr = '';

     // var newStrLen = Math.floor(elemWidth / 7);
     var absScaleOffset = 0;
     if (timeLineScalingFactor == 2) { absScaleOffset = 1; };
     if (timeLineScalingFactor == 3) { absScaleOffset = 4; };
     if (timeLineScalingFactor == 4) { absScaleOffset = 6; };
     if (timeLineScalingFactor == 5) { absScaleOffset = 5; };
     var newStrLen = Math.floor(elemWidth / 7) + absScaleOffset;

     // htmlStr += '<b>' + lineArray[0] + '</b>' + '<br>';
     htmlStr += '<b>' + lineArray[0].substr(0,newStrLen) + '</b>' + '<br>';
     for(i=1; i<lineArrayLen ;++i) {
        htmlStr += lineArray[i].substr(0,newStrLen) + '<br>';
     }
     htmlStr = htmlStr.replace(/ /g, "&nbsp;");
  }
  return htmlStr;
}

$(function() {
	// Drag & Drop
  $("div.eco_1").draggable({  	  
  	  cursor: 'move', containment: 'document', opacity: 0.5, snap: false, scope: 'first', start: handleDragStart, stop: handleDragStop, revert: 'invalid'
  });
  // Drop on time slots
  $("div.time_slot").droppable({
  	  accept: "div.eco_1", scope: "first", drop: handleDropVhtEco
  	  // , out: handleOutVhtEco
  });
  // Drop (back) on eco container
  $("#eco_container").droppable({
  	  accept: "div.eco_1", scope: "first", drop: handleDropEcoContainer
  });
});


function handleDragStart(event, ui) {
  globalStartPosLeftOfElemDragged = parseInt(ui.offset.left);
  globalStartPosTopOfElemDragged = parseInt(ui.offset.top);

  globalElemDraggedZIndex = $(this).css('z-index');
  $(this).css('z-index', '10');
  
  // Check blinking state
  var draggableId = $(this).attr('id');
  draggableId = draggableId.substr(6);
  var ecoLetsBlink = '';
  ajaxRequestGet('../include/ajaxReqDisposition.php', 'mode=jobGetParent&jbId=' + draggableId);
  if (retParentId == '' || retParentId == '0') {
     ajaxRequestGet('../include/ajaxReqDisposition.php', 'mode=jobGetChild&jbId=' + draggableId);
     if (retChildId != '' && retChildId != '0') {
     	  ecoLetsBlink = retChildId;
     }
  } else {
  	 ecoLetsBlink = retParentId;
  }
  if (ecoLetsBlink != '') {
  	 startBlink(ecoLetsBlink);
  }
}

function handleDragStop(event, ui) {
  var offsetXPos = parseInt(ui.offset.left);
  var offsetYPos = parseInt(ui.offset.top);

  $(this).css('z-index', globalElemDraggedZIndex);
  globalElemDraggedZIndex = 10;

  // elem = $(event.target);
  // elem.offset({ top: offsetYPosNew, left: offsetXPosNew });  // Set new position of the element (Works!)
  // alert(elem.attr('id'));  // Get attribute of the element (Works!)
}

// Handles the drop to the time line
function handleDropVhtEco(event, ui) {
  var draggable = ui.draggable;
  var draggableId = draggable.attr('id');
  // alert(draggable.children().attr('id'));  // Works!
  // alert(draggable.children().last().attr('id'));  // Works!
  
  elem = $(event.target);
  var elemId = elem.attr('id');
  // ID of the container is like "crvhId_hour_hourUnit" => split by "_" to get the current data
  if (elemId != '') {
     var elemIdDataArray = elemId.split("_");
     // var elemIdDataArrayLen = elemIdDataArray.length;
     crvhId = elemIdDataArray[0];
     hour = elemIdDataArray[1];
     hourUnit = elemIdDataArray[2];
  };

  // Get eco ID of the draggable eco object
  var ecoId = draggableId.substring(6);
  var elemIdToBeMoved = '#eco_2_' + ecoId;
  var ecoArrayLen = ecoArray.length;
  var ecoResetToSource = false;

  // Make association between eco and vehicle persistent in db
  if (crvhId != '' && ecoId != '') {
  	 var draggableTimeslots = draggable.attr('timeslots');
  	 var draggableIsInstallation = draggable.attr('is_installation');

  	 // Check vehicle is an installation one if eco is
  	 if (draggableIsInstallation == '1') {
  	    ajaxRequestGet('../include/ajaxReqLib.php', 'mode=0&db_table=couriervehicle&db_id_field=crvh_id&search_value=' + crvhId + '&db_return_field=crvh_service');
  	    if (retValue != '' && (retValue & 2) != 2) {
 	    	 	 alert('<?php echo getLngt(wrapPhrase("Achtung: Montage erforderlich, Fahrzeug ist kein Montagefahrzeug!")) ?>');
  	    }
  	 }

     // 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 ?>');
     	  if (jobMultipleDayTimeunitsOfSelectedDay != '' && jobMultipleDayTimeunitsOfSelectedDay != '0') {
     	  	 ecoMultDayTimeunitsOfSelectedDay = parseInt(jobMultipleDayTimeunitsOfSelectedDay);
     	  }
     }

     // Check time problem of the job being not able to be moved regarding to existence of parent or children jobs
     var moveJob = true;
     ajaxRequestGet('../include/ajaxReqDisposition.php', 'mode=checkMovedJobDependingOnAnotherJob&jbId=' + ecoId + '&currDay=<?php echo $currentSelectedDay ?>&hour=' + hour + '&hourUnit=' + hourUnit);
     if (timeProblem != '' && timeProblem < '0') {
     	  if ('<?php echo $parMaskDispositionCheckDeliveryBeforeService ?>' != '1') {
     	     timeProblem = (-(timeProblem)).toString();
           alert('<?php echo getLngt("Die Lieferung muss vor der Montage erfolgen!") ?>' + ' [<?php echo getLngt("Referenzauftrag") ?>: ' + timeProblem + ']');
     	     ecoResetToSource = true;
     	     moveJob = false;
        } else {
     	     timeProblem = (-(timeProblem)).toString();
           alert('<?php echo getLngt("Achtung! Es existiert eine zeitlich vorgelagerte Montage!") ?>' + ' [<?php echo getLngt("Referenzauftrag") ?>: ' + timeProblem + ']');
        }
     }
     if (moveJob) {
     	  // Get current vehicle the eco has been dragged from to check eco has been moved to another vehicle
        if (timeProblem != '' && timeProblem > '0') {
           var crvhIdFrom = '';
           ajaxRequestGet('../include/ajaxReqLib.php', 'mode=2&db_table=vehicledisposition&db_id_field=jb_id&search_value=' + timeProblem + '&db_return_field=crvh_id');
           if (retValue != '') {
              crvhIdFrom = retValue;
              if (crvhIdFrom != crvhId) {
              	  alert('<?php echo getLngt("Es existiert noch ein verknüpfter Auftrag auf dem anderen Fahrzeug!") ?>');
              }
           }
        }
     	  <?php if ($userTypeName == "hq") : ?>
          // Check vehicle is blocked
          ajaxRequestGet('../include/ajaxReqDisposition.php', 'mode=crvhIsBlocked&crvhId=' + crvhId + '&currDay=<?php echo $currentSelectedDay ?>');
          if (retValue == '1') {
          	  alert('<?php echo getLngt("Achtung, das Fahrzeug ist für den selektierten Tag gesperrt!") ?>');
          }
        <?php endif; ?>
        // Check the availability of the specified vehicle for the requested interval
        if (ecoMultDayTimeunitsOfSelectedDay > 0) {
           ajaxRequestGet('../include/ajaxReqDisposition.php', 'mode=checkAvailabilityCrvhMultipleDayJb&crvhId=' + crvhId + '&currDay=<?php echo $currentSelectedDay ?>&hour=' + hour + '&hourUnit=' + hourUnit + '&jbId=' + ecoId + '&csId=<?php echo $csId ?>&hourTimeUnits=<?php echo $hourTimeUnits ?>');
        } else {
        	 ajaxRequestGet('../include/ajaxReqDisposition.php', 'mode=checkAvailabilityCrvhJb&crvhId=' + crvhId + '&currDay=<?php echo $currentSelectedDay ?>&hour=' + hour + '&hourUnit=' + hourUnit + '&timeslots=' + draggableTimeslots + '&jbId=' + ecoId + '&csId=<?php echo $csId ?>&hourTimeUnits=<?php echo $hourTimeUnits ?>');
        }
        if (capacityProblem == '2') {
             if ('<?php echo $checkTotalweight ?>' == '1') {
          	     alert('<?php echo getLngt("Die Nutzlast des Fahrzeugs scheint ausgereizt!") ?>');
          	 }
          	 capacityProblem = '';
        }
        if (capacityProblem == '') {
        
           // 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
           	  // ....
           }
        
           // Persistent update of the new time interval for the eco into the DB
           ajaxRequestGet('../include/ajaxReqDisposition.php', 'mode=setAssocCrvhJb&crvhId=' + crvhId + '&currDay=<?php echo $currentSelectedDay ?>&hour=' + hour + '&hourUnit=' + hourUnit + '&timeslots=' + draggableTimeslots + '&jbId=' + ecoId + '&csId=<?php echo $csId ?>&hourTimeUnits=<?php echo $hourTimeUnits ?>');
           if (isUpdatedInDb == '1') {
        
              draggable.css('position', 'absolute');
              draggable.css('left', masterArray[crvhId][hour][hourUnit][1] + "px");
              draggable.css('top', masterArray[crvhId][hour][hourUnit][2] + "px");
           	
           	  // Modify styles of the displayed eco on the timeline regarding the needed timeslots
              $(elemIdToBeMoved).css('position', 'absolute');
              $(elemIdToBeMoved).css('left', (masterArray[crvhId][hour][hourUnit][1] + ecoDragBarWidth) + "px");
              $(elemIdToBeMoved).css('top', masterArray[crvhId][hour][hourUnit][2] + "px");
              var elemWidth = (draggableTimeslots - 1) * timeUnitWidth;

              // If eco is multiple day then overwrite with timeslots of the selected day
              if (ecoMultDayTimeunitsOfSelectedDay > 0) {
              	 elemWidth = (ecoMultDayTimeunitsOfSelectedDay - 1) * timeUnitWidth;
              }
              
              // Recompute width regarding to   
              elemWidth += (timeUnitWidth - ecoDragBarWidth);
              
           	  $(elemIdToBeMoved).css('width', elemWidth + 'px');  // Resize eco for output in vehicle timeline

              // Eco has been set to the new time slot => Update "jb_ordertime"
              newOrdertime = '<?php echo $currentSelectedDay ?>' + ' ' + padl(hour.toString(),2,'0') + ':' + padl((hourUnit * (60 / <?php echo $hourTimeUnits ?>).toString()),2,'0') + ':00';
        	    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);
        
              // Reset the length of text of the element regarding the timeslots
              var htmlStr = resizeEcoContent(ecoId, elemWidth);
              $(elemIdToBeMoved).html(htmlStr);
        
              // Set z-index because of scrolling problem
              draggable.css('z-index', '5');
              $(elemIdToBeMoved).css('z-index', '4');
              globalElemDraggedZIndex = 5;
        
              <?php if ($userTypeName == "hq") : ?>
                // Iterate eco array (eco container) for setting position to ''
                for(i=0; i<ecoArrayLen ;++i) {
                  if (ecoArray[i][0] == ecoId) {
                  	 ecoArray[i][0] = '';
                     break;
                  }
                }
              <?php endif; ?>
           } else {
           	  // Eco is NOT stored in db
           	  ecoResetToSource = true;
           }
        } else {
        	  // Eco is NOT stored in db
        	  ecoResetToSource = true;
        	  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!") ?>');
        	  }
        }
     }
  }

  // Eco is NOT stored in db. Move draggable element back to source and reset JS masterArray
  if (ecoResetToSource) {
     draggable.css('left', globalStartPosLeftOfElemDragged + "px");
     draggable.css('top', globalStartPosTopOfElemDragged + "px");

     draggable.css('z-index', globalElemDraggedZIndex);
     $(elemIdToBeMoved).css('z-index', globalElemDraggedZIndex - 1);
  }
}

function handleOutVhtEco(event, ui) {
  var draggable = ui.draggable;
  draggable.css('position', 'absolute');
  draggable.css('left', globalStartPosLeftOfElemDragged + "px");
  draggable.css('top', globalStartPosTopOfElemDragged + "px");  
}

// Handles dropping (back) to the eco container
function handleDropEcoContainer(event, ui) {
  var draggable = ui.draggable;
  var draggableId = draggable.attr('id');
  var ecoId = draggableId.substring(6);
  var elemIdToBeMoved = '#eco_2_' + ecoId;

  // Iterate eco array
  var ecoArrayLen = ecoArray.length;
  var checkRestOfElementsForSameEcoId = 0;
  for(i=0; i<ecoArrayLen ;++i) {
  	 // Search free position or use the same because the eco is moved inside the container only
     if (ecoArray[i][0] == '' || ecoArray[i][0] == ecoId) {

     	  // Set draggable element (back) to the first free position in eco container
        draggable.css('position', 'fixed');
        draggable.css('left', ecoArray[i][1] + "px");
        draggable.css('top', ecoArray[i][2] + "px");
        
        // Set corresponding eco element according to the draggable element before
        $(elemIdToBeMoved).css('position', 'fixed');
        $(elemIdToBeMoved).css('left', (ecoArray[i][1] + 10) + "px");
        $(elemIdToBeMoved).css('top', ecoArray[i][2] + "px");
        $(elemIdToBeMoved).css('width', '130px');  // Resize eco for standard width for output in eco container

        // Set z-index because of scrolling problem
        draggable.css('z-index', '8');
        $(elemIdToBeMoved).css('z-index', '7');
        globalElemDraggedZIndex = 8;

        if (ecoArray[i][0] == '') { checkRestOfElementsForSameEcoId = i; };
     	  ecoArray[i][0] = ecoId;     	  
        break;
     }     
  } 
  // Eleminate double entry in case of movement inside the eco container
  if (checkRestOfElementsForSameEcoId > 0) {
  	 for(i=checkRestOfElementsForSameEcoId+1; i<ecoArrayLen ;++i) {
  	 	  if (ecoArray[i][0] == ecoId) {
  	 	  	 ecoArray[i][0] = '';
  	 	  	 break;
  	 	  }
  	 }	
  }

  // Remove potential existing eco on any vehicle 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
  	  // ....
  }
  
  var htmlStr = '';
  // Reset the length of text of the dragged element regarding the timeslots
  htmlStr = resizeEcoContent(ecoId, 130);
  $(elemIdToBeMoved).html(htmlStr);
}

// Opens a new (popup-)window with specified parameters
function popupWindow(url,title,config) {

  // popup = window.open(url,title,config);

  var widthPopupWin = screen.width - 80;
  var heightPopupWin = screen.height - 180;
  var leftPopupWin = (screen.width / 2) - (widthPopupWin / 2);
  var topPopupWin = (screen.height / 2) - (heightPopupWin / 2);
  var popup;
  popup = window.open(url,title,
    "dependent=yes,width=" + widthPopupWin + ",height=" +
    heightPopupWin +",left=" + leftPopupWin + ",top=" + topPopupWin +
    ",scrollbars=yes");  
  
}

function finishPage(mode) {
  var ok = true;
  if (mode == 'xxxx') {
     if (!confirm('<?php echo getLngt("Blah?") ?>')) {
        ok = false;
     };  
  };
  if (ok) {
  	 document.forms[0].f_act.value = mode;
  	 document.forms[0].submit();
  }
};


function openMap(crSid) {
  var widthPopupWin = 1200;
  var heightPopupWin = 800;
  var leftPopupWin = (screen.width / 2) - (widthPopupWin / 2) - 12;
  var topPopupWin = (screen.height / 2) - (heightPopupWin / 2) - 50;
  var popupWin;
  popupWin = window.open("../locating/map.php?cr_sid=" + crSid + "&currDay=<?php echo $currentSelectedDay ?>","","dependent=yes,width=" + widthPopupWin + ",height=" + heightPopupWin +",left=" + leftPopupWin + ",top=" + topPopupWin + ",scrollbars=yes");
};

function openCourierVehicles(crvhId) {
  var widthPopupWin = 1200;
  var heightPopupWin = 800;
  var leftPopupWin = (screen.width / 2) - (widthPopupWin / 2) - 12;
  var topPopupWin = (screen.height / 2) - (heightPopupWin / 2) - 50;
  var popupWin;
  popupWin = window.open("../admin/courier_vehicle.php?f_crvh_id=" + crvhId,"","dependent=yes,width=" + widthPopupWin + ",height=" + heightPopupWin +",left=" + leftPopupWin + ",top=" + topPopupWin + ",scrollbars=yes");
};

function openCartageNote(crvhId) {
  var widthPopupWin = 1200;
  var heightPopupWin = 800;
  var leftPopupWin = (screen.width / 2) - (widthPopupWin / 2) - 12;
  var topPopupWin = (screen.height / 2) - (heightPopupWin / 2) - 50;
  var popupWin;
  popupWin = window.open("../admin/pdf_generic_function.php?functionName=<?php echo $parMaskDispositionFunctionnameCartageNote?>&par_01=" + crvhId + "&par_02=<?php echo $currentSelectedDay ?>","","dependent=yes,width=" + widthPopupWin + ",height=" + heightPopupWin +",left=" + leftPopupWin + ",top=" + topPopupWin + ",scrollbars=yes");
};

function openDeliveryStatistic(crvhId) {
  var widthPopupWin = 1200;
  var heightPopupWin = 800;
  var leftPopupWin = (screen.width / 2) - (widthPopupWin / 2) - 12;
  var topPopupWin = (screen.height / 2) - (heightPopupWin / 2) - 50;
  var popupWin;
  popupWin = window.open("../admin/pdf_generic_function.php?functionName=getDeliveryStatistic&par_01=" + crvhId + "&par_02=<?php echo $currentSelectedDay ?>","","dependent=yes,width=" + widthPopupWin + ",height=" + heightPopupWin +",left=" + leftPopupWin + ",top=" + topPopupWin + ",scrollbars=yes");
};

function openJobDetails(jbId) {
  var widthPopupWin = 1400;
  var heightPopupWin = 800;
  var leftPopupWin = (screen.width / 2) - (widthPopupWin / 2) - 12;
  var topPopupWin = (screen.height / 2) - (heightPopupWin / 2) - 50;
  var popupWin;
  popupWin = window.open("../admin/jb_detail.php?job_id=" + jbId,"","dependent=yes,width=" + widthPopupWin + ",height=" + heightPopupWin +",left=" + leftPopupWin + ",top=" + topPopupWin + ",scrollbars=yes");
};

// Every element (service unit serialno, job ID, zipcode, ...) has some possibilities to be selected for
function selAction(actionObjType, actionObjId, actionObjIdInfo, actionDescription, actionURL) {
	var frm = document.forms[0];
	// IMPORTANT: Init parameters to be submitted because no DB operation will be executed for the next page submit for a specified service unit !!!
	frm.f_actionObjType.value = '';
	frm.f_actionObjId.value = '';
	frm.f_actionID.value = '';
	// Define selected form parameters
	frm.actionObjType.value = actionObjType;
	frm.actionObjId.value = actionObjId;
  var selectedHour = '';
  var selectedMinute = '';

  if (actionObjType == 'crvh') {
     // Check vehicle is blocked
     var crvhBlockedState = '';
     ajaxRequestGet('../include/ajaxReqDisposition.php', 'mode=crvhBlockedState&crvhId=' + actionObjId + '&currDay=<?php echo $currentSelectedDay ?>');
     if (retBlockedState != '') {
     	  crvhBlockedState = retBlockedState;
     }

     // Get courier ID of the vehicle
     var crId = '';
  	 ajaxRequestGet('../include/ajaxReqLib.php', 'mode=0&db_table=couriervehicle&db_id_field=crvh_id&search_value=' + actionObjId + '&db_return_field=cr_id');
     if (retValue != '') {
     	  crId = retValue;
     }

     // Get state of the carrier being enabled or disabled for disposition
     crDispositionState = '0';
     if (crId != '') {
  	    ajaxRequestGet('../include/ajaxReqLib.php', 'mode=0&db_table=courier&db_id_field=cr_id&search_value=' + crId + '&db_return_field=cr_disposition');
        if (retValue != '') {
     	     crDispositionState = retValue;
        }
     }

  	 // Get vehicle data to be displayed
     ajaxRequestGet('../include/ajaxReqDisposition.php', 'mode=getCrvhData&crvhId=' + actionObjId + '&currDay=<?php echo $currentSelectedDay ?>');
     if (retCrvhData != '') {
     	 actionDescription = actionDescription + retCrvhData;
     }

     vSetElementContent('ac_title', '<b>' + actionObjIdInfo + '</b>');
  	 vSetElementContent('ac_description', actionDescription);
  	 <?php if ($userTypeName == "hq") : ?>
  	   vSetElementContent('ac_01', '<a href="javascript:execAjaxAction(\'' + actionObjType + '\',\'' + actionObjId + '\',' + '\'101\'' + ')"><?php echo getLngt("Standort auf der Karte") ?></a>');
  	   vSetElementContent('ac_02', '<a href=\"javascript:openCartageNote(\'' + actionObjId + '\');\"><?php echo getLngt("Rollkarte als PDF anzeigen") ?></a>');
  	   vSetElementContent('ac_03', '<a href=\"javascript:openCourierVehicles(\'' + actionObjId + '\');\"><?php echo getLngt("Fahrzeugstammblatt") ?></a>');
  	   if ((crvhBlockedState & 2) != 2) {
  	      vSetElementContent('ac_04', '<a href="javascript:execAjaxAction(\'' + actionObjType + '\',\'' + actionObjId + '\',' + '\'104\'' + ')"><?php echo getLngt(wrapPhrase("Rollkarte aufs Endgerät", "vehicle_disposition")) ?></a>');
  	   } else {
  	   	  vSetElementContent('ac_04', '<?php echo getLngt("Rollkarte aufs Endgerät") ?>');
  	   }
  	   vSetElementContent('ac_05', '<a href=\"javascript:openDeliveryStatistic(\'' + actionObjId + '\');\"><?php echo getLngt("Auslieferstatistik") ?></a>');
  	   if ((crvhBlockedState & 2) != 2) {
  	      vSetElementContent('ac_06', '<a href=\"javascript:execAjaxAction(\'' + actionObjType + '\',\'' + actionObjId + '\',' + '\'106\'' + ');\"><?php echo getLngt("Rollkarte auf folgendes Fahrzeug übertragen:") ?></a>&nbsp;&nbsp;<input type="text" name="f_crvh_sid_cartage_note_move_to" value="" size="7">');
  	   } else {
  	   	  vSetElementContent('ac_06', '<?php echo getLngt("Rollkarte auf folgendes Fahrzeug übertragen:") ?>');
  	   }
  	   if ((crvhBlockedState & 1) == 1) {
  	      vSetElementContent('ac_07', '<a href="javascript:execAjaxAction(\'' + actionObjType + '\',\'' + actionObjId + '\',' + '\'107\'' + ')"><?php echo getLngt("Fahrzeug für diesen Tag freigeben") ?></a>');
  	   } else {
  	   	  vSetElementContent('ac_07', '<a href="javascript:execAjaxAction(\'' + actionObjType + '\',\'' + actionObjId + '\',' + '\'207\'' + ')"><?php echo getLngt("Fahrzeug für diesen Tag blockieren") ?></a>');
  	   }
  	   if (crDispositionState == '1') {
  	      if ((crvhBlockedState & 2) == 2) {
  	         vSetElementContent('ac_08', '<a href="javascript:execAjaxAction(\'' + actionObjType + '\',\'' + actionObjId + '\',' + '\'108\'' + ')"><?php echo getLngt("Fahrzeug der unternehmerseitigen Disposition entziehen") ?></a>');
  	      } else {
  	      	  vSetElementContent('ac_08', '<a href="javascript:execAjaxAction(\'' + actionObjType + '\',\'' + actionObjId + '\',' + '\'208\'' + ')"><?php echo getLngt("Fahrzeug für die unternehmerseitige Disposition freigeben") ?></a>');
  	      }
  	   } else {
  	   	  vSetElementContent('ac_08', '');
  	   }
  	   if ((crvhBlockedState & 2) != 2) {
  	      vSetElementContent('ac_09', '<a href="javascript:execAjaxAction(\'' + actionObjType + '\',\'' + actionObjId + '\',' + '\'109\'' + ')"><?php echo getLngt("Rollkarte per Mail senden") ?></a>');
  	   } else {
  	   	  vSetElementContent('ac_09', '<?php echo getLngt("Rollkarte per Mail senden") ?>');
  	   }
  	   vSetElementContent('ac_10', '<a href="javascript:execAjaxAction(\'' + actionObjType + '\',\'' + actionObjId + '\',' + '\'110\'' + ')"><?php echo getLngt("Rollkarte umsortieren") ?></a>');
  	   vSetElementContent('ac_11', '');
  	   vSetElementContent('ac_12', '');
  	   vSetElementContent('ac_13', '');

       // Display vehicle remark for a special day
       // ajaxRequestGet('../include/ajaxReqLib.php', 'mode=2&db_table=vehicleavailability&db_id_field=<?php echo urlencode("vha_day = '" . $currentSelectedDay . "' AND crvh_id") ?>&search_value=' + actionObjId + '&db_return_field=vha_remark');
       ajaxRequestGet('../include/ajaxReqLib.php', 'mode=2&submode=1&db_table=vehicleavailability&clause=' + encodeURI(escape("vha_day = '<?php echo $currentSelectedDay ?>' AND crvh_id = '" + actionObjId  + "'")) + '&db_return_field=vha_remark');
       // var ac_14_readonly = 'readonly'; if (jbStatus != '' && jbStatus != '2') { ac_14_readonly = '';};
       var ac_14_readonly = '';
       vSetElementContent('ac_14', '<a href="javascript:execAjaxAction(\'' + actionObjType + '\',\'' + actionObjId + '\',' + '\'114\'' + ')"><?php echo getLngt("Bemerkung speichern") ?></a><br><textarea class="f8np1" name="f_crvh_114_vha_remark" cols="60" rows="7" ' + ac_14_readonly + '>' + retValue + '</textarea>');
       
       vSetElementContent('ac_15', '');
       vSetElementContent('ac_16', '');

     <?php elseif ($userTypeName == "cr") : ?>
  	   vSetElementContent('ac_01', '<a href="javascript:execAjaxAction(\'' + actionObjType + '\',\'' + actionObjId + '\',' + '\'101\'' + ')"><?php echo getLngt("Standort auf der Karte") ?></a>');
  	   vSetElementContent('ac_02', '<a href=\"javascript:openCartageNote(\'' + actionObjId + '\');\"><?php echo getLngt("Rollkarte als PDF anzeigen") ?></a>');
  	   vSetElementContent('ac_03', '<a href="javascript:execAjaxAction(\'' + actionObjType + '\',\'' + actionObjId + '\',' + '\'104\'' + ')"><?php echo getLngt("Rollkarte aufs Endgerät") ?></a>');
  	   vSetElementContent('ac_04', '<a href="javascript:execAjaxAction(\'' + actionObjType + '\',\'' + actionObjId + '\',' + '\'109\'' + ')"><?php echo getLngt("Rollkarte per Mail senden") ?></a>');
  	   vSetElementContent('ac_05', '');
  	   vSetElementContent('ac_06', '');
  	   vSetElementContent('ac_07', '');
  	   vSetElementContent('ac_08', '');
  	   vSetElementContent('ac_09', '');
  	   vSetElementContent('ac_10', '<a href="javascript:execAjaxAction(\'' + actionObjType + '\',\'' + actionObjId + '\',' + '\'110\'' + ')"><?php echo getLngt("Rollkarte umsortieren") ?></a>');
  	   vSetElementContent('ac_11', '');
  	   vSetElementContent('ac_12', '');
  	   vSetElementContent('ac_13', '');
  	   vSetElementContent('ac_14', '');
  	   vSetElementContent('ac_15', '');
  	   vSetElementContent('ac_16', '');
  	 <?php endif; ?>
  }

  if (actionObjType == 'jb') {
  	 // Get jb_status
  	 var jbStatus = '';
  	 ajaxRequestGet('../include/ajaxReqLib.php', 'mode=2&db_table=job&db_id_field=jb_id&search_value=' + actionObjId + '&db_return_field=jb_status');
  	 if (retValue != '') {
        jbStatus = retValue;
     }
     // Get jb_offer
  	 var jbOffer = '';
  	 ajaxRequestGet('../include/ajaxReqLib.php', 'mode=2&db_table=job&db_id_field=jb_id&search_value=' + actionObjId + '&db_return_field=jb_offer');
  	 if (retValue != '') {
        jbOffer = retValue;
     }
     // Get differing SMS time
  	 var jbSMSTime = '';
  	 ajaxRequestGet('../include/ajaxReqLib.php', 'mode=6&db_table=genericdatacontainer&id_01=gdc_obj_type&value_01=jb&id_02=gdc_obj_id&value_02=' + actionObjId + '&id_03=gdc_gen_fieldname&value_03=sms_time&db_return_field=gdc_content');
  	 if (retValue != '') {
        jbSMSTime = retValue;
     }
  	 // Get existence in table "vehicledisposition"
  	 var jbExistInVhd = '0';
  	 ajaxRequestGet('../include/ajaxReqLib.php', 'mode=2&db_table=vehicledisposition&db_id_field=jb_id&search_value=' + actionObjId + '&db_return_field=crvh_id');
  	 if (retValue != '') {
        jbExistInVhd = '1';
     }
  	 // Get jb_ordertime
  	 var jbOrdertime = '';
  	 ajaxRequestGet('../include/ajaxReqLib.php', 'mode=2&db_table=job&db_id_field=jb_id&search_value=' + actionObjId + '&db_return_field=jb_ordertime');
  	 if (retValue != '') {
        jbOrdertime = retValue;
     }
     // To remove eco taken by the carrier from "vehicledisposion" check (jb_status == "1") AND (current selected day != orderdate)
     var jbMultipleDayRemovableByCurrentSelectedDay = '';
     if (jbStatus == '1' && jbExistInVhd == '1' && jbOrdertime.substr(0,10) != '<?php echo $currentSelectedDay ?>') {
        ajaxRequestGet('../include/ajaxReqDisposition.php', 'mode=isMultipleDayJob&jbId=' + actionObjId + '&csId=<?php echo $csId ?>');
        if (isMultipleDayJob != '' && isMultipleDayJob != '0') {
        	 jbMultipleDayRemovableByCurrentSelectedDay = '1';
        }
     }
     
  	 vSetElementContent('ac_title', '<b>' + actionObjIdInfo + '</b>');
     if (jbStatus != '') {
     	  ajaxRequestGet('../include/ajaxReqDisposition.php', 'mode=getJobcalculatorData&jbId=' + actionObjId);
     	  if (retTratData != '') {
     	  	 actionDescription = '<table><tr><td style="width:200px; vertical-align:top;">' + actionDescription + '</td><td style="width:10px;"></td><td style="vertical-align:top;">' + retTratData + '</td></tr></table>';
     	  }
     }
  	 vSetElementContent('ac_description', actionDescription);
  	 <?php if ($userTypeName == "hq") : ?>
  	   vSetElementContent('ac_01', '<a href=\"javascript:openJobDetails(\'' + actionObjId + '\');\"><?php echo getLngt("Auftragsdetails") ?></a>');
       vSetElementContent('ac_02', '<a href="../admin/jb_list.php' + actionURL + '" target="_blank"><?php echo getLngt("Auftragsliste") ?></a>');
  	   if (jbStatus != '' && jbStatus != '2' && jbOffer == '1') {
          vSetElementContent('ac_03', '<a href="../jobs/job_edit.php?jb_id=' + actionObjId + '" target="_blank"><?php echo getLngt("Auftrag bearbeiten") ?></a>');
       } else {
  	      vSetElementContent('ac_03', '');
  	   }
  	   if (jbStatus == '9' && jbExistInVhd == '1') {
  	      vSetElementContent('ac_04', '<a href="javascript:execAjaxAction(\'' + actionObjType + '\',\'' + actionObjId + '\',' + '\'104\'' + ')"><?php echo getLngt("Auftrag senden") ?></a>');
  	   } else {
  	      if (jbStatus == '1') {
  	         vSetElementContent('ac_04', '<a href="javascript:execAjaxAction(\'' + actionObjType + '\',\'' + actionObjId + '\',' + '\'204\'' + ')"><?php echo getLngt("Auftrag zurückholen") ?></a>');
  	      } else {
  	      	 vSetElementContent('ac_04', '');
  	      }
  	   }
  	   if (jbStatus == '9') {
  	      vSetElementContent('ac_05', '<a href="javascript:execAjaxAction(\'' + actionObjType + '\',\'' + actionObjId + '\',' + '\'105\'' + ')"><?php echo getLngt("Auftrag auf das selektierte Datum setzen") ?></a>');
  	   } else {
  	      vSetElementContent('ac_05', '');
  	   }
  	   if (jbExistInVhd != '1' && jbStatus == '9') {
  	   	  vSetElementContent('ac_06', '<a href="javascript:execAjaxAction(\'' + actionObjType + '\',\'' + actionObjId + '\',' + '\'106\'' + ')"><?php echo getLngt("Startuhrzeit in der SMS") ?></a>&nbsp;&nbsp;<?php echo $outputDayTimes ?>');
  	      if (jbSMSTime != '') {
             var selectedHour = jbSMSTime.substr(0,2);
             var selectedMinute = jbSMSTime.substr(3,2);
             setSelectedValue('f_day_time_hour_from_new', selectedHour);
             setSelectedValue('f_day_time_minute_from_new', selectedMinute);
          }
       } else {
          vSetElementContent('ac_06', '');
       }
  	   if (jbMultipleDayRemovableByCurrentSelectedDay == '1') {
  	   	  vSetElementContent('ac_07', '<a href="javascript:execAjaxAction(\'' + actionObjType + '\',\'' + actionObjId + '\',' + '\'107\'' + ')"><?php echo getLngt("Reservierung freigeben") ?></a>');
       } else {
          vSetElementContent('ac_07', '');
       }
  	   vSetElementContent('ac_08', '');
  	   // Change time units of the eco if it is NOT associated with a vehicle (no entry in "vehicledisposition")
  	   if (jbExistInVhd != '1' && jbStatus == '9') {
  	      ajaxRequestGet('../include/ajaxReqLib.php', 'mode=0&db_table=job&db_id_field=jb_id&search_value=' + actionObjId + '&db_return_field=jb_timeunits');
          vSetElementContent('ac_09', '<a href="javascript:execAjaxAction(\'' + actionObjType + '\',\'' + actionObjId + '\',' + '\'109\'' + ')"><?php echo getLngt("Zeiteinheiten setzen") ?></a>&nbsp;&nbsp;<input type="text" name="f_jb_109_timeunits" value="' + retValue + '" size="5">');
       } else {
          vSetElementContent('ac_09', '');
       }
       // Job enabled for carrier disposition
       if (jbExistInVhd == '1') {
  	      if (jbStatus == '0') {
  	         vSetElementContent('ac_10', '<a href="javascript:execAjaxAction(\'' + actionObjType + '\',\'' + actionObjId + '\',' + '\'110\'' + ')"><?php echo getLngt("Auftrag der unternehmerseitigen Disposition entziehen") ?></a>');
  	      }
  	      if (jbStatus == '9') {
  	      	  vSetElementContent('ac_10', '<a href="javascript:execAjaxAction(\'' + actionObjType + '\',\'' + actionObjId + '\',' + '\'210\'' + ')"><?php echo getLngt("Auftrag für die unternehmerseitige Disposition freigeben") ?></a>');
  	      }
  	   }
       // Display tour remark
       ajaxRequestGet('../include/ajaxReqLib.php', 'mode=2&db_table=tour&db_id_field=<?php echo urlencode("tr_sort = 2 AND jb_id") ?>&search_value=' + actionObjId + '&db_return_field=tr_remark');
       var ac_14_readonly = 'readonly'; if (jbStatus != '' && jbStatus != '2') { ac_14_readonly = '';};
       vSetElementContent('ac_14', '<a href="javascript:execAjaxAction(\'' + actionObjType + '\',\'' + actionObjId + '\',' + '\'114\'' + ')"><?php echo getLngt("Bemerkung speichern") ?></a><br><textarea class="f8np1" name="f_jb_114_tr_remark" cols="60" rows="7" ' + ac_14_readonly + '>' + retValue + '</textarea>');
       // Get tourarticle data if exist
       if (jbStatus != '') {
       	  ajaxRequestGet('../include/ajaxReqDisposition.php', 'mode=getTourarticleData&jbId=' + actionObjId);
       	  if (retTratData != '') {
       	  	 $('ac_15').css('width', "500px");
       	  	 $('ac_15').css('height', "200px");
       	  	 $('ac_15').css('overflow', 'scroll');
       	  	 vSetElementContent('ac_15', retTratData);
       	  } else {
       	  	vSetElementContent('ac_15', '');
       	  }
       }
       // Display internal remark
       ajaxRequestGet('../include/ajaxReqLib.php', 'mode=6&db_table=genericdatacontainer&id_01=gdc_obj_type&value_01=jb&id_02=gdc_obj_id&value_02=' + actionObjId + '&id_03=gdc_gen_fieldname&value_03=internal_remark&db_return_field=gdc_content');
       var ac_16_readonly = 'readonly'; if (jbStatus != '' && jbStatus != '2') { ac_16_readonly = '';};
       vSetElementContent('ac_16', '<a href="javascript:execAjaxAction(\'' + actionObjType + '\',\'' + actionObjId + '\',' + '\'116\'' + ')"><?php echo getLngt("INTERNE Bemerkung speichern") ?></a><br><textarea class="f8np1" name="f_jb_116_internal_remark" cols="60" rows="7" ' + ac_16_readonly + '>' + retValue + '</textarea>');       
     <?php elseif ($userTypeName == "cr") : ?>
  	   if (jbStatus == '0' && jbExistInVhd == '1') {
  	      vSetElementContent('ac_01', '<a href="javascript:execAjaxAction(\'' + actionObjType + '\',\'' + actionObjId + '\',' + '\'104\'' + ')"><?php echo getLngt("Auftrag senden") ?></a>');
  	   } else {
  	      if (jbStatus == '1') {
  	         vSetElementContent('ac_01', '<a href="javascript:execAjaxAction(\'' + actionObjType + '\',\'' + actionObjId + '\',' + '\'204\'' + ')"><?php echo getLngt("Auftrag zurückholen") ?></a>');
  	      } else {
  	      	 vSetElementContent('ac_01', '');
  	      }
  	   }
       // Get tourarticle data if exist
       if (jbStatus != '') {
       	  ajaxRequestGet('../include/ajaxReqDisposition.php', 'mode=getTourarticleData&jbId=' + actionObjId);
       	  if (retTratData != '') {
       	  	 $('ac_02').css('width', "500px");
       	  	 $('ac_02').css('height', "200px");
       	  	 $('ac_02').css('overflow', 'scroll');
       	  	 vSetElementContent('ac_02', retTratData);
       	  } else {
       	  	vSetElementContent('ac_02', '');
       	  }
       }
       vSetElementContent('ac_03', '');
       vSetElementContent('ac_04', '');
	     vSetElementContent('ac_05', '');
  	   vSetElementContent('ac_06', '');
  	   vSetElementContent('ac_07', '');
  	   vSetElementContent('ac_08', '');
       vSetElementContent('ac_09', '');
       vSetElementContent('ac_10', '');
       vSetElementContent('ac_11', '');
       vSetElementContent('ac_12', '');

       // Display tour remark
       ajaxRequestGet('../include/ajaxReqLib.php', 'mode=2&db_table=tour&db_id_field=<?php echo urlencode("tr_sort = 2 AND jb_id") ?>&search_value=' + actionObjId + '&db_return_field=tr_remark');
       var ac_14_readonly = 'readonly'; if (jbStatus != '' && jbStatus != '2') { ac_14_readonly = '';};
       vSetElementContent('ac_14', '<a href="javascript:execAjaxAction(\'' + actionObjType + '\',\'' + actionObjId + '\',' + '\'114\'' + ')"><?php echo getLngt("Bemerkung speichern") ?></a><br><textarea class="f8np1" name="f_jb_114_tr_remark" cols="60" rows="7" ' + ac_14_readonly + '>' + retValue + '</textarea>');
     <?php endif; ?>
  }
  myshow('actioncontainer');
}

// Execute a selected action for a specified object
function execAction(actionObjType, actionObjId, actionID) {
	myhide('actioncontainer');
	var frm = document.forms[0];
  if (actionObjType != '' && actionObjId != '' && actionID != '') {
  	 frm.f_actionObjType.value = actionObjType;
	   frm.f_actionObjId.value = actionObjId;
	   frm.f_actionID.value = actionID;
	   finishPage('processAction');
  }
}

// Execute a selected action for a specified object
function execAjaxAction(actionObjType, actionObjId, actionID) {
	// myhide('actioncontainer');
	var frm = document.forms[0];
  var selectedHour;
  var selectedMinute;
  if (actionObjType != '' && actionObjId != '' && actionID != '') {
     if (actionObjType == 'crvh') {
        if (actionID == '101') {
           ajaxRequestGet('../include/ajaxReqLib.php', 'mode=0&db_table=couriervehicle&db_id_field=crvh_id&search_value=' + actionObjId + '&db_return_field=crvh_sid');
           if (retValue != '') {
              ajaxRequestGet('../include/ajaxReqLib.php', 'mode=0&db_table=courier&db_id_field=crvh_sid&search_value=' + retValue + '&db_return_field=cr_sid');
              if (retValue != '') {
                 openMap(retValue);  // Open map with cr_sid
              }
           }
        }
        if (actionID == '104') {
           ajaxRequestGet('../include/ajaxReqDisposition.php', 'mode=sendCartageNote&crvhId=' + actionObjId + '&currDay=<?php echo $currentSelectedDay ?>');
           if (updateOK == '1') {
              finishPage('');  // Reload because ecos have been removed from FDS
           } else {
           	  alert('<?php echo getLngt("Der Vorgang war erfolglos. Bitte nochmal versuchen! Ansonsten bitte an den Support weitergeben!") ?>');
           }
        }
        if (actionID == '106') {
           var crvhSidMovedTo = frm.f_crvh_sid_cartage_note_move_to.value;
        	 if (crvhSidMovedTo != '') {
              ajaxRequestGet('../include/ajaxReqDisposition.php', 'mode=moveCartageNote&crvhId=' + actionObjId + '&crvhSidMovedTo=' + crvhSidMovedTo + '&currDay=<?php echo $currentSelectedDay ?>&csId=<?php echo $csId ?>&hourTimeUnits=<?php echo $hourTimeUnits ?>');
              if (movementState == '1') {
                 finishPage('');  // Reload because ecos have been moved from one vehicle to the other
              } else {
              	if (movementState == '2') {
              		 alert('<?php echo getLngt("Mindestens eine Zeiteinheit auf dem Zielfahrzeug ist noch belegt. Keiner der Aufträge wurde verschoben.") ?>');
                } else {
              	   alert('<?php echo getLngt("Es wurden keine Aufträge verschoben.") ?>');
                }
              }
           } else {
           	 alert('<?php echo getLngt("Bitte ein Fahrzeug angeben!") ?>');
           }
        }
        if (actionID == '107') {
           ajaxRequestGet('../include/ajaxReqDisposition.php', 'mode=crvhUnblock&crvhId=' + actionObjId + '&currDay=<?php echo $currentSelectedDay ?>');
           if (retValue == 'SET_UNBLOCKED') {
              ajaxRequestGet('../include/ajaxReqDisposition.php', 'mode=crvhBlockedState&crvhId=' + actionObjId + '&currDay=<?php echo $currentSelectedDay ?>');
              var crvhBgCol = '#AADDAA';
              if (retBlockedState != '') {
              	 if ((retBlockedState & 2) == 2) {
              	 	  crvhBgCol = '#BBBBBB';  // Courier disposition unblocked but vehicle blocked by headquarters
              	 }
              }
              $('#' + actionObjId).css('background-color', crvhBgCol);
              alert('<?php echo getLngt("Das Fahrzeug wurde freigegeben für den Tag!") ?>');
           } else {
           	  if (retValue == 'IS_UNBLOCKED') {
           	     alert('<?php echo getLngt("Das Fahrzeug ist schon freigegeben für den Tag!") ?>');
           	  } else {
           	  	 alert('<?php echo getLngt("Der Vorgang war erfolglos. Bitte nochmal versuchen! Ansonsten bitte an den Support weitergeben!") ?>');
           	  }
           }
        }
        if (actionID == '207') {
           ajaxRequestGet('../include/ajaxReqDisposition.php', 'mode=crvhBlock&crvhId=' + actionObjId + '&currDay=<?php echo $currentSelectedDay ?>');
           if (retValue == 'SET_BLOCKED') {
              ajaxRequestGet('../include/ajaxReqDisposition.php', 'mode=crvhBlockedState&crvhId=' + actionObjId + '&currDay=<?php echo $currentSelectedDay ?>');
              var crvhBgCol = '#FF6A6A';
              if (retBlockedState != '') {
              	 if ((retBlockedState & 2) == 2) {
              	 	  crvhBgCol = '#BBBBBB';  // Courier disposition unblocked but vehicle blocked by headquarters
              	 }
              }
              $('#' + actionObjId).css('background-color', crvhBgCol);
              alert('<?php echo getLngt("Das Fahrzeug wurde geblockt für den Tag!") ?>');
           } else {
           	  if (retValue == 'IS_BLOCKED') {
           	     alert('<?php echo getLngt("Das Fahrzeug ist schon geblockt für den Tag!") ?>');
           	  } else {
           	  	 alert('<?php echo getLngt("Der Vorgang war erfolglos. Bitte nochmal versuchen! Ansonsten bitte an den Support weitergeben!") ?>');
           	  }
           }
        }
        if (actionID == '108') {
           ajaxRequestGet('../include/ajaxReqDisposition.php', 'mode=crvhUnblockForCourierDispo&crvhId=' + actionObjId + '&currDay=<?php echo $currentSelectedDay ?>');
           if (retValue == 'SET_UNBLOCKED') {
           	  /*
              ajaxRequestGet('../include/ajaxReqDisposition.php', 'mode=crvhBlockedState&crvhId=' + actionObjId + '&currDay=<?php echo $currentSelectedDay ?>');
              var crvhBgCol = '#AADDAA';
              if (retBlockedState != '') {
              	 if ((retBlockedState & 1) == 1) {
              	 	  crvhBgCol = '#FF6A6A';  // Courier disposition unblocked but vehicle blocked by headquarters              	 	  
              	 }
              }
              $('#' + actionObjId).css('background-color', crvhBgCol);
              */
              alert('<?php echo getLngt("Das Fahrzeug wurde für den Tag der unternehmerseitigen Disposition entzogen!") ?>');
              finishPage('');  // Reload because ecos have changed the color and are enabled for drag and drop
           } else {
           	  if (retValue == 'IS_UNBLOCKED') {
           	     alert('<?php echo getLngt("Das Fahrzeug ist NICHT für die unternehmerseitige Disposition freigegeben!") ?>');
           	  } else {
           	  	 alert('<?php echo getLngt("Der Vorgang war erfolglos. Bitte nochmal versuchen! Ansonsten bitte an den Support weitergeben!") ?>');
           	  }
           }
        }
        if (actionID == '208') {
           ajaxRequestGet('../include/ajaxReqDisposition.php', 'mode=crvhBlockForCourierDispo&crvhId=' + actionObjId + '&currDay=<?php echo $currentSelectedDay ?>');
           if (retValue == 'SET_BLOCKED') {
           	  // $('#' + actionObjId).css('background-color', '#BBBBBB');
              alert('<?php echo getLngt("Das Fahrzeug wurde für den Tag für die unternehmerseitige Disposition freigegeben!") ?>');
              finishPage('');  // Reload because ecos have changed the color and are disabled for drag and drop
           } else {
           	  if (retValue == 'IS_BLOCKED') {
           	     alert('<?php echo getLngt("Das Fahrzeug ist schon für den Tag für die unternehmerseitige Disposition freigegeben!") ?>');
           	  } else {
           	  	 alert('<?php echo getLngt("Der Vorgang war erfolglos. Bitte nochmal versuchen! Ansonsten bitte an den Support weitergeben!") ?>');
           	  }
           }
        }
        if (actionID == '109') {
        	 if (confirm('<?php echo getLngt("Möchten Sie die Rollkarte per Mail an die voreingestellten Mailadressen verschicken?") ?>')) {
              ajaxRequestGet('../include/ajaxReqDisposition.php', 'mode=mailCartageNote&crvhId=' + actionObjId + '&csId=<?php echo $csId ?>&currDay=<?php echo $currentSelectedDay ?>');
              if (mailSentOK == '1') {
                 alert('<?php echo getLngt("Die Mail scheint erfolgreich versendet!") ?>');
              } else {
              	 alert('<?php echo getLngt("Die Mail wurde vermutlich nicht gesendet!") ?>');
              }
           }
        }
        if (actionID == '110') {
        	 if (confirm('<?php echo getLngt("Möchten Sie die Rollkarte umsortieren?") ?>')) {
              // crvhEco[" . $crvhId . "][" . $i . "]
              $("#itemsort_crvh").val(actionObjId);
              var numOfEcosOfVehicle = crvhEco[actionObjId].length;
              $("#itemsort_num_of_ecos").val(numOfEcosOfVehicle);
              var itemSortEco;
              var itemContent = '';
              var ecoCartageNote;
              var ecoCartageNoteString = '';
              var ecoOrderTimeByItemSort = '';
              for(i=0; i<numOfEcosOfVehicle; ++i) {
              	 ecoCartageNote = crvhEco[actionObjId][i];
              	 ecoCartageNoteString = ecoCartageNote.toString();
              	 itemSortEco = 'is_' + padl(i.toString(),2,'0');
              	 $("#itemsort_sortable").append('<li id="' + itemSortEco + '"></li>');
              	 // Select boxes for order time
               	 ecoOrderTimeByItemSort = '<select id="' + ecoCartageNoteString + '_hour" name="' + ecoCartageNoteString + '_hour" class="f8np1"><?php echo addOptionsFromRange("0","23","","","2","0",1,"") ?></select>';
               	 ecoOrderTimeByItemSort += '<select id="' + ecoCartageNoteString + '_minute" name="' + ecoCartageNoteString + '_minute" class="f8np1"><?php echo addOptionsFromRange("0","59","","","2","0",10,"") ?></select>';
                 itemContent = '<table><tr><td width="70%">' + ecoTextDefaultArray[ecoCartageNote] + '</td><td width="30%" align="canter">' + ecoOrderTimeByItemSort + '</td></tr></table>';
                 // $('#' + itemSortEco).html(ecoTextDefaultArray[ecoCartageNote]);
                 $('#' + itemSortEco).html(itemContent);
              	 // Get order time of the current job to init the select boxes
              	 ajaxRequestGet('../include/ajaxReqLib.php', 'mode=0&db_table=job&db_id_field=jb_id&search_value=' + ecoCartageNote + '&db_return_field=jb_ordertime');
  	             if (retValue != '') {
                    selectedHour = retValue.substr(11,2);
                    selectedMinute = retValue.substr(14,2);
                    if (selectedHour == '') { selectedHour = '0'; };
                    selectedHour = parseInt(selectedHour);
                    selectedMinute = parseInt(selectedMinute);
                    $("#" + ecoCartageNoteString + '_hour').val(selectedHour);
                    if (selectedMinute == '') { selectedMinute = '0'; }
                    $("#" + ecoCartageNoteString + '_minute').val(selectedMinute);
                 }
              }
              myhide('actioncontainer');
              callItemSort();
           }
        }
        if (actionID == '114') {
           if (frm.f_crvh_114_vha_remark) {
           	  var currVhaRemark = frm.f_crvh_114_vha_remark.value;
              ajaxRequestGet('../include/ajaxReqLib.php', 'mode=100&db_table=vehicleavailability&db_id_field=crvh_id&search_value=' + actionObjId + '&db_op_field=vha_remark&new_content=' + encodeURI(escape(currVhaRemark)) + '&clause=' + encodeURI(escape("<?php echo " vha_day = '" . $currentSelectedDay . "'" ?>")));
              // finishPage('');  // Reload for display the new
           }
        }
     }
     if (actionObjType == 'jb') {
        if (actionID == '104') {
           ajaxRequestGet('../include/ajaxReqDisposition.php', 'mode=sendSingleJob&jbId=' + actionObjId);
           if (updateOK == '1') {
              finishPage('');  // Reload because ecos have be changed in FDS
           }
        }
        if (actionID == '204') {
           ajaxRequestGet('../include/ajaxReqDisposition.php', 'mode=revokeSingleJob&jbId=' + actionObjId);
           if (updateOK == '1') {
              finishPage('');  // Reload because ecos have be changed in FDS
           }
        }
        if (actionID == '105') {
        	 var selectedDate = padl(getSelectedValue('selYear'),2) + '-' + padl(getSelectedValue('selMonth'),2) + '-' + getSelectedValue('selDay');
        	 if (selectedDate != '<?php echo $currentSelectedDay ?>') {
        	 	  selectedDate = selectedDate + ' ' + '06:00:00';
              ajaxRequestGet('../include/ajaxReqDisposition.php', 'mode=changeDateOfJob&jbId=' + actionObjId + '&content=' + selectedDate);
              if (updateOK == '1') {
                 finishPage('');  // Reload page with the new selected day the job has been changed to
              }
           } else {
           	  alert('<?php echo getLngt("Sie haben noch denselben Tag in der Auswahl. Bitte ändern Sie im Menu das Datum für die Verschiebung!") ?>');
        	 }
        }
        if (actionID == '106') {
           if (frm.f_day_time_hour_from_new && frm.f_day_time_minute_from_new) {
           	  
           	  selectedHour = getSelectedValue('f_day_time_hour_from_new');
           	  selectedMinute = getSelectedValue('f_day_time_minute_from_new');
           	  if (selectedHour != '' && selectedMinute != '') {
                 if (confirm('<?php echo getLngt("Möchten Sie SMS-Versand für diesen Auftrag auf die folgende Uhrzeit setzen?") ?> ' + selectedHour + ':' + selectedMinute)) {
                    ajaxRequestGet('../include/ajaxReqDisposition.php', 'mode=setSMSTime&jbId=' + actionObjId + '&value_01=' + selectedHour + '&value_02=' + selectedMinute);
                    if (retVal == '') {
                       alert('<?php echo getLngt("Die eingestellte Versandzeit wurde NICHT gespeichert!") ?>');
                    } else {
                    	 alert('<?php echo getLngt("Die Versandzeit wurde gespeichert!") ?>');
                    }
                 }
              }
           }
        }
        if (actionID == '107') {
        	 // Eco is multiple day job. Remove all reservations in "vehicledisposition" from the current selected day and future days. It has been checked that current selected day does NOT EQUAL to the orderdate of the eco!
        	 if (confirm('<?php echo getLngt("Möchten Sie die Reservierung für diesen Auftrag entfernen?") ?>')) {
        	    ajaxRequestGet('../include/ajaxReqDisposition.php', 'mode=removeMultipleDayJobTimeunitsFromFDS&jbId=' + actionObjId + '&csId=<?php echo $csId ?>&currDay=<?php echo $currentSelectedDay ?>');
              if (retVal == '') {
                 alert('<?php echo getLngt("Die Reservierung konnte NICHT entfernt werden!") ?>');
              } else {
              	 alert('<?php echo getLngt("Die Reservierung wurde entfernt!") ?>');
              }
        	 }
        }
        if (actionID == '109') {
           if (frm.f_jb_109_timeunits) {
           	  var currTimeUnits = frm.f_jb_109_timeunits.value;
           	  if (checkIsNaN(currTimeUnits, '<?php echo getLngt("Bitte geben Sie eine Zahl ein!") ?>')) {
                 ajaxRequestGet('../include/ajaxReqLib.php', 'mode=100&db_table=job&db_id_field=jb_id&search_value=' + actionObjId + '&db_op_field=jb_timeunits&new_content=' + currTimeUnits);
                 finishPage('');  // Reload for display the new
              }
           }
        }
        if (actionID == '110') {
           ajaxRequestGet('../include/ajaxReqDisposition.php', 'mode=jobUnblockForCourierDispo&jbId=' + actionObjId);
           if (retValue == '1') {
              alert('<?php echo getLngt("Der Auftrag wurde der unternehmerseitigen Disposition entzogen!") ?>');
              finishPage('');  // Reload because ecos have changed the color and are enabled for drag and drop
           }
        }
        if (actionID == '210') {
           ajaxRequestGet('../include/ajaxReqDisposition.php', 'mode=jobBlockForCourierDispo&jbId=' + actionObjId);
           if (retValue == '1') {
              alert('<?php echo getLngt("Der Auftrag wurde für die unternehmerseitige Disposition freigegeben!") ?>');
              finishPage('');  // Reload because ecos have changed the color and are enabled for drag and drop
           }
        }
        if (actionID == '114') {
           if (frm.f_jb_114_tr_remark) {
           	  var currTrRemark = frm.f_jb_114_tr_remark.value;
              ajaxRequestGet('../include/ajaxReqLib.php', 'mode=100&db_table=tour&db_id_field=jb_id&search_value=' + actionObjId + '&db_op_field=tr_remark&new_content=' + encodeURI(escape(currTrRemark)) + '&clause=tr_sort=2');
              // finishPage('');  // Reload for display the new
           }
        }
        if (actionID == '116') {
           if (frm.f_jb_116_internal_remark) {
           	  var internalRemark = frm.f_jb_116_internal_remark.value;
              ajaxRequestGet('../include/ajaxReqLib.php', 'mode=500&wrap_html=1&value_01=jb&value_02=' + actionObjId + '&value_03=internal_remark&value_04=' + encodeURI(escape(internalRemark)) + '&value_05=');
              // finishPage('');  // Reload for display the new
           }
        }
     }
  }
}


// Block/Unblock current day
function callCheckDayBlocked(mode) {
	if (mode == '1') {
		 if (confirm('<?php echo getLngt("Möchten Sie den aktuell selektierten Tag von der Terminvergabe herausnehmen?") ?>')) {
		    ajaxRequestGet('../include/ajaxReqDisposition.php', 'mode=dayBlock&csId=<?php echo $csId ?>&currDay=<?php echo $currentSelectedDay ?>');
        if (retBlockedState != '') {
        	  finishPage('');  // Reload for display the new
        }
     }
  } else {
  	 if (confirm('<?php echo getLngt("Möchten Sie den aktuell selektierten Tag für die Terminvergabe freigeben?") ?>')) {
		    ajaxRequestGet('../include/ajaxReqDisposition.php', 'mode=dayUnblock&csId=<?php echo $csId ?>&currDay=<?php echo $currentSelectedDay ?>');
        if (retBlockedState != '') {
        	  finishPage('');  // Reload for display the new
        }
     }
  }
}


// **** BLINKING START ****
var ecoIdBlink = '';
var ecoBlinkTimeout = '';
var ecoBlinkState = '';

// Lets element blink
function jobBlink() {
  $("#eco_2_" + ecoIdBlink).fadeOut('slow', function() {
    $(this).fadeIn('slow', function() {
    });
  });
};

function startBlink(ecoId) {
	// Stop current blinking state
	stopBlink();
	// Set new blinking state
	ecoIdBlink = ecoId;
  ecoBlinkTimeout = self.setTimeout("startBlink()", 30000);
  ecoBlinkState = self.setInterval("jobBlink(ecoIdBlink)", 2000);
}

function stopBlink() {  
  if (ecoBlinkTimeout) {
     self.clearTimeout(ecoBlinkTimeout);
     ecoBlinkTimeout = '';
  }
  if (ecoBlinkState) {
     self.clearInterval(ecoBlinkState);
     ecoBlinkState = ''
  }
  ecoIdBlink = '';
}
// **** BLINKING END ****


// **** MENU SELECTION START ****
var menuSelectionIdDisplayed = false;

function callMenuSelection() {
	if (menuSelectionIdDisplayed) {
		 myhide('menuselectioncontainer');
		 menuSelectionIdDisplayed = false;
  } else {
     myshow('menuselectioncontainer');
     menuSelectionIdDisplayed = true;
  }
}
// **** MENU SELECTION END ****


// **** SERVICE-FILTER START ****
var serviceFilterAreDisplayed = false;

function callServiceFilter() {
	if (serviceFilterAreDisplayed) {
		 myhide('servicefiltercontainer');
		 serviceFilterAreDisplayed = false;
  } else {
     myshow('servicefiltercontainer');
     serviceFilterAreDisplayed = true;
  }
}
// **** SERVICE-FILTER END ****


// **** ITEM SORT START ****
var itemSortIsDisplayed = false;

function callItemSort() {
	if (itemSortIsDisplayed) {
		 myhide('itemsortcontainer');
		 itemSortIsDisplayed = false;
		 // Remove all appended items !!!!
		 $("#itemsort_sortable li").remove();
  } else {
     myshow('itemsortcontainer');
     itemSortIsDisplayed = true;
  }
}

function finishPageItemSort() {
	// Get current vehicle to be sorted
	var crvhId = $("#itemsort_crvh").val();
	var ecoCartageNote;
  var orderTimes = '';  
	var numOfEcosOfVehicle = $("#itemsort_num_of_ecos").val();
	if (!isNaN(numOfEcosOfVehicle)) {
     for(var i=0; i<numOfEcosOfVehicle ;++i) {
     	  // Define serialized string for the order times, e.g. "1_8_20_2_9_40_3_10_50"  (1. Auftrag 08.20 Uhr, 2. Auftrag 09.40 Uhr, 3. Auftrag 10.50 Uhr)
     	  ecoCartageNote = crvhEco[crvhId][i];
     	  ecoCartageNoteString = ecoCartageNote.toString();
     	  if (orderTimes != '') {orderTimes += '_'};
     	  orderTimes += ecoCartageNote + '_' + $("#" + ecoCartageNoteString + "_hour").val() + '_' + $("#" + ecoCartageNoteString + "_minute").val();
     }
  }
	// Serialize sorted cartage note
	var sorted = $("#itemsort_sortable").sortable("serialize", { key: "content[]" });
  // ajaxRequestGet('../include/ajaxReqDisposition.php', 'mode=sortVehicleTimeline&csId=<?php echo $csId ?>&crvhId=' + crvhId + '&currDay=<?php echo $currentSelectedDay ?>&hourTimeUnits=<?php echo $hourTimeUnits ?>&' + sorted);
  ajaxRequestGet('../include/ajaxReqDisposition.php', 'mode=sortVehicleTimelineByNewOrdertimes&csId=<?php echo $csId ?>&crvhId=' + crvhId + '&currDay=<?php echo $currentSelectedDay ?>&hourTimeUnits=<?php echo $hourTimeUnits ?>&' + sorted + '&value_01=' + orderTimes);
  if (isSorted == '1') {
     finishPage('');
  } else {
     alert('<?php echo getLngt("Die Uhrzeiten sind leider nicht chronologisch!") ?>');
  }
}

$(function() {
  $( "#itemsort_sortable" ).sortable();
  // $( "#itemsort_sortable" ).disableSelection();
  $( "#itemsort_sortable" ).enableSelection();
});
// **** ITEM SORT END ****


// **** CALENDAR START ****
var calendarIsDisplayed = false;

function callCalendar() {
	if (calendarIsDisplayed) {
		 myhide('calendarcontainer');
		 calendarIsDisplayed = false;
  } else {
     myshow('calendarcontainer');
     calendarIsDisplayed = true;
  }
}

// Calendar data
function calendarFunc(year, month, day) {
	myhide('calendarcontainer');
  var monthStr = String(month);
  var dayStr = String(day);
  if (month < 10)
    monthStr = '0' + monthStr;
  if (day < 10)
    dayStr = '0' + dayStr;
  document.forms[0].selDay.value = dayStr;
  document.forms[0].selMonth.value = monthStr;
  document.forms[0].selYear.value = year;
  document.forms[0].dateSelectionByCalendar.value = '1';
  <?php if ($parMaskDispositionCalenderSubmitDisabled == "1") : ?>
    callCalendar();
  <?php else : ?>
    document.forms[0].submit();
  <?php endif; ?>
}
// **** CALENDAR END *****

function execBodyOnLoad() {
	myhide('actioncontainer');
	myhide('calendarcontainer');
	myhide('servicefiltercontainer');
	myhide('itemsortcontainer');
	myhide('menuselectioncontainer');
	initForm();
	calendarMonthInit('calendar', <?php echo $selYear ?>, <?php echo $selMonth ?>, true, true);
  <?php
    if (false) :
       if ($maskDisplay00Switch == "1") : echo "changeHideShow('maskDisplay00','on');"; else : echo "changeHideShow('maskDisplay00','off');"; endif;
       if ($maskDisplay01Switch == "1") : echo "changeHideShow('maskDisplay01','on');"; else : echo "changeHideShow('maskDisplay01','off');"; endif;
       if ($maskDisplay02Switch == "1") : echo "changeHideShow('maskDisplay02','on');"; else : echo "changeHideShow('maskDisplay02','off');"; endif;
       if ($maskDisplay03Switch == "1") : echo "changeHideShow('maskDisplay03','on');"; else : echo "changeHideShow('maskDisplay03','off');"; endif;
       if ($maskDisplay04Switch == "1") : echo "changeHideShow('maskDisplay04','on');"; else : echo "changeHideShow('maskDisplay04','off');"; endif;
       if ($maskDisplay05Switch == "1") : echo "changeHideShow('maskDisplay05','on');"; else : echo "changeHideShow('maskDisplay05','off');"; endif;
       if ($maskDisplay06Switch == "1") : echo "changeHideShow('maskDisplay06','on');"; else : echo "changeHideShow('maskDisplay06','off');"; endif;
       if ($maskDisplay07Switch == "1") : echo "changeHideShow('maskDisplay07','on');"; else : echo "changeHideShow('maskDisplay07','off');"; endif;
       
       if ($jsExecBodyOnLoadArray[0] == "1") : echo "setSuFormData();"; endif;
       if ($jsExecBodyOnLoadArray[1] == "1") : echo "resetSuFormData();"; endif;
       if ($jsExecBodyOnLoadArray[2] == "1") : echo "getServiceunitData('" . $f_su_admin_filter_1 . "');"; endif;
    endif;
  ?>
  myshow('maincontent');
  displayStatusMessage();
}

// ajaxRequestGet('../include/ajaxReqDisposition.php', 'mode=2&atId=' + at_id_bundle);
// ajaxRequestGet('../include/ajaxReqLib.php', 'mode=0&db_table=article&db_id_field=at_id&db_return_field=at_name&search_value=' + at_id);  


-->
</script>


<?php
  // Browser specific setup for special <div>....</div> as "actioncontainer"
  if ($isFirefox) :
     $actioncontainerDivPos = "style=\"position:fixed; top:100px; left:450; width:700px; height:700px; z-index:12; overflow:auto; background-color:#AACCAA;\"";
     $calendarcontainerDivPos = "style=\"position:fixed; top:100px; left:650; width:180px; height:190px; z-index:13; overflow:auto; background-color:#AAAACC;\"";
     $servicefiltercontainerDivPos = "style=\"position:fixed; top:100px; left:950; width:150px; height:250px; z-index:13; overflow:auto; background-color:#AACCAA;\"";
     $itemsortcontainerDivPos = "style=\"position:fixed; top:110px; left:100; width:500px; height:800px; z-index:14; overflow:auto; background-color:#AACCAA;\"";
     $menuselectioncontainerDivPos = "style=\"position:fixed; top:100px; left:100; width:250px; height:150px; z-index:13; overflow:auto; background-color:#AACCAA;\"";
  else :
     $actioncontainerDivPos = "";
?>
   <style type="text/css">
     #actioncontainer { position:absolute; top:100px; left:450px; width:700px; height:700px; z-index:12; background-color:#AACCAA; }
     #calendarcontainer { position:absolute; top:100px; left:650px; width:180px; height:190px; z-index:13; background-color:#AAAACC; }
     #servicefiltercontainer { position:absolute; top:100px; left:950px; width:150px; height:250px; z-index:13; background-color:#AACCAA; }
     #itemsortcontainer { position:absolute; top:110px; left:100px; width:500px; height:800px; z-index:14; background-color:#AACCAA; }
     #menuselectioncontainer { position:absolute; top:100px; left:100px; width:250px; height:150px; z-index:13; background-color:#AACCAA; }
     html>body #actioncontainer { position: fixed; }
   </style>
   <!--[if lt IE 7]>
   <style type="text/css">
     @media screen {
       html, body {
         height: 100%; overflow-y: hidden;
       }
       #scrollcontainer {
         height: 100%; width: 100%; overflow: auto;
       }
     }
   </style>
   <![endif]-->
<?php   
  endif;
?>

<style type="text/css">
  #itemsort_sortable { list-style-type: none; margin: 0; padding: 0; }
  #itemsort_sortable li { margin: 3px 3px 3px 10px; padding: 0.4em; padding-left: 1.5em; font-size: 8pt; height: 90px; width: 450px; background-color:#88BB88; color: #000000; }
</style>

</head>

<body onLoad="<?php echo $phpCurrentNavigationOnLoad ?>execBodyOnLoad();">

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

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

<form name="vehicledisposition" action="../admin/vehicle_disposition.php" method="post">
  <input type="hidden" name="f_act" value="">
  <?php // echo $phpCurrentNavigationInputHidden ?>
  <input type="hidden" name="deactivateMenu" value="<?php echo ec($deactivateMenu) ?>">

  <input type="hidden" name="f_actionObjType" value="<?php echo $f_actionObjType ?>">
  <input type="hidden" name="f_actionObjId" value="<?php echo $f_actionObjId ?>">
  <input type="hidden" name="f_actionID" value="<?php echo $f_actionID ?>">
  
  <input type="hidden" name="dateSelectionByCalendar" value="">
  <input type="hidden" name="restrictedAccess" value="<?php echo $restrictedAccess ?>">

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


  <!-- Disposition menu -->
  <?php echo $outputMenu ?>

  <!-- Container eco -->
  <?php echo $outputEco ?>

  <!-- Container vehicle -->
  <?php echo $outputVehicle ?>

  <!-- Container for actions -->
  <div id="actioncontainer" <?php echo $actioncontainerDivPos ?>>
  	<input type="hidden" name="actionObjType" value="">
  	<input type="hidden" name="actionObjId" value="">
  	
  	<?php echo defineButtonType08("Schließen", "action_actioncontainer_close", "myhide('actioncontainer');", "100", "", "") ?>
  	<?php echo htmlDivLineSpacer("30px"); ?>
  	
  	<div style="float:left;width:40px;height:100%">
  		&nbsp;
    </div>
    <div>
  	  <div id="ac_title"></div>
  	  <?php echo htmlDivLineSpacer("20px"); ?>
  	  <div id="ac_description"></div>
  	  <?php echo htmlDivLineSpacer("10px"); ?>
  	  <div id="ac_01"></div>
  	  <?php echo htmlDivLineSpacer("5px"); ?>
  	  <div id="ac_02"></div>
  	  <?php echo htmlDivLineSpacer("5px"); ?>
  	  <div id="ac_03"></div>
  	  <?php echo htmlDivLineSpacer("5px"); ?>
  	  <div id="ac_04"></div>
  	  <?php echo htmlDivLineSpacer("5px"); ?>
  	  <div id="ac_05"></div>
  	  <?php echo htmlDivLineSpacer("5px"); ?>
  	  <div id="ac_06"></div>
  	  <?php echo htmlDivLineSpacer("5px"); ?>
  	  <div id="ac_07"></div>
  	  <?php echo htmlDivLineSpacer("5px"); ?>
  	  <div id="ac_08"></div>
  	  <?php echo htmlDivLineSpacer("5px"); ?>
  	  <div id="ac_09"></div>
  	  <?php echo htmlDivLineSpacer("5px"); ?>
  	  <div id="ac_10"></div>
  	  <?php echo htmlDivLineSpacer("5px"); ?>
  	  <div id="ac_11"></div>
  	  <?php echo htmlDivLineSpacer("5px"); ?>
  	  <div id="ac_12"></div>
  	  <?php echo htmlDivLineSpacer("5px"); ?>
  	  <div id="ac_13"></div>
  	  <?php echo htmlDivLineSpacer("5px"); ?>
  	  <div id="ac_14"></div>
  	  <?php echo htmlDivLineSpacer("5px"); ?>
  	  <div id="ac_15"></div>
  	  <?php echo htmlDivLineSpacer("5px"); ?>
  	  <div id="ac_16"></div>
  	  <?php echo htmlDivLineSpacer("5px"); ?>
  	</div>
  </div>

  <!-- Container for menu entries -->
  <div id="menuselectioncontainer" <?php echo $menuselectioncontainerDivPos ?>>
  	<div id="menuselection" style="text-align:center; vertical-align:middle;"></div>
    <?php  	
      // Menu selections
      if ($userTypeName == "hq") :
         $outMenuSelection = "<table>";
         // Headquarters checkboxes
         if (authCheckEmployeeRights($emp_id, "10")) :
            $outMenuSelection .= "<tr>\n";
            $outMenuSelection .= "<td>" . getLngt("Niederlassung") . ":</td>\n";
            $outMenuSelection .= "<td><select class=\"f8np1\" name=\"f_hq_id\" id=\"f_hq_id\" onChange=\"finishPage('');\">\n";
            $outMenuSelection .= getHeadquartersOptions(array($f_hq_id), $f_hq_id);   // Attention: $f_hq_id is converted to an array !!!!
            $outMenuSelection .= "</select></td>\n";
            $outMenuSelection .= "<tr>\n";
         endif;
         // Group selection (all groups with state "read only" will be displayed)
         $outMenuSelection .= "<tr>\n";
         $outMenuSelection .= "<td>" . getLngt("Gruppe") . ":</td>\n";
         $outMenuSelection .= "<td><select class=\"f8np1\" name=\"grpId\" id=\"grpId\" onChange=\"finishPage('');\">\n";
         $outMenuSelection .= "  <option value=\"\"" . ($parMaskDispositionGroup == "" ? "selected" : "") . ">" . getLngt("----") . "</option>\n";
         $outMenuSelection .=    addOptionsFromTable("groups AS grp","grp.grp_id","grp.grp_name","grp.grp_id","grp.md_id = '" . $md_id . "' AND grp.grp_readonly = '1'",$parMaskDispositionGroup);
         $outMenuSelection .= "</select></td>\n";
         $outMenuSelection .= "<tr>\n";
         /*
         // Customer selection
         $outMenuSelection .= "<tr>\n";
         $outMenuSelection .= "<td>" . getLngt("Kunde") . ":</td>\n";
         $outMenuSelection .= "<td><select class=\"f8np1\" name=\"csId\" id=\"csId\" onChange=\"finishPage('');\">\n";
         $outMenuSelection .= "  <option value=\"\"" . ($parMaskDispositionCustomer == "" ? "selected" : "") . ">" . getLngt("----") . "</option>\n";
         // OLD: Get all customers
         // OLD: Attention: In getSQLMandatorArray(array($f_hq_id)) the argument is converted to an array !!!! 
         // OLD: $outMenuSelection .=    addOptionsFromTable("customer AS cs, company AS cmp","cs.cs_id","cmp.cmp_comp","cmp.cmp_comp","cs.hq_id IN " . getSQLMandatorArray(array($f_hq_id)) . " AND cmp.cmp_id = cs.cmp_id AND cmp.cmp_comp != 'EXTERN' AND cs.cs_id_parent != '0' AND NOT isnull(cs.cs_id_parent) ",$parMaskDispositionCustomer);
         // Get customers associated to the selected group only
         $outMenuSelection .=    addOptionsFromTable("customer AS cs, company AS cmp","cs.cs_id","cmp.cmp_comp","cmp.cmp_comp","cs.hq_id IN " . getSQLMandatorArray(array($f_hq_id)) . " AND cmp.cmp_id = cs.cmp_id AND cmp.cmp_comp != 'EXTERN' AND cs.cs_id_parent != '0' AND NOT isnull(cs.cs_id_parent) AND cs.cs_group LIKE '%," . $parMaskDispositionGroup . ",%'",$parMaskDispositionCustomer);
         $outMenuSelection .= "</select></td>\n";
         $outMenuSelection .= "<tr>\n";
         */
         $outMenuSelection .= "</table>";
         echo $outMenuSelection;
      endif;
    ?>
  	<?php echo htmlDivLineSpacer("5px"); ?>
  	<div style="text-align:center; vertical-align:middle;"><input type="button" name="close_menuSelection" value="<?php echo "Schließen" ?>" onClick="callMenuSelection();"></div>
  </div>

  <!-- Container for calendar -->
  <div id="calendarcontainer" <?php echo $calendarcontainerDivPos ?>>
  	<div id="calendar" style="text-align:center; vertical-align:middle;"></div>
  	<?php echo htmlDivLineSpacer("5px"); ?>
  	<div style="text-align:center; vertical-align:middle;"><input type="button" name="close_calendar" value="<?php echo "Schließen" ?>" onClick="callCalendar();"></div>
  </div>

  <!-- Container for service filter -->
  <div id="servicefiltercontainer" <?php echo $servicefiltercontainerDivPos ?>>
  	<div id="servicefilter" style="text-align:center; vertical-align:middle;"></div>
    <?php  	
      // Services checkboxes
      echo getLngt("Dienstleistung(en)") . "<br>";
      echo addCheckboxesFromTable("f_services","metatype","mt_sort","mt_mapped_value","mt_sort","mt_type = 'service' AND mt_objtype = '' AND mt_objid = '0' AND mt_sort != '1'",$f_services, "<br>");
    ?>
  	<?php echo htmlDivLineSpacer("5px"); ?>
  	<div style="text-align:center; vertical-align:middle;"><input type="button" name="close_servicefilter" value="<?php echo "Schließen" ?>" onClick="callServiceFilter();"></div>
  </div>

  <!-- Container for item sort -->
  <div id="itemsortcontainer" <?php echo $itemsortcontainerDivPos ?>>
  	<div style="text-align:center; vertical-align:middle;">
      <input type="hidden" id="itemsort_crvh" name="itemsort_crvh" value="">
      <input type="hidden" id="itemsort_num_of_ecos" name="itemsort_num_of_ecos" value="">
  		<input type="button" name="close_itemsort" value="<?php echo "Schließen" ?>" onClick="callItemSort();">&nbsp;&nbsp;&nbsp;&nbsp;
  		<input type="button" name="store_itemsort" value="<?php echo "Speichern" ?>" onClick="finishPageItemSort();">
  	</div>
  	<div id="itemsort" style="text-align:left; vertical-align:middle;">
      <ul id="itemsort_sortable">
      </ul>
  	</div>
  </div>

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

</html>