<?php
/*=======================================================================
 *
 * jb_list.php   (*** BWV ***)
 *
 * Autor: Marc Vollmann
 *
  =======================================================================*/

include_once ("../include/mcglobal.inc.php");
include_once ("../include/auth.inc.php");
include_once ("../include/html.inc.php");
include_once ("../include/caglobal.inc.php");    // Only for courier-list
include_once ("../include/copy_job.inc.php");    // E.g. for "Storno"
include_once ("../include/ranking.inc.php");     // Checks ranking to be lost or not


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

// Check HTTP-Parameters
getSecHttpVars("1",array("f_act", "customerId", "cscIdRoot", "cscIdActual", "statusMessage", "dbhistory",
                         "defaultListStatus", "maskNumOfWin", "maskNumOfWins", "showScalingMenu", 
                         "jb_status", "jb_sort", "job_no_from", "job_no_to",
                         "day_from", "month_from", "year_from", "day_to", "month_to", "year_to",
                         "jb_id_storno", "jb_storno_costs", "jb_storno_rhythm", "f_jb_id",
                         "f_cr_sid", "f_cr_sid_search", "f_area_from", "f_area_to", 
                         "f_filter", "f_filter_active", "f_filter_vehicletype", "f_sort_direction",
                         "f_search_ad_street", "f_search_ad_zipcode", "f_search_ad_city", 
                         "f_search_tr_comp", "f_search_tr_person", "f_search_tr_remark", 
                         "f_search_tr_commission_no", 
                         "f_search_ad_street_payer", "f_search_ad_zipcode_payer", "f_search_ad_city_payer", 
                         "f_search_cmp_comp_payer", "f_search_cs_eid_payer", "f_search_csc_name_payer",
                         "f_filter_browse_start", "f_hq_id", "distance", "useRemoteDB"));

// Number of frames and definition of frame names (e.g. for date fields)
if (!isset($maskNumOfWin)) : $maskNumOfWin = ""; endif;    // ONLY is set if more than one frame
$currentFrameName = "maincontent";
if (is_numeric($maskNumOfWin)) :
   $currentFrameName = "content" . $maskNumOfWin;
endif;

// Define constants before changing the database
$maskJoblistStartdateYesterdayPRE = getParameterValue("0", "MASK_JOBLIST_STARTDATE_YESTERDAY");
$maskJoblistBrowseMaxPRE = getParameterValue($emp_id, "MASK_JOBLIST_BROWSE_MAX");
$maskJoblistShowUpToVhtPRE = getParameterValue($emp_id, "MASK_JOBLIST_SHOW_UPTO_VHT");
$displayedListColsPRE = getParameterValue($emp_id, "MASK_JB_LIST_LONGHAUL_COLS");
$displayedListColsPRE2 = getParameterValue("0", "MASK_JB_LIST_LONGHAUL_COLS", $hqId);
$specialOrderByTakenJobsPRE = getParameterValue("0", "MASK_JOBLIST_TAKENJOB_ORDERBY");
$jobHopsToBeSearchedInPRE = getParameterValue("0", "JOBLIST_NUM_OF_HOPS", "0");

// Define rights before changing the database
$empHasRight10 = authCheckEmployeeRights($emp_id, "10");
$empHasRight12 = authCheckEmployeeRights($emp_id, "12");

// ******************************************************
// Very special treatment for access to remote database
include_once ("../include/bwv.inc.php");
$remoteDBisActive = false;
if (BWV2_checkEmpRemoteDBAccess($useRemoteDB, $emp_id)) :
   $remoteDBisActive = BWV2_setRemoteDBAccessParameter();
endif;
$constLonghaulActive = "";
if ($remoteDBisActive) :   
   if ($f_hq_id == "") : $f_hq_id = array(); endif;
   if (count($f_hq_id) == 0) : array_push($f_hq_id, getMinOfField("headquarters", "hq_id", "")); endif;
   $constLonghaulActive = getParameterValue("0", "LONGHAUL_ACTIVE_REMOTE_DB", "0");
   $currentFrameName .= "1";
endif;
// ******************************************************

$userTypeName = "hq";
if ($jb_status == "") : $jb_status = "$defaultListStatus"; endif;       // Initilize job status with default
if ($jb_status == "") : $jb_status = "9"; endif;                        // Initilize job status if no default exists

if (!is_numeric($job_no_from)) : $job_no_from = ""; endif;
if (!is_numeric($job_no_to)) : $job_no_to = ""; endif;
$f_cr_sid_search = trim($f_cr_sid_search);
if ($statusMessage == "") : $statusMessage = ""; endif;
if ($f_filter_vehicletype == "") : $f_filter_vehicletype = "0"; endif;
if ($distance == "") : $distance = "80"; endif;
if ($f_filter_browse_start == "") : $f_filter_browse_start = "0"; endif;
if ($f_sort_direction == "1") :
   $f_sort_direction_text = "DESC";     // DESCending
else :
   $f_sort_direction = "0";
   $f_sort_direction_text = "ASC";      // Sort is ASCending (default in SQL)
endif;    


// Decision to use the archive or normal tables
getDBNames($dbhistory);

// Filters: "Show permanent jobs", "Show future jobs", "Show incomplete jobs"
$filter_job_permanent = "checked";
$filter_job_future = "";
$filter_job_incomplete = "";
$filter_only_not_exported = "";
$filter_no_storno = "";
$filter_printview = "";
$filter_searchdeep = "";
$filter_only_longhaul = "";
$filter_only_offer = "";

if ($f_filter_active == "1") :      // Check if entry is from menu or joblist by itself ...
   $filter_job_permanent = "";
   $filter_job_future = "";
endif;
if ($f_filter != "") :
   if (!(array_search("job_permanent",$f_filter) === FALSE)) : $filter_job_permanent = "checked"; endif;
   if (!(array_search("job_future",$f_filter) === FALSE)) : $filter_job_future = "checked"; endif;
   if (!(array_search("job_incomplete",$f_filter) === FALSE)) : $filter_job_incomplete = "checked"; endif;
   if (!(array_search("job_only_not_exported",$f_filter) === FALSE)) : $filter_only_not_exported = "checked"; endif;
   if (!(array_search("job_no_storno",$f_filter) === FALSE)) : $filter_no_storno = "checked"; endif;
   if (!(array_search("job_cr_favoured",$f_filter) === FALSE)) : $filter_cr_favoured = "checked"; endif;
   if (!(array_search("job_tr_time_check",$f_filter) === FALSE)) : $filter_tr_time_check = "checked"; endif;
   if (!(array_search("job_printview",$f_filter) === FALSE)) : $filter_printview = "checked"; endif;
   if (!(array_search("job_tr_searchdeep",$f_filter) === FALSE)) : $filter_searchdeep = "checked"; endif;
   if (!(array_search("job_only_longhaul",$f_filter) === FALSE)) : $filter_only_longhaul = "checked"; endif;
   if (!(array_search("job_only_offer",$f_filter) === FALSE)) : $filter_only_offer = "checked"; endif;
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;

// HQ_ID string e.g. for courier list
$f_hq_id_string = implode(",", $f_hq_id);

// Current number of headquarters of the mandator
$numOfHq = getCountOfTable("mandatorheadquarters", "md_id = '" . $md_id . "'");

// Get usr_id of the current employee (session)
$currentSessionUsrId = getFieldValueFromId("employee", "emp_id", $emp_id, "usr_id");

// Get the general invmode for the headquarter
$mediationMode = MODE_INTERMEDIATION;
if ($mediationMode == "") :
   $mediationMode = getFieldValueFromId("headquarters", "hq_id", "$hq_id", "hq_invmode");
endif;

// Look-up for existence of the mediation-area
if ($mediationMode == "1") :
   // mediation area equals a single zipcode
   if ($f_area_from != "") :
      if (!existsEntry("serviceplz",array("srvp_plz",$f_area_from))) :
         $f_area_from = "";
      endif;
   endif;
   if ($f_area_to != "") :
      if (!existsEntry("serviceplz",array("srvp_plz",$f_area_to))) :
         $f_area_to = "";
      endif;
   endif;
elseif ($mediationMode == "2" || $mediationMode == "3") :
   // mediation area is an aggregation of zipcodes
   if ($f_area_from != "") :
      if (!existsEntry("serviceplzarea",array("srvpa_name",$f_area_from))) :
         $f_area_from = "";
      endif;
   endif;
   if ($f_area_to != "") :
      if (!existsEntry("serviceplzarea",array("srvpa_name",$f_area_to))) :
         $f_area_to = "";
      endif;
   endif;   
endif;

// Check range of date. All fields have to be set
if ($day_from == "" || $month_from == "" || $year_from == "" || 
    $day_to == "" || $month_to == "" || $year_to == "") :
    
    // Initialize date-ranges to the current date
    $fromDateRange = getDateTime("3") . " 00:00:00";
    $toDateRange = getDateTime("3") . " 23:59:59";
    
    // $maskJoblistStartdateYesterday = getParameterValue("0", "MASK_JOBLIST_STARTDATE_YESTERDAY");
    $maskJoblistStartdateYesterday = $maskJoblistStartdateYesterdayPRE;
    if ($maskJoblistStartdateYesterday == "1") :
       $day_from = getDateTime("day_yesterday");
       $month_from = getDateTime("month_yesterday");
       $year_from = getDateTime("year_yesterday");
    else :
       $day_from = getDateTime("day");
       $month_from = getDateTime("month");
       $year_from = getDateTime("year");
    endif;
    $day_to = getDateTime("day_tomorrow");
    $month_to = getDateTime("month_tomorrow");
    $year_to = getDateTime("year_tomorrow");
else :
    $fromDateRange = $year_from . "-" . pad($month_from,2) . "-" . pad($day_from,2) . " 00:00:00";
    $toDateRange = $year_to . "-" . pad($month_to,2) . "-" . pad($day_to,2) . " 23:59:59";
endif;

// All open jobs in the future have to be displayed
if ($filter_job_future != "") : $toDateRange = ""; endif;


// Get parameter values
// $maskJoblistBrowseMax = getParameterValue($emp_id, "MASK_JOBLIST_BROWSE_MAX");
$maskJoblistBrowseMax = $maskJoblistBrowseMaxPRE;
if ($maskJoblistBrowseMax == "" || !is_numeric($maskJoblistBrowseMax) || $maskJoblistBrowseMax < 100 || $maskJoblistBrowseMax > 1000) :
   $maskJoblistBrowseMax = 100;
endif;
// $maskJoblistShowUpToVht = getParameterValue($emp_id, "MASK_JOBLIST_SHOW_UPTO_VHT");
$maskJoblistShowUpToVht = $maskJoblistShowUpToVhtPRE;
if ($maskJoblistShowUpToVht == "0" || !is_numeric($maskJoblistShowUpToVht)) :
   $maskJoblistShowUpToVht = "";
endif;


   // *** Save job-informations (Begin) ***

   if ($f_act == "setCourier" && $f_cr_sid != "" && $f_jb_id != "") :

      // Get current cr_id of the job before changing the courier
      $crIdCurrent = getFieldValueFromId("job","jb_id",$f_jb_id,"cr_id");
      $crIdOrderCurrent = getFieldValueFromId("job","jb_id",$f_jb_id,"cr_id_order");
      
      getDbFieldValues("courier",array("cr_id","cr_occupied"),array("cr_sid",$f_cr_sid));
      if ($cr_id != "") :
      
         // Special treatment according areas
         $jbAdressIdStart = getFieldValueFromClause("tour", "ad_id", "jb_id = '" . $f_jb_id . "' AND tr_sort = '1'");
         $jbZipcodeStart = getFieldValueFromId("address", "ad_id", $jbAdressIdStart, "ad_zipcode");
         $arLooseRanking = looseRanking($cr_id, $jbZipcodeStart);

         $currentTime = getDateTime("0");

         TA("B");            

         // Update job
         // According to be TA-safe the WHERE-Clause depends on the current list the user is in
         $jbStatusString = " (jb_status = '8' OR jb_status = '9' OR jb_status = '0' OR jb_status = '1') ";
         if (is_numeric($jb_status)) : $jbStatusString = "jb_status = '" . $jb_status . "'"; endif;
         $res = updateStmt("job", "jb_id", $f_jb_id, array("cr_id", "", "cr_id_order", $cr_id, "jb_status", "0", "cr_sid", $f_cr_sid, "jb_globaljob", "0", "jb_autoranking", "0"), $jbStatusString);

         if ($db->affected_rows > 0) :

            // Set current assigning time for revoking a job if not taken by the courier
            if (existsEntry("autoranking",array("jb_id",$f_jb_id,"cr_id",$cr_id))) :
               updateStmt("autoranking", "jb_id", $f_jb_id, array("ar_challenge", "0", "ar_lastassigntime", $currentTime, "ar_looseranking", $arLooseRanking, "ar_locating", "0"),"cr_id = '" . $cr_id . "'");
            else :
               insertStmt("autoranking", array("jb_id", $f_jb_id, "cr_id", $cr_id, "ar_challenge", "0", "ar_lastassigntime", $currentTime, "ar_looseranking", $arLooseRanking, "ar_locating", "0"));
            endif;

            // Insert PDA command to remove job (take cr_id/cr_id_order before changing)
            $currentTimePDA = getDateTime("datetime_plus_offset", array(0,0,30,0,0,0), $formatStr = "Y-m-d H:i:s");
            if ($crIdCurrent != "" && $crIdCurrent != "0") :
               insertPDACommand($hq_id, $crIdCurrent, "4", "1", $f_jb_id, $currentTimePDA, "");
            endif;
            if ($crIdOrderCurrent != "" && $crIdOrderCurrent != "0" && $crIdOrderCurrent != $crIdCurrent) :
               insertPDACommand($hq_id, $crIdOrderCurrent, "4", "1", $f_jb_id, $currentTimePDA, "");
            endif;
            
            // Write logdata into log database
            writeToLogDB("7",$hq_id,$f_jb_id,$currentSessionUsrId,$cr_id,$f_cr_sid,"","LOST_RANKING=" . ($arLooseRanking == "1" ? "YES" : "NO"));
         endif;

         TA("C");
         TA("E");
      endif;
   endif;   
   
   // *** Save job-informations (End) ***   
   
   
   // Get the array for formatting the database-values for the output according to the defined type
   $outputFormatField = defineOutputFormats();


   // --- TEMPLATE ----------------

   // Search filter in use? If NOT then do NOT enable the print view !!!
   $searchFiltersInUse = FALSE;
   if (strlen($f_search_ad_street) > 2 || strlen($f_search_ad_zipcode) > 2 || strlen($f_search_ad_city) > 2 ||
       strlen($f_search_tr_comp) > 2 || strlen($f_search_tr_person) > 2 || strlen($f_search_tr_remark) > 2 || strlen($f_search_tr_commission_no) > 2 ||
       strlen($f_search_ad_street_payer) > 2 || strlen($f_search_ad_zipcode_payer) > 2 || strlen($f_search_ad_city_payer) > 2 ||
       strlen($f_search_cmp_comp_payer) > 2 || strlen($f_search_cs_eid_payer) > 2 || strlen($f_search_csc_name_payer) > 2) :
       
       $searchFiltersInUse = TRUE;
   endif;
   
   // Initiate template-object
   $tpl = new IntegratedTemplate();
   if ($filter_printview == "checked" && $searchFiltersInUse) :
      $tpl->loadTemplatefile("jb_list_print.tpl.htm", true, true);
   else :
      $tpl->loadTemplatefile("jb_list.tpl.htm", true, true);
   endif;

   // Identification-parameters
   $tpl->setCurrentBlock("customerId"); $tpl->setVariable("_customerId_", ec($customerId)); $tpl->parseCurrentBlock("customerId");
   $tpl->setCurrentBlock("cscIdRoot"); $tpl->setVariable("_cscIdRoot_", ec($cscIdRoot)); $tpl->parseCurrentBlock("cscIdRoot");
   $tpl->setCurrentBlock("cscIdActual"); $tpl->setVariable("_cscIdActual_", ec($cscIdActual)); $tpl->parseCurrentBlock("cscIdActual");
   $tpl->setCurrentBlock("empIdMaster"); $tpl->setVariable("_empIdMaster_", ec($empIdMaster)); $tpl->parseCurrentBlock("empIdMaster");
   
   $tpl->setCurrentBlock("maskNumOfWin"); $tpl->setVariable("_maskNumOfWin_", $maskNumOfWin); $tpl->parseCurrentBlock("maskNumOfWin");
   $tpl->setCurrentBlock("currentFrameName"); $tpl->setVariable("_currentFrameName_", $currentFrameName); $tpl->parseCurrentBlock("currentFrameName");
   
   $tpl->setCurrentBlock("jb_sort"); $tpl->setVariable("_jb_sort_", $jb_sort); $tpl->parseCurrentBlock("jb_sort");
   $tpl->setCurrentBlock("statusmessage"); $tpl->setVariable("_statusmessage_", $statusMessage); $tpl->parseCurrentBlock("statusmessage");

   $tpl->setCurrentBlock("filter_job_permanent"); $tpl->setVariable("_filter_job_permanent_", $filter_job_permanent); $tpl->parseCurrentBlock("filter_job_permanent");
   $tpl->setCurrentBlock("filter_job_future"); $tpl->setVariable("_filter_job_future_", $filter_job_future); $tpl->parseCurrentBlock("filter_job_future");
   $tpl->setCurrentBlock("filter_job_incomplete"); $tpl->setVariable("_filter_job_incomplete_", $filter_job_incomplete); $tpl->parseCurrentBlock("filter_job_incomplete");

   $filterOnlyOfferCheckbox = "";
   if ($jb_status == "9") :   
      $filterOnlyOfferCheckbox .= "&nbsp;&nbsp;<input type=\"checkbox\" name=\"f_filter[]\" value=\"job_only_offer\"" . $filter_only_offer .  "> Nur Angebote" . "&nbsp;";
   endif;
   $tpl->setCurrentBlock("filter_job_only_offer"); $tpl->setVariable("_filter_job_only_offer_", $filterOnlyOfferCheckbox); $tpl->parseCurrentBlock("filter_job_only_offer");

   // ONLY for scaling the lists (frames)
   $set_list_scaling = "";
   if ($showScalingMenu == "1" && $maskNumOfWins > 1) :
      // Scaling factor for homogeneous scaling (no percent values set manually) ONLY default!
      $scale = round(100 / $maskNumOfWins);
      // Generate pulldowns
      $set_list_scaling .= "<tr><td colspan=\"4\">";
      for ($j = 1; $j <= $maskNumOfWins; $j++) :
          $set_list_scaling .= "Liste " . $j . ": ";
          $set_list_scaling .= "<select class=\"f8np1\" name=\"percentScaleValueWin_" . $j . "\">\n";
          $set_list_scaling .= "  <option value=\"" . $scale . "\" selected>&nbsp;</option>\n";
          $set_list_scaling .= "  <option value=\"10\">10</option>\n <option value=\"20\">20</option>\n <option value=\"30\">30</option>\n";
          $set_list_scaling .= "  <option value=\"40\">40</option>\n <option value=\"50\">50</option>\n <option value=\"60\">60</option>\n";
          $set_list_scaling .= "  <option value=\"70\">70</option>\n <option value=\"80\">80</option>\n <option value=\"90\">90</option>\n";
          $set_list_scaling .= "</select>\n";
          $set_list_scaling .= "(%)&nbsp;&nbsp;\n";
      endfor;
      // Define submit for scaling
      $set_list_scaling .= "<input class=\"f8np1\" type=\"button\" name=\"action\" value=\"Skalierung setzen\" onClick=\"finishPageForScaling(" . $maskNumOfWins . ");\">\n";
      $set_list_scaling .= "</td></tr>";
   endif;
   $tpl->setCurrentBlock("set_list_scaling"); $tpl->setVariable("_set_list_scaling_", $set_list_scaling); $tpl->parseCurrentBlock("set_list_scaling");


   // --- JOB -------------------

   // initialize
   if ($filter_printview == "checked" && $searchFiltersInUse) :
      $titles = "Nr.,Preis,Firma,Kurier,Fahrz.,Zeit,";
      $titles .= "Startadresse,,,,,Etappe 2,,,,,Etappe 3,,,,,Etappe 4,,,,,Etappe 5,,,,,Etappe 6,,,,";
   
      $fields = "jb_id,jb_ordertime,business_volume,tr_comp,cr_sid,vht_value,";
      $fields .= "address_1_street,address_1_zipcode,address_1_city,tour_1_person,tour_1_signname,tour_1_sign,";
      $fields .= "address_2_street,address_2_zipcode,address_2_city,tour_2_person,tour_2_signname,tour_2_sign,";
      $fields .= "address_3_street,address_3_zipcode,address_3_city,tour_3_person,tour_3_signname,tour_3_sign,";
      $fields .= "address_4_street,address_4_zipcode,address_4_city,tour_4_person,tour_4_signname,tour_4_sign,";
      $fields .= "address_5_street,address_5_zipcode,address_5_city,tour_5_person,tour_5_signname,tour_5_sign,";
      $fields .= "address_6_street,address_6_zipcode,address_6_city,tour_6_person,tour_6_signname,tour_6_sign";

      $aligns = "l,l,l,l,l,l,l,l,l,l,l,l,l,l,l,l,l,l,l,l,l,l,l,l,l,l,l,l,l,l,l,l,l,l,l,l";
      $valigns = ",,,,,,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t";
      
      $cellTextPre = "Auftrag: ,Zeit: ,Betrag: ,Abholung: ,Fahrer: ,Fahrzeug:";
      
      $newline = "001101001001001001001001001001001000";   // Set only for print layout
      $emptylines = "1";
      $noColoredCells = "1";
      $noTableHeader = "1";
   else :  

      $dspTitles = array();                                $dspFields = array();                                    $dspAligns = array();                                  
      $dspTitles["jb_id"] = "Nr.";                         $dspFields["jb_id"] = "jb_id";                           $dspAligns["jb_id"] = "r";
      $dspTitles["business_volume"] = "Preis";             $dspFields["business_volume"] = "business_volume";       $dspAligns["business_volume"] = "r";
      $dspTitles["jb_tourname"] = "Tourenname";            $dspFields["jb_tourname"] = "jb_tourname";               $dspAligns["jb_tourname"] = "l";
      $dspTitles["tr_comp"] = "Firma";                     $dspFields["tr_comp"] = "tr_comp";                       $dspAligns["tr_comp"] = "l";
      $dspTitles["tr_comp2"] = "Fa.2";                     $dspFields["tr_comp2"] = "tr_comp2";                     $dspAligns["tr_comp2"] = "l";
      $dspTitles["streethsno"] = "Startadresse";           $dspFields["streethsno"] = "streethsno";                 $dspAligns["streethsno"] = "l";
      $dspTitles["jb_tourzipcodes"] = "PLZn";              $dspFields["jb_tourzipcodes"] = "jb_tourzipcodes";       $dspAligns["jb_tourzipcodes"] = "c";
      $dspTitles["jb_tourcities"] = "Orte";                $dspFields["jb_tourcities"] = "jb_tourcities";           $dspAligns["jb_tourcities"] = "c";
      $dspTitles["vht_value"] = "Fahrz.";                  $dspFields["vht_value"] = "vht_value";                   $dspAligns["vht_value"] = "c";
      $dspTitles["jb_ordertime"] = "Auftragszeit";         $dspFields["jb_ordertime"] = "jb_ordertime";             $dspAligns["jb_ordertime"] = "c";
      $dspTitles["jb_reserv"] = "R.";                      $dspFields["jb_reserv"] = "jb_reserv";                   $dspAligns["jb_reserv"] = "c";
      $dspTitles["jb_permanent"] = "D.";                   $dspFields["jb_permanent"] = "jb_permanent";             $dspAligns["jb_permanent"] = "c";
      $dspTitles["cr_id_favoured"] = "B.";                 $dspFields["cr_id_favoured"] = "cr_id_favoured";         $dspAligns["cr_id_favoured"] = "c";
      $dspTitles["jb_csc_id"] = "K.";                      $dspFields["jb_csc_id"] = "jb_csc_id";                   $dspAligns["jb_csc_id"] = "c";
      $dspTitles["cr_sid"] = "Kurier";                     $dspFields["cr_sid"] = "cr_sid";                         $dspAligns["cr_sid"] = "c";
      $dspTitles["jb_latesttaketime"] = "Spät.Annahmez.";  $dspFields["jb_latesttaketime"] = "jb_latesttaketime";   $dspAligns["jb_latesttaketime"] = "c";
      $dspTitles["jb_taketime"] = "Annahme";               $dspFields["jb_taketime"] = "jb_taketime";               $dspAligns["jb_taketime"] = "c";
      $dspTitles["jb_edit"] = "Bearb.";                    $dspFields["jb_edit"] = "jb_edit";                       $dspAligns["jb_edit"] = "c";
      $dspTitles["jb_cr_price"] = "Frachtvergütung";       $dspFields["jb_cr_price"] = "jb_cr_price";               $dspAligns["jb_cr_price"] = "r";
      $dspTitles["jb_cr_subprice"] = "Frachtvergütung&nbsp;o.Z.";    $dspFields["jb_cr_subprice"] = "jb_cr_subprice";    $dspAligns["jb_cr_subprice"] = "r";
      $dspTitles["ad_zipcode"] = "Start-PLZ";              $dspFields["ad_zipcode"] = "ad_zipcode";                 $dspAligns["ad_zipcode"] = "c";
      $dspTitles["ad2_zipcode"] = "2. PLZ";                $dspFields["ad2_zipcode"] = "ad2_zipcode";               $dspAligns["ad2_zipcode"] = "c";
      $dspTitles["jb_lastzipcode"] = "Ziel-PLZ";           $dspFields["jb_lastzipcode"] = "jb_lastzipcode";         $dspAligns["jb_lastzipcode"] = "c";
      $dspTitles["jb_dispoinfo"] = "Dispo-Info";           $dspFields["jb_dispoinfo"] = "jb_dispoinfo";             $dspAligns["jb_dispoinfo"] = "l";
      

      // Get the parameter to set the order of the columns to be displayed
      // $displayedListCols = getParameterValue($emp_id, "MASK_JB_LIST_LONGHAUL_COLS");
      $displayedListCols = $displayedListColsPRE;
      if ($displayedListCols == "") :
         // $displayedListCols = getParameterValue("0", "MASK_JB_LIST_LONGHAUL_COLS", $hqId);
         $displayedListCols = $displayedListColsPRE2;
         if ($displayedListCols == "") :
            // Default settings
            // $displayedListCols = "jb_id,business_volume,jb_tourname,tr_comp,tr_comp2,streethsno,ad_zipcode,jb_lastzipcode,vht_value,jb_ordertime,jb_reserv,jb_permanent,cr_id_favoured,jb_csc_id,cr_sid";
            $displayedListCols = "jb_id,business_volume,jb_tourname,tr_comp,tr_comp2,streethsno,jb_tourzipcodes,vht_value,jb_ordertime,jb_reserv,jb_permanent,cr_id_favoured,jb_csc_id,cr_sid";
            $displayedListCols .= (FALSE ? ",jb_latesttaketime" : "");                 // Latest taketime
            $displayedListCols .= ",jb_taketime";
            $displayedListCols .= ($jb_status != "ALL" ? ",jb_storno" : "");           // Storno
            $displayedListCols .= ",jb_edit";
         endif;
      endif;
      $displayedListColsArray = spliti(",",$displayedListCols);
      $displayedListColsArrayLen = count($displayedListColsArray);

      $tmpKeys = array_keys($dspFields);
      $titles = ""; $fields = ""; $aligns = "";
      for ($i = 0; $i < $displayedListColsArrayLen; $i++) {
          // Search for the value "$displayedListColsArray" in "$dspColArray" and get the key (index)
          $j = array_search($displayedListColsArray[$i], $tmpKeys);
          if (!($j === FALSE)) :
             $titles .= $dspTitles[$tmpKeys[$j]] . ",";
             $fields .= $dspFields[$tmpKeys[$j]] . ",";
             $aligns .= $dspAligns[$tmpKeys[$j]] . ",";
          endif;
      }
      // Remove last ","-sign
      if (substr($titles, -1) == ",") : $titles = substr($titles, 0, -1); endif;
      if (substr($fields, -1) == ",") : $fields = substr($fields, 0, -1); endif;
      if (substr($aligns, -1) == ",") : $aligns = substr($aligns, 0, -1); endif;
   endif;

   $titlesArray = spliti(",",$titles);
   $fieldsArray = spliti(",",$fields);
   $fieldsLength = count($fieldsArray);   
   $alignsArray = spliti(",",$aligns);
   $valignsArray = spliti(",",$valigns);
   $cellTextPreArray = spliti(",",$cellTextPre);

   $fieldClause = getDBFields("job") . "," . getDBFields("jb_edit") . "," . getDBFields("jb_tourzipcodes") . "," . getDBFields("jb_tourcities") . "," . getDBFields("tour") . "," . getDBFields("address") . "," . 
                  getDBFields("vehicletype") . "," . getDBFields("ad_street_hsno") . "," . getDBFields("jb_latesttaketime");
   if (MASK_JOBLIST_TOTALPRICE == "1") :
      $fieldClause .= "," . "SUM(trs.trs_price * ((100 - trs.trs_discount) / 100)) AS business_volume ";
   else :
      $fieldClause .= "," . "jb.jb_totalprice AS business_volume ";
   endif;
   $fieldClause .= "," . " ad2.ad_zipcode AS ad2_zipcode " . "," . " srvpt.srvpt_traveltime , jb.csc_id AS jb_csc_id ";
   $fieldClause .= "," . " SUBSTRING_INDEX(SUBSTRING(jb.jb_tourdata, 1, (INSTR(jb.jb_tourdata, '|') - 1) ), ';', -1) AS jb_lastzipcode ";
   // $fieldClause .= "," . " jb.jb_tourdata AS jb_lastzipcode ";

   if ($constLonghaulActive != "1") :
      $fieldClause .= "," . " SQRT(POW(ABS(srvp.srvp_latitude - srvp2.srvp_latitude),2) + POW(ABS(srvp.srvp_longitude - srvp2.srvp_longitude),2)) AS nb ";
   endif;

   // Active if jb_status IN (8,9,0,1) OR filter is set
   if (($jb_status != "ALL" && $jb_status != "2" && $jb_status != "1") || $filter_tr_time_check == "checked") :
      // $fieldClause .= "," . " UNIX_TIMESTAMP(tr.tr_finishtime) AS time1, UNIX_TIMESTAMP(tr2.tr_finishtime) AS time2, UNIX_TIMESTAMP(tr3.tr_finishtime) AS time3";
      // $fieldClause .= "," . " UNIX_TIMESTAMP(tr4.tr_finishtime) AS time4, UNIX_TIMESTAMP(tr5.tr_finishtime) AS time5, UNIX_TIMESTAMP(tr6.tr_finishtime) AS time6";
   endif;
   if (MASK_JOBLIST_CR_FAVOURED == "1") :
      if (($jb_status != "ALL" && $jb_status != "2" && $jb_status != "1") || $filter_cr_favoured == "checked") :
         $fieldClause .= "," . " cscr.cr_id AS cr_id_favoured " . "," . " cr.vht_id AS vht_id_cr_favoured ";
      endif;
   else :
      $fieldClause .= "," . " jb.jb_cr_fav AS cr_id_favoured ";
   endif;

   if ($filter_printview == "checked" && $searchFiltersInUse) :
      $fieldClause .= "," . " CONCAT(ad_search_1.ad_street,' ',tr_search_1.tr_hsno) AS address_1_street ";
      $fieldClause .= "," . " ad_search_1.ad_zipcode AS address_1_zipcode " . "," . " ad_search_1.ad_city AS address_1_city ";
      $fieldClause .= "," . " tr_search_1.tr_sign AS tour_1_sign " . "," . " tr_search_1.tr_signname AS tour_1_signname " . "," . " tr_search_1.tr_person AS tour_1_person ";
      
      $fieldClause .= "," . " CONCAT(ad_search_2.ad_street,' ',tr_search_2.tr_hsno) AS address_2_street ";
      $fieldClause .= "," . " ad_search_2.ad_zipcode AS address_2_zipcode " . "," . " ad_search_2.ad_city AS address_2_city ";
      $fieldClause .= "," . " tr_search_2.tr_sign AS tour_2_sign " . "," . " tr_search_2.tr_signname AS tour_2_signname " . "," . " tr_search_2.tr_person AS tour_2_person ";
      
      $fieldClause .= "," . " CONCAT(ad_search_3.ad_street,' ',tr_search_3.tr_hsno) AS address_3_street ";
      $fieldClause .= "," . " ad_search_3.ad_zipcode AS address_3_zipcode " . "," . " ad_search_3.ad_city AS address_3_city ";
      $fieldClause .= "," . " tr_search_3.tr_sign AS tour_3_sign " . "," . " tr_search_3.tr_signname AS tour_3_signname " . "," . " tr_search_3.tr_person AS tour_3_person ";
      
      $fieldClause .= "," . " CONCAT(ad_search_4.ad_street,' ',tr_search_4.tr_hsno) AS address_4_street ";
      $fieldClause .= "," . " ad_search_4.ad_zipcode AS address_4_zipcode " . "," . " ad_search_4.ad_city AS address_4_city ";
      $fieldClause .= "," . " tr_search_4.tr_sign AS tour_4_sign " . "," . " tr_search_4.tr_signname AS tour_4_signname " . "," . " tr_search_4.tr_person AS tour_4_person ";
      
      $fieldClause .= "," . " CONCAT(ad_search_5.ad_street,' ',tr_search_5.tr_hsno) AS address_5_street ";
      $fieldClause .= "," . " ad_search_5.ad_zipcode AS address_5_zipcode " . "," . " ad_search_5.ad_city AS address_5_city ";
      $fieldClause .= "," . " tr_search_5.tr_sign AS tour_5_sign " . "," . " tr_search_5.tr_signname AS tour_5_signname " . "," . " tr_search_5.tr_person AS tour_5_person ";
      
      $fieldClause .= "," . " CONCAT(ad_search_6.ad_street,' ',tr_search_6.tr_hsno) AS address_6_street ";
      $fieldClause .= "," . " ad_search_6.ad_zipcode AS address_6_zipcode " . "," . " ad_search_6.ad_city AS address_6_city ";
      $fieldClause .= "," . " tr_search_6.tr_sign AS tour_6_sign " . "," . " tr_search_6.tr_signname AS tour_6_signname " . "," . " tr_search_6.tr_person AS tour_6_person ";
   endif;

   $fromClause = $dbh_tr . " AS tr, address AS ad, serviceplz AS srvp2, serviceplz AS srvp LEFT JOIN serviceplztraveltime AS srvpt ON srvp.srvp_id = srvpt.srvp_id AND srvpt.hq_id = jb.hq_id, ";
   $fromClause .= " metatype AS vht, " . $dbh_jb . " AS jb";
   if (MASK_JOBLIST_TOTALPRICE == "1") :
      $fromClause .= " LEFT JOIN " . $dbh_trs . " AS trs ON trs.jb_id = jb.jb_id ";
   endif;
   $fromClause .= " LEFT JOIN " . $dbh_tr . " AS tr2 ON tr2.jb_id = jb.jb_id AND tr2.tr_sort = '2' ";
   $fromClause .= " LEFT JOIN address AS ad2 ON ad2.ad_id = tr2.ad_id ";
   
   if (($jb_status != "ALL" && $jb_status != "2" && $jb_status != "1") || $filter_tr_time_check == "checked" || ($filter_printview == "checked" && $searchFiltersInUse)) :
      $fromClause .= " LEFT JOIN " . $dbh_tr . " AS tr3 ON tr3.jb_id = jb.jb_id AND tr3.tr_sort = '3' ";
      $fromClause .= " LEFT JOIN " . $dbh_tr . " AS tr4 ON tr4.jb_id = jb.jb_id AND tr4.tr_sort = '4' ";
      $fromClause .= " LEFT JOIN " . $dbh_tr . " AS tr5 ON tr5.jb_id = jb.jb_id AND tr5.tr_sort = '5' ";
      $fromClause .= " LEFT JOIN " . $dbh_tr . " AS tr6 ON tr6.jb_id = jb.jb_id AND tr6.tr_sort = '6' ";
   endif;
   if (MASK_JOBLIST_CR_FAVOURED == "1") :
      if (($jb_status != "ALL" && $jb_status != "2" && $jb_status != "1") || $filter_cr_favoured == "checked") :
         // $fromClause .= " LEFT JOIN costcenter AS csc ON jb.csc_id_payer = csc.csc_id ";
         $fromClause .= " LEFT JOIN costcenter AS csc ON (jb.csc_id_payer = csc.csc_id) OR (jb.csc_id_payer_cash = csc.csc_id) ";
         $fromClause .= " LEFT JOIN customercourier AS cscr ON csc.cs_id = cscr.cs_id AND cscr_sort = '1' AND cscr_relation = '1' ";
         $fromClause .= " LEFT JOIN courier AS cr ON cscr.cr_id = cr.cr_id AND cr.vht_id >= jb.vht_id ";
      endif;
   endif;

   $whereClause = "";
   $orderByClause = "jb_ordertime";
   if ($jb_sort != "") : 
      $orderByClause = $fieldsArray[$jb_sort]; 
   else :
      $defSortValue = array_search("jb_ordertime",$fieldsArray);
      if (!($defSortValue === FALSE)) :
         $jb_sort = $defSortValue;
      endif;
      // List of jobs taken by the courier in special order: ORDER BY jb_taketime
      if ($jb_status == "1") :
         // $specialOrderByTakenJobs = getParameterValue("0", "MASK_JOBLIST_TAKENJOB_ORDERBY");
         $specialOrderByTakenJobs = $specialOrderByTakenJobsPRE;
         if ($specialOrderByTakenJobs == "1") :
            $defSortValue = array_search("jb_taketime",$fieldsArray);
            if (!($defSortValue === FALSE)) :
               $orderByClause = $fieldsArray[$defSortValue];
               $jb_sort = $defSortValue;
            endif;         
         endif;
      endif;
   endif;
   // ASCending or DESCending
   // if ($orderByClause == "jb_ordertime") : $orderByClause = "jb_ordertime ASC"; endif;
   $orderByClause .= " " . $f_sort_direction_text . " ";


   // $whereClause .= " jb.hq_id = " . $hq_id . " AND ";
   $whereClause .= " jb.hq_id IN " . getSQLMandatorArray($f_hq_id) . " AND ";
     
   // Separate list for each status
   if ($jb_status != "" && is_numeric($jb_status)) : $whereClause .= "jb.jb_status = " . $jb_status . " AND "; endif;
   /*
   // Separate list for each status but jb_status = "9" and jb_status = "0" in ONE list
   // ATTENTION: To use this (again), remove entry for job_status = "9" in metatype !!!
   if ($jb_status != "") :
      if ($jb_status == "0") : 
         $whereClause .= "(jb.jb_status = 0 OR jb.jb_status = 9) AND ";
      else :
         $whereClause .= "jb.jb_status = " . $jb_status . " AND ";
      endif;
   endif;
   */
   
   // Only show longhaul jobs
   if ($filter_only_longhaul == "checked") :
      $whereClause .= " (NOT isnull(jb.jb_longhaul) AND jb.jb_longhaul != '0' AND jb.jb_longhaul != '2') AND ";
   endif;
   
   // Only show incomplete jobs
   if ($filter_job_incomplete == "checked") :
      $whereClause .= " jb.jb_incomplete = '1' AND ";
   endif;

   // Only show incomplete jobs
   if ($jb_status == "9" && $filter_only_offer == "checked") :
      $whereClause .= " jb.jb_offer = '1' AND ";
   endif;
   
   // Especially ONE vehicle type
   if (is_numeric($f_filter_vehicletype) && $f_filter_vehicletype > 0) :
      $whereClause .= " jb.vht_id = '" . $f_filter_vehicletype . "' AND ";
   endif;

   // Display vehicle type only up to "$maskJoblistShowUpToVht" (overruled by filter "$f_filter_vehicletype" !!!)
   if ($maskJoblistShowUpToVht != "" && $f_filter_vehicletype == 0) :
      $whereClause .= " jb.vht_id <= '" . $maskJoblistShowUpToVht . "' AND ";
   endif;

   $whereClause .= "(jb.vht_id = vht.mt_sort AND vht.mt_type = 'vehicletype') AND ";
   // time-range (disabled if existence of id-range-search)
   if ($job_no_from == "" && $job_no_to == "") :
      if ($fromDateRange != "") :
         $whereClause .= "jb.jb_ordertime >= '$fromDateRange' AND ";
      endif;
      if ($toDateRange != "") :
         $whereClause .= "jb.jb_ordertime <= '$toDateRange' AND ";
      endif;
   endif;
   // id-range   
   if ($job_no_from != "") :
      $whereClause .= "jb.jb_id >= '$job_no_from' AND ";
   endif;
   if ($job_no_to != "") :
      $whereClause .= "jb.jb_id <= '$job_no_to' AND ";
   endif;
   // sid
   if ($f_cr_sid_search != "") :
      $whereClause .= "jb.cr_sid = '$f_cr_sid_search' AND ";
   endif;
   // mediation-area
   if ($f_area_from != "") :
      $whereClause .= "jb.jb_mediationarea_name >= '$f_area_from' AND ";
   endif;
   if ($f_area_to != "") :
      $whereClause .= "jb.jb_mediationarea_name <= '$f_area_to' AND ";
   endif;
   // general
   $whereClause .= "jb.jb_id = tr.jb_id AND tr.tr_sort = 1 AND tr.ad_id = ad.ad_id ";


   // Optional search filters for list of done jobs
   if ($jb_status == "2") :
       // Only show not exported jobs
       if ($filter_only_not_exported == "checked") :
          $whereClause .= " AND (ISNULL(jb.jb_export_time) OR (jb.jb_export_time = '0000-00-00 00:00:00')) ";
       endif;
       // Do not show storno jobs
       if ($filter_no_storno == "checked") :
          $whereClause .= " AND (ISNULL(jb.jb_storno) OR (jb.jb_storno = '0')) ";
       endif;
   endif;


   // Optional search filters for list of done or of all jobs
   if ($jb_status == "ALL" || $jb_status == "2") :
      if ($searchFiltersInUse) :

         // Get GLOBAL parameter for the number of hops to be searched in
         $jobHopsToBeSearchedIn == "";
         if ($filter_searchdeep == "checked") :
            // $jobHopsToBeSearchedIn = getParameterValue("0", "JOBLIST_NUM_OF_HOPS", "0");
            $jobHopsToBeSearchedIn = $jobHopsToBeSearchedInPRE;
         endif;
         if ($jobHopsToBeSearchedIn == "" || !is_numeric($jobHopsToBeSearchedIn)) :
            $jobHopsToBeSearchedIn = "6";   // Default
         endif;

         for ($j = 1; $j <= $jobHopsToBeSearchedIn; $j++) :
         
             $fromClause .= " LEFT JOIN " . $dbh_tr . " AS tr_search_" . $j . " ON jb.jb_id = tr_search_" . $j . ".jb_id AND tr_search_" . $j . ".tr_sort = '" . $j . "' ";
             $fromClause .= " LEFT JOIN address AS ad_search_" . $j . " ON tr_search_" . $j . ".ad_id = ad_search_" . $j . ".ad_id ";
         endfor;

         // Payer (!)
         $fromClause .= " LEFT JOIN costcenter AS csc_search_payer ON jb.csc_id_payer = csc_search_payer.csc_id ";
         $fromClause .= " LEFT JOIN customer AS cs_search_payer ON csc_search_payer.cs_id = cs_search_payer.cs_id ";
         $fromClause .= " LEFT JOIN company AS cmp_search_payer ON cs_search_payer.cmp_id = cmp_search_payer.cmp_id ";
         $fromClause .= " LEFT JOIN address AS ad_search_payer ON cmp_search_payer.ad_id = ad_search_payer.ad_id ";


         if ($f_search_ad_street != "") : 
            $whereClause .= " AND (";
            for ($j = 1; $j < $jobHopsToBeSearchedIn; $j++) :
                $whereClause .= " ad_search_" . $j . ".ad_street LIKE '%" . $f_search_ad_street . "%' OR"; 
            endfor;
            $whereClause .= " ad_search_" . $jobHopsToBeSearchedIn . ".ad_street LIKE '%" . $f_search_ad_street . "%'";
            $whereClause .= ") ";
         endif;
         if ($f_search_ad_zipcode != "") : 
            $whereClause .= " AND (";
            for ($j = 1; $j < $jobHopsToBeSearchedIn; $j++) :
                $whereClause .= " ad_search_" . $j . ".ad_zipcode LIKE '%" . $f_search_ad_zipcode . "%' OR";
            endfor;
            $whereClause .= " ad_search_" . $jobHopsToBeSearchedIn . ".ad_zipcode LIKE '%" . $f_search_ad_zipcode . "%'";
            $whereClause .= ") ";
         endif;
         if ($f_search_ad_city != "") : 
            $whereClause .= " AND (";
            for ($j = 1; $j < $jobHopsToBeSearchedIn; $j++) :
                $whereClause .= " ad_search_" . $j . ".ad_city LIKE '%" . $f_search_ad_city . "%' OR";
            endfor;
            $whereClause .= " ad_search_" . $jobHopsToBeSearchedIn . ".ad_city LIKE '%" . $f_search_ad_city . "%'";
            $whereClause .= ") ";
         endif;
         if ($f_search_tr_comp != "") : 
            $whereClause .= " AND (";
            for ($j = 1; $j < $jobHopsToBeSearchedIn; $j++) :
                $whereClause .= " tr_search_" . $j . ".tr_comp LIKE '%" . $f_search_tr_comp . "%' OR";
            endfor;
            $whereClause .= " tr_search_" . $jobHopsToBeSearchedIn . ".tr_comp LIKE '%" . $f_search_tr_comp . "%'";
            $whereClause .= ") ";
         endif;
         if ($f_search_tr_person != "") : 
            $whereClause .= " AND (";
            for ($j = 1; $j < $jobHopsToBeSearchedIn; $j++) :
                $whereClause .= " tr_search_" . $j . ".tr_person LIKE '%" . $f_search_tr_person . "%' OR";
            endfor;
            $whereClause .= " tr_search_" . $jobHopsToBeSearchedIn . ".tr_person LIKE '%" . $f_search_tr_person . "%'";
            $whereClause .= ") ";
         endif;
         if ($f_search_tr_remark != "") : 
            $whereClause .= " AND (";
            for ($j = 1; $j < $jobHopsToBeSearchedIn; $j++) :
                $whereClause .= " tr_search_" . $j . ".tr_remark LIKE '%" . $f_search_tr_remark . "%' OR";
            endfor;
            $whereClause .= " tr_search_" . $jobHopsToBeSearchedIn . ".tr_remark LIKE '%" . $f_search_tr_remark . "%'";
            $whereClause .= ") ";
         endif;
         if ($f_search_tr_commission_no != "") : 
            $whereClause .= " AND (";
            for ($j = 1; $j < $jobHopsToBeSearchedIn; $j++) :
                $whereClause .= " tr_search_" . $j . ".tr_commission_no LIKE '%" . $f_search_tr_commission_no . "%' OR";
            endfor;
            $whereClause .= " tr_search_" . $jobHopsToBeSearchedIn . ".tr_commission_no LIKE '%" . $f_search_tr_commission_no . "%'";
            $whereClause .= ") ";
         endif;

         // Payer (!)
         if ($f_search_ad_street_payer != "") : 
            $whereClause .= " AND (ad_search_payer.ad_street LIKE '%" . $f_search_ad_street_payer . "%') ";
         endif;
         if ($f_search_ad_zipcode_payer != "") : 
            $whereClause .= " AND (ad_search_payer.ad_zipcode LIKE '%" . $f_search_ad_zipcode_payer . "%') ";
         endif;
         if ($f_search_ad_city_payer != "") : 
            $whereClause .= " AND (ad_search_payer.ad_city LIKE '%" . $f_search_ad_city_payer . "%') ";
         endif;
         if ($f_search_cmp_comp_payer != "") : 
            $whereClause .= " AND (cmp_search_payer.cmp_comp LIKE '%" . $f_search_cmp_comp_payer . "%') ";
         endif;
         if ($f_search_cs_eid_payer != "") : 
            $whereClause .= " AND (cs_search_payer.cs_eid LIKE '%" . $f_search_cs_eid_payer . "%') ";
         endif;
         if ($f_search_csc_name_payer != "") : 
            $whereClause .= " AND (csc_search_payer.csc_name LIKE '%" . $f_search_csc_name_payer . "%') ";
         endif;
      endif;
   endif;

   // Distance of longhaul jobs
   $whereClause2 = $whereClause;
   if (is_numeric($distance) && $distance > 0) :
     if ($constLonghaulActive == "1") :
        $whereClauseLonghaul = " AND (NOT isnull(jb.jb_longhaul) AND jb.jb_longhaul != '0' AND jb.jb_longhaul != '2')";    // Longhaul mode activated
     else :
        $whereClauseLonghaul = " AND SUBSTRING_INDEX(SUBSTRING(jb.jb_tourdata, 1, (INSTR(jb.jb_tourdata, '|') - 1) ), ';', -1) = srvp2.srvp_plz AND" . 
                               " SQRT(POW(ABS(srvp.srvp_latitude - srvp2.srvp_latitude),2) + POW(ABS(srvp.srvp_longitude - srvp2.srvp_longitude),2)) >= ((" . $distance . " *  0.56720633650927) / 50.02) ";
/*
        $whereClauseLonghaul = "( (SUBSTRING_INDEX(SUBSTRING(jb.jb_tourdata, 1, (INSTR(jb.jb_tourdata, '|') - 1) ), ';', -1) = srvp2.srvp_plz AND" . 
                               " SQRT(POW(ABS(srvp.srvp_latitude - srvp2.srvp_latitude),2) + POW(ABS(srvp.srvp_longitude - srvp2.srvp_longitude),2)) >= ((" . $distance . " *  0.56720633650927) / 50.02) ) OR " .			       
			       "( LEFT(ad.ad_zipcode, 1) NOT IN ('0','1','2','3','4','5','6','7','8','9','.',' ','')  OR  LEFT(SUBSTRING_INDEX(SUBSTRING(jb.jb_tourdata, 1, (INSTR(jb.jb_tourdata, '|') - 1) ), ';', -1) ,1) NOT IN ('0','1','2','3','4','5','6','7','8','9','.',' ','')  ) ) AND ";
*/
        $whereClauseLonghaul2 = "AND ( LEFT(ad.ad_zipcode, 1) NOT IN ('0','1','2','3','4','5','6','7','8','9','.',' ','')  OR  LEFT(SUBSTRING_INDEX(SUBSTRING(jb.jb_tourdata, 1, (INSTR(jb.jb_tourdata, '|') - 1) ), ';', -1) ,1) NOT IN ('0','1','2','3','4','5','6','7','8','9','.',' ','')  ) ";
     endif;
     $whereClause .= $whereClauseLonghaul;      
     $whereClause2 .= $whereClauseLonghaul2;
   endif;

   // The relation HAS TO exist, because it is a longhaul job
   $whereClause .= " AND ad.ad_zipcode = srvp.srvp_plz";

   // Group for price
   if (MASK_JOBLIST_TOTALPRICE == "1") :
      $whereClause .= " GROUP BY trs.jb_id ";
      $whereClause2 .= " GROUP BY trs.jb_id ";
   endif;

   // Set limit for browsing
   // $f_filter_browse_start contains the factor to be multiplicated with the number of rows to be displayed
   $orderByClause .= " LIMIT ". ($f_filter_browse_start * $maskJoblistBrowseMax) . "," . $maskJoblistBrowseMax;

   // Generate statement
   $sqlquery = generateStatement($fieldClause,$fromClause,$whereClause,$orderByClause);

   $fieldClause2 = "jb.jb_id,jb.csc_id,jb.vht_id,jb.vht_id_real,jb.csc_id_payer,jb.jb_payment,jb.jb_outlay,jb.jb_weight,jb.jb_ordertime,"
                 . "jb.jb_reserv,jb.jb_permanent,jb.jb_permanent2,jb.jp_permenddat,jb.jb_specials,jb.cr_id,jb.cr_sid,"
                 . "jb.cr_id_order,jb.cr_id_permanent,jb.jb_cr_filter,jb.jb_cr_filter_opt,jb.jb_waitstorno,jb.jb_waittime,"
                 . "jb.jb_taketime,jb.jb_tourname,jb.jb_status,jb.jb_type,jb.jb_incomplete,jb.jb_storno,jb.jb_finishtime,jb.jb_warningtime,jb.jb_createtime,"
                 . "jb.emp_id,jb.jb_fixprice,jb.jb_serviceprice,jb.jb_totalprice,jb.jb_cr_price,jb.jb_cr_subprice,jb.jb_id_parent,jb.jb_booktime,"
                 . "jb.jb_export_time,jb.jb_postage,jb.jb_modify,jb.jb_longhaul,jb.jb_dispoinfo,jb.jb_offer,jb.jb_subtotalprice,"
                 . "jb.jb_markup,jb.csc_id_related,jb.jb_timeunits,jb.jb_service,jb.jb_id AS jb_edit,jb.jb_tourdata AS jb_tourzipcodes,jb.jb_tourdata AS jb_tourcities,"
                 . "tr.tr_id,tr.ad_id,tr.tr_sort,tr.tr_comp,tr.tr_comp2,tr.tr_hsno,tr.tr_remark,tr.tr_person,tr.tr_phone,tr.csc_id,"
                 . "tr.tr_km_extra,tr.tr_srv_extra,tr.tr_status,tr.tr_sign,tr.tr_signname,tr.tr_ware_from_to,tr.tr_finishtime,"
                 . "tr.tr_commission_no,ad.ad_street,ad.ad_zipcode,ad.ad_city,ad.ad_country,ad.ad_modify,"
                 . "vht.mt_sort AS vht_sort,vht.mt_value AS vht_value,"
                 . "CONCAT(ad.ad_street,' ',tr.tr_hsno) AS streethsno,"
                 . "jb.jb_ordertime AS jb_latesttaketime, jb.jb_totalprice AS business_volume , ad2.ad_zipcode AS ad2_zipcode,"
                 . "' ' AS srvpt_traveltime, jb.csc_id AS jb_csc_id, ' ' AS jb_lastzipcode, '0' AS nb,"
                 . "jb.jb_cr_fav AS cr_id_favoured ";
   $fromClause2 = "tour AS tr, address AS ad, metatype AS vht, ". 
                         "job AS jb LEFT JOIN tour AS tr2 ON tr2.jb_id = jb.jb_id AND tr2.tr_sort = '2' LEFT JOIN address AS ad2 ON ad2.ad_id = tr2.ad_id ";
   
   $sqlquery2 = generateStatement($fieldClause2,$fromClause2,$whereClause2,$orderByClause);

   $sqlquery = "(" . $sqlquery . ") UNION (" . $sqlquery2 . ")";
// echo $sqlquery . "<br>";
// FILTER-DEFINITIONS
   $filter_status = addOptionsFromTable("metatype","mt_sort","mt_value","mt_sort","mt_type = 'job_longhaul_status'",($jb_status == "ALL" ? "10" : $jb_status));

   // Date-ranges 
   $filter_dateranges = "von:\n";
   $filter_dateranges .= "<select name=\"day_from\" class=\"f8np1\" onchange=\"fillDateFieldsCheck(0, '" . $currentFrameName . "', 'jb_list', 'day_from', 'day_from', 'month_from', 'year_from', '', '', '', 'day_to', 'month_to', 'year_to', '', '', '')\"></select>\n";
   $filter_dateranges .= "<select name=\"month_from\" class=\"f8np1\" onchange=\"fillDateFieldsCheck(0, '" . $currentFrameName . "', 'jb_list', 'month_from', 'day_from', 'month_from', 'year_from', '', '', '', 'day_to', 'month_to', 'year_to', '', '', '')\"></select>\n";
   $filter_dateranges .= "<select name=\"year_from\" class=\"f8np1\" onchange=\"fillDateFieldsCheck(0, '" . $currentFrameName . "', 'jb_list', 'year_from', 'day_from', 'month_from', 'year_from', '', '', '', 'day_to', 'month_to', 'year_to', '', '', '')\"></select>\n";

   $filter_dateranges .= "bis:\n";
   $filter_dateranges .= "<select name=\"day_to\" class=\"f8np1\" onchange=\"fillDateFieldsCheck(0, '" . $currentFrameName . "', 'jb_list', 'day_to', 'day_from', 'month_from', 'year_from', '', '', '', 'day_to', 'month_to', 'year_to', '', '', '')\"></select>\n";
   $filter_dateranges .= "<select name=\"month_to\" class=\"f8np1\" onchange=\"fillDateFieldsCheck(0, '" . $currentFrameName . "', 'jb_list', 'month_to', 'day_from', 'month_from', 'year_from', '', '', '', 'day_to', 'month_to', 'year_to', '', '', '')\"></select>\n";
   $filter_dateranges .= "<select name=\"year_to\" class=\"f8np1\" onchange=\"fillDateFieldsCheck(0, '" . $currentFrameName . "', 'jb_list', 'year_to', 'day_from', 'month_from', 'year_from', '', '', '', 'day_to', 'month_to', 'year_to', '', '', '')\"></select>\n";
   $filter_dateranges .= "</td>";

   // Vehicle type
   $filter_vehicletype = "&nbsp;&nbsp;Typ:\n";
   $filter_vehicletype .= "<select name=\"f_filter_vehicletype\" class=\"f8np1\">\n";
   $filter_vehicletype .= addOptionsFromTable("metatype","mt_sort","mt_value","mt_sort","mt_type = 'vehicletype'",$f_filter_vehicletype);
   $filter_vehicletype .= "</select>\n";

   // Distance of longhaul jobs
   $filter_distance = "&nbsp;&nbsp;Mindestdistanz:\n";
   $filter_distance .= "<select name=\"distance\">" . addOptionsFromArray(array("50","60","70","80","90","100","150","200","300","400","500"), $distance, "") . "</select> [KM]\n";

   // Buttons for sort
   $filter_sort_direction = "";
   if ($f_sort_direction == "0") :
      $filter_sort_direction .= "<input type=\"image\" src=\"../images/arrow2_up_disabled.jpg\" alt=\"Aufsteigend\" height=\"15\" width=\"15\" disabled>&nbsp;";
      $filter_sort_direction .= "<input type=\"image\" src=\"../images/arrow2_down.jpg\" alt=\"Absteigend\" height=\"15\" width=\"15\" onClick=\"javascript:setSortState(1);\">";
   else :
      $filter_sort_direction .= "<input type=\"image\" src=\"../images/arrow2_up.jpg\" alt=\"Aufsteigend\" height=\"15\" width=\"15\" onClick=\"javascript:setSortState(0);\">&nbsp;";
      $filter_sort_direction .= "<input type=\"image\" src=\"../images/arrow2_down_disabled.jpg\" alt=\"Absteigend\" height=\"15\" width=\"15\" disabled>";
   endif;
   
   // Buttons for browsing
   $filter_browse = "<input class=\"f8np1\" type=\"button\" value=\"<\" onClick=\"setBrowseStartRange(1);\" " . ($f_filter_browse_start == 0 ? "disabled" : "") . ">";
   $filter_browse .= "&nbsp;" . ($f_filter_browse_start * $maskJoblistBrowseMax) . "-" . (($f_filter_browse_start * $maskJoblistBrowseMax) + $maskJoblistBrowseMax) . "&nbsp;";
   $filter_browse .= "<input class=\"f8np1\" type=\"button\" value=\">\" onClick=\"setBrowseStartRange(2);\" " . ($f_filter_browse_start > 8 ? "disabled" : "") . ">";

   // Javascript-function as template only for
   $js_date = "<script type=\"text/javascript\">\n";
   $js_date .= "<!--\n";
   $js_date .= "var enableCancellationWithCosts = '" . MASK_JOBLIST_CANCELLATION_WITH_COSTS . "';";   // This line only is needed for cancellation (Storno)
   $js_date .= "\n\n";
   $js_date .= "function initForm() {\n";
   $js_date .= "  fillDateFields(1,\"" . $currentFrameName . "\",\"jb_list\",\"\",\"day_from\",\"month_from\",\"year_from\",\"\",\"\",\"\");\n";
   $js_date .= "  setDateTimeFields(\"" . $currentFrameName . "\",\"jb_list\",".$day_from.",".$month_from.",".$year_from.", \"\", \"\", \"day_from\", \"month_from\", \"year_from\", \"\", \"\", \"\");\n";
   $js_date .= "  fillDateFields(1,\"" . $currentFrameName . "\",\"jb_list\", \"\", \"day_to\", \"month_to\", \"year_to\", \"\", \"\", \"\");\n";
   $js_date .= "  setDateTimeFields(\"" . $currentFrameName . "\",\"jb_list\",".$day_to.",".$month_to.",".$year_to.", \"\", \"\", \"day_to\", \"month_to\", \"year_to\", \"\", \"\", \"\");\n";

   $js_date .= "}\n";
   $js_date .= "-->\n";
   $js_date .= "</script>\n";


   // Other special filters (parameter $filters_out ONLY for output)
   $filters_out = "";
   $filter_01 = ""; $filter_02 = ""; $filter_03 = ""; $filter_04 = ""; $filter_05 = ""; $filter_06 = ""; $filter_07 = "";
   
   if ($jb_status == "ALL" || $jb_status == "2") :
      
      $filters_out .= "<tr><td colspan=\"4\">\n";
      if (MASK_JOBLIST_CR_FAVOURED == "1") :
         $filter_01 .= "<input type=\"checkbox\" name=\"f_filter[]\" value=\"job_cr_favoured\"" . $filter_cr_favoured .  "> Bevorzugte Kuriere" . "&nbsp;&nbsp;&nbsp;";
      endif;
      // $filter_02 .= "<input type=\"checkbox\" name=\"f_filter[]\" value=\"job_tr_time_check\"" . $filter_tr_time_check .  "> Prüfung Etappenzeit" . "&nbsp;&nbsp;&nbsp;";

      if ($jb_status == "2") :
         $filter_03 .= "<input type=\"checkbox\" name=\"f_filter[]\" value=\"job_only_not_exported\"" . $filter_only_not_exported .  "> Nur nicht exportierte" . "&nbsp;&nbsp;&nbsp;";
         $filter_04 .= "<input type=\"checkbox\" name=\"f_filter[]\" value=\"job_no_storno\"" . $filter_no_storno .  "> Keine stornierten" . "&nbsp;&nbsp;&nbsp;";
         // $filter_05 .= "<input type=\"checkbox\" name=\"f_filter[]\" value=\"job_printview\"" . $filter_printview .  "> Druckansicht" . "&nbsp;&nbsp;&nbsp;";
      endif;
      if ($empHasRight12) :
         $filter_06 .= "<input type=\"checkbox\" name=\"f_filter[]\" value=\"job_tr_searchdeep\"" . $filter_searchdeep .  "> Suche in allen Etappen" . "&nbsp;&nbsp;&nbsp;";
      endif;

      $filters_out .= $filter_01;     // Filter for coloumn favoured couriers
      $filters_out .= $filter_02;     // Filter for computing time between stops
      $filters_out .= $filter_03;     // Filter for done and not exported jobs
      $filters_out .= $filter_04;     // Filter for no storno jobs
      $filters_out .= $filter_05;     // Print view
      $filters_out .= $filter_06;     // Filter for searchdeep in tour
      // $filters_out .= $filter_07;  // Filter for longhaul (see below output association to filter of mandators !!!)
      $filters_out .= "</td></tr>";
   endif;

   // Mandators filter
   $filterMandators = "";
   if ($empHasRight10) :
      /*
      $filter_07 = "<input type=\"checkbox\" name=\"f_filter[]\" value=\"job_only_longhaul\"" . $filter_only_longhaul .  "> Nur Ferntouren" . "&nbsp;&nbsp;&nbsp;";
      $filterMandators = "<tr><td colspan=\"4\" valign=\"center\">" . $filter_07 . "&nbsp;&nbsp;&nbsp;Niederlassungen:&nbsp;&nbsp;&nbsp;" .
                         addCheckboxesFromTable("f_hq_id","headquarters","hq_id","hq_mnemonic","hq_mnemonic","",$f_hq_id, "&nbsp;&nbsp;&nbsp;") .
                         "<input type=\"button\" name=\"f_hq_check_all\" value=\"Alle\" onClick=\"hqCheckAll(" . $numOfHq . ");\">" .
                         "<input type=\"button\" name=\"f_hq_uncheck_all\" value=\"Keine\" onClick=\"hqUncheckAll(" . $numOfHq . ");\">" .
                         "<br><br></td></tr>";
      */                 
      $filterMandators = "<tr><td colspan=\"4\" valign=\"center\">Niederlassungen:&nbsp;&nbsp;&nbsp;" .
                         addCheckboxesFromTable("f_hq_id","headquarters","hq_id","hq_mnemonic","hq_mnemonic","",$f_hq_id, "&nbsp;&nbsp;&nbsp;") .
                         "<input type=\"button\" name=\"f_hq_check_all\" value=\"Alle\" onClick=\"hqCheckAll(" . $numOfHq . ");\">" .
                         "<input type=\"button\" name=\"f_hq_uncheck_all\" value=\"Keine\" onClick=\"hqUncheckAll(" . $numOfHq . ");\">" .
                         "<br><br></td></tr>";                         
   endif;

   // Search fields
   $filter_search = "";
   if ($jb_status == "ALL" || $jb_status == "2") :
      // Search parameter for tour data
      $f_search_ad_street = trim($f_search_ad_street);
      $f_search_ad_zipcode = trim($f_search_ad_zipcode);
      $f_search_ad_city = trim($f_search_ad_city);      
      $f_search_tr_comp = trim($f_search_tr_comp);
      $f_search_tr_person = trim($f_search_tr_person);
      $f_search_tr_remark = trim($f_search_tr_remark);
      $f_search_tr_commission_no = trim($f_search_tr_commission_no);
      
      // Search parameter for payer data
      $f_search_ad_street_payer = trim($f_search_ad_street_payer);
      $f_search_ad_zipcode_payer = trim($f_search_ad_zipcode_payer);
      $f_search_ad_city_payer = trim($f_search_ad_city_payer);      
      $f_search_cmp_comp_payer = trim($f_search_cmp_comp_payer);
      $f_search_cs_eid_payer = trim($f_search_cs_eid_payer);
      $f_search_csc_name_payer = trim($f_search_csc_name_payer);
      

      // Filter for tour data
      $filter_search .= "<tr><td colspan=\"5\">";
      $filter_search .= "ETAPPEN-FILTER: &nbsp;&nbsp;";
      $filter_search .= "Str.: <input type=\"text\" class=\"f8np1\" name=\"f_search_ad_street\" value=\"" . $f_search_ad_street . "\" size=\"10\">\n";
      $filter_search .= "PLZ: <input type=\"text\" class=\"f8np1\" name=\"f_search_ad_zipcode\" value=\"" . $f_search_ad_zipcode . "\" size=\"5\">\n";
      $filter_search .= "Ort: <input type=\"text\" class=\"f8np1\" name=\"f_search_ad_city\" value=\"" . $f_search_ad_city . "\" size=\"10\">\n";
      $filter_search .= "Firma: <input type=\"text\" class=\"f8np1\" name=\"f_search_tr_comp\" value=\"" . $f_search_tr_comp . "\" size=\"10\">\n";
      $filter_search .= "Person: <input type=\"text\" class=\"f8np1\" name=\"f_search_tr_person\" value=\"" . $f_search_tr_person . "\" size=\"10\">\n";
      $filter_search .= "Bemerkung: <input type=\"text\" class=\"f8np1\" name=\"f_search_tr_remark\" value=\"" . $f_search_tr_remark . "\" size=\"10\">\n";
      $filter_search .= "Komm.-Nr.: <input type=\"text\" class=\"f8np1\" name=\"f_search_tr_commission_no\" value=\"" . $f_search_tr_commission_no . "\" size=\"10\">\n";
      $filter_search .= "</td></tr>";
      
      // Filter for payer data
      $filter_search .= "<tr><td colspan=\"5\">";
      $filter_search .= "BEZAHLER-FILTER: ";
      $filter_search .= "Str.: <input type=\"text\" class=\"f8np1\" name=\"f_search_ad_street_payer\" value=\"" . $f_search_ad_street_payer . "\" size=\"10\">\n";
      $filter_search .= "PLZ: <input type=\"text\" class=\"f8np1\" name=\"f_search_ad_zipcode_payer\" value=\"" . $f_search_ad_zipcode_payer . "\" size=\"5\">\n";
      $filter_search .= "Ort: <input type=\"text\" class=\"f8np1\" name=\"f_search_ad_city_payer\" value=\"" . $f_search_ad_city_payer . "\" size=\"10\">\n";
      $filter_search .= "Firma: <input type=\"text\" class=\"f8np1\" name=\"f_search_cmp_comp_payer\" value=\"" . $f_search_cmp_comp_payer . "\" size=\"10\">\n";
      $filter_search .= "EID: <input type=\"text\" class=\"f8np1\" name=\"f_search_cs_eid_payer\" value=\"" . $f_search_cs_eid_payer . "\" size=\"10\">\n";
      $filter_search .= "Kst.-Name: <input type=\"text\" class=\"f8np1\" name=\"f_search_csc_name_payer\" value=\"" . $f_search_csc_name_payer . "\" size=\"10\">\n";
      $filter_search .= "</td></tr>";      
   endif;


   // Send request to database
   if ($jb_status == "2" || $jb_status == "10" || $jb_status == "ALL") :
      getDb2Connection();     // Try to connect request server because of performance
      $result = $db2->query($sqlquery);
   else :
      $result = $db->query($sqlquery);
   endif;
   if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());

   // Filter
   $tpl->setCurrentBlock("dbhistory"); $tpl->setVariable("_dbhistory_", $dbhistory); $tpl->parseCurrentBlock("dbhistory");
   $tpl->setCurrentBlock("js_date"); $tpl->setVariable("_js_date_", $js_date); $tpl->parseCurrentBlock("js_date");
   $tpl->setCurrentBlock("f_sort_direction"); $tpl->setVariable("_f_sort_direction_", $f_sort_direction); $tpl->parseCurrentBlock("f_sort_direction");
   $tpl->setCurrentBlock("filter_status"); $tpl->setVariable("_filter_status_", $filter_status); $tpl->parseCurrentBlock("filter_status");
   $tpl->setCurrentBlock("filter_dateranges"); $tpl->setVariable("_filter_dateranges_", $filter_dateranges); $tpl->parseCurrentBlock("filter_dateranges");
   $tpl->setCurrentBlock("filter_idranges_from"); $tpl->setVariable("_filter_idranges_from_", $job_no_from); $tpl->parseCurrentBlock("filter_idranges_from");
   $tpl->setCurrentBlock("filter_idranges_to"); $tpl->setVariable("_filter_idranges_to_", $job_no_to); $tpl->parseCurrentBlock("filter_idranges_to");
   $tpl->setCurrentBlock("filter_crsid"); $tpl->setVariable("_filter_crsid_", $f_cr_sid_search); $tpl->parseCurrentBlock("filter_crsid");
   $tpl->setCurrentBlock("filter_areas_from"); $tpl->setVariable("_filter_areas_from_", $f_area_from); $tpl->parseCurrentBlock("filter_areas_from");
   $tpl->setCurrentBlock("filter_areas_to"); $tpl->setVariable("_filter_areas_to_", $f_area_to); $tpl->parseCurrentBlock("filter_areas_to");
   $tpl->setCurrentBlock("filter_vehicletype"); $tpl->setVariable("_filter_vehicletype_", $filter_vehicletype); $tpl->parseCurrentBlock("filter_vehicletype");
   $tpl->setCurrentBlock("filter_distance"); $tpl->setVariable("_filter_distance_", $filter_distance); $tpl->parseCurrentBlock("filter_distance");
   $tpl->setCurrentBlock("filter_sort_direction"); $tpl->setVariable("_filter_sort_direction_", $filter_sort_direction); $tpl->parseCurrentBlock("filter_sort_direction");
   $tpl->setCurrentBlock("filter_browse_start"); $tpl->setVariable("_filter_browse_start_", $f_filter_browse_start); $tpl->parseCurrentBlock("filter_browse_start");   
   $tpl->setCurrentBlock("filter_browse"); $tpl->setVariable("_filter_browse_", $filter_browse); $tpl->parseCurrentBlock("filter_browse");
   $tpl->setCurrentBlock("filter_search"); $tpl->setVariable("_filter_search_", $filter_search); $tpl->parseCurrentBlock("filter_search");
   $tpl->setCurrentBlock("filters_out"); $tpl->setVariable("_filters_out_", $filters_out); $tpl->parseCurrentBlock("filters_out");
   $tpl->setCurrentBlock("filter_mandators"); $tpl->setVariable("_filter_mandators_", $filterMandators); $tpl->parseCurrentBlock("filter_mandators");
   $tpl->setCurrentBlock("useRemoteDB"); $tpl->setVariable("_useRemoteDB_", $useRemoteDB); $tpl->parseCurrentBlock("useRemoteDB");
   

   // Special links   
   $special_links = "";
   $special_links .= "<a href=\"javascript:openCourierStatistics();\">K</a>";
   if ($jb_status == "9") :
      $special_links .= "&nbsp;&nbsp;<a href=\"javascript:goAutoranking();\">A</a>";
      if ($empHasRight10) :
         $special_links .= "&nbsp;&nbsp;<a href=\"javascript:openMap();\">BWV</a>";
         
         // ******************************************************
         // Very special treatment for access to remote database
         if (BWV2_checkEmpRemoteDBAccess("13", $emp_id)) :
            $special_links .= "&nbsp;&nbsp;<a href=\"javascript:openMap2();\">BWV2</a>";
         endif;
         // ******************************************************
      endif;
   endif;
   if ($jb_status == "1") :      
      $special_links .= "&nbsp;&nbsp;<a href=\"javascript:openMfHistory();\">N</a>";
      $openMsgs = getCountOfTable("phoenix_log.messageforum", "hq_id = '" . $hq_id . "' AND mf_createtime >= '" . getDateTime("3") . " 00:00:00' AND mf_createtime <= '" . getDateTime("3") . " 23:59:59' AND  mf_usr_type = '3' AND mf_state < '2'");
      if ($openMsgs > "0") :
         $special_links .= "&nbsp;<img src=\"../images/question.gif\" height=\"11\" width=\"10\" border=\"0\">";
      endif;
   endif;
   if ($jb_status == "2") :
      $special_links .= "&nbsp;&nbsp;<a href=\"javascript:openJobInvoiceAssoc();\">R</a>";
   endif;
   $tpl->setCurrentBlock("special_links"); $tpl->setVariable("_special_links_", $special_links); $tpl->parseCurrentBlock("special_links");


   // Header and entries of the list   
   if ($jb_status == "2") :
      $summationField = "business_volume";
   endif;
   // Used in following include-file
   $targetPath = "longhaul";
   $jobEditParameter = "&useRemoteDB=" . ec($useRemoteDB);

   // include_once ("../include/jb_list_defineoutput.inc.php");
   include_once ("../longhaul/jb_list_defineoutput.inc.php");
   
   if ($jb_status == "2" && $sumOfSummationField != 0 && $filter_printview == "") :
      $jobentry = "<tr><td class=\"f8np1_red\">EINTRÄGE:</td><td class=\"f8np1_red\" align=\"left\" colspan=\"" . (count($fieldsArray) - 1) . "\">" . $rowCounter . "</td></tr>\n";
      $jobentry .= "<tr><td class=\"f8np1_red\">GESAMTSUMME:</td><td class=\"f8np1_red\" align=\"left\" colspan=\"" . (count($fieldsArray) - 1) . "\">" . number_format(round($sumOfSummationField,2), 2, ",", ".") . "</td></tr>\n";
      
      $tpl->setCurrentBlock("jobentry");
      $tpl->setVariable("_jobentry_", $jobentry);
      $tpl->parseCurrentBlock("jobentry");
   endif;
   
   $result->free();
   
   // List of the couriers
   $tpl->setCurrentBlock("javascript");

   // wenn MASK_AUTO_REFRESH == 0, dann wird die Kurierliste dynamisch (bei Aufruf) aufgebaut
   // wenn MASK_AUTO_REFRESH == 1, dann wird die Kurierliste statisch (hier) aufgebaut
   if (MASK_AUTO_REFRESH == "1"):
     include_once("../jobs/job_courier.inc.php");
   endif;
   $tpl->setVariable("_auto_refresh_", MASK_AUTO_REFRESH);
   $tpl->setVariable("_cr_id_order_list_", "var MASK_COURIER_SORT_BY_OCCUPIED = \"\";\n" . $cr_id_order_list . $cr_id_order_list2 . $vht_id_str_js . $customercourier_list . "when = \"" . date("H:i") . "\";\n");
   $tpl->parseCurrentBlock("javascript");   
   
   $reload_status = "1";
   if ($jb_status == "2" || $jb_status == "10" || $jb_status == "ALL") :
      $reload_status = "0";
   endif;
   $tpl->setCurrentBlock("reload_status"); $tpl->setVariable("_reload_status_", $reload_status); $tpl->parseCurrentBlock("reload_status");
 
      
   // Show all templates
   $tpl->show();
?>
   
