<?php
/*=======================================================================
 *
 * inc_vehicle.inc.php
 *
 * Autor: Marc Vollmann
 *
 * Functions for vehicles
 *
 =======================================================================*/   


include_once ("../include/inc_services.inc.php");
include_once ("../include/inc_job.inc.php");


// Returns the statement for a vehicle list
function getStmtVehicleList ($whereClause = "", $orderByClause = "") {
  $retStmt = "";
  if ($whereClause != "") : $whereClause = " AND " . $whereClause; endif;
  if ($orderByClause != "") : $orderByClause = " ORDER BY " . $orderByClause; endif;
  $retStmt = "SELECT crvh.crvh_id, crvh.vht_id, crvh.cr_id, crvh.crvh_id_inv, crvh.crvh_sort, crvh.crvh_sid, crvh.crvh_comm_no,"
             . "     crvh.crvh_vh_sign, crvh.crvh_vh_name, crvh.crvh_licence_date, crvh.crvh_owner, crvh.crvh_env_badge_level, crvh.crvh_prov,"
             . "     crvh.crvh_payload, crvh.crvh_totalweight, crvh.crvh_length, crvh.crvh_width,"
             . "     crvh.crvh_height, crvh.crvh_position, crvh.crvh_aperture_height_side, crvh.crvh_aperture_height_rear, crvh.crvh_mobile, crvh.crvh_insurance_name,"
             . "     crvh.crvh_insurance_no, crvh.crvh_filter, crvh.crvh_service, crvh.crvh_remark, crvh.crvh_freetext_1, crvh.crvh_special,"
             . "     crvh.crvh_funding_state, crvh.crvh_funding_final_installment, crvh.crvh_funding_residual_value, crvh.crvh_pda_usage, crvh.crvh_system_fee, crvh.crvh_drivetype,"
             . "     crvh.crvh_partner_premium, crvh.crvh_partner_text, crvh.crvh_partner_commission, crvh.crvh_advertising_allowance, crvh.crvh_transport_insurance_amount,"
             . "     crvh.crvh_transport_insurance_date, crvh.crvh_business_liability_insurance_amount, crvh.crvh_business_liability_insurance_date, crvh.crvh_system_fee_amount"
             . " FROM couriervehicle AS crvh, courier AS cr"
             . " WHERE cr.cr_id = crvh.cr_id " .$whereClause
             .   $orderByClause;
  return $retStmt;
}

// Returns the statement to get the data of a special vehicle
function getStmtVehicle ($crvhId, $whereClause = "", $orderByClause = "") {
  $retStmt = "";
  if ($crvhId != "" && is_numeric($crvhId)) :
     if ($whereClause != "") : $whereClause = " AND " . $whereClause; endif;
     if ($orderByClause != "") : $orderByClause = " ORDER BY " . $orderByClause; endif;
     $retStmt = "SELECT crvh.crvh_id, crvh.vht_id, crvh.cr_id, crvh.crvh_id_inv, crvh.crvh_sort, crvh.crvh_sid, crvh.crvh_comm_no,"
                . "     crvh.crvh_vh_sign, crvh.crvh_vh_name, crvh.crvh_licence_date, crvh.crvh_owner, crvh.crvh_env_badge_level, crvh.crvh_prov,"
                . "     crvh.crvh_payload, crvh.crvh_totalweight, crvh.crvh_length, crvh.crvh_width,"
                . "     crvh.crvh_height, crvh.crvh_position, crvh.crvh_aperture_height_side, crvh.crvh_aperture_height_rear, crvh.crvh_mobile, crvh.crvh_insurance_name,"
                . "     crvh.crvh_insurance_no, crvh.crvh_filter, crvh.crvh_service, crvh.crvh_remark, crvh.crvh_freetext_1,"
                . "     crvh.crvh_corporate_identity, crvh.crvh_special, crvh.crvh_vhd_disabled,"
                . "     crvh.crvh_funding_state, crvh.crvh_funding_final_installment, crvh.crvh_funding_residual_value, crvh.crvh_pda_usage, crvh.crvh_system_fee, crvh.crvh_drivetype,"
                . "     crvh.crvh_partner_premium, crvh.crvh_partner_text, crvh.crvh_partner_commission, crvh.crvh_advertising_allowance, crvh.crvh_transport_insurance_amount,"
                . "     crvh.crvh_transport_insurance_date, crvh.crvh_business_liability_insurance_amount, crvh.crvh_business_liability_insurance_date, crvh.crvh_system_fee_amount"
                . " FROM couriervehicle AS crvh, courier AS cr"
                . " WHERE crvh.crvh_id = '" . $crvhId . "' AND cr.cr_id = crvh.cr_id " .$whereClause
                .   $orderByClause;
  endif;
  return $retStmt;
}

// Returns the statement to get the vehicle-customer relation(s)
function getStmtCustomerVehicleRelation ($crvhId, $csId, $whereClauseCalled = "", $orderByClause = "") {
  $retStmt = "";
  if (($crvhId != "" && is_numeric($crvhId)) || ($csId != "" && is_numeric($csId))) :
     $whereClause = "";
     if ($crvhId != "") :
        $whereClause .= "csvh.crvh_id = '" . $crvhId . "'";
     endif;
     if ($csId != "") : 
        if ($whereClause != "") : $whereClause .= " AND "; endif;
        $whereClause .= "csvh.cs_id = '" . $csId . "'";
     endif;
     if ($whereClauseCalled != "") : $whereClause .= " AND " . $whereClauseCalled; endif;
     if ($orderByClause != "") : $orderByClause = " ORDER BY " . $orderByClause; endif;

     $retStmt = "SELECT crvh.crvh_id, crvh.crvh_sid, crvh.crvh_service, crvh.cr_id, cmp.cmp_comp, cmp.cmp_comp2, cs.cs_id, cs.cs_eid,"
                . "     cs.hq_id, csvh.csvh_relation, csvh.csvh_day_times, csvh.csvh_description, usr.usr_id, usr.usr_name, usr.usr_firstname"
                . " FROM customervehicle AS csvh, couriervehicle AS crvh, customer AS cs, company AS cmp, courier AS cr, user AS usr"
                . " WHERE " . $whereClause . "        AND"
                . "       crvh.crvh_id = csvh.crvh_id AND"
                . "       cs.cs_id = csvh.cs_id       AND"
                . "       cmp.cmp_id = cs.cmp_id      AND"
                . "       crvh.cr_id = cr.cr_id       AND"
                . "       cr.usr_id = usr.usr_id"
                . " " . $orderByClause;
  endif;
  return $retStmt;
}

// Returns the statement to get the start timeslot of a specified job
function getStmtVehicledispositionData ($jbId, $crvhId, $currday, $orderByClause = "") {
  $retStmt = "";
  if (($jbId != "" && is_numeric($jbId)) || ($crvhId != "" && is_numeric($crvhId) && $currday != "")) :
     $whereClause = "";
     if ($jbId != "") :
        $whereClause .= "vhd.jb_id = '" . $jbId . "' AND ";
     endif;
     if ($crvhId != "") :
         $whereClause .= "vhd.crvh_id = '" . $crvhId . "' AND LEFT(vhd_timeslot, 10) = '" . $currDay . "' AND ";
     endif;
     if ($orderByClause != "") : $orderByClause = " ORDER BY " . $orderByClause; endif;
     $retStmt = "SELECT vhd.vhd_timeslot, vhd.crvh_id"
                . " FROM  vehicledisposition AS vhd, couriervehicle AS crvh"
                . " WHERE " . $whereClause
                . "       vhd.crvh_id = crvh.crvh_id"
                . " " . $orderByClause;
  endif;
  return $retStmt;
}

// Returns the statement to get available capacities
function getStmtVehicleCapacityData ($whereClause, $orderByClause = "", $maxLimitOfRows = "", $fieldClause = "") {
  $retStmt = "";
  if ($whereClause != "") :
     if ($orderByClause != "") : $orderByClause = " ORDER BY " . $orderByClause; endif;
     if ($fieldClause != "") : $fieldClause = ", " . $fieldClause; endif;
     $limitClause = "";
     if ($maxLimitOfRows != "" && is_numeric($maxLimitOfRows)) :
        $limitClause = "LIMIT 0," . $maxLimitOfRows;
     endif;
     /*
     // Statement without relation to "customervehicle"
     $retStmt = "SELECT vha.vha_day, vha.crvh_id, vhat.vhat_daytime, vhat.vhat_timeunits, vhat.vhat_starttimeunit, crvh.crvh_service" . $fieldClause
                . " FROM vehicleavailability AS vha, vehicleavailabilitytimeunits AS vhat, couriervehicle AS crvh"
                . " WHERE vha.vha_id = vhat.vha_id AND vha.crvh_id = crvh.crvh_id AND " . $whereClause
                . " " . $orderByClause . " " . $limitClause;
     */
     $retStmt = "SELECT vha.vha_day, vha.crvh_id, vhat.vhat_daytime, vhat.vhat_timeunits, vhat.vhat_starttimeunit, crvh.crvh_service" . $fieldClause
                . " FROM vehicleavailability AS vha, vehicleavailabilitytimeunits AS vhat, couriervehicle AS crvh, customervehicle AS csvh"
                . " WHERE vha.vha_id = vhat.vha_id AND vha.crvh_id = crvh.crvh_id AND crvh.crvh_id = csvh.crvh_id AND " . $whereClause
                . " " . $orderByClause . " " . $limitClause;
  endif;
  return $retStmt;
}

// *************************************************************************************************************************

// Gets a vehicle list according to the where clause
function getVehicleList ($whereClause = "", $orderByClause = "") {
	global $db, $PHP_SELF;
	global $f_hq_id;
	$retArray = array();  
  $sqlquery = getStmtVehicleList($whereClause, $orderByClause);
  $result = $db->query($sqlquery);
  if (DB::isError($result)):
     $retArray = array("202","<err_no>202</err_no>\n","<err_desc>" . getLngt("Datenbankfehler") . "</err_desc>\n");
  else:
     while ($row = $result->fetch_assoc()):
           $retArray[] = array($row["crvh_id"], $row["vht_id"], $row["cr_id"], $row["crvh_sort"], $row["crvh_sid"], $row["crvh_comm_no"], $row["crvh_vh_sign"], $row["crvh_vh_name"],
                               $row["crvh_licence_date"], $row["crvh_owner"], $row["crvh_owner"], $row["crvh_env_badge_level"], $row["crvh_prov"], $row["crvh_payload"],
                               $row["crvh_totalweight"], $row["crvh_length"], $row["crvh_width"], $row["crvh_height"], $row["crvh_position"], $row["crvh_aperture_height_side"], 
                               $row["crvh_aperture_height_rear"], $row["crvh_mobile"], $row["crvh_insurance_name"], $row["crvh_insurance_no"], $row["crvh_filter"], $row["crvh_remark"], 
                               $row["crvh_freetext_1"], $row["crvh_special"], $row["crvh_service"], $row["crvh_id_inv"], $row["crvh_pda_usage"], $row["crvh_system_fee"], $row["crvh_drivetype"],
                               $row["crvh_partner_premium"], $row["crvh_partner_text"], $row["crvh_partner_commission"], $row["crvh_advertising_allowance"], $row["crvh_transport_insurance_amount"],
                               $row["crvh_transport_insurance_date"], $row["crvh_business_liability_insurance_amount"], $row["crvh_business_liability_insurance_date"], $row["crvh_system_fee_amount"]);
     endwhile;
     $result->free();
  endif;
	return $retArray;
}

// Gets ALL data from a special vehicle
function getVehicle ($crvhId, $whereClause = "", $orderByClause = "", $retMode = "") {
	global $db, $PHP_SELF;
	global $emp_id, $usr_id, $hq_id, $f_hq_id;

	$retArray = array();	

	// Global parameters will be defined by default
	if ($retMode == "") :
     global $f_crvh_id,$f_vht_id,$f_crvh_sort,$f_crvh_id_inv,$f_crvh_sid,$f_crvh_comm_no,$f_crvh_vh_sign,$f_crvh_vh_name,$f_crvh_licence_date,$f_crvh_licence_date_year;
     global $f_crvh_licence_date_month,$f_crvh_owner,$f_crvh_owner_month,$f_crvh_owner_year,$f_crvh_env_badge_level,$f_crvh_prov,$f_crvh_payload,$f_crvh_totalweight;
     global $f_crvh_length,$f_crvh_width,$f_crvh_height,$f_crvh_position,$f_crvh_aperture_height_side,$f_crvh_aperture_height_rear,$f_crvh_mobile;
     global $f_crvh_insurance_name,$f_crvh_insurance_no,$f_crvh_filter,$f_crvh_service, $f_crvh_vhd_disabled;
     global $f_crvh_remark,$f_crvh_freetext_1,$f_crvh_special,$f_crvh_corporate_identity,$f_crvh_funding_state, $f_crvh_funding_residual_value;
     global $f_crvh_funding_final_installment, $f_crvh_funding_final_installment_month, $f_crvh_funding_final_installment_year;
     global $f_crvh_pda_usage, $f_crvh_system_fee, $f_crvh_drivetype;
     global $f_crvh_partner_premium, $f_crvh_partner_text, $f_crvh_partner_commission, $f_crvh_advertising_allowance, $f_crvh_transport_insurance_amount;
     global $f_crvh_transport_insurance_date, $f_crvh_business_liability_insurance_amount, $f_crvh_business_liability_insurance_date, $f_crvh_system_fee_amount;
	endif;

  // Mandator filter
  if ($f_hq_id == "") : $f_hq_id = array(); endif;
  if (count($f_hq_id) == 0) : array_push($f_hq_id, $hq_id); endif;

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

     // Get statement
     $sqlquery = getStmtVehicle($crvhId, $whereClause, $orderByClause);

     $result = $db->query($sqlquery);
     if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
     while ($row = $result->fetch_assoc()):
           if ($retMode == "1") :
              $retArray["crvh_id"]                                  = $row["crvh_id"];
              $retArray["vht_id"]                                   = $row["vht_id"];
              $retArray["crvh_id_inv"]                              = $row["crvh_id_inv"];
              $retArray["crvh_sort"]                                = $row["crvh_sort"];
              $retArray["crvh_sid"]                                 = $row["crvh_sid"];
              $retArray["crvh_comm_no"]                             = $row["crvh_comm_no"];
              $retArray["crvh_vh_sign"]                             = $row["crvh_vh_sign"];
              $retArray["crvh_vh_name"]                             = $row["crvh_vh_name"];
              $retArray["crvh_licence_date"]                        = $row["crvh_licence_date"];
              $retArray["crvh_licence_date_year"]                   = substr($row["crvh_licence_date"], 0, 4);
              $retArray["crvh_licence_date_month"]                  = substr($row["crvh_licence_date"], 5, 2);
              $retArray["crvh_owner"]                               = $row["crvh_owner"];
              $retArray["crvh_owner_year"]                          = substr($row["crvh_owner"], 0, 4);
              $retArray["crvh_owner_month"]                         = substr($row["crvh_owner"], 5, 2);
              $retArray["crvh_env_badge_level"]                     = $row["crvh_env_badge_level"];
              $retArray["crvh_prov"]                                = $row["crvh_prov"];
              $retArray["crvh_payload"]                             = $row["crvh_payload"];
              $retArray["crvh_totalweight"]                         = $row["crvh_totalweight"];
              $retArray["crvh_length"]                              = $row["crvh_length"];
              $retArray["crvh_width"]                               = $row["crvh_width"];
              $retArray["crvh_height"]                              = $row["crvh_height"];
              $retArray["crvh_position"]                            = $row["crvh_position"];
              $retArray["crvh_aperture_height_side"]                = $row["crvh_aperture_height_side"];
              $retArray["crvh_aperture_height_rear"]                = $row["crvh_aperture_height_rear"];
              $retArray["crvh_mobile"]                              = $row["crvh_mobile"];
              $retArray["crvh_insurance_name"]                      = $row["crvh_insurance_name"];
              $retArray["crvh_insurance_no"]                        = $row["crvh_insurance_no"];
              $retArray["crvh_filter"]                              = $row["crvh_filter"];
              $retArray["crvh_service"]                             = $row["crvh_service"];
              $retArray["crvh_remark"]                              = $row["crvh_remark"];
              $retArray["crvh_freetext_1"]                          = $row["crvh_freetext_1"];
              $retArray["crvh_special"]                             = $row["crvh_special"];
              $retArray["crvh_vhd_disabled"]                        = $row["crvh_vhd_disabled"];
              $retArray["crvh_corporate_identity"]                  = $row["crvh_corporate_identity"];
              $retArray["crvh_funding_state"]                       = $row["crvh_funding_state"];
              $retArray["crvh_funding_residual_value"]              = $row["crvh_funding_residual_value"];
              $retArray["crvh_funding_final_installment"]           = $row["crvh_funding_final_installment"];
              $retArray["crvh_funding_final_installment_year"]      = substr($row["crvh_licence_date"], 0, 4);
              $retArray["crvh_funding_final_installment_month"]     = substr($row["crvh_licence_date"], 5, 2);
              $retArray["crvh_pda_usage"]                           = $row["crvh_pda_usage"];
              $retArray["crvh_system_fee"]                          = $row["crvh_system_fee"];
              $retArray["crvh_drivetype"]                           = $row["crvh_drivetype"];
              $retArray["crvh_partner_premium"]                     = $row["crvh_partner_premium"];
              $retArray["crvh_partner_text"]                        = $row["crvh_partner_text"];
              $retArray["crvh_partner_commission"]                  = $row["crvh_partner_commission"];
              $retArray["crvh_advertising_allowance"]               = $row["crvh_advertising_allowance"];
              $retArray["crvh_transport_insurance_amount"]          = $row["crvh_transport_insurance_amount"];
              $retArray["crvh_transport_insurance_date"]            = $row["crvh_transport_insurance_date"];
              $retArray["crvh_business_liability_insurance_amount"] = $row["crvh_business_liability_insurance_amount"];
              $retArray["crvh_business_liability_insurance_date"]   = $row["crvh_business_liability_insurance_date"];
              $retArray["crvh_system_fee_amount"]                   = $row["crvh_system_fee_amount"];
           else :
              // $retMode == "" <=> default <=> set global parameters
              $f_crvh_id                                  = $row["crvh_id"];
              $f_vht_id                                   = $row["vht_id"];
              $f_crvh_id_inv                              = $row["crvh_id_inv"];
              $f_crvh_sort                                = $row["crvh_sort"];
              $f_crvh_sid                                 = $row["crvh_sid"];
              $f_crvh_comm_no                             = $row["crvh_comm_no"];
              $f_crvh_vh_sign                             = $row["crvh_vh_sign"];
              $f_crvh_vh_name                             = $row["crvh_vh_name"];
              $f_crvh_licence_date                        = $row["crvh_licence_date"];
              $f_crvh_licence_date_year                   = substr($f_crvh_licence_date, 0, 4);
              $f_crvh_licence_date_month                  = substr($f_crvh_licence_date, 5, 2);
              $f_crvh_owner                               = $row["crvh_owner"];
              $f_crvh_owner_year                          = substr($f_crvh_owner, 0, 4);
              $f_crvh_owner_month                         = substr($f_crvh_owner, 5, 2);
              $f_crvh_env_badge_level                     = $row["crvh_env_badge_level"];
              $f_crvh_prov                                = $row["crvh_prov"];
              $f_crvh_payload                             = $row["crvh_payload"];
              $f_crvh_totalweight                         = $row["crvh_totalweight"];
              $f_crvh_length                              = $row["crvh_length"];
              $f_crvh_width                               = $row["crvh_width"];
              $f_crvh_height                              = $row["crvh_height"];
              $f_crvh_position                            = $row["crvh_position"];
              $f_crvh_aperture_height_side                = $row["crvh_aperture_height_side"];
              $f_crvh_aperture_height_rear                = $row["crvh_aperture_height_rear"];
              $f_crvh_mobile                              = $row["crvh_mobile"];
              $f_crvh_insurance_name                      = $row["crvh_insurance_name"];
              $f_crvh_insurance_no                        = $row["crvh_insurance_no"];
              $f_crvh_filter                              = $row["crvh_filter"];
              $f_crvh_service                             = $row["crvh_service"];
              $f_crvh_remark                              = $row["crvh_remark"];
              $f_crvh_freetext_1                          = $row["crvh_freetext_1"];
              $f_crvh_special                             = $row["crvh_special"];
              $f_crvh_vhd_disabled                        = $row["crvh_vhd_disabled"];
              $f_crvh_corporate_identity                  = $row["crvh_corporate_identity"];
              $f_crvh_funding_state                       = $row["crvh_funding_state"];
              $f_crvh_funding_residual_value              = $row["crvh_funding_residual_value"];
              $f_crvh_funding_final_installment           = $row["crvh_funding_final_installment"];
              $f_crvh_funding_final_installment_year      = substr($f_crvh_funding_final_installment, 0, 4);
              $f_crvh_funding_final_installment_month     = substr($f_crvh_funding_final_installment, 5, 2);
              $f_crvh_pda_usage                           = $row["crvh_pda_usage"]; 
              $f_crvh_system_fee                          = $row["crvh_system_fee"];
              $f_crvh_drivetype                           = $row["crvh_drivetype"];
              $f_crvh_partner_premium                     = $row["crvh_partner_premium"];
              $f_crvh_partner_text                        = $row["crvh_partner_text"];
              $f_crvh_partner_commission                  = $row["crvh_partner_commission"];
              $f_crvh_advertising_allowance               = $row["crvh_advertising_allowance"];
              $f_crvh_transport_insurance_amount          = $row["crvh_transport_insurance_amount"];
              $f_crvh_transport_insurance_date            = $row["crvh_transport_insurance_date"];
              $f_crvh_business_liability_insurance_amount = $row["crvh_business_liability_insurance_amount"];
              $f_crvh_business_liability_insurance_date   = $row["crvh_business_liability_insurance_date"];
              $f_crvh_system_fee_amount                   = $row["crvh_system_fee_amount"];
           endif;
     endwhile;
     $result->free();
  endif;

	return $retArray;
}


// Gets potential restriction regarding to the availibility of the specified vehicle for the specified day (and perhaps for the specified customer)
// Returns an array with the daytimes and their associated zones
function getDaytimeAvailabilityOfVehicle ($crvhId, $weekDay, $csId, $mode = "") {
  $retArray = array();
  if ($crvhId != "" && is_numeric($crvhId) && $weekDay != "" && is_numeric($weekDay) && $csId != "" && is_numeric($csId)) :
  
     // Get the customer-vehicle-relation if does exist
     $csvhDayTimesString = getFieldValueFromClause("customervehicle","csvh_day_times","crvh_id = '" . $crvhId . "' AND cs_id = '" . $csId . "' AND csvh_relation = '1'");
     // getStmtCustomerVehicleRelation($crvhId, $csId, ....);  // Could be called, too...

     if ($csvhDayTimesString != "") :

        // Get array of day times (default, no mt_objtype and no mt_objid)
        // $dayTimes = getColVectorFromDB2ArrayByClause("metatype", "mt_sort", "mt_type = 'day_time' AND mt_objtype = 'cs' AND mt_objid = '" . $csId . "'", "", "mt_sort", "");
        // $dayTimesLen = count($dayTimes);
        
        $dayTimesArrayOfTheWeek = getKeyValueArrayFromString($csvhDayTimesString, "|", "=");

        $tmpDayTimes = $dayTimesArrayOfTheWeek[$weekDay];
        $tmpDayTimesArray = spliti(",", $tmpDayTimes);
        $tmpDayTimesArrayLen = count($tmpDayTimesArray);

        for ($i = 0; $i < $tmpDayTimesArrayLen; $i++) :
            $tmp2 = spliti("-", $tmpDayTimesArray[$i]);
            if ($mode == "1") :               
               $retArray[$tmp2[0]] = $tmp2[1];    // $retArray[daytime] = zone;
            elseif ($mode == "2") :
               $retArray[$tmp2[1]][] = $tmp2[0];  // $retArray[zone][] = daytime;
            else :
               $retArray[] = array($tmp2[0], $tmp2[1]);  // Pair of daytime and zone
            endif;
        endfor;
     endif;
  endif;
  return $retArray;  // => e.g. array(array(0, 0), array(1, 2), array(2, 9999)) <=> Vormittags im Kerngebiet, nachmittags im Sekundärgebiet Süd und abends nicht aktiv
}


// Gets jobs for graphically disposition output
// 0. Gets all jobs out of the table "vehicledisposition" associated to the specified vehicle and day
// 1. Gets taken jobs by the couriers/vehicles
// 2. Gets finished jobs by the couriers/vehicles
// 3. Gets jobs NOT being associated to ANY vehicle for the selected day only
// Attention: There is no restriction against customer
function getVehicleJobList ($crvhId, $currDay, $timeUnitWidth, $mode = "0", $specialWhereClause = "") {
	global $db, $PHP_SELF, $debug;
	global $f_hq_id, $selDay, $selMonth, $selYear, $timeLineScalingFactor;

	$retArray = array();
  if (($crvhId != "" && is_numeric($crvhId) || $mode == "3") && $currDay != "") :
  
     if ($timeUnitWidth == "" || !is_numeric($timeUnitWidth)) : $timeUnitWidth = 11; endif;
     if ($timeLineScalingFactor == "") : $timeLineScalingFactor = 1; endif;

     $doContinue = false;
     $fromClause = "";
     $whereClause = "";
     $orderByClause = "";
     if ($mode == "0") :
        $jbIdArray = getColVectorFromDB2ArrayByClause("vehicledisposition", "jb_id", "crvh_id = '" . $crvhId . "' AND LEFT(vhd_timeslot, 10) = '" . $currDay . "' AND jb_id != '0'", "", "", "DISTINCT");
        $jbIdArrayLen = count($jbIdArray);
        if ($jbIdArrayLen > 0) :
           $jbIdString = implode(",", $jbIdArray);
           $whereClause .= " jb.jb_id IN (" . $jbIdString . ") AND";
           $doContinue = true;
        endif;
     elseif ($mode == "1") :
        $fromClause .= ", courier AS cr, couriervehicle AS crvh";
        $whereClause .= " jb.jb_status = '1' AND LEFT(jb.jb_ordertime, 10) = '" . $currDay . "' AND jb.cr_id = cr.cr_id AND cr.cr_sid = crvh.crvh_sid AND crvh.crvh_id = '" . $crvhId . "' AND";
        $doContinue = true;
     elseif ($mode == "2") :
        $fromClause .= ", couriervehicle AS crvh";
        $whereClause .= " jb.jb_status = '2' AND LEFT(jb.jb_ordertime, 10) = '" . $currDay . "' AND jb.cr_sid = crvh.crvh_sid AND crvh.crvh_id = '" . $crvhId . "' AND";
        $doContinue = true;
     elseif ($mode == "3") :
        $fromClause .= "";
        $whereClause .= " jb.jb_status = '9' AND LEFT(jb.jb_ordertime, 10) = '" . $currDay . "' AND jb.hq_id = '" . $f_hq_id . "' AND (NOT EXISTS (SELECT 1 FROM vehicledisposition AS vhd WHERE vhd.jb_id = jb.jb_id)) AND";
        $orderByClause .= "ad2_zipcode, jb_id";
        $doContinue = true;
     endif;

     if ($doContinue) :

        // Get parameter for special output structure
        $parMaskDispositionItemDisplayMode = getParameterValue("0", "MASK_DISPOSITION_ITEM_DISPLAY_MODE", $f_hq_id);
        if ($parMaskDispositionItemDisplayMode == "") :
           $parMaskDispositionItemDisplayMode = getParameterValue("0", "MASK_DISPOSITION_ITEM_DISPLAY_MODE", "0");
        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 parameter for special output
        $parMaskDispositionItemShowZipcode = getParameterValue("0", "MASK_DISPOSITION_ITEM_SHOW_ZIPCODE", $f_hq_id);
        if ($parMaskDispositionItemShowZipcode == "") :
           $parMaskDispositionItemShowZipcode = getParameterValue("0", "MASK_DISPOSITION_ITEM_SHOW_ZIPCODE", "0");
        endif;

        if ($specialWhereClause != "") : $whereClause .= $specialWhereClause; endif;
        if ($orderByClause == "") : $orderByClause = "RIGHT(jb.jb_ordertime,8)"; endif;

        $sqlquery = "SELECT jb.jb_id, jb.hq_id, jb.jb_timeunits, jb.jb_service, jb.cr_id, jb.cr_sid, jb.jb_ordertime, jb.jb_totalprice, jb.jb_serviceprice, jb.jb_cr_price, jb.jb_offer,"
                     . "    jb.jb_freetext_1, jb.jb_id_parent, tr.tr_comp, tr.tr_remark, tr2.tr_comp AS tr2_comp, tr2.tr_comp2 AS tr2_comp2, tr2.tr_remark AS tr2_remark, tr2.tr_phone AS tr2_phone,"
                     . "    ad.ad_street, tr.tr_hsno, tr.tr_floor, ad.ad_zipcode, ad.ad_city, ad2.ad_street AS ad2_street, tr2.tr_hsno AS tr2_hsno, tr2.tr_floor AS tr2_floor,"
                     . "    tr2.tr_person AS tr2_person, tr2.tr_mediationarea_name AS tr2_mediationarea_name,"
                     . "    ad2.ad_zipcode AS ad2_zipcode, ad2.ad_city AS ad2_city, csc.csc_id, csc.csc_name, csc.cs_id, tx.tx_value,"
                     . "    gdc1.gdc_content AS gdc1_content, gdc2.gdc_content AS gdc2_content, gdc3.gdc_content AS gdc3_content, gdc4.gdc_content AS gdc4_content"
                     . " FROM job AS jb LEFT JOIN tax AS tx ON tx.tx_id = jb.jb_sales_tax_rate"
                     . "                LEFT JOIN genericdatacontainer AS gdc1 ON gdc1.gdc_obj_id = jb.jb_id AND gdc1.gdc_obj_type = 'jb' AND gdc1.gdc_gen_fieldname = 'jb_service_job'"
                     . "                LEFT JOIN genericdatacontainer AS gdc2 ON gdc2.gdc_obj_id = jb.jb_id AND gdc2.gdc_obj_type = 'jb' AND gdc2.gdc_gen_fieldname = 'timewindow_name'"
                     . "                LEFT JOIN genericdatacontainer AS gdc3 ON gdc3.gdc_obj_id = jb.jb_id AND gdc3.gdc_obj_type = 'jb' AND gdc3.gdc_gen_fieldname = 'is_operative'"
                     . "                LEFT JOIN genericdatacontainer AS gdc4 ON gdc4.gdc_obj_id = jb.jb_id AND gdc4.gdc_obj_type = 'jb' AND gdc4.gdc_gen_fieldname = 'hide',"
                     . "      tour AS tr, address AS ad, tour AS tr2, address AS ad2, costcenter AS csc" . $fromClause
                     . " WHERE " . $whereClause
                     . "       (isnull(jb.jb_storno) OR jb.jb_storno = '0' OR jb.jb_storno = '1' OR jb.jb_storno = '3') AND"
                     . "       jb.jb_timeunits > '0'          AND"
                     . "       csc.csc_id = jb.csc_id_related AND"
                     . "       tr.jb_id = jb.jb_id            AND"
                     . "       tr.tr_sort = '1'               AND"
                     . "       tr.ad_id = ad.ad_id            AND"
                     . "       tr2.jb_id = jb.jb_id           AND"
                     . "       tr2.tr_sort = '2'              AND"
                     . "       tr2.ad_id = ad2.ad_id"
                     . " ORDER BY " . $orderByClause;
if ($debug) :
   if ($mode == "1") : echo $sqlquery . "<br><br>"; endif;
endif;
        $result = $db->query($sqlquery);
        $count = 0;
        while ($row = $result->fetch_assoc()):

              // Get tax value assotiated to the job
              $taxFactor = 1.19;  // Init
              if ($row["tx_value"] != "" && is_numeric($row["tx_value"])) :
                 $taxFactor = 1 + ($row["tx_value"] / 100);
              endif;
              $retArray[$count]["tax_factor"] = $taxFactor;
        
              $retArray[$count]["jb_id"] = $row["jb_id"];
              $retArray[$count]["hq_id"] = $row["hq_id"];
              $retArray[$count]["jb_id_parent"] = $row["jb_id_parent"];
              $retArray[$count]["jb_timeunits"] = $row["jb_timeunits"];
              $retArray[$count]["jb_service"] = $row["jb_service"];
              $retArray[$count]["jb_is_installation"] = (((int)$row["jb_service"] & 2) == 2 ? "1" : "0");
              $retArray[$count]["jb_totalprice"] = ($row["jb_totalprice"] * $taxFactor);
              $retArray[$count]["jb_serviceprice"] = ($row["jb_serviceprice"] * $taxFactor);
              $retArray[$count]["jb_cr_price"] = ($row["jb_cr_price"] * $taxFactor);
              $retArray[$count]["jb_offer"] = $row["jb_offer"];
              $retArray[$count]["jb_freetext_1"] = trim($row["jb_freetext_1"]);
              $retArray[$count]["cr_id"] = $row["cr_id"];
              $retArray[$count]["cr_sid"] = $row["cr_sid"];
              $retArray[$count]["csc_id"] = $row["csc_id"];
              $retArray[$count]["csc_name"] = $row["csc_name"];
              $retArray[$count]["cs_id"] = $row["cs_id"];
              $retArray[$count]["jb_ordertime"] = $row["jb_ordertime"];
              $retArray[$count]["ad2_street"] = $row["ad2_street"];
              $retArray[$count]["tr2_hsno"] = $row["tr2_hsno"];
              $retArray[$count]["tr2_floor"] = $row["tr2_floor"];
              $retArray[$count]["tr2_person"] = $row["tr2_person"];
              $retArray[$count]["ad2_zipcode"] = $row["ad2_zipcode"];
              $retArray[$count]["ad2_city"] = $row["ad2_city"];
              $retArray[$count]["tr2_comp"] = $row["tr2_comp"];
              $retArray[$count]["tr2_comp2"] = $row["tr2_comp2"];
              $retArray[$count]["tr_comp"] = $row["tr_comp"];
              $retArray[$count]["ad_street"] = $row["ad_street"];
              $retArray[$count]["tr_hsno"] = $row["tr_hsno"];
              $retArray[$count]["ad_zipcode"] = $row["ad_zipcode"];
              $retArray[$count]["ad_city"] = $row["ad_city"];
              $retArray[$count]["tr2_phone"] = $row["tr2_phone"];
              $retArray[$count]["gdc1_content"] = $row["gdc1_content"];
              $retArray[$count]["gdc2_content"] = $row["gdc2_content"];
              $retArray[$count]["jb_is_operative"] = $row["gdc3_content"];
              $retArray[$count]["jb_hide"] = $row["gdc4_content"];
              $retArray[$count]["tr2_mediationarea_name"] = $row["tr2_mediationarea_name"];

              // Get total weight of the job
              $retArray[$count]["trat_totalweight"] = getTratTotalweight($row["jb_id"]);
              // Get total weight of the job
              $retArray[$count]["trat_totalpieces"] = getTratPackingPieces($row["jb_id"]);

              // $retArray[$count]["mt_time_interval"] = getDaytimeTimeInterval($row["jb_ordertime"], $row["cs_id"]);
              // $retArray[$count]["mt_time_interval"] = getJobDaytimeTimeInterval($row["jb_ordertime"], trim($row["jb_freetext_1"]), $row["cs_id"], "");
              $retArray[$count]["mt_time_interval"] = substr($retArray[$count]["jb_freetext_1"],12);
              
              $itemLinePrefix = array();
              if ($parMaskDispositionItemShowZipcode == "1") :
                 $zipcodeLen = strlen($row["ad2_zipcode"]);
                 for ($i = 0; $i < $zipcodeLen; $i++) :
                     $itemLinePrefix[$i] = substr($row["ad2_zipcode"],$i,1) . "|";
                 endfor;
              endif;
              $itemLinePrefixLen = count($itemLinePrefix);

              // Get the parent level of the job
              /*
              $retArray[$count]["jb_parent_level"] = 0;
              if ($row["jb_id_parent"] != "" && $row["jb_id_parent"] != 0) :
                 // $retArray[$count]["jb_parent_level"] = getJobParentCascadeLevel($row["jb_id"]);         // Take the CURRENT JOB ID to check the cascade level
                 $retArray[$count]["jb_parent_level"] = getJobParentCascadeLevel($row["jb_id_parent"], 1);  // Take the PARENT JOB ID to check for the cascade level
              endif;
              */

              if ($mode == "3") : 
                 $ecoTimeUnits = 12;
              else :
                 $ecoTimeUnits = $row["jb_timeunits"];
                 if ($ecoTimeUnits == "" || !is_numeric($ecoTimeUnits)) : $ecoTimeUnits = 12; endif;
              endif;
              
              // Scaling of text output
              $absScaleOffset = 0;
              if ($parMaskDispositionItemDisplayMode == "1") :
                 if ($timeLineScalingFactor == 2) : $absScaleOffset = 0; endif;
                 if ($timeLineScalingFactor == 3) : $absScaleOffset = -5; endif;
                 if ($timeLineScalingFactor == 4) : $absScaleOffset = -5; endif;
                 if ($timeLineScalingFactor == 5) : $absScaleOffset = -11; endif;
              elseif ($parMaskDispositionItemDisplayMode == "2") :
                 if ($timeLineScalingFactor == 2) : $absScaleOffset = 1; endif;
                 if ($timeLineScalingFactor == 3) : $absScaleOffset = -1; endif;
                 if ($timeLineScalingFactor == 4) : $absScaleOffset = -5; endif;
                 if ($timeLineScalingFactor == 5) : $absScaleOffset = -11; endif;
              else :
                 if ($timeLineScalingFactor == 2) : $absScaleOffset = 1; endif;
                 if ($timeLineScalingFactor == 3) : $absScaleOffset = 1; endif;
                 if ($timeLineScalingFactor == 4) : $absScaleOffset = -5; endif;
                 if ($timeLineScalingFactor == 5) : $absScaleOffset = -7; endif;
              endif;
              $newStrLen = floor(((($ecoTimeUnits - 1) * $timeUnitWidth) * $timeLineScalingFactor) / 10) + $absScaleOffset;


              $ecoOutBodyDefault = "";
              if ($parMaskDispositionItemDisplayMode == "1") :
                 $ecoOutBodyDefault .= $retArray[$count]["tr2_comp"] . "<br>";
                 $ecoOutBodyDefault .= $row["tr2_mediationarea_name"] . "<br>";
                 $ecoOutBodyDefault .= $row["tr2_comp2"] . "<br>";
                 // $ecoOutBodyDefault .= $row["jb_timeunits"] . " " . getLngt("ZE") . "<br>";
                 $ecoOutBodyDefault .= number_format(round(($row["jb_totalprice"] * $taxFactor), 2), 2, ",", ".") . " €<br>";
                 $ecoOutBodyDefault .= number_format(round($retArray[$count]["trat_totalweight"], 2), 2, ",", ".") . " " . getLngt("KG");
              elseif ($parMaskDispositionItemDisplayMode == "2") :
                 $ecoOutBodyDefault .= ($itemLinePrefixLen > 0 ? "-|" : "") . $retArray[$count]["gdc2_content"] . "<br>";
                 $ecoOutBodyDefault .= $itemLinePrefix[0] . $row["tr2_comp"] . "<br>";
                 $ecoOutBodyDefault .= $itemLinePrefix[1] . $row["tr2_person"] . "<br>";
                 $ecoOutBodyDefault .= $itemLinePrefix[2] . $row["ad2_street"] . " " . $row["tr2_hsno"] . "<br>";
                 $ecoOutBodyDefault .= $itemLinePrefix[3] . $row["ad2_zipcode"] . " " . $row["ad2_city"] . "<br>";
                 $ecoOutBodyDefault .= $itemLinePrefix[4] . number_format(round($retArray[$count]["trat_totalweight"], 0), 0, ",", ".") . " " . getLngt("KG") . " / " . $retArray[$count]["trat_totalpieces"] . " " . getLngt("Stk.");
              else: 
                 $ecoOutBodyDefault .= ($itemLinePrefixLen > 0 ? "-|" : "") . $retArray[$count]["mt_time_interval"] . "<br>";
                 $ecoOutBodyDefault .= $itemLinePrefix[0] . $row["ad2_street"] . " " . $row["tr2_hsno"] . "<br>";
                 $ecoOutBodyDefault .= $itemLinePrefix[1] . $row["ad2_zipcode"] . " " . $row["ad2_city"] . "<br>";
                 $ecoOutBodyDefault .= $itemLinePrefix[2] . $row["jb_timeunits"] . " " . getLngt("ZE") . "<br>";
                 $ecoOutBodyDefault .= $itemLinePrefix[3] . number_format(round(($row["jb_totalprice"] * $taxFactor), 2), 2, ",", ".") . " €<br>";
                 $ecoOutBodyDefault .= $itemLinePrefix[4] . number_format(round($retArray[$count]["trat_totalweight"], 3), 3, ",", ".") . " " . getLngt("KG");
              endif;
              $retArray[$count]["eco_body_default"] = my_str_check_js($ecoOutBodyDefault);

              $ecoOutBody = "";
              if ($mode == "3") :
                 if ($parMaskDispositionItemDisplayMode == "1") :
                    $ecoOutBody .= $retArray[$count]["tr2_comp"] . "<br>";
                    $ecoOutBody .= substr($row["tr2_mediationarea_name"],0,20) . "<br>";
                    $ecoOutBody .= substr($row["tr2_comp2"],0,15) . "<br>";
                    // $ecoOutBody .= str_replace("§","&nbsp;",$row["jb_timeunits"] . "§" . getLngt("ZE")) . "<br>";
                    $ecoOutBody .= number_format(round(($row["jb_totalprice"] * $taxFactor), 2), 2, ",", ".") . " €<br>";
                    $ecoOutBody .= number_format(round($retArray[$count]["trat_totalweight"], 2), 2, ",", ".") . " " . getLngt("KG");
                 elseif ($parMaskDispositionItemDisplayMode == "2") :
                    $ecoOutBody .= ($itemLinePrefixLen > 0 ? "-|" : "") . $retArray[$count]["gdc2_content"] . "<br>";
                    $ecoOutBody .= str_replace("§","&nbsp;",$itemLinePrefix[0] . substr($row["tr2_comp"],0,20)) . "<br>";
                    $ecoOutBody .= str_replace("§","&nbsp;",$itemLinePrefix[1] . substr($row["tr2_person"],0,20)) . "<br>";
                    $ecoOutBody .= str_replace("§","&nbsp;",$itemLinePrefix[2] . str_replace(" ","§",substr($row["ad2_street"],0,15)) . "§" . substr($row["tr2_hsno"],0,5)) . "<br>";
                    $ecoOutBody .= str_replace("§","&nbsp;",$itemLinePrefix[3] . substr($row["ad2_zipcode"],0,5) . "§" . str_replace(" ","§",substr($row["ad2_city"],0,12))) . "<br>";
                    $ecoOutBody .= $itemLinePrefix[4] . number_format(round($retArray[$count]["trat_totalweight"], 0), 0, ",", ".") . " " . getLngt("KG") . " / " . $retArray[$count]["trat_totalpieces"] . " " . getLngt("Stk.");
                 else :
                    $ecoOutBody .= ($itemLinePrefixLen > 0 ? "-|" : "") . $retArray[$count]["mt_time_interval"] . "<br>";
                    $ecoOutBody .= str_replace("§","&nbsp;",$itemLinePrefix[0] . str_replace(" ","§",substr($row["ad2_street"],0,15)) . "§" . substr($row["tr2_hsno"],0,5)) . "<br>";
                    $ecoOutBody .= str_replace("§","&nbsp;",$itemLinePrefix[1] . substr($row["ad2_zipcode"],0,5) . "§" . str_replace(" ","§",substr($row["ad2_city"],0,12))) . "<br>";
                    $ecoOutBody .= str_replace("§","&nbsp;",$itemLinePrefix[2] . $row["jb_timeunits"] . "§" . getLngt("ZE")) . "<br>";
                    $ecoOutBody .= $itemLinePrefix[3] . number_format(round(($row["jb_totalprice"] * $taxFactor), 2), 2, ",", ".") . " €<br>";
                    $ecoOutBody .= $itemLinePrefix[4] . number_format(round($retArray[$count]["trat_totalweight"], 3), 3, ",", ".") . " " . getLngt("KG");
                 endif;
                 $retArray[$count]["eco_body"] = my_str_check_js($ecoOutBody);
              else :
                 if ($parMaskDispositionItemDisplayMode == "1") :
                    $ecoOutBody .= substr($retArray[$count]["tr2_comp"],0,$newStrLen) . "<br>";
                    $ecoOutBody .= str_replace("§","&nbsp;",substr(str_replace(" ","§",$row["tr2_mediationarea_name"]),0,$newStrLen)) . "<br>";
                    $ecoOutBody .= str_replace("§","&nbsp;",substr($row["tr2_comp2"],0,$newStrLen)) . "<br>";
                    // $ecoOutBody .= str_replace("§","&nbsp;",substr($row["jb_timeunits"] . "§" . getLngt("ZE"),0,$newStrLen)) . "<br>";
                    $ecoOutBody .= substr(number_format(round(($row["jb_totalprice"] * $taxFactor), 2), 2, ",", ".") . " €",0,$newStrLen) . "<br>";
                    $ecoOutBody .= substr(number_format(round($retArray[$count]["trat_totalweight"], 2), 2, ",", ".") . " " . getLngt("KG"),0,$newStrLen);
                 elseif ($parMaskDispositionItemDisplayMode == "2") :
                    $ecoOutBody .= substr(($itemLinePrefixLen > 0 ? "-|" : "") . $retArray[$count]["gdc2_content"],0,$newStrLen) . "<br>";
                    $ecoOutBody .= str_replace("§","&nbsp;",substr($itemLinePrefix[0] . $row["tr2_comp"],0,$newStrLen)) . "<br>";
                    $ecoOutBody .= str_replace("§","&nbsp;",substr($itemLinePrefix[1] . $row["tr2_person"],0,$newStrLen)) . "<br>";
                    $ecoOutBody .= str_replace("§","&nbsp;",substr($itemLinePrefix[2] . str_replace(" ","§",$row["ad2_street"]) . "§" . $row["tr2_hsno"],0,$newStrLen)) . "<br>";
                    $ecoOutBody .= str_replace("§","&nbsp;",substr($itemLinePrefix[3] . $row["ad2_zipcode"] . "§" . str_replace(" ","§",$row["ad2_city"]),0,$newStrLen)) . "<br>";
                    $ecoOutBody .= str_replace("§","&nbsp;",substr($itemLinePrefix[4] . number_format(round($retArray[$count]["trat_totalweight"], 0), 0, ",", ".") . " " . getLngt("KG") . "§/§" . str_replace(" ","§",$retArray[$count]["trat_totalpieces"] . " " . getLngt("Stk.")),0,$newStrLen)) . "<br>";
                 else :
                    $ecoOutBody .= substr(($itemLinePrefixLen > 0 ? "-|" : "") . $retArray[$count]["mt_time_interval"],0,$newStrLen) . "<br>";
                    $ecoOutBody .= str_replace("§","&nbsp;",substr($itemLinePrefix[0] . str_replace(" ","§",$row["ad2_street"]) . "§" . $row["tr2_hsno"],0,$newStrLen)) . "<br>";
                    $ecoOutBody .= str_replace("§","&nbsp;",substr($itemLinePrefix[1] . $row["ad2_zipcode"] . "§" . str_replace(" ","§",$row["ad2_city"]),0,$newStrLen)) . "<br>";
                    $ecoOutBody .= str_replace("§","&nbsp;",substr($itemLinePrefix[2] . $row["jb_timeunits"] . "§" . getLngt("ZE"),0,$newStrLen)) . "<br>";
                    $ecoOutBody .= substr($itemLinePrefix[3] . number_format(round(($row["jb_totalprice"] * $taxFactor), 2), 2, ",", ".") . " €",0,$newStrLen) . "<br>";
                    $ecoOutBody .= substr($itemLinePrefix[4] . number_format(round($retArray[$count]["trat_totalweight"], 3), 3, ",", ".") . " " . getLngt("KG"),0,$newStrLen);
                 endif;
                 $retArray[$count]["eco_body"] = my_str_check_js($ecoOutBody);
              endif;

              $ecoOutBodyFull = "";
              if ($parMaskDispositionItemDisplayMode == "1") :
                 $ecoOutBodyFull .= $row["tr2_comp"] . "<br>";
                 $ecoOutBodyFull .= $row["tr2_mediationarea_name"] . "<br><br>";
                 // $ecoOutBodyFull .= $row["ad2_street"] . " " . $row["tr2_hsno"] . "<br>";
                 $ecoOutBodyFull .= $row["ad2_zipcode"] . " " . $row["ad2_city"] . "<br>";
                 $ecoOutBodyFull .= $row["tr2_phone"] . "<br>";
                 $ecoOutBodyFull .= $row["jb_timeunits"] . " " . getLngt("ZE") . "<br>";
              elseif ($parMaskDispositionItemDisplayMode == "2") :
                 $ecoOutBodyFull .= getLngt("Zusage") . ": " . $retArray[$count]["gdc2_content"] . "<br>";
                 $ecoOutBodyFull .= "<br>";
                 $ecoOutBodyFull .= $row["tr2_comp"] . "<br>";
                 if ($row["tr2_person"] != "") :
                    $ecoOutBodyFull .= $row["tr2_person"] . "<br>";
                 endif;
                 $ecoOutBodyFull .= $row["ad2_street"] . " " . $row["tr2_hsno"] . "<br>";
                 if ($row["tr2_floor"] != "" && $row["tr2_floor"] != "0") :
                    $ecoOutBodyFull .= "[" . getLngt("Etage") . ": " . $row["tr2_floor"] . "]<br>";
                 endif;
                 $ecoOutBodyFull .= $row["ad2_zipcode"] . " " . $row["ad2_city"] . "<br>";
                 $ecoOutBodyFull .= $row["tr2_phone"] . "<br>";
              else :
                 // $ecoOutBodyFull .= substr($row["jb_ordertime"],11,5) . "<br>";
                 $ecoOutBodyFull .= getLngt("Zusage") . ": " . $retArray[$count]["mt_time_interval"] . "<br>";
                 /*
                 $ecoOutBodyFull .= getLngt("Akt.") . ": " . $retArray[$count]["mt_time_interval"] . "<br>";
                 if ($retArray[$count]["jb_freetext_1"] != "") :
                    $ecoOutBodyFull .= "[" . getLngt("Org.") . ": " . $retArray[$count]["jb_freetext_1"] . "]" . "<br>";
                 endif;
                 */
                 $ecoOutBodyFull .= "<br>";
                 $ecoOutBodyFull .= $row["tr2_comp"] . "<br>";
                 $ecoOutBodyFull .= $row["ad2_street"] . " " . $row["tr2_hsno"] . "<br>";
                 if ($row["tr2_floor"] != "" && $row["tr2_floor"] != "0") :
                    $ecoOutBodyFull .= "[" . getLngt("Etage") . ": " . $row["tr2_floor"] . "]<br>";
                 endif;
                 $ecoOutBodyFull .= $row["ad2_zipcode"] . " " . $row["ad2_city"] . "<br>";
                 $ecoOutBodyFull .= $row["tr2_phone"] . "<br>";
                 $ecoOutBodyFull .= $row["jb_timeunits"] . " " . getLngt("ZE") . "<br>";
                 // $ecoOutBodyFull .= number_format(round(($row["jb_totalprice"] * $taxFactor), 2), 2, ",", ".") . "&nbsp;€";
                 // $ecoOutBodyFull .= number_format(round($retArray[$count]["trat_totalweight"], 3), 3, ",", ".") . " " . getLngt("KG");
              endif;
              $retArray[$count]["eco_body_full"] = my_str_check_js($ecoOutBodyFull);

              if ($mode == "3") :
                 $ecoOutUrlList = "?maskNumOfWins=1&jb_status=9&day_from=$selDay&month_from=$selMonth&year_from=$selYear&day_to=$selDay&month_to=$selMonth&year_to=$selYear";
                 $ecoArray[$count]["eco_url_list"] = my_str_check_js($ecoOutUrlList);
              endif;

              $count++;
        endwhile;
        $result->free();        
     endif;
  endif;
  return $retArray;
}

// Checks the availability of the specified vehicle for a specified time interval (for a special job)
function checkAvailableVehicleCapacity ($crvhId, $currDay, $startTimeslotToBeChecked, $endTimeslotToBeChecked, $jbId) {
  global $db, $PHP_SELF;
  $retVal = "";
  // [1.] Check time slots available
  $sqlquery = "SELECT DISTINCT jb_id FROM vehicledisposition WHERE crvh_id = '" . $crvhId . "' AND jb_id != '" . $jbId . "' AND vhd_timeslot >= '" . $startTimeslotToBeChecked . "' AND vhd_timeslot < '" . $endTimeslotToBeChecked . "'";
  $result = $db->query($sqlquery);
  if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
  while ($row = $result->fetch_assoc()):
        if ($row["jb_id"] != "" && $row["jb_id"] != "0") :
           $retVal = "1";
        endif;
  endwhile;
  $result->free();

  // [2.] Check vehicle restrictions (weight, positions, etc.)
  if ($retVal == "" && $jbId != "") :
     // Get the total weight of all articles of the specified job
     $atWeightToBeChecked = getTratTotalweight($jbId);
     if ($atWeightToBeChecked != 0) :
        $vhaWeightCapacityFree = getFieldValueFromClause("vehicleavailability","vha_weight","crvh_id = '" . $crvhId . "' AND vha_day = '" . $currDay . "'");
        if ($vhaWeightCapacityFree < $atWeightToBeChecked) :
           $retVal = "2";
        endif;
     endif;
  endif;
  return $retVal;
}

// Generate all new timeslot entries for the vehicle for the specified day
function generatePersistentTimeslots ($crvhId, $currDay, $hourTimeUnits, $csId) {
  global $db, $PHP_SELF;

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

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

     // * Insert into "vehicledisposition" *
     for ($i = 0; $i <= 23; $i++) :
         for ($j = 0; $j < $hourTimeUnits; $j++) :
             $vhdTimeslot = $currDay . '_' . pad($i, 2) . '_' . pad($j, 2);
             insertStmt("vehicledisposition", array("crvh_id",$crvhId,"vhd_timeslot",$vhdTimeslot,"jb_id","0"));
         endfor;
     endfor;

     // * Insert into "vehicleavailability" *
     // Get data of the vehicle (weight, positions, payload, etc.)
     $crvhFields = getFieldsValueFromId("couriervehicle", "crvh_id", $crvhId, array("crvh_payload","crvh_position"));
     insertStmt("vehicleavailability", array("vha_day",$currDay,"crvh_id",$crvhId,"vha_weight",$crvhFields[0],"vha_position",$crvhFields[1],"vha_lock","0"));
     $vhaIdNew = getLastInsertId();

     // * Insert into "vehicleavailabilitytimeunits" *
     // Get all customers the current vehicle is associated to
     // Iterate all customers to get the superset of possible timeslots of all day times
     $customersAssociatedToCurrentVehicle = getColVectorFromDB2Array("customervehicle","crvh_id",$crvhId,"cs_id","");
     $customersAssociatedToCurrentVehicleLen = count($customersAssociatedToCurrentVehicle);
     if ($customersAssociatedToCurrentVehicleLen == 0 && $csId != "" && is_numeric($csId) && $csId > 0) :
        $customersAssociatedToCurrentVehicle = array($csId);
        $customersAssociatedToCurrentVehicleLen = count($customersAssociatedToCurrentVehicle);
     endif;

     for ($k = 0; $k < $customersAssociatedToCurrentVehicleLen; $k++) :
         // Get zone array depending in the week day
         $tmpDaytimeZoneArray = getDaytimeAvailabilityOfVehicle($crvhId, $weekDay, $customersAssociatedToCurrentVehicle[$k], "1");  // $tmpDaytimeZoneArray[daytime] = zone
     
         // Get daytimes of the customer associated to the current vehicle
         $dayTimeSlots = metatypeGetMappedValues("day_time", $hourTimeUnits, $customersAssociatedToCurrentVehicle[$k], "cs", "");
         $dayTimeSlotsLen = count($dayTimeSlots);
         for ($l = 0; $l < $dayTimeSlotsLen; $l++) :
             $countFreeTimeUnits = 0;
             $currStartHour = intval(substr($dayTimeSlots[$l][0],0,2));
             $currStartTimeUnit = intval(substr($dayTimeSlots[$l][0],3,2));
             $currEndHour = intval(substr($dayTimeSlots[$l][1],0,2));
             $currEndTimeUnit = intval(substr($dayTimeSlots[$l][1],3,2));
             
             // Start time slot is the same like the beginning of the current day time interval
             $startTimeUnitOfFreeTimeSlot = substr($dayTimeSlots[$l][0],0,5);

             // Independent from the beginning of the daytime first 
             // Loop start hour of the current day time
             $tmpHourTimeUnits = $hourTimeUnits;
             if ($currStartHour == $currEndHour) :
                $tmpHourTimeUnits = ($currEndTimeUnit + 1);  // Increment because of loop checks for "<" and not for "<="
             endif;
             for ($j = $currStartTimeUnit; $j < $tmpHourTimeUnits; $j++) :
                 $countFreeTimeUnits++;
             endfor;
             // Loop complete hours with all hour time units
             $tmpHour = $currStartHour + 1;
             for ($i = $tmpHour; $i < $currEndHour; $i++) :
                 for ($j = 0; $j < $hourTimeUnits; $j++) :
                     $countFreeTimeUnits++;
                 endfor;
             endfor;
             // Loop last hour
             if ($currStartHour < $currEndHour) :
                for ($j = 0; $j < $currEndTimeUnit; $j++) :
                    $countFreeTimeUnits++;
                endfor;
             endif;

             if ($countFreeTimeUnits > 0) :
                // The stored "cs_id" is an information only. It could be used to check free capacities for a special customer.
                insertStmt("vehicleavailabilitytimeunits", array("vha_id",$vhaIdNew,"vhat_daytime",$l,"vhat_timeunits",$countFreeTimeUnits,"cs_id",$customersAssociatedToCurrentVehicle[$k],"vhat_srvz_no",$tmpDaytimeZoneArray[$l],"vhat_starttimeunit",$startTimeUnitOfFreeTimeSlot));
             endif;
         endfor;
     endfor;
  endif;
}

// Updates the state of the vehicle availability of a single day.
// Additional(!) functionality to make a faster decision for appointment search later on based on these redundant data.
// $crvhId        : Vehicle ID
// $csId          : Customer the vehicle is associated to
// $startTimeslot : First timeslot when the job has to start
function updateVehicleAvailability ($crvhId, $csId, $startTimeslot = "", $hourTimeUnits = "") {
  global $db, $PHP_SELF;
  $retVal = "";

  // 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;

  if ($crvhId != "" && $startTimeslot != "" && $hourTimeUnits != "" && $csId != "") :
     $currDay = substr($startTimeslot, 0, 10);
     $vhaId = getFieldValueFromClause("vehicleavailability","vha_id","crvh_id = '" . $crvhId . "' AND vha_day = '" . $currDay . "'");

     if ($vhaId != "") :

        // Get current day (today) and current time (now) to compare it with $currDay (from $startTimeslot) ONLY
        // If it is the same day (today) then do not involve past timeunits !!!!
        $currentDay = getDateTime("3");   // "Y-m-d"
        $currentTime = getDateTime("4");  // Current time ("H:i:s")
        $currentTimeUnit = substr($currentTime,0,2) . "_" . pad(strval(ceil(intval(substr($currentTime,3,2)) * ($hourTimeUnits / 60))), 2);

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

        // Get zone array depending on the week day
        $tmpDaytimeZoneArray = getDaytimeAvailabilityOfVehicle($crvhId, $weekDay, $csId, "1");  // $tmpDaytimeZoneArray[daytime] = zone

        // Get time slot array of day times of the specified customer REDUCED by the current vehicle is associated to the time slot being checked for any day time
        $tmpDayTimeSlots = metatypeGetMappedValues("day_time", $hourTimeUnits, $csId, "cs", "");
        $tmpDayTimeSlotsLen = count($tmpDayTimeSlots);

        $dayTimeSlots = array();
        $endOfWorkDay = "";
        for ($i = 0; $i < $tmpDayTimeSlotsLen; $i++) :
            if ($tmpDaytimeZoneArray[$i] != "9999") :
               $dayTimeSlots[$i] = $tmpDayTimeSlots[$i];
               $endOfWorkDay = $tmpDayTimeSlots[$i][1];  // Important because of whole day units have to be limited by max work time !!!!
            endif;
        endfor;
        $dayTimeSlotsLen = count($dayTimeSlots);

        // Remove all entries for the specified vehicle AND for the specified day in table "vehicleavailabilitytimeunits"
        deleteStmt("vehicleavailabilitytimeunits","vha_id = '" . $vhaId . "' AND cs_id = '" . $csId . "'");

        // Renew the timeslot structure regarding the values in table "vehicledisposition"
        // Get all time unit data of the current vehicle for the specified day, daytime and zone
        $timeUnitArray = getColVectorFromDB2ArrayByClause("vehicledisposition", "jb_id", "crvh_id = '" . $crvhId . "' AND LEFT(vhd_timeslot, 10) = '" . $currDay . "'", "vhd_timeslot", "vhd_timeslot", "");
        $timeUnitArrayLen = count($timeUnitArray);
        if ($timeUnitArrayLen > 0) :

           // Init free capacity array ($countFreeTimeUnits) of the specified vehicle and specified customer and specified day for each daytime.
           $countFreeTimeUnits = array();
           $startTimeUnitOfFreeTimeSlot = array();
           $remCountFreeTimeUnits = array();

           // Init free capacity WITHOUT daytime restriction
           $countFreeTimeUnitsMoreDaytimes = array();
           $startTimeUnitOfFreeTimeSlotMoreDaytimes = array();
           $remCountFreeTimeUnitsMoreDaytimes = array();
           $remStartTimeUnitOfFreeTimeSlotMoreDaytimes = array();

           for ($k = 0; $k < $tmpDayTimeSlotsLen; $k++) :
               if (is_array($dayTimeSlots[$k])) :
                  $countFreeTimeUnits[$k] = 0;
                  $startTimeUnitOfFreeTimeSlot[$k] = "";
                  $remCountFreeTimeUnits[$k] = 0;
                  
                  $countFreeTimeUnitsMoreDaytimes[$k] = 0;
                  $startTimeUnitOfFreeTimeSlotMoreDaytimes[$k] = "";
                  $remCountFreeTimeUnitsMoreDaytimes[$k] = 0;
                  $remStartTimeUnitOfFreeTimeSlotMoreDaytimes[$k] = "";
               endif;
           endfor;

           for ($i = 0; $i <= 23; $i++) :
               for ($j = 0; $j < $hourTimeUnits; $j++) :

                   $currHour = pad($i, 2);
                   $currTimeUnit = pad($j, 2);
                   $ctu = $currHour . '_' . $currTimeUnit;
                   $vhdTimeslot = $currDay . '_' . $ctu;

                   // Check SELECTED DAY in "$currDay" being in the future. All future days may not be restricted.
                   // If the selected day is "today" then continue with future timeunits of today only.
                   // Free timeunits can be counted from now to the future only
                   if ($currDay > $currentDay || ($currDay == $currentDay && $ctu >= $currentTimeUnit)) :

                      // * ITERATE FOR EACH DAYTIME *
                      // 1. It could be possible the intervals are NOT defined in order (e.g. daytime 0 <=> "12.30 - 15.59, 1 <=> 07.00 - 12.29")!!!!
                      // 2. It could be possible the intervals have intersections (e.g. daytime 0 <=> "12.30 - 15.59, 1 <=> 15.00 - 19.59" => Intersection 15.00 - 15.59)!!!!
                      // Therefore iterate ALL defined time slots defined for the customer with separated counters for free time units.
                      // Check for time unit being in any customer time slot the current vehicle is associated to (checked above)

                      // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
                      // for ($k = 0; $k < $dayTimeSlotsLen; $k++) :
                      // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
                        for ($k = 0; $k < $tmpDayTimeSlotsLen; $k++) :

                            // * Check for each daytime of the day *
                            if (is_array($dayTimeSlots[$k])) :
                               if ($dayTimeSlots[$k][0] <= $ctu && $ctu < $dayTimeSlots[$k][1]) :

                                  if ($startTimeUnitOfFreeTimeSlot[$k] == "") :
                                     $startTimeUnitOfFreeTimeSlot[$k] = $ctu;
                                  endif;
     
                                  $doInsert = true;
                                  $jbIdAssocInTimeUnit = $timeUnitArray[$vhdTimeslot];  // Get job ID potentially associated to the current time unit
                                  if ($jbIdAssocInTimeUnit == "0") :  // No job is associated to this single time unit (array from table "vehicledisposition")
                                     $countFreeTimeUnits[$k]++;
                                     $doInsert = false;
                                  endif;
                                  if ($countFreeTimeUnits[$k] == 0) :
                                     $startTimeUnitOfFreeTimeSlot[$k] = "";
                                     $doInsert = false;
                                  endif;
     
                                  if ($doInsert) :  // Important to check for "$countFreeTimeUnits > 0" because next time units (after "$doInsert == true") having the same job have not to be inserted !!!!
                                     insertStmt("vehicleavailabilitytimeunits", array("vha_id",$vhaId,"vhat_daytime",$k,"vhat_timeunits",$countFreeTimeUnits[$k],"cs_id",$csId,"vhat_srvz_no",$tmpDaytimeZoneArray[$k],"vhat_starttimeunit",$startTimeUnitOfFreeTimeSlot[$k]));
                                     $retVal .= "(" . $k . ", " . $countFreeTimeUnits[$k] . ", " . $startTimeUnitOfFreeTimeSlot[$k] . ") ";
                                     
                                     if ($remCountFreeTimeUnits[$k] < $countFreeTimeUnits[$k]) :
                                        $remCountFreeTimeUnits[$k] = $countFreeTimeUnits[$k];
                                     endif;
                                     $countFreeTimeUnits[$k] = 0;
                                     $startTimeUnitOfFreeTimeSlot[$k] = "";
                                  endif;
                               endif;
     
                               // * Check for whole day *
                               if ($ctu >= $dayTimeSlots[$k][0] && $ctu < $endOfWorkDay) :
     
                                  if ($remStartTimeUnitOfFreeTimeSlotMoreDaytimes[$k] == "") :
                                     $remStartTimeUnitOfFreeTimeSlotMoreDaytimes[$k] = $ctu;
                                  endif;
                                  if ($startTimeUnitOfFreeTimeSlotMoreDaytimes[$k] == "") :
                                     $startTimeUnitOfFreeTimeSlotMoreDaytimes[$k] = $ctu;
                                  endif;
     
                                  $jbIdAssocInTimeUnit = $timeUnitArray[$vhdTimeslot];  // Get job ID potentially associated to the current time unit
                                  if ($jbIdAssocInTimeUnit == "0") :  // No job is associated to this single time unit (array from table "vehicledisposition")
                                     $countFreeTimeUnitsMoreDaytimes[$k]++;
                                  else :
                                     if ($remCountFreeTimeUnitsMoreDaytimes[$k] == 0 && $ctu >= $dayTimeSlots[$k][1] && ($currDay > $currentDay || ($currDay == $currentDay && $dayTimeSlots[$k][1] >= $currentTimeUnit))) :
                                        $remCountFreeTimeUnitsMoreDaytimes[$k] = $countFreeTimeUnitsMoreDaytimes[$k];
                                        $remStartTimeUnitOfFreeTimeSlotMoreDaytimes[$k] = $startTimeUnitOfFreeTimeSlotMoreDaytimes[$k];
                                     endif;
                                  
                                     $countFreeTimeUnitsMoreDaytimes[$k] = 0;
                                     $startTimeUnitOfFreeTimeSlotMoreDaytimes[$k] = "";
                                  endif;
                               endif;
                            endif;
                      endfor;
                   endif;  // Check for availavle timeunits from NOW() only
               endfor;
           endfor;
           // Store the rest of the free time units
           for ($k = 0; $k < $tmpDayTimeSlotsLen; $k++) :
               if (is_array($dayTimeSlots[$k])) :
                  if ($countFreeTimeUnits[$k] > 0) :  // Important to check for "$countFreeTimeUnits > 0" because next time units (after "$doInsert == true") having the same job have not to be inserted !!!!
                     insertStmt("vehicleavailabilitytimeunits", array("vha_id",$vhaId,"vhat_daytime",$k,"vhat_timeunits",$countFreeTimeUnits[$k],"cs_id",$csId,"vhat_srvz_no",$tmpDaytimeZoneArray[$k],"vhat_starttimeunit",$startTimeUnitOfFreeTimeSlot[$k]));
                     $retVal .= "(" . $k . ", " . $countFreeTimeUnits[$k] . ", " . $startTimeUnitOfFreeTimeSlot[$k] . ") ";
   
                     if ($remCountFreeTimeUnits[$k] < $countFreeTimeUnits[$k]) :
                        $remCountFreeTimeUnits[$k] = $countFreeTimeUnits[$k];
                     endif;
                  endif;
               endif;
           endfor;
           // Store the whole day time units
           for ($k = 0; $k < ($tmpDayTimeSlotsLen - 1); $k++) :
               // Needed only if NO job is on the timeline
               if (is_array($dayTimeSlots[$k])) :
                  if ($remCountFreeTimeUnitsMoreDaytimes[$k] == 0 && ($currDay > $currentDay || ($currDay == $currentDay && $dayTimeSlots[$k][1] >= $currentTimeUnit))) :
                      $remCountFreeTimeUnitsMoreDaytimes[$k] = $countFreeTimeUnitsMoreDaytimes[$k];
                      $remStartTimeUnitOfFreeTimeSlotMoreDaytimes[$k] = $startTimeUnitOfFreeTimeSlotMoreDaytimes[$k];
                  endif;
   
                  if ($remCountFreeTimeUnitsMoreDaytimes[$k] > $remCountFreeTimeUnits[$k]) :
                     insertStmt("vehicleavailabilitytimeunits", array("vha_id",$vhaId,"vhat_daytime",$k,"vhat_timeunits",$remCountFreeTimeUnitsMoreDaytimes[$k],"cs_id",$csId,"vhat_srvz_no",$tmpDaytimeZoneArray[$k],"vhat_starttimeunit",$remStartTimeUnitOfFreeTimeSlotMoreDaytimes[$k]));
                     $retVal .= "(" . $k . ", " . $countFreeTimeUnits[$k] . ", " . $startTimeUnitOfFreeTimeSlot[$k] . ") ";
                  endif;
               endif;
           endfor;
        endif;
     endif;
  endif;
  return $retVal;
}

// Wrapper function: Iterate ALL customer the vehicle is associated to
// $crvhId        : Vehicle ID
// $csId          : Can be empty (customer the vehicle is associated to)
// $startTimeslot : First timeslot when the job has to start
function updateAllCsVehicleAvailability ($crvhId, $csId, $startTimeslot = "", $hourTimeUnits = "") {
  global $db, $PHP_SELF;
  $retVal = "";

  // 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;

  if ($crvhId != "" && $startTimeslot != "" && $hourTimeUnits != "") :
     // Get all related customer the vehicle is associated to
     $csArray = getColVectorFromDB2ArrayByClause("customervehicle", "cs_id", "crvh_id = '" . $crvhId . "'", "", "", "DISTINCT");
     $csArrayLen = count($csArray);

     for ($i = 0; $i < $csArrayLen; $i++) :
         $retVal = updateVehicleAvailability($crvhId, $csArray[$i], $startTimeslot, $hourTimeUnits);
     endfor;
  endif;
  return $retVal;
}

// Get available vehicles regarding to a special delivery request
function getAvailableVehicles ($csId, $dayFrom, $dayTo, $daytime, $zipcode, $hourTimeUnits, $neededTimeUnits = "", $service = "", $weight = 0, $positions = 0, $orderByClause = "", $maxLimitOfRows = "", $specialWhereClause = "") {
	global $db, $PHP_SELF;
  $retArray = array();

  if ($csId != "" && $dayFrom != "" && $zipcode != "" && $hourTimeUnits != "" && $neededTimeUnits != "") :

     $whereClause = "vhat.cs_id = '" . $csId . "'";                                                                            // Customer has to be defined

     // Check mode for association between zone and zipcode being disjunct or not.
     $dispositionAssocZoneZipcode = getParameterValue("0", "DISPOSITION_ASSOC_ZONE_ZIPCODE_NOT_DISJUNCT", $hq_id);
     if ($dispositionAssocZoneZipcode == "") : $dispositionAssocZoneZipcode = getParameterValue("0", "DISPOSITION_ASSOC_ZONE_ZIPCODE_NOT_DISJUNCT", "0"); endif;
     if ($dispositionAssocZoneZipcode == "") : $dispositionAssocZoneZipcode = "0"; endif;

     // Get zone from the zipcode depending on the customer
     if ($dispositionAssocZoneZipcode == "1") :
        $zoneNoArray = getServiceZonesByCustomerAndZipcode($csId, $zipcode);
        if (count($zoneNoArray) == 0) :
           return "ERR:ZIPCODE_NOT_IN_ANY_ZONE" . " [1] " . $csId . " [2] " . $dayFrom . " [3] " . $zipcode . " [4] " . $hourTimeUnits . " [5] " . $neededTimeUnits;
        endif;
        $whereClause .= " AND (vhat.vhat_srvz_no IN (" . implode(",", $zoneNoArray) . ") OR vhat.vhat_srvz_no = '')";          // Zipcode (for delivery or service) has to be defined
     else :
        $zoneNo = getServiceZoneByCustomerAndZipcode($csId, $zipcode);
        if ($zoneNo == "") :
           return "ERR:ZIPCODE_NOT_IN_ANY_ZONE" . " [1] " . $csId . " [2] " . $dayFrom . " [3] " . $zipcode . " [4] " . $hourTimeUnits . " [5] " . $neededTimeUnits;
        endif;
        if ($zoneNo == "") : return "ERR:NO_ZONE"; endif;
        $whereClause .= " AND (vhat.vhat_srvz_no = '" . $zoneNo . "' OR vhat.vhat_srvz_no = '')";                              // Zipcode (for delivery or service) has to be defined
     endif;

     if ($dayFrom != "") :                                                                                                     // Restriction regarding date ranges
        $whereClause .= " AND vha.vha_day >= '" . $dayFrom . "'";
        if ($dayTo == "") : $dayTo = $dayFrom; endif;
        $whereClause .= " AND vha.vha_day <= '" . $dayTo . "'";
     endif;
     // $whereClause .= " AND vha.vha_blocked = '0' ";                                                                         // Do not request for blocked vehicles
     $whereClause .= " AND (vha.vha_blocked & 1 = 0) ";                                                                        // Do not request for blocked vehicles (bit 0 only)
     if (is_array($daytime)) :
        if (count($daytime) > 0) : $whereClause .= " AND vhat.vhat_daytime IN ('" . implode("','", $daytime) . "')"; endif;    // Request for more daytimes
     else :
        if ($daytime != "") : $whereClause .= " AND vhat.vhat_daytime = '" . $daytime . "'"; endif;                            // Request for a special daytime only
     endif;                                                                                                                    
     if ($neededTimeUnits != "") : $whereClause .= " AND vhat.vhat_timeunits >= '" . $neededTimeUnits . "'"; endif;            // Look for at least <$neededTimeUnits> time units being available
     if ($weight > 0) : $whereClause .= " AND vha.vha_weight >= '" . $weight . "'"; endif;                                     // Weight (payload)
     if ($positions > 0) : $whereClause .= " AND vha.vha_position >= '" . $positions . "'"; endif;                             // Positions
     if ($service != "") : $whereClause .= " AND (crvh.crvh_service & " . $service . " = " . $service . ") "; endif;           // Service(s)

     // Special cases
     $whereClause .= " AND csvh.cs_id = '" . $csId . "'";                                                                      // Customer has to be related to the searched vehicles !!!!
     if ($specialWhereClause != "") : $whereClause .= " AND " . $specialWhereClause; endif;                                    // Special filter (like "delivery time", etc.)

     $sqlquery = getStmtVehicleCapacityData($whereClause, $orderByClause, $maxLimitOfRows, $fieldClause);
// echo $sqlquery . "<br><br>";
     $result = $db->query($sqlquery);
     if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
     while ($row = $result->fetch_assoc()):
           $tmpVhaDay = $row["vha_day"];
           $tmpCrvhSid = getFieldValueFromId("couriervehicle", "crvh_id", $row["crvh_id"], "crvh_sid");
           $tmpDaytimeValues = getFieldValueFromClause("metatype","mt_value","mt_type = 'day_time' AND mt_objtype = 'cs' AND mt_objid = '" . $csId . "' AND mt_sort = '" . $row["vhat_daytime"] . "'");
           $tmpDaytimeMappedValues = getFieldValueFromClause("metatype","mt_mapped_value","mt_type = 'day_time' AND mt_objtype = 'cs' AND mt_objid = '" . $csId . "' AND mt_sort = '" . $row["vhat_daytime"] . "'");
           $tmpStarttime = substr($row["vhat_starttimeunit"],0,2) . ":" . pad(strval(floor(intval(substr($row["vhat_starttimeunit"],3,2)) * (60 / $hourTimeUnits))), 2);
           // $tmpService = getMappedPrimes($row["crvh_service"]);
           // $tmpService = implode(",", getColVectorFromDB2ArrayByClause("metatype", "LEFT(mt_value,2)", "mt_type = 'service' AND mt_objtype = '' AND mt_objid = '0' AND mt_sort IN (" . implode(",", mcConvertNum2Sel($row["crvh_service"])) . ")", "", "mt_sort", ""));
           $tmpService = implode(",", getColVectorFromDB2ArrayByClause("metatype", "mt_mapped_value", "mt_type = 'service' AND mt_objtype = '' AND mt_objid = '0' AND mt_sort IN (" . implode(",", mcConvertNum2Sel($row["crvh_service"])) . ")", "", "mt_sort", ""));

           $retArray[] = array($tmpVhaDay, $tmpCrvhSid, $tmpDaytimeValues, $row["vhat_timeunits"], $tmpStarttime, $tmpService, $row["vhat_daytime"], $row["crvh_id"], substr($row["vhat_starttimeunit"],0,2), substr($row["vhat_starttimeunit"],3,2), $tmpDaytimeMappedValues, $row["crvh_service"]);
     endwhile;
     $result->free();
  else :
     return "ERR:PARAMETER" . " [1] " . $csId . " [2] " . $dayFrom . " [3] " . $zipcode . " [4] " . $hourTimeUnits . " [5] " . $neededTimeUnits;
  endif;
  return $retArray;
}

// Removes or generates the "Fast Disposition Structure" for a special vehicle (e.g. after removal of a vehicle or removal of a special relation to the customer)
// $crvhId        : Vehicle ID
// $execMode      : Execution mode ("1" = Remove all entries, "2" = Update FDS from today to the last future day) for the selected vehicle
// $csId          : System customer associated to the current vehicle
// $crvhFieldsBeforeUpdate : Values before modification to compute delta values
// $numOfDays     : Number of days in the future the structure will be generated (again)
// $hourTimeUnits : Number of timeunits of one hour (by default 6)
function generateVehicleFastDispositionStructure ($crvhId, $execMode, $csId = "", $crvhFieldsBeforeUpdate = "", $numOfDays = "", $hourTimeUnits = "") {
	global $db, $PHP_SELF;

  if ($crvhId != "" && is_numeric($crvhId) && $execMode != "") :

     // Check FDS is enabled
     $fastDispositionStructureEnabled = getParameterValue("0", "FAST_DISPOSITION_STRUCTURE_ENABLED", "0");

     // Check FDS access by parameter for the given customer (being "system customer" [e.g. "csc_id_related" has to be set for visualisation in graphical disposition])
     $parFdsCustomerEnabled = "";
     /*
     if ($fastDispositionStructureEnabled != "1" && $csId != "") :
        $parFdsCustomerEnabled = getParameterValue("0", "FDS_CUSTOMER_ENABLED_CS_" . $csId, "0");

        // Check for activation by meta customer
        if ($parFdsCustomerEnabled != "1") :
            $csIdParent = getFieldValueFromId("customer","cs_id",$csId,"cs_id_parent");
            $parFdsCustomerEnabled = getParameterValue("0", "FDS_CUSTOMER_ENABLED_CS_" . $csIdParent, "0");
        endif;
     endif;
     */
     if ($fastDispositionStructureEnabled != "1") :
         // Check for system customer associated to the current vehicle
         // Get all related customer the vehicle is associated to
         $csArray = getColVectorFromDB2ArrayByClause("customervehicle", "cs_id", "crvh_id = '" . $crvhId . "'", "", "", "DISTINCT");
         $csArrayLen = count($csArray);
         if ($csArrayLen > 0) :
            $parFdsCustomerEnabled = "1";
         endif;
     endif;

     if ($fastDispositionStructureEnabled == "1" || $parFdsCustomerEnabled == "1") :

        // Current timestamp
        $currentTimestamp = getDateTime("0");
        $currentDay = getDateTime("3");   // "Y-m-d"
        $selDay = getDateTime("day");
        $selMonth = getDateTime("month");
        $selYear = getDateTime("year");
        if ($numOfDays == "") : 
           $lastVhaDay = getOneStmt("SELECT vha_day FROM vehicleavailability WHERE crvh_id = '" . $crvhId . "' ORDER BY vha_day DESC", "vha_day");
           $date1 = new DateTime($lastVhaDay);
           $date2 = new DateTime($currentDay);
           $diff = $date1->diff($date2);
           $numOfDays = $diff->days;
           if (!is_numeric($numOfDays) || $numOfDays < 30) : $numOfDays = 14; endif;
        endif;
        if ($numOfDays == "") : $numOfDays = 120; 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;

        // Remove entries in "vehicleavailabilitytimeunits" for a single customer only, e.g. by removing a vehicle
        // After one or more removals this function "generateVehicleFastDispositionStructure($crvhId, "2")" should be called to update (renew) the FDS !!!!
        if ($execMode == "0" && $csId != "" && is_numeric($csId)) :
           $vhaIdToRemoveArray = getColVectorFromDB2ArrayByClause("vehicleavailabilitytimeunits AS vhat, vehicleavailability AS vha", "vhat.vha_id", "vhat.vha_id = vha.vha_id AND vha.crvh_id = '" . $crvhId . "' AND vhat.cs_id = '" . $csId . "'", "", "", "DISTINCT");
           $vhaIdToRemoveArrayLen = count($vhaIdToRemoveArray);
           if ($vhaIdToRemoveArrayLen > 0) :
              deleteStmt("vehicleavailabilitytimeunits","vha_id IN (" . implode(",", $vhaIdToRemoveArray) . ")");  // Remove all future entries in FDS.vehicleavailabilitytimeunits for the special vehicle
           endif;
        endif;

        // Remove ALL entries of a special vehicle in the FDS (e.g. by removing a vehicle)
        if ($execMode == "1") :
           $vhaIdToRemoveArray = getColVectorFromDB2ArrayByClause("vehicleavailability", "vha_id", "crvh_id = '" . $crvhId . "'", "", "", "");
           $vhaIdToRemoveArrayLen = count($vhaIdToRemoveArray);
           if ($vhaIdToRemoveArrayLen > 0) :
              deleteStmt("vehicleavailabilitytimeunits","vha_id IN (" . implode(",", $vhaIdToRemoveArray) . ")");  // Remove ALL entries in FDS.vehicleavailabilitytimeunits for the special vehicle
           endif;
           deleteStmt("vehicleavailability","crvh_id = '" . $crvhId . "'");  // Remove ALL entries for the special vehicle in "vehicleavailability"
           deleteStmt("vehicledisposition","crvh_id = '" . $crvhId . "'");   // Remove ALL entries for the special vehicle in "vehicledisposition"
        endif;

        // Update (renew) FDS for the special vehicle
        if ($execMode == "2") :
            for ($k = 0; $k < $numOfDays; $k++) :
                $tmpDate = getDateTime("format", array(0,0,0,$selMonth,$selDay + $k,$selYear), "Y-m-d");
                updateAllCsVehicleAvailability($crvhId, $csId, $tmpDate, $hourTimeUnits);
            endfor;
        endif;

        // Generate new virginal FDS for the special vehicle. It will be called e.g. after creating a new vehicle
        if ($execMode == "3") :
           // Iterate the next x days
           for ($k = 0; $k < $numOfDays; $k++) :
               $tmpDate = getDateTime("format", array(0,0,0,$selMonth,$selDay + $k,$selYear), "Y-m-d");
               if (!existsEntry("vehicledisposition",array("crvh_id",$crvhId,"LEFT(vhd_timeslot, 10)",$tmpDate))) :
                  // Generate all new timeslot entries for the vehicle for the specified day
                  generatePersistentTimeslots($crvhId, $tmpDate, $hourTimeUnits, $csId);
               else :
                  // The FDS does exist. Update (renew) FDS for the special vehicle
                  updateAllCsVehicleAvailability($crvhId, $csId, $tmpDate, $hourTimeUnits);
               endif;
           endfor;
        endif;

        // Update the specific vehicle parameter ONLY (payload, positions, etc.). Timeunits will be NOT changed, therefore update table "vehicleavailability" ONLY
        if ($execMode == "4" && is_array($crvhFieldsBeforeUpdate)) :
           // Get current (new) vehicle data           
           $crvhFields = getFieldsValueFromId("couriervehicle", "crvh_id", $crvhId, array("crvh_payload","crvh_position"));
           // Get difference between the current (new) vehicle values and the old values of the current vehicle before the update [from master data both]
           $tmpDiffWeight = $crvhFields[0] - $crvhFieldsBeforeUpdate[0];      
           $tmpDiffPositions = $crvhFields[1] - $crvhFieldsBeforeUpdate[1];
           // Iterate the next x days
           for ($k = 0; $k < $numOfDays; $k++) :
               $tmpDate = getDateTime("format", array(0,0,0,$selMonth,$selDay + $k,$selYear), "Y-m-d");
               // Recompute remaining capacities in FDS.vehicleavailability for the special vehicle for all future days !!!!
               // If nothing has changed then do NOT update the FDS.
               $doUpdate = false;
               if ($tmpDiffWeight != 0 || $tmpDiffPositions != 0) :
                  // $tmpBool = getDbFieldValues("vehicleavailability", array("vha_weight", "vha_position"), array("crvh_id", $crvhId, "vha_day", $tmpDate));
                  $vhaWeight = getFieldValueFromClause("vehicleavailability", "vha_weight", "crvh_id = '" . $crvhId . "' AND vha_day = '" . $tmpDate . "'");
                  $vhaPosition = getFieldValueFromClause("vehicleavailability", "vha_position", "crvh_id = '" . $crvhId . "' AND vha_day = '" . $tmpDate . "'");
                  if ($tmpDiffWeight != 0 && $vhaWeight != "") :
                     $vhaWeight = $vhaWeight + $tmpDiffWeight;
                     if ($vhaWeight < 0) : $vhaWeight = 0; endif;
                     $doUpdate = true;
                  endif;
                  if ($tmpDiffPositions != 0 && $vhaPosition != "") :
                     $vhaPosition = $vhaPosition + $tmpDiffPositions;
                     if ($vhaPosition < 0) : $vhaPosition = 0; endif;
                     $doUpdate = true;
                  endif;
               endif;
               if ($doUpdate) :
                  updateStmt("vehicleavailability","crvh_id",$crvhId,array("vha_weight",$vhaWeight,"vha_position",$vhaPosition), "vha_day = '" . $tmpDate . "'");
               endif;
           endfor;
        endif;
     endif;
  endif;
}

// Removes an association ("disposition reservation") between job and vehicle
function removeAssocCrvhJb ($jbId, $csId = "", $hourTimeUnits = "", $doCommitTA = "") {
	global $db, $PHP_SELF;
	global $hq_id, $usr_id;
  
  $retBool = false;
  if ($jbId != "" && is_numeric($jbId)) :
  
     // Get related customer from job if does not exist
     if ($csId == "" || !is_numeric($csId)) :
        $cscIdRelated = getFieldValueFromId("job", "jb_id", $jbId, "csc_id_related");
        $csId = getFieldValueFromId("costcenter", "csc_id", $cscIdRelated, "cs_id");
     endif;
     
     if ($csId != "") :

        TA("B");

        // 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 vehicle associated to the specified job currently
        $sqlStmt = getStmtVehicledispositionData($jbId,"","","vhd.jb_id, vhd.vhd_timeslot LIMIT 0,1");  // Get statement for start timeslot of the job
        $crvhId = getOneStmt($sqlStmt, "crvh_id");
        if ($crvhId != "") :
           // Get ordertime for logging
           $jbOrdertime = getFieldValueFromId("job", "jb_id", $jbId, "jb_ordertime");

           // Check for "multiple day" job
           if (isMultipleDayJob($jbId, $csId) == "0") :

              $startTimeslot = getOneStmt($sqlStmt, "vhd_timeslot");
              $currDay = substr($startTimeslot, 0, 10);
              $timeslots = getFieldValueFromId("job", "jb_id", $jbId, "jb_timeunits");

              if ($currDay != "") :
                 // Use semaphore(!) for combination "vehicle and day" and lock the vehicle for this day
                 $res = updateStmt("vehicleavailability", "crvh_id", $crvhId, array("vha_lock", "1"), "vha_day = '" . $currDay . "' AND vha_lock = '0'");
                 if ($db->affected_rows > 0) :

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

                       // updateVehicleAvailability($crvhId, $csId, $startTimeslot, $hourTimeUnits);  // Write redundant data for appointment search later on
                       updateAllCsVehicleAvailability($crvhId, $csId, $startTimeslot, $hourTimeUnits);

                      // Update vehicle restrictions (weight, positions, etc.)
                      if ($jbId != "") :
                         $atWeightJb = getTratTotalweight($jbId);  // Get the total weight of all articles of the specified job
                         $capacityFreeWeight = getFieldValueFromClause("vehicleavailability","vha_weight","crvh_id = '" . $crvhId . "' AND vha_day = '" . $currDay . "'");  // Get free weight capacity of the specified vehicle
                         $capacityFreeWeight = $capacityFreeWeight + $atWeightJb;
                         updateStmt("vehicleavailability", "crvh_id", $crvhId, array("vha_weight", $capacityFreeWeight), "vha_day = '" . $currDay . "'");
                      endif;

                       $retBool = true;

                       // Write logdata into log database
                       $logCrvhSid = getFieldValueFromId("couriervehicle", "crvh_id", $crvhId, "crvh_sid");
                       writeToLogDB("123",$hq_id,$jbId,$usr_id,"",$logCrvhSid,$csId,"MULT_DAY=0|START=".$startTimeslot."|UNITS=".$timeslots."|ORDERTIME_OLD=".$jbOrdertime);
                    endif;

                    // Reset semaphore
                    updateStmt("vehicleavailability", "crvh_id", $crvhId, array("vha_lock", "0"), "vha_day = '" . $currDay . "'");
                 endif;
              endif;
           else :
// *******************************************************************************
// MULTIPLE DAYS
              // Get days involved by a single (installation) job
              $dayArray = getColVectorFromDB2ArrayByClause("vehicledisposition", "LEFT(vhd_timeslot,10) AS day", "jb_id = '" . $jbId . "'", "", "", "DISTINCT");
              $dayArrayLen = count($dayArray);
              $logDays = "";
              if ($dayArrayLen > 0) :
                 $res = updateStmt("vehicledisposition", "jb_id", $jbId, array("jb_id", '0'), "");
                 if ($db->affected_rows > 0) :
                    for ($i = 0; $i < $dayArrayLen; $i++) :
                        $currDay = $dayArray[$i];
                        
                        if ($logDays != "") : $logDays .= ","; endif;
                        $logDays .= $currDay;

                        // Set semaphore
                        updateStmt("vehicleavailability", "crvh_id", $crvhId, array("vha_lock", "1"), "vha_day = '" . $currDay . "' AND vha_lock = '0'");

                        // Recompute vehicle availability state
                        // updateVehicleAvailability($crvhId, $csId, $currDay, $hourTimeUnits);  // Write redundant data for appointment search later on
                        updateAllCsVehicleAvailability($crvhId, $csId, $currDay, $hourTimeUnits);

                        // Presently multiple days are for installation jobs only! There are no weights to be recomputed
                        if (false) :
                           $atWeightJb = getTratTotalweight($jbId);  // Get the total weight of all articles of the specified job
                           $capacityFreeWeight = getFieldValueFromClause("vehicleavailability","vha_weight","crvh_id = '" . $crvhId . "' AND vha_day = '" . $currDay . "'");  // Get free weight capacity of the specified vehicle
                           $capacityFreeWeight = $capacityFreeWeight + $atWeightJb;
                           updateStmt("vehicleavailability", "crvh_id", $crvhId, array("vha_weight", $capacityFreeWeight), "vha_day = '" . $currDay . "'");
                        endif;

                        // Reset semaphore
                        updateStmt("vehicleavailability", "crvh_id", $crvhId, array("vha_lock", "0"), "vha_day = '" . $currDay . "'");
                    endfor;
                    
                    // Write logdata into log database
                    $logCrvhSid = getFieldValueFromId("couriervehicle", "crvh_id", $crvhId, "crvh_sid");
                    $logTimeslots = getFieldValueFromId("job", "jb_id", $jbId, "jb_timeunits");
                    writeToLogDB("123",$hq_id,$jbId,$usr_id,"",$logCrvhSid,$csId,"MULT_DAY=1|DAYS=".$logDays."|UNITS=".$logTimeslots."|ORDERTIME_OLD=".$jbOrdertime);
                 endif;
              endif;
// *******************************************************************************
           endif;
        endif;
// writeToFile("../log/vhd.log", "-------- REMOVE END ---------------------------------------------------------------------------");

        // Final check of the job state, because the state could be changed during modification in disposition
        $jbState = getFieldValueFromId("job", "jb_id", $jbId, "jb_status");
        if ($doCommitTA == "1" || $jbState == "9" || $jbState == "0") :
           TA("C");
        else :
           TA("R");
           $retBool = false;
        endif;
        TA("E");
     endif;
  endif;
  return $retBool;
}


// Sets an association ("disposition reservation") between job and vehicle
function setAssocCrvhJb ($jbId, $crvhId, $csId, $currDay, $hour, $hourUnit, $timeslots, $hourTimeUnits = "", $doCommitTA = "") {
	global $db, $PHP_SELF;
	global $hq_id, $usr_id;

  // 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;

  $retBool = false;
  if ($hourTimeUnits != "" && is_numeric($hourTimeUnits) && $crvhId != "" && is_numeric($crvhId) && $currDay != "" && $hour != "" && is_numeric($hour) && 
     is_numeric($hourUnit) && $timeslots != "" && is_numeric($timeslots) && $jbId != "" && is_numeric($jbId) && $csId != "" && is_numeric($csId)) :

     TA("B");

     // Check for "multiple day" job
     if (isMultipleDayJob($jbId, $csId) == "0") :

        // Use semaphore(!) for combination "vehicle and day" and lock the vehicle for this day
        $res = updateStmt("vehicleavailability", "crvh_id", $crvhId, array("vha_lock", "1"), "vha_day = '" . $currDay . "' AND vha_lock = '0'");
        if ($db->affected_rows > 0) :

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

           /*
           // ATTENTION: The system has to follow the precondition that all entries of all timeslots have to exist for the specified vehicle !!!!
           if (!existsEntry("vehicledisposition",array("crvh_id",$crvhId,"LEFT(vhd_timeslot, 10)",$currDay))) :
              // Generate all new timeslot entries for the vehicle for the specified day
              generatePersistentTimeslots($crvhId, $currDay, $hourTimeUnits, $csId);
              $capacityProblem = "";
           else :
              $capacityProblem = checkAvailableVehicleCapacity($crvhId, $currDay, $startTimeslotToBeChecked, $endTimeslotToBeChecked, $jbId);
           endif;
           */

           $capacityProblem = checkAvailableVehicleCapacity($crvhId, $currDay, $startTimeslotToBeChecked, $endTimeslotToBeChecked, $jbId);

           // if ($capacityProblem == "") :  // ALL restrictions have to be achieved !!!!  **** ATTENTION: CHANGES WILL EFFECT Javascript in "vehicle_disposition" !!!! ****
           if ($capacityProblem == "" || $capacityProblem == "2") :  // Restriction payload check will not be achieved. (Presently...!)
              $res = updateStmt("vehicledisposition", "crvh_id", $crvhId, array("jb_id", $jbId), "vhd_timeslot >= '" . $startTimeslotToBeChecked . "' AND vhd_timeslot < '" . $endTimeslotToBeChecked . "'");
              if ($db->affected_rows > 0) :

                 // updateVehicleAvailability($crvhId, $csId, $startTimeslotToBeChecked, $hourTimeUnits);  // Write redundant data for delivery appointment search later on
                 updateAllCsVehicleAvailability($crvhId, $csId, $startTimeslotToBeChecked, $hourTimeUnits);

                 // Check vehicle restrictions (weight, positions, etc.)
                 if ($jbId != "") :
                    $atWeightJb = getTratTotalweight($jbId);  // Get the total weight of all articles of the specified job

                    $capacityFreeWeight = getFieldValueFromClause("vehicleavailability","vha_weight","crvh_id = '" . $crvhId . "' AND vha_day = '" . $currDay . "'");  // Get free weight capacity of the specified vehicle

                    $capacityFreeWeight = $capacityFreeWeight - $atWeightJb;
                    updateStmt("vehicleavailability", "crvh_id", $crvhId, array("vha_weight", $capacityFreeWeight), "vha_day = '" . $currDay . "'");
                 endif;

                 $retBool = true;

                 // Write logdata into log database
                 $logCrvhSid = getFieldValueFromId("couriervehicle", "crvh_id", $crvhId, "crvh_sid");
                 writeToLogDB("124",$hq_id,$jbId,$usr_id,"",$logCrvhSid,$csId,"MULT_DAY=0|START=".$startTimeslotToBeChecked."|UNITS=".$timeslots);
              endif;
           endif;

           // Reset semaphore
           updateStmt("vehicleavailability", "crvh_id", $crvhId, array("vha_lock", "0"), "vha_day = '" . $currDay . "'");
        endif;
     else :
// *******************************************************************************
// MULTIPLE DAYS
        // Get the the number of days with their time units 
        // E.g. jb_timeunits = 116 and $csRelatedMaxTimeunitsService = 48 <=> retArray[0] = 48, retArray[1] = 48, retArray[2] = 20 (rest of example with 116)
        $daysWithJobTimeUnitsArray = getMultipleDayJobTimeUnitsPerDay($jbId, $csId);
// writeToFile("../log/vhd.log", $daysWithJobTimeUnitsArray[0] . " - " . $daysWithJobTimeUnitsArray[1] . " - " . $daysWithJobTimeUnitsArray[2]);
        $daysWithJobTimeUnitsArrayLen = count($daysWithJobTimeUnitsArray);
        if ($daysWithJobTimeUnitsArrayLen > 0) :
           // Get earliest start time of the related customer
           $parCsRelatedDayStartTimeunit = getObjectBasedParameterValue("CS_DAY_TIMEUNIT_START", $csId, $hq_id);
           if ($parCsRelatedDayStartTimeunit == "") :
              // Gets the first (start)timeunit of the first daytime interval from metatype (e.g. "08_00") !!!!
              $tmpTimeIntervalArray = metatypeGetMappedValues("day_time", $hourTimeUnits, $csId, "cs", "");
              $parCsRelatedDayStartTimeunit = $tmpTimeIntervalArray[0][0];
           endif;
           if ($parCsRelatedDayStartTimeunit == "") : $parCsRelatedDayStartTimeunit = "08_00"; endif;  // Fallback

           $allDaysLocked = true;
           $dayLockedArray = array();
           $vhtDayCapacities = true;
           $timeSlotArray = array();
// writeToFile("../log/vhd.log", "[1. ITERATION]");
           for ($i = 0; $i < $daysWithJobTimeUnitsArrayLen; $i++) :
               $tmpDay = getDateTime("format", array(0,0,0,substr($currDay,5,2),substr($currDay,8,2) + $i,substr($currDay,0,4)), "Y-m-d");
// writeToFile("../log/vhd.log", "tmpDay : " . $tmpDay);
               // Lock vehicle for this day
               $res = updateStmt("vehicleavailability", "crvh_id", $crvhId, array("vha_lock", "1"), "vha_day = '" . $tmpDay . "' AND vha_lock = '0'");
               if ($db->affected_rows == 0) :
                  $allDaysLocked = false;
                  $dayLockedArray[$i] = false;
                  break;
               else :
                  $dayLockedArray[$i] = true;
               endif;
               // Get first timeslot and last timeslot (interval) to check the vehicle availability
               if ($i == 0) :
                  $startTimeslotToBeChecked = $tmpDay . '_' . pad($hour, 2) . '_' . pad($hourUnit, 2);
                  $tmpHour = $hour;
                  $tmpHourUnit = $hourUnit;
               else :
                  $startTimeslotToBeChecked = $tmpDay . '_' . $parCsRelatedDayStartTimeunit;
                  $tmpHour = substr($parCsRelatedDayStartTimeunit,0,2);
                  $tmpHourUnit = substr($parCsRelatedDayStartTimeunit,3,2);
               endif;
               for ($j = 0; $j < $daysWithJobTimeUnitsArray[$i]; $j++) :
                   $tmpHourUnit++;
                   if ($tmpHourUnit == $hourTimeUnits) :
                      $tmpHour++;
                      $tmpHourUnit = 0;
                   endif;
               endfor;
               $endTimeslotToBeChecked = $tmpDay . '_' . pad($tmpHour, 2) . '_' . pad($tmpHourUnit, 2);
               $timeSlotArray[$i] = array($startTimeslotToBeChecked, $endTimeslotToBeChecked);
               $capacityProblem = checkAvailableVehicleCapacity($crvhId, $tmpDay, $startTimeslotToBeChecked, $endTimeslotToBeChecked, $jbId);
               if ($capacityProblem == "1") :  // Restriction payload check will not be achieved. (Presently...!)
                  $vhtDayCapacities = false;
                  break;
               endif;
           endfor;
// writeToFile("../log/vhd.log", "[2. ITERATION]");
           // Reserve timeslots in FDS
           if ($allDaysLocked && $vhtDayCapacities) :
              $logDays = "";
              for ($i = 0; $i < $daysWithJobTimeUnitsArrayLen; $i++) :
                  $tmpDay = getDateTime("format", array(0,0,0,substr($currDay,5,2),substr($currDay,8,2) + $i,substr($currDay,0,4)), "Y-m-d");
                  $startTimeslotToBeChecked = $timeSlotArray[$i][0];
                  $endTimeslotToBeChecked = $timeSlotArray[$i][1];
                  $res = updateStmt("vehicledisposition", "crvh_id", $crvhId, array("jb_id", $jbId), "vhd_timeslot >= '" . $startTimeslotToBeChecked . "' AND vhd_timeslot < '" . $endTimeslotToBeChecked . "'");
                  if ($db->affected_rows > 0) :

                     // updateVehicleAvailability($crvhId, $csId, $tmpDay, $hourTimeUnits);  // Write redundant data for delivery appointment search later on
                     updateAllCsVehicleAvailability($crvhId, $csId, $tmpDay, $hourTimeUnits);

                     // Check vehicle restrictions (weight, positions, etc.)
                     if ($jbId != "") :
                        $atWeightJb = getTratTotalweight($jbId);  // Get the total weight of all articles of the specified job
                        $capacityFreeWeight = getFieldValueFromClause("vehicleavailability","vha_weight","crvh_id = '" . $crvhId . "' AND vha_day = '" . $currDay . "'");  // Get free weight capacity of the specified vehicle
                        $capacityFreeWeight = $capacityFreeWeight - $atWeightJb;
                        updateStmt("vehicleavailability", "crvh_id", $crvhId, array("vha_weight", $capacityFreeWeight), "vha_day = '" . $currDay . "'");
                     endif;

                     if ($logDays != "") : $logDays .= ","; endif;
                     $logDays .= $tmpDay;

                     $retBool = true;
                  endif;
              endfor;
           endif;
// writeToFile("../log/vhd.log", "[3. ITERATION]");
           // Unlock 
           for ($i = 0; $i < $daysWithJobTimeUnitsArrayLen; $i++) :
               if ($dayLockedArray[$i]) :
                  $tmpDay = getDateTime("format", array(0,0,0,substr($currDay,5,2),substr($currDay,8,2) + $i,substr($currDay,0,4)), "Y-m-d");
                  updateStmt("vehicleavailability", "crvh_id", $crvhId, array("vha_lock", "0"), "vha_day = '" . $tmpDay . "'");
               endif;
           endfor;
        endif;
        
        // Write logdata into log database
        $logCrvhSid = getFieldValueFromId("couriervehicle", "crvh_id", $crvhId, "crvh_sid");
        writeToLogDB("124",$hq_id,$jbId,$usr_id,"",$logCrvhSid,$csId,"MULT_DAY=0|DAYS=".$logDays."|UNITS=".$timeslots);        
// *******************************************************************************
     endif;
// writeToFile("../log/vhd.log", "-------- SET END ---------------------------------------------------------------------------");

     // Final check of the job state, because the state could be changed during modification in disposition
     $jbState = getFieldValueFromId("job", "jb_id", $jbId, "jb_status");
     if ($doCommitTA == "1" || $jbState == "9" || $jbState == "0") :
        TA("C");
     else :
        TA("R");
        $retBool = false;
     endif;
     TA("E");
  endif;
  return $retBool;
}


// Checks vehicle being blocked for a special day
function crvhIsBlocked ($crvhId, $currDay, $blockBit = 0) {
	global $db, $PHP_SELF;

  $retIsBlocked = true;  // Init
  if ($crvhId != "" && is_numeric($crvhId) && $currDay != "") :

     // Get block mode from bit
     $blockMode = pow(2,$blockBit);
  
     $vhaBlocked = getFieldValueFromClause("vehicleavailability","vha_blocked","crvh_id = '" . $crvhId . "' AND vha_day = '" . $currDay . "'");     
     if (($vhaBlocked & $blockMode) == 0) :
        $retIsBlocked = false;
     endif;
  endif;
  return $retIsBlocked;
}


// Checks vehicle being blocked for a special day
function crvhBlockedState ($crvhId, $currDay) {
	global $db, $PHP_SELF;

  $retBlockedState = "";  // Init
  if ($crvhId != "" && is_numeric($crvhId) && $currDay != "") :
     $retBlockedState = getFieldValueFromClause("vehicleavailability","vha_blocked","crvh_id = '" . $crvhId . "' AND vha_day = '" . $currDay . "'");
  endif;
  return $retBlockedState;
}


// Blocks a vehicle for a special day and for a special block mode 
// $blockBit: Bit 0 <=> block vehicle by headquarters disposition only
//          : Bit 1 <=> block vehicle for disposition of the courier by himself <=> courier CAN administrate the jobs
function crvhBlock ($crvhId, $currDay, $blockBit = 0) {
	global $db, $PHP_SELF;
	
   $retBlocked = "";
   if ($crvhId != "" && is_numeric($crvhId) && $currDay != "") :

      // Get block mode from bit
      $blockMode = pow(2,$blockBit);

      // Check current state
      $crvhBlockedState = crvhBlockedState($crvhId, $currDay);
      if ($crvhBlockedState != "") :
         if (($crvhBlockedState & $blockMode) == $blockMode) :
            $retBlocked = "IS_BLOCKED";  // Already blocked regarding the requested block mode
         else :
            $crvhBlockedState = ($crvhBlockedState | $blockMode);
            $res = updateStmt("vehicleavailability", "crvh_id", $crvhId, array("vha_blocked", $crvhBlockedState), "vha_day = '" . $currDay . "'");   
            if ($db->affected_rows > 0) :
               $retBlocked = "SET_BLOCKED";  // Set to blocked
            endif;
         endif;
      endif;
   endif;
  return $retBlocked;
}


// Unblocks a vehicle for a special day
// $blockBit: Bit 0 <=> unblock vehicle by headquarters disposition only
//          : Bit 1 <=> unblock vehicle for disposition of the courier by himself <=> courier CANNOT administrate the jobs
function crvhUnblock ($crvhId, $currDay, $blockBit = 0) {
	global $db, $PHP_SELF;
	
   $retUnblocked = "";
   if ($crvhId != "" && is_numeric($crvhId) && $currDay != "") :

      // Get block mode from bit
      $blockMode = pow(2,$blockBit);

      // Check current state
      $crvhBlockedState = crvhBlockedState($crvhId, $currDay);
      if ($crvhBlockedState != "") :
         if (($crvhBlockedState & $blockMode) == $blockMode) :
            $crvhBlockedState = ($crvhBlockedState & ~$blockMode);
            $res = updateStmt("vehicleavailability", "crvh_id", $crvhId, array("vha_blocked", $crvhBlockedState), "vha_day = '" . $currDay . "'");
            if ($db->affected_rows > 0) :
               $retUnblocked = "SET_UNBLOCKED";  // Set to unblocked
            endif;
         else :
            $retUnblocked = "IS_UNBLOCKED";  // Already unblocked regarding the requested block mode
         endif;
      endif;
   endif;
  return $retUnblocked;
}


// Blocks a vehicle for a special day to ENABLE courier disposition
function crvhBlockForCourierDispo ($crvhId, $currDay) {
	global $db, $PHP_SELF;
	global $usr_id;
	
   $retBlocked = "";
   
   // Get courier from vehicle
   $crId = getFieldValueFromId("couriervehicle", "crvh_id", $crvhId, "cr_id");   
   
   if ($crvhId != "" && is_numeric($crvhId) && $currDay != "" && $crId != "" && is_numeric($crId)) :

      // Check current state
      $crvhBlockedState = crvhBlockedState($crvhId, $currDay);

      if ($crvhBlockedState != "") :
         if (($crvhBlockedState & 2) == 2) :
            $retBlocked = "IS_BLOCKED";  // Already blocked regarding the requested block mode
         else :
            // Set bit 1 (decimal 2) in vha.vha_blocked
            $retBlocked = crvhBlock($crvhId, $currDay, 1);

            if ($retBlocked == "SET_BLOCKED") :

               // Block all jobs of the vehicle of the selected day
               $jbIdArray = getColVectorFromDB2ArrayByClause("vehicledisposition", "jb_id", "crvh_id = '" . $crvhId . "' AND LEFT(vhd_timeslot, 10) = '" . $currDay . "' AND jb_id != '0'", "", "", "DISTINCT");
               $jbIdArrayLen = count($jbIdArray);

               if ($jbIdArrayLen > 0) :
                  $crvhSid = getFieldValueFromId("couriervehicle", "crvh_id", $crvhId, "crvh_sid");
               
                  // $tmpJbIdArray = getColVectorFromDB2ArrayByClause("job", "jb_id", "jb_id IN (" . implode(',', $jbIdArray) . ") AND jb_status = '9' AND (ISNULL(cr_id_order) OR cr_id_order = '0') AND jb_offer = '0'", "", "", "");
                  $tmpJbIdArray = getColVectorFromDB2ArrayByClause("job", "jb_id", "jb_id IN (" . implode(',', $jbIdArray) . ") AND jb_status = '9' AND jb_offer = '0'", "", "", "");
                  $jbIdArray = $tmpJbIdArray;
                  $jbIdArrayLen = count($jbIdArray);

                  if ($jbIdArrayLen > 0) :
                     for ($i = 0; $i < $jbIdArrayLen; $i++) :
                         updateStmt("job", "jb_id", $jbIdArray[$i], array("cr_id", "", "cr_id_order", $crId, "jb_status", "0", "cr_sid", $crvhSid), "jb_status = '9'");
                     endfor;
                  endif;
               endif;
            endif;
         endif;
      endif;
   endif;
  return $retBlocked;
}


// Unblocks a vehicle for a special day to DISABLE courier disposition
function crvhUnblockForCourierDispo ($crvhId, $currDay) {
	global $db, $PHP_SELF;
	global $usr_id;
	
   $retUnblocked = "";
   
   // Get courier from vehicle
   $crId = getFieldValueFromId("couriervehicle", "crvh_id", $crvhId, "cr_id");   
   
   if ($crvhId != "" && is_numeric($crvhId) && $currDay != "" && $crId != "" && is_numeric($crId)) :

      // Check current state
      $crvhBlockedState = crvhBlockedState($crvhId, $currDay);
      if ($crvhBlockedState != "") :
         if (($crvhBlockedState & 2) == 2) :

            // Set bit 1 (decimal 2) in vha.vha_blocked
            $retUnblocked = crvhUnblock($crvhId, $currDay, 1);

            if ($retUnblocked == "SET_UNBLOCKED") :
               // Block all jobs of the vehicle of the selected day
               $jbIdArray = getColVectorFromDB2ArrayByClause("vehicledisposition", "jb_id", "crvh_id = '" . $crvhId . "' AND LEFT(vhd_timeslot, 10) = '" . $currDay . "' AND jb_id != '0'", "", "", "DISTINCT");
               $jbIdArrayLen = count($jbIdArray);

               if ($jbIdArrayLen > 0) :
                  // $crvhSid = getFieldValueFromId("couriervehicle", "crvh_id", $crvhId, "crvh_sid");

                  $tmpJbIdArray = getColVectorFromDB2ArrayByClause("job", "jb_id", "jb_id IN (" . implode(',', $jbIdArray) . ") AND jb_status = '0' AND jb_offer = '0'", "", "", "");
                  $jbIdArray = $tmpJbIdArray;
                  $jbIdArrayLen = count($jbIdArray);

                  if ($jbIdArrayLen > 0) :
                     for ($i = 0; $i < $jbIdArrayLen; $i++) :
                         updateStmt("job", "jb_id", $jbIdArray[$i], array("cr_id", "", "cr_id_order", "", "jb_status", "9", "cr_sid", ""), "jb_status = '0'");
                     endfor;
                  endif;
               endif;
            endif;
         else :
            $retUnblocked = "IS_UNBLOCKED";  // Already blocked regarding the requested block mode
         endif;
      endif;
   endif;
  return $retUnblocked;
}


// Unblocks a vehicle for a special day to DISABLE courier disposition
function cartageNoteSendMail ($csId, $crvhId, $currDay) {
	global $db, $PHP_SELF;

  $retVal = "0";

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

     $path = getAbsoluteSystemPath();

     // Get mail address data for the related customer. (No global parameter checks !!!!)
     $parMailToAddresses = getObjectBasedParameterValue("MAIL_CARTAGE_NOTE_MAIL_TO", $csId, "", "", "1");
     $parMailCcAddresses = getObjectBasedParameterValue("MAIL_CARTAGE_NOTE_MAIL_CC", $csId, "", "", "1");
     $parMailBccAddresses = getObjectBasedParameterValue("MAIL_CARTAGE_NOTE_MAIL_BCC", $csId, "", "", "1");
     $parMailSenderAddress = getObjectBasedParameterValue("MAIL_CARTAGE_NOTE_MAIL_SENDER", $csId, "", "", "1");

     if ($parMailToAddresses != "" && $parMailSenderAddress != "") : 

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

        // Title, mail subject and mail text !!!!
        $title = getLngt("ROLLKARTE") . " " . $crvhSid . " " . $currDay;

        // Configure system command parameters
        //            auth             log_group    f_act                         title            hqId     iln. dwl. typ pgs pth functionName       par_01          par_02
        $cmdParStr = "acapella7890 \"" . $crvhSid . "\" calculateAndSendMailPDF \"" . $title . "\" " . $crHqId . " 0 0 pdf \"\" \"\" getCartageNote " . $crvhId . " " . $currDay . " ";
        //            par_03 ....                       par_10
        $cmdParStr .= "\"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" ";
        //            mail_to                          file       mail_sbj       mail_text att_file_typ     mail_cc                         mail_bcc                         mail_sender                 parKeyForLogFile                objId cascadingObjType
        $cmdParStr .= "\"" . $parMailToAddresses . "\" \"\" \"" . $title . "\" \"" . $title . "\" pdf \"" . $parMailCcAddresses . "\" \"" . $parMailBccAddresses . "\" \"" . $parMailSenderAddress . "\" AUTOMAILER_CARTAGE_NOTE_LOGFILE \"\" \"\"";

        $system_result = "";
        $cmd = "php " . $path . "/admin/pdf_generic_function.php " . $cmdParStr . " >" . $path . "/log/auto_cartage_note.stdout+err 2>&1 &";
        $ausgabe = system($cmd, $system_result);
        // echo $system_result . "<br>";
        $retVal = "1";
     endif;
  endif;
  return $retVal;
}


// 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)
// Parameters:
// $csId : ID of the related customer
// $clockTimeInterval : ID of the related customer
function getNumOfTimeUnitsBetweenInterval($csId, $clockTimeInterval, $hourTimeUnits = "") {
	global $db, $PHP_SELF;

  $retVal = "0";

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

     // 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;

     // Check daytime array being empty
     if (!is_array($clockTimeInterval) || count($clockTimeInterval) == 0) :
        $clockTimeInterval = metatypeGetMappedValues("day_time", "", $csId, "cs", "1");
     endif;
     $clockTimeIntervalLen = count($clockTimeInterval);
     $tmpWorkingTimeMinutes = 0;
     $tmpWorkingStartTime = "";
     $tmpWorkingEndTime = "";
     for ($i = 0; $i < $clockTimeIntervalLen; $i++) :
         if ($tmpWorkingStartTime == "" || $clockTimeInterval[$i][0] < $tmpWorkingStartTime) :
            $tmpWorkingStartTime = $clockTimeInterval[$i][0];
         endif;
         if ($tmpWorkingEndTime == "" || $clockTimeInterval[$i][1] > $tmpWorkingEndTime) :
            $tmpWorkingEndTime = $clockTimeInterval[$i][1];
         endif;
     endfor;
     if ($tmpWorkingStartTime != "" && $tmpWorkingEndTime != "") :
        if ($tmpWorkingEndTime > $tmpWorkingStartTime) :
           $tmpWorkingTimeMinutes = ((intval(substr($tmpWorkingEndTime,0,2)) - intval(substr($tmpWorkingStartTime,0,2))) * 60) - intval(substr($tmpWorkingStartTime,3,2)) + intval(substr($tmpWorkingEndTime,3,2));
        endif;
     endif;
     // Compute number of time units from clock time interval
     $retVal = floor($tmpWorkingTimeMinutes / (60 / $hourTimeUnits));
  endif;
  return $retVal;
}


// Gets jobs of the cartage note from a single vehicle and a single day
function getCrvhCartageNote ($crvhId, $currDay = "", $mode = "") {

  $retArray = array();

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

     if ($currDay == "") : $currDay = getDateTime("3"); endif;

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

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

     if ($mode == "1") :

        $geoCoordinatesArray = array();
        for ($i = 0; $i < $retArrayLen; $i++) :
            // Get commission no of 2nd station
            $atiData02 = "";
            $atiData03 = "";
            $trCommissionNo = getFieldValueFromClause("tour","tr_commission_no","jb_id = '" . $retArray[$i] . "' AND tr_sort = '2'");
            $trAdId = getFieldValueFromClause("tour","ad_id","jb_id = '" . $retArray[$i] . "' AND tr_sort = '2'");
            if ($trCommissionNo != "") :
               $atiData02 = getFieldValueFromClause("articleitem","ati_data_02","ati_serialno = '" . $trCommissionNo . "'");
               $atiData03 = getFieldValueFromClause("articleitem","ati_data_03","ati_serialno = '" . $trCommissionNo . "'");
            endif;
            if (($atiData02 != "" && $atiData03 != "") || ($trAdId != "") && is_numeric($trAdId) && $trAdId > "0") :
               $geoCoordinatesArray[] = array($atiData03, $atiData02, $trAdId, $trCommissionNo);
            endif;
        endfor;
        $retArray = $geoCoordinatesArray;
     endif;
  endif;
  return $retArray;
}
?>
