<?php
/*=======================================================================
 *
 * inc_serviceunit.inc.php
 *
 * Autor: Marc Vollmann
 *
 *
 =======================================================================*/   


// Converts the type of the specified data field ("ati.ati_data_0x" <=> "data_0x")
function convertATIdataFields($valueToBeConverted, $atiDataFieldNum) {
  global $atiColsTypesArray;
  $retVal = "";
  // $atiColsTypesArray = array("varchar","number","number","date","integer","float2","integer","float2","float2","","","","","integer","integer","integer");
  $atiColsTypesArrayLen = count($atiColsTypesArray);
  if ($valueToBeConverted != "") :
     if ($atiColsTypesArray[$atiDataFieldNum] == "integer") : $retVal = number_format($valueToBeConverted, 0, ",", ".");
     elseif ($atiColsTypesArray[$atiDataFieldNum] == "float2") : $retVal = number_format($valueToBeConverted, 2, ",", ".");
     elseif ($atiColsTypesArray[$atiDataFieldNum] == "datetime") : $retVal = formatOutput($valueToBeConverted,"datetime","3");
     elseif ($atiColsTypesArray[$atiDataFieldNum] == "date") : $retVal = formatOutput($valueToBeConverted,"datetime","4");
     else : // ...
     endif;
  endif;
  return $retVal;
}

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

// Check level of a specified service unit to be critical
function getCriticalLevelOfSU ($atiSerialNo, $dataSU) {
	global $hq_id;
  global $f_tv_01, $f_tv_02, $f_tv_03, $f_tv_04, $f_tv_05, $f_tv_06, $f_tv_07, $f_tv_08, $f_tv_09, $f_tv_10;
  global $f_tv_11, $f_tv_12, $f_tv_13, $f_tv_14, $f_tv_15, $f_tv_16, $f_tv_17, $f_tv_18, $f_tv_19, $f_tv_20;
  global $f_tv_21, $f_tv_22, $f_tv_23, $f_tv_24, $f_tv_25;
  global $criticalMessageArray;
   
  // Return value [[0] == true <=> critical by message, [1] == true <=> is critical by money values, [2] == true <=> is semi critical by money values, [3] == true <=> is marked for "permanently critical"]
  $retArray = array(false, false, false, false);
   
  // Check for critical state based on a message of the serviceunit
  $data_17_array = spliti(",", $dataSU[17]);
  if ($dataSU[17] != "") :
     $data_17_array_len = count($data_17_array);
     for ($i = 0; $i < $data_17_array_len; $i++) :
         $x = array_search($data_17_array[$i], $criticalMessageArray);
         if (!($x === FALSE)) :
            $retArray[0] = true;
            break;
         endif;
     endfor;
  endif;

  // Check for money values
  $suIsCriticalArray = array();
  $suIsCriticalStr = getParameterValue("0", "SU_ATI_TV_COMPARISON", $hq_id);
  if ($suIsCriticalStr != "") :
     $suIsCriticalArray = spliti(",", $suIsCriticalStr);
  else :
     $retArray[1] = ($dataSU[5] != "" && $dataSU[5] >= $f_tv_04) || 
                    ($dataSU[6] != "" && $dataSU[6] >= $f_tv_02) || 
                    ($dataSU[7] != "" && $dataSU[7] > 0 && $dataSU[7] <= $f_tv_05) || 
                    ($dataSU[8] != "" && $dataSU[8] > 0 && $dataSU[8] <= $f_tv_06) || 
                    ($dataSU[9] != "" && $dataSU[9] > 0 && $dataSU[9] <= $f_tv_07);
                    // Message    $suHasCriticalMsg
                    // Intervall: ($dataSU[18] != "" && $dataSU[18] > 0 && $dataSU[18] >= $probability_tv_red)
                    // Status     ($data_16_a != "" && $data_16_b != "" && $data_16_a > 0 && $data_16_b > 0 && $data_16_a <= $data_16_b)

     $retArray[2] = ($dataSU[5] != "" && $dataSU[5] >= $f_tv_03) || 
                    ($dataSU[6] != "" && $dataSU[6] >= $f_tv_01);
                    // Intervall: ($dataSU[18] != "" && $dataSU[18] > 0 && $dataSU[18] >= $probability_tv_yellow);
  endif;

  // Check for service unit OR stock to be permanent marked as "critical"
  if ($atiSerialNo != "") :
     $suIsCriticalByPermanentStr = getParameterValue("0", "SU_IS_CRITICAL_PERMANENTLY", $hq_id);
     if ($suIsCriticalByPermanentStr != "") :
        $suIsCriticalByPermanentArray = spliti(",", $suIsCriticalByPermanentStr);
        $x = array_search($atiSerialNo, $suIsCriticalByPermanentArray);
        if (!($x === FALSE)) :
           $retArray[3] = true;
        endif;
     endif;
  endif;

  return $retArray;
}

// Get current persistent states of the serviceunits
// $mode : "0" = No restrictions, "1" = Define output only, "2" = Generate optimization array with geo-coordinates
function getPersistentStates ($mode = "0") {
	global $db, $PHP_SELF;
	global $f_act, $hq_id, $rootStockSU, $f_su_chkbx, $numOfRowsSU, $f_su_sort_sequence, $f_su_orderByCol, $f_pt_filter_1, $f_search, $maxNumOfTours, $maxNumOfAtiDataFields, $f_su_tour_no;
	global $f_suLoadStates, $suRoutePlanningArray, $outEventStatesArray, $atiColsTypesArray, $criticalMessageArray, $dataSU, $calCurrentDayNumOfTheWeek;
  global $f_tv_01, $f_tv_02, $f_tv_03, $f_tv_04, $f_tv_05, $f_tv_06, $f_tv_07, $f_tv_08, $f_tv_09, $f_tv_10;
  global $f_tv_11, $f_tv_12, $f_tv_13, $f_tv_14, $f_tv_15, $f_tv_16, $f_tv_17, $f_tv_18, $f_tv_19, $f_tv_20;
  global $f_tv_21, $f_tv_22, $f_tv_23, $f_tv_24, $f_tv_25;
  global $colArray;

  $displayedListColsTypes = getParameterValue("0", "MASK_ATI_LIST_COLS_FIELDTYPES", $hq_id);
  if ($displayedListColsTypes == "") :
     $fieldClause = "at.at_eid, at.at_name, ati.at_id, ati.ati_serialno, ati.stk_id, stk.stk_name, "
                  . "ati.ati_data_01, CAST(ati.ati_data_02 AS DECIMAL(10,7)) AS ati_data_02, CAST(ati.ati_data_03 AS DECIMAL(10,7)) AS ati_data_03, ati.ati_data_04, "
                  . "CAST(ati.ati_data_05 AS DECIMAL(8,2)) AS ati_data_05, CAST(ati.ati_data_06 AS DECIMAL(8,2)) AS ati_data_06, CAST(ati.ati_data_07 AS DECIMAL(8,2)) AS ati_data_07, "
                  . "CAST(ati.ati_data_08 AS DECIMAL(8,2)) AS ati_data_08, CAST(ati.ati_data_09 AS DECIMAL(8,2)) AS ati_data_09, "
                  . "ati.ati_data_10, ati.ati_data_11, ati.ati_data_12, ati.ati_data_13, ati.ati_data_14, ati.ati_data_15, "
                  . "ati.ati_data_16, ati.ati_data_17, ati.ati_data_18, ati.ati_data_19, ati.ati_data_20, "
                  . "ati.ati_data_21, ati.ati_data_22, ati.ati_data_23, ati.ati_data_24, ati.ati_data_25, "
                  . "stk.stk_name, stk.stk_hsno, stk.ad_id, ad.ad_street, ad.ad_zipcode, ad.ad_city, ad.ad_country";
  endif;
  $whereClause = "";
  if ($f_search != "") :
     $whereClause = " (ati.ati_serialno LIKE '%" . $f_search . "%' OR stk.stk_name LIKE '%" . $f_search . "%' OR ati.ati_data_01 LIKE '%" . $f_search . "%' OR"
                  . "  ad.ad_street LIKE '%" . $f_search . "%' OR stk.stk_hsno LIKE '%" . $f_search . "%' OR ad.ad_zipcode LIKE '%" . $f_search . "%' OR ad.ad_city LIKE '%" . $f_search . "%' OR"
                  . "  ati.ati_data_05 LIKE '%" . $f_search . "%' OR ati.ati_data_06 LIKE '%" . $f_search . "%' OR ati.ati_data_07 LIKE '%" . $f_search . "%' OR"
                  . "  ati.ati_data_08 LIKE '%" . $f_search . "%' OR ati.ati_data_09 LIKE '%" . $f_search . "%') ";
  endif;

  // Sort sequence for the serviceunits
  $suOrderByClause = "";
  $sortseq = "";
  if ($f_su_sort_sequence == "1") : $sortseq = " DESC"; endif;   // ASC or DESC
  $displayedListColsOrderBy = getParameterValue("0", "MASK_SU_LIST_COLS_ORDER_BY", $hq_id);
  if ($displayedListColsOrderBy == "") :
     // ATTENTION: Presently hardcoded for HOCHBAHN!!! Use vector to make generic CAST structure...!!!
     $orderByColArray = array("ati.ati_serialno",
                              "stk.stk_name<SORT_SEQ>,ati.ati_data_01",
                              "",
                              "",
                              "ati.ati_data_19",
                              "",
                              "ad.ad_zipcode",
                              "CAST(ati.ati_data_02 AS DECIMAL(10,7))",
                              "CAST(ati.ati_data_03 AS DECIMAL(10,7))",
                              "CAST(ati.ati_data_05 AS DECIMAL(8,2))",
                              "CAST(ati.ati_data_06 AS DECIMAL(8,2))",
                              "CAST(ati.ati_data_07 AS DECIMAL(8,2))",
                              "CAST(ati.ati_data_08 AS DECIMAL(8,2))",
                              "CAST(ati.ati_data_09 AS DECIMAL(8,2))",
                              "ati.ati_data_04",
                              "ati.ati_data_17",
                              "CAST(ati.ati_data_18 AS DECIMAL(6,2))",
                              "ati.ati_data_16",
                              "ati.ati_data_25");
  endif;
  if ($f_su_orderByCol == "") : $f_su_orderByCol = "0"; endif;   // Contains the number of the current column to be sorted
  $suOrderByClause = $orderByColArray[$f_su_orderByCol];
  if ($suOrderByClause != "") :
     $suOrderByClause = str_replace("<SORT_SEQ>", $sortseq, $suOrderByClause) . $sortseq;
  endif;

  $sqlStmt = getStmtGenericStockArticleItems("0", $rootStockSU, "", "1", $whereClause, $fieldClause, $suOrderByClause, "");
  // echo $sqlStmt . "<br>";
  if ($sqlStmt != "") :  
     $result = $db->query($sqlStmt);     
     if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
     $numOfRowsSU = 0;
     while ($row = $result->fetch_assoc()):
           $numOfRowsSU++;
           $tmpSuLoadStates = $f_suLoadStates;  // Do NOT overwrite the global value, therefore take temp value
           $ptChecked = "";
           $ptBgCol = "";
           $ptDisplayRow = true;

           // Init ALL elements
           for ($i = 0; $i <= $maxNumOfAtiDataFields; $i++) :
               $dataSU[$i] = "";
           endfor;
           // Set elements
           for ($i = 1; $i <= $maxNumOfAtiDataFields; $i++) :
               $dataSU[$i] = $row["ati_data_" . pad($i, 2)];
           endfor;

           // *** Special treatment of fields ***
           // SW
           $dataSU[16] = str_replace("|", "-,-", $dataSU[16]);
           $tmpArray = spliti("-,-", $dataSU[16]);
           $data_16_a = $tmpArray[0];
           $data_16_b = $tmpArray[1];
           $data_16_c = $tmpArray[2];

           // Check for critical state 
           $criticalStateArray = getCriticalLevelOfSU($row["ati_serialno"], $dataSU);

           // State of the service unit to be permanent "critical" (e.g. selling point, booth, etc)
           $suIsCriticalPermanently = $criticalStateArray[3];

           // Is there at least one critical message
           $ptBgCol_17 = "";
           $suHasCriticalMsg = $criticalStateArray[0];
           if ($suHasCriticalMsg) :
              $ptBgCol_17 = "background-color:" . $colArray["red"] . ";";
           endif;
           if ($dataSU[17] != "") :
              $dataSU[17] = str_replace(",", "<br>", $dataSU[17]);
           else :
              $dataSU[17] = "&nbsp;";
           endif;

           // Check for overwriting the preselection of the vehicle by the user !!!
           // Check the number of entries in the database for (daily) preselection of the service unit
           // - If there is one value only (like "1" for "vehicle 1", ...) this value has to be taken for every day of the week
           // - If there is a list (concatenation by comma) then take the single week days, begin to count with 1 = Monday up to 7 = Sunday
           //   If the list has less than 7 elements (= days of a week) then start with monday
           $data_21_b = $f_su_tour_no[$row["ati_serialno"]];
           if ($data_21_b != "" && is_numeric($data_21_b)) : 
              $dataSU[21] = $data_21_b;
           else :
              if ($dataSU[21] != "") :
                 $tmpAti21Array = spliti(",",$dataSU[21]);
                 $tmpAti21ArrayLen = count($tmpAti21Array);
                 if ($tmpAti21ArrayLen > 1) :
                    $dataSU[21] = $tmpAti21Array[($calCurrentDayNumOfTheWeek - 1)];
                 endif;
              endif;
           endif;

           // Probability threshold values
           $probability_tv_yellow = getParameterValue("0", "MASK_ATIH_PROBABILITY_VALUE_YELLOW", $hq_id);
           if ($probability_tv_yellow == "") : $probability_tv_yellow = 70; endif;
           $probability_tv_red = getParameterValue("0", "MASK_ATIH_PROBABILITY_VALUE_RED", $hq_id);
           if ($probability_tv_red == "") : $probability_tv_red = 90; endif;

           // Initial check for threshold values
           $suIsCritical = $criticalStateArray[1];
           $suIsSemiCritical = $criticalStateArray[2];

           if ($suIsCritical) :
               // Critical serviceunits
               if ($tmpSuLoadStates == "1" || $tmpSuLoadStates == "3") :
                  $ptChecked = "checked";   // Set critical values
               endif;
               $ptBgCol = "background-color:" . $colArray["red"] . ";";
               if ($f_pt_filter_1 == "2") :   // Display NOT critical ONLY
                  $ptDisplayRow = false;
               endif;
           elseif ($suIsSemiCritical) :
               // Semi critical serviceunits
               $ptBgCol = "background-color:" . $colArray["yellow"] . ";";
               // if ($f_pt_filter_1 == "X") :   // Display NOT critical ONLY
               //    $ptDisplayRow = false;
               // endif;
           else :
               // Not critical serviceunits
               if ($f_pt_filter_1 == "1") :   // Display critical ONLY
                  $ptDisplayRow = false;
               endif;
           endif;
/*
           if ($suIsCritical || $suIsSemiCritical) :
               // Critical serviceunits
               if ($suIsCritical && ($tmpSuLoadStates == "1" || $tmpSuLoadStates == "3")) :
                  $ptChecked = "checked";   // Set critical values
               endif;
               if ($suIsCritical) :
                  $ptBgCol = "background-color:" . $colArray["red"] . ";";
               else :
                  $ptBgCol = "background-color:" . $colArray["yellow"] . ";";
               endif;
               if ($f_pt_filter_1 == "2") :   // Display NOT critical ONLY
                  $ptDisplayRow = false;
               endif;
           else :
               // Not critical serviceunits
               if ($f_pt_filter_1 == "1") :   // Display critical ONLY
                  $ptDisplayRow = false;
               endif;
           endif;
*/
           if ($tmpSuLoadStates == "0" || $tmpSuLoadStates == "3") :
              // Set submitted values (default)
              if (in_array($row["ati_serialno"], $f_su_chkbx)) :
                 $ptChecked = "checked";
              endif;
           elseif ($tmpSuLoadStates == "2") :
              // Check for loaded values
              if ($dataSU[20] == "1") :
                 $ptChecked = "checked";
              endif;
           endif;

           if ($suIsCriticalPermanently) :
              $ptChecked = "checked";
              $ptBgCol = "background-color:" . $colArray["light_blue"] . ";";
           endif;

           if (substr($row["ati_serialno"], 0, 3) == "BS_") :
              $ptBgCol = "background-color:" . $colArray["green"] . ";";
           endif;

           if ($mode == "0" || $mode == "1") :
              if ($ptDisplayRow) :

                 $currRowStr = "<tr>\n";
                 $currRowStr .= "  <td class=\"f8np1\" style=\"width:45;text-align:left;" . $ptBgCol . "\" onClick=\"selAction('ati_serialno','" . $row["ati_serialno"] . "','" . $row["stk_name"] . "');\"><b>" . $row["ati_serialno"] . "</b></td>\n";
                 $currRowStr .= "  <td class=\"f8np1\" style=\"width:20;text-align:center;" . $ptBgCol . "\" id=\"". $row["ati_serialno"] . "_notice\"><b>" . ($dataSU[25] != "" ? "*" : "") . "</b></td>\n";
                 $currRowStr .= "  <td class=\"f8np1\" style=\"width:240;text-align:left;" . $ptBgCol . "\"><b>" . $row["stk_name"] . "</b><br>" . $row["ati_data_01"] . "</td>\n";
                 $currRowStr .= "  <td class=\"f8np1\" style=\"width:30;text-align:center;" . "" . "\">" . "<input type=\"checkbox\" name=\"f_su_chkbx[]\" value=\"". $row["ati_serialno"] . "\" onChange=\"setCheckboxStateVectorWasChanged();\" " . $ptChecked . " >" . "</td>\n";

                 // Preselection of the tour number
                 $currRowStr .= "  <td class=\"f8np1\" style=\"width:30;text-align:center;" . "" . "\">\n";
                 $currRowStr .= "    <select name=\"f_su_tour_no[" . $row["ati_serialno"] . "]\">\n";
                 $currRowStr .=        addOptionsFromRange("1", $maxNumOfTours, $dataSU[21], "YES");  // $dataSU[21] <=> Preselected vehicle of the (current) day
                 $currRowStr .= "    </select>\n";
                 $currRowStr .= "  </td>\n";
                 
                 $currRowStr .= "  <td class=\"f8np1\" style=\"width:50;text-align:center;" . "" . "\">" . $dataSU[19] . "&nbsp;</td>\n";
                 $currRowStr .= "  <td class=\"f8np1\" style=\"width:50;text-align:center;" . "" . "\">" . $row["ad_zipcode"] . "</td>\n";
                 // $currRowStr .= "  <td class=\"f8np1\" style=\"width:120;text-align:center;" . "" . "\">" . $dataSU[2] . "</td>\n";
                 // $currRowStr .= "  <td class=\"f8np1\" style=\"width:120;text-align:center;" . "" . "\">" . $dataSU[3] . "</td>\n";

                 $ptBgCol = "";
                 if ($dataSU[5] != "" && $dataSU[5] >= $f_tv_03) :
                    $ptBgCol = "background-color:" . $colArray["yellow"] . ";";
                 endif;
                 if ($dataSU[5] != "" && $dataSU[5] >= $f_tv_04) :
                    $ptBgCol = "background-color:" . $colArray["red"] . ";";
                 endif;
                 $dataSU[5] = convertATIdataFields($dataSU[5], "4");
                 $currRowStr .= "  <td class=\"f8np1\" style=\"width:60;text-align:right;" . $ptBgCol . "\">" . $dataSU[5] . "&nbsp;</td>\n";

                 $ptBgCol = "";
                 if ($dataSU[6] != "" && $dataSU[6] >= $f_tv_01) :
                    $ptBgCol = "background-color:" . $colArray["yellow"] . ";";
                 endif;
                 if ($dataSU[6] != "" && $dataSU[6] >= $f_tv_02) :
                    $ptBgCol = "background-color:" . $colArray["red"] . ";";
                 endif;
                 $dataSU[6] = convertATIdataFields($dataSU[6], "5");
                 $currRowStr .= "  <td class=\"f8np1\" style=\"width:60;text-align:right;" . $ptBgCol . "\">" . $dataSU[6] . "&nbsp;</td>\n";

                 $ptBgCol = "";
                 if ($dataSU[7] != "" && $dataSU[7] <= $f_tv_05) :
                    $ptBgCol = "background-color:" . $colArray["red"] . ";";
                 endif;
                 $dataSU[7] = convertATIdataFields($dataSU[7], "6");
                 $currRowStr .= "  <td class=\"f8np1\" style=\"width:60;text-align:right;" . $ptBgCol . "\">" . $dataSU[7] . "&nbsp;</td>\n";

                 $ptBgCol = "";
                 if ($dataSU[8] != "" && $dataSU[8] <= $f_tv_06) :
                    $ptBgCol = "background-color:" . $colArray["red"] . ";";
                 endif;
                 $dataSU[8] = convertATIdataFields($dataSU[8], "7");
                 $currRowStr .= "  <td class=\"f8np1\" style=\"width:60;text-align:right;" . $ptBgCol . "\">" . $dataSU[8] . "&nbsp;</td>\n";

                 $ptBgCol = "";
                 if ($dataSU[9] != "" && $dataSU[9] <= $f_tv_07) :
                    $ptBgCol = "background-color:" . $colArray["red"] . ";";
                 endif;
                 $dataSU[9] = convertATIdataFields($dataSU[9], "8");
                 $currRowStr .= "  <td class=\"f8np1\" style=\"width:60;text-align:right;" . $ptBgCol . "\">" . $dataSU[9] . "&nbsp;</td>\n";

                 $dataSU[4] = convertATIdataFields($dataSU[4], "3");
                 $currRowStr .= "  <td class=\"f8np1\" style=\"width:80;text-align:center;" . "" . "\">" . $dataSU[4] . "&nbsp;</td>\n";

                 // Messages of service units
                 $currRowStr .= "  <td class=\"f8np1\" style=\"width:80;text-align:center;" . $ptBgCol_17 . "\">" . $dataSU[17] . "</td>\n";

                 // Major probabilities regarding to the service intervals
                 $ptBgCol = "";
                 if ($dataSU[18] != "" && $dataSU[18] >= $probability_tv_red) :
                    $ptBgCol = "background-color:" . $colArray["red"] . ";";
                 endif;
                 if ($dataSU[18] != "" && $dataSU[18] >= $probability_tv_yellow) :
                    $ptBgCol = "background-color:" . $colArray["red"] . ";";
                 endif;
                 $currRowStr .= "  <td class=\"f8np1\" style=\"width:40;text-align:center;" . $ptBgCol . "\">" . $dataSU[18] . "&nbsp;%</td>\n";

                 // Prio states according to the messages
                 $ptBgCol = "";
                 if ($data_16_a != "" && $data_16_b != "" && $data_16_a > 0 && $data_16_b > 0 && $data_16_a <= $data_16_b) :
                    $ptBgCol = "background-color:" . $colArray["red"] . ";";
                 endif;
                 $currRowStr .= "  <td class=\"f8np1\" style=\"width:40;text-align:center;" . $ptBgCol . "\">" . $data_16_b . "&nbsp;[" . $data_16_a . "]&nbsp;</td>\n";
                 
                 $currRowStr .= "</tr>\n";

                 $outEventStatesArray[] = $currRowStr;
              endif;
           endif;

           // Generate optimization array
           if ($mode == "0" || $mode == "2") :
              if ($f_act == "optimizePT" && $ptChecked == "checked") :
                 $suRoutePlanningArray[$f_su_tour_no[$row["ati_serialno"]]][] = array($row["ati_serialno"], $row["ati_data_03"], $row["ati_data_02"]);
              endif;
           endif;
     endwhile;
     $result->free();
  endif;
}


// Get the list of service jobs
function getServiceJoblist () {
	global $db, $PHP_SELF;
	global $f_act, $hq_id, $rootStockSU, $numOfRowsJB, $f_jb_orderByCol, $f_jb_sort_sequence, $outJobArray, $f_search;
	global $f_jb_filter_1, $f_jb_filter_2, $f_jb_filter_3;
	global $fromDateRange_jb, $toDateRange_jb;
  global $colArray;

  $fieldClause = "jb.jb_id, jb.jb_status, jb.jb_ordertime, jb.cr_sid, jb.jb_taketime, jb.jb_finishtime, jb.emp_id, jb.jb_invtext, "
               . "tr.tr_sort, tr.tr_comp, tr.tr_commission_no, tr.tr_remark, tr.tr_status, tr.tr_finishtime, "
               . "ad.ad_id, ad.ad_street, tr.tr_hsno, ad.ad_zipcode, ad.ad_city, ad.ad_country";
  $fromClause = "job AS jb, courier AS cr, tour AS tr, address AS ad";
  $whereClause = "jb.cr_id = cr.cr_id AND jb.jb_id = tr.jb_id AND tr.ad_id = ad.ad_id AND "
               . "jb.jb_ordertime >= '" . $fromDateRange_jb . "' AND jb.jb_ordertime <= '" . $toDateRange_jb . "' AND "
               . "(ISNULL(jb.jb_storno) OR (jb.jb_storno = '0')) ";
  if ($f_jb_filter_1 == "1") :
     $whereClause .= " AND jb.jb_status != '2'";
  elseif ($f_jb_filter_1 == "2") :
     $whereClause .= " AND jb.jb_status = '2'";
  endif;
  if ($f_jb_filter_2 != "") :
     $whereClause .= " AND tr.tr_commission_no = '" . $f_jb_filter_2 . "'";
  endif;
  if ($f_jb_filter_3 != "") :
     $fromClause .= " LEFT JOIN stock AS stk ON ad.ad_id = stk.ad_id";
     $whereClause .= " AND stk.stk_name = '" . $f_jb_filter_3 . "'";
  endif;
  if ($f_search != "") :
     $whereClause = " (jb.cr_sid LIKE '%" . $f_search . "%' OR jb.jb_invtext LIKE '%" . $f_search . "%' OR tr.tr_comp LIKE '%" . $f_search . "%' OR"
                  . "  tr.tr_commission_no LIKE '%" . $f_search . "%' OR tr.tr_remark LIKE '%" . $f_search . "%' OR"
                  . "  ad.ad_street LIKE '%" . $f_search . "%' OR tr.tr_hsno LIKE '%" . $f_search . "%' OR"
                  . "  ad.ad_zipcode LIKE '%" . $f_search . "%' OR ad.ad_city LIKE '%" . $f_search . "%') ";
  endif;

  // Sort sequence of the service jobs
  $orderByClause = "";
  $sortseq = "";
  if ($f_jb_sort_sequence == "1") : $sortseq = " DESC"; endif;   // ASC or DESC
  $orderByColArray = array("jb.jb_id" . $sortseq . ",tr.tr_sort" . $sortseq,
                           "jb.cr_sid" . $sortseq . ",jb.jb_id" . $sortseq,
                           "tr.tr_sort" . $sortseq,
                           "tr.tr_finishtime" . $sortseq,
                           "tr.tr_commission_no" . $sortseq,
                           "ad.ad_street" . $sortseq . ",ad.ad_zipcode" . $sortseq,
                           "ad.ad_zipcode" . $sortseq . ",ad.ad_street" . $sortseq,
                           "jb.jb_ordertime" . $sortseq,
                           "jb.jb_taketime" . $sortseq,
                           "jb.jb_finishtime" . $sortseq,
                           "tr.tr_remark" . $sortseq);
  if ($f_jb_orderByCol == "") : $f_jb_orderByCol = "0"; endif;   // Contains the number of the current column to be sorted
  $orderByClause = $orderByColArray[$f_jb_orderByCol];
  $sqlStmt = generateStatement($fieldClause,$fromClause,$whereClause,$orderByClause);
  // echo $sqlStmt . "<br>";
  if ($sqlStmt != "") :
     $result = $db->query($sqlStmt);     
     if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
     $numOfRowsJB = $result->numRows();
     // if ($numOfRowsJB > 0) :
        $numOfRowsJB = 0;
        $lineToggler = 0;
        while ($row = $result->fetch_assoc()):
              $jbDisplayRow = true;

              if ($row["jb_status"] == "2") :
                  // Finished service jobs
                  $jbBgCol = "background-color:#55FF55";

                  // If running OR finished service jobs are displayed ONLY, then toggle backgroundcolors of the rows
                  // ATTENTION: Could be enabled only if ORDER BY field(s) would be regognized !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
                  /*
                  if ($f_jb_filter_1 == "1") :
   	                 if ($lineToggler == 0) : $lineToggler = 1; else : $lineToggler = 0; endif;
                     $cellColor = getListColorGeneric($numOfRowsJB, $lineToggler, $colArray["green"], $colArray["green"], "#55FF55", "#55FF55");
                     $jbBgCol = "background-color:" . $cellColor . ";";
                  endif;
                  */
              else :
                  // Running service jobs
                  $jbBgCol = "background-color:#FFFF55";

                  // If running OR finished service jobs are displayed ONLY, then toggle backgroundcolors of the rows
                  // ATTENTION: Could be enabled only if ORDER BY field(s) would be regognized !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
                  /*
                  if ($f_jb_filter_1 == "1") :
   	                 if ($lineToggler == 0) : $lineToggler = 1; else : $lineToggler = 0; endif;
                     $cellColor = getListColorGeneric($numOfRowsJB, $lineToggler, $colArray["yellow"], $colArray["yellow"], "#FFFF55", "#FFFF55");
                     $jbBgCol = "background-color:" . $cellColor . ";";
                  endif;
                  */
              endif;

              if ($jbDisplayRow) :
                 $tmpTrFinishtime = $row["tr_finishtime"];
                 if ($tmpTrFinishtime == "0000-00-00 00:00:00") : $tmpTrFinishtime = ""; endif;
                 $tmpjbOrdertime = $row["jb_ordertime"];
                 if ($tmpjbOrdertime == "0000-00-00 00:00:00") : $tmpjbOrdertime = ""; endif;
                 $tmpjbTaketime = $row["jb_taketime"];
                 if ($tmpjbTaketime == "0000-00-00 00:00:00") : $tmpjbTaketime = ""; endif;
                 $tmpJbFinishtime = $row["jb_finishtime"];
                 if ($tmpJbFinishtime == "0000-00-00 00:00:00") : $tmpJbFinishtime = ""; endif;
                 $tmpTrRemark = $row["tr_remark"];
                 if ($tmpTrRemark != "") :
                    $tmpTrRemark = str_replace("|", "<br>", $tmpTrRemark);
                 endif;

                 $tmpOutJob = "<tr>\n";
                 $tmpOutJob .= "  <td class=\"f8np1\" style=\"width:40;text-align:right;" . $jbBgCol . "\" onClick=\"selAction('jb_id','" . $row["jb_id"] . "','" . "" . "');\"><b>" . $row["jb_id"] . "&nbsp;</b></td>\n";
                 $tmpOutJob .= "  <td class=\"f8np1\" style=\"width:40;text-align:center;" . $jbBgCol . "\"><b>" . $row["cr_sid"] . "</b></td>\n";
                 $tmpOutJob .= "  <td class=\"f8np1\" style=\"width:20;text-align:right;" . $jbBgCol . "\"><b>" . $row["tr_sort"] . "&nbsp;</b></td>\n";
                 $tmpOutJob .= "  <td class=\"f8np1\" style=\"width:120;text-align:center;" . $jbBgCol . "\"><b>" . $tmpTrFinishtime . "</b></td>\n";
                 $tmpOutJob .= "  <td class=\"f8np1\" style=\"width:50;text-align:center;" . $jbBgCol . "\"><b>" . $row["tr_commission_no"] . "</b></td>\n";
                 $tmpOutJob .= "  <td class=\"f8np1\" style=\"width:240;text-align:left;" . $jbBgCol . "\"><b>&nbsp;" . $row["ad_street"] . "</b></td>\n";
                 $tmpOutJob .= "  <td class=\"f8np1\" style=\"width:50;text-align:center;" . $jbBgCol . "\"><b>" . $row["ad_zipcode"] . "</b></td>\n";
                 // $tmpOutJob .= "  <td class=\"f8np1\" style=\"width:120;text-align:center;" . $jbBgCol . "\"><b>" . $tmpjbOrdertime . "</b></td>\n";
                 // $tmpOutJob .= "  <td class=\"f8np1\" style=\"width:120;text-align:center;" . $jbBgCol . "\"><b>" . $tmpjbTaketime . "</b></td>\n";
                 // $tmpOutJob .= "  <td class=\"f8np1\" style=\"width:120;text-align:center;" . $jbBgCol . "\"><b>" . $tmpJbFinishtime . "</b></td>\n";
                 $tmpOutJob .= "  <td class=\"f8np1\" style=\"text-align:left;" . $jbBgCol . "\"><b>" . $tmpTrRemark . "</b></td>\n";
                 $tmpOutJob .= "</tr>\n";

                 $outJobArray[] = $tmpOutJob;

                 $numOfRowsJB++;
              endif;
        endwhile;
        $result->free();
     // endif;
  endif;
}


// Get articleitem history data
function getSuHistoryData ($mode = "0", $whereClause = "", $orderByClause = "") {
	global $db, $PHP_SELF;
	global $hq_id, $rootStockSU, $numOfRowsLOG, $f_search, $f_log_sort_sequence, $f_log_orderByCol, $outLogArray, $f_log_filter_1;
  global $f_tv_01, $f_tv_02, $f_tv_03, $f_tv_04, $f_tv_05, $f_tv_06, $f_tv_07, $f_tv_08, $f_tv_09, $f_tv_10;
  global $f_tv_11, $f_tv_12, $f_tv_13, $f_tv_14, $f_tv_15, $f_tv_16, $f_tv_17, $f_tv_18, $f_tv_19, $f_tv_20;
  global $f_tv_21, $f_tv_22, $f_tv_23, $f_tv_24, $f_tv_25;
  global $colArray;

  $atihColsTypesArray = array();
  $atihColsTypes = getParameterValue("0", "STK_ATIH_COLUMN_TYPES", $hq_id);   // Normally it will be kongruent to the parameter "STK_ATI_COLUMN_TYPES"
  if ($atihColsTypes != "") :
     $atihColsTypesArray = spliti(",", $atihColsTypes);
  else :
     // Default
     $atihColsTypesArray = array("varchar","number","number","datetime","integer","float2","integer","float2","float2","","","","","integer","integer");
  endif;

  $displayedListColsTypes = getParameterValue("0", "MASK_ATIH_LIST_COLS_FIELDTYPES", $hq_id);
  if ($displayedListColsTypes == "") :
     $fieldClause = "atih.atih_createtime, atih.atih_serialno, atih.atih_data_01, CAST(atih.atih_data_02 AS DECIMAL(10,7)) AS atih_data_02, CAST(atih.atih_data_03 AS DECIMAL(10,7)) AS atih_data_03, atih.atih_data_04, "
                  . "CAST(atih.atih_data_05 AS DECIMAL(8,2)) AS atih_data_05, CAST(atih.atih_data_06 AS DECIMAL(8,2)) AS atih_data_06, CAST(atih.atih_data_07 AS DECIMAL(8,2)) AS atih_data_07, "
                  . "CAST(atih.atih_data_08 AS DECIMAL(8,2)) AS atih_data_08, CAST(atih.atih_data_09 AS DECIMAL(8,2)) AS atih_data_09, "
                  . "atih.atih_data_10, atih.atih_data_11, atih.atih_data_12, atih.atih_data_13, atih.atih_data_14, atih.atih_data_15, "
                  . "atih.atih_data_16, atih.atih_data_17, atih.atih_data_18, atih.atih_data_19, atih.atih_data_20, "
                  . "atih.atih_data_21, atih.atih_data_22, atih.atih_data_23, atih.atih_data_24, atih.atih_data_25";
  endif;
  $fromClause = "phoenix_log.articleitemhistory AS atih, phoenix.stock AS stk";
  $whereClause = "atih.stk_id = stk.stk_id " . $whereClause;

  // Sort sequence of the log data
  $sortseq = "";
  if ($f_log_sort_sequence == "1") : $sortseq = " DESC"; endif;   // ASC or DESC
  $orderByColArray = array("atih.atih_data_04" . $sortseq);
  if ($f_log_orderByCol == "") : $f_log_orderByCol = "0"; endif;  // Contains the number of the current column to be sorted
  $orderByClause = $orderByColArray[$f_log_orderByCol];
  $sqlStmt = generateStatement($fieldClause,$fromClause,$whereClause,$orderByClause);
  // echo $sqlStmt . "<br>";
  if ($sqlStmt != "") :
     $result = $db->query($sqlStmt);
     if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
     $numOfRowsLOG = 0;
     $lineToggler = 0;
     if ($mode == "0" || $mode == "2") :
        $daysSinceLastService_05 = array(); $daysSinceLastService_06 = array(); $daysSinceLastService_07 = array(); $daysSinceLastService_08 = array(); $daysSinceLastService_09 = array();
        $lastServiceDate_05 = ""; $lastServiceDate_06 = ""; $lastServiceDate_07 = ""; $lastServiceDate_08 = ""; $lastServiceDate_09 = "";
        $rem_data_04 = ""; $rem_data_05 = "0"; $rem_data_06 = "0"; $rem_data_07 = "0"; $rem_data_08 = "0"; $rem_data_09 = "0"; 
     endif;
     while ($row = $result->fetch_assoc()):

           $data_04 = convertATIdataFields($row["atih_data_04"], "3");
           $data_05 = $row["atih_data_05"];    if ($data_05 == "0") : $data_05 = ""; endif;
           $data_06 = $row["atih_data_06"];    if ($data_06 == "0") : $data_06 = ""; endif;
           $data_07 = $row["atih_data_07"];    if ($data_07 == "0") : $data_07 = ""; endif;
           $data_08 = $row["atih_data_08"];    if ($data_08 == "0") : $data_08 = ""; endif;
           $data_09 = $row["atih_data_09"];    if ($data_09 == "0") : $data_09 = ""; endif;

           if ($mode == "0" || $mode == "1") :
              // Init according to row filter
              if ($f_log_filter_1 == "1") :
                 $logDisplayRow = false;
              elseif ($f_log_filter_1 == "2") :
                 $logDisplayRow = true;
              else :
                 $logDisplayRow = true;
              endif;
              if ($lineToggler == 0) : $lineToggler = 1; else : $lineToggler = 0; endif;
              // $cellColor = getListColorGeneric($numOfRowsLOG, $lineToggler, "#88FF88", "#88FF88", "#BBFFBB", "#BBFFBB");
              // $logBgCol = "background-color:" . $cellColor . ";";
           
              $logBgCol = "background-color:" . $colArray["green"] . ";";
              $currRowStr = "<tr>\n";
              $currRowStr .= "  <td class=\"f8np1\" style=\"width:120;text-align:center;" . $logBgCol . "\"><b>" . $data_04 . "&nbsp;</b></td>\n";
              
              if ($data_05 != "" && $data_05 >= $f_tv_03) :
                 $logBgCol = "background-color:" . $colArray["yellow"] . ";";
              endif;
              if ($data_05 != "" && $data_05 >= $f_tv_04) :
                 $logBgCol = "background-color:" . $colArray["red"] . ";";
                 if ($f_log_filter_1 == "1") : $logDisplayRow = true; endif;
                 if ($logDisplayRow == true && $f_log_filter_1 == "2") : $logDisplayRow = false; endif;
              endif;
              $currRowStr .= "  <td class=\"f8np1\" style=\"text-align:right;" . $logBgCol . "\"><b>" . $data_05 . "&nbsp;</b></td>\n";
              
              $logBgCol = "background-color:" . $colArray["green"] . ";";
              if ($data_06 != "" && $data_06 >= $f_tv_01) :
                 $logBgCol = "background-color:" . $colArray["yellow"] . ";";
              endif;
              if ($data_06 != "" && $data_06 >= $f_tv_02) :
                 $logBgCol = "background-color:" . $colArray["red"] . ";";
                 if ($f_log_filter_1 == "1") : $logDisplayRow = true; endif;
                 if ($logDisplayRow == true && $f_log_filter_1 == "2") : $logDisplayRow = false; endif;
              endif;
              $currRowStr .= "  <td class=\"f8np1\" style=\"text-align:right;" . $logBgCol . "\"><b>" . $data_06 . "&nbsp;</b></td>\n";
              
              $logBgCol = "background-color:" . $colArray["green"] . ";";
              if ($data_07 != "" && $data_07 <= $f_tv_05) :
                 $logBgCol = "background-color:" . $colArray["red"] . ";";
                 if ($f_log_filter_1 == "1") : $logDisplayRow = true; endif;
                 if ($logDisplayRow == true && $f_log_filter_1 == "2") : $logDisplayRow = false; endif;
              endif;
              $currRowStr .= "  <td class=\"f8np1\" style=\"text-align:right;" . $logBgCol . "\"><b>" . $data_07 . "&nbsp;</b></td>\n";
              
              $logBgCol = "background-color:" . $colArray["green"] . ";";
              if ($data_08 != "" && $data_08 <= $f_tv_06) :
                 $logBgCol = "background-color:" . $colArray["red"] . ";";
                 if ($f_log_filter_1 == "1") : $logDisplayRow = true; endif;
                 if ($logDisplayRow == true && $f_log_filter_1 == "2") : $logDisplayRow = false; endif;
              endif;
              $currRowStr .= "  <td class=\"f8np1\" style=\"text-align:right;" . $logBgCol . "\"><b>" . $data_08 . "&nbsp;</b></td>\n";
              
              $logBgCol = "background-color:" . $colArray["green"] . ";";
              if ($data_09 != "" && $data_09 <= $f_tv_07) :
                 $logBgCol = "background-color:" . $colArray["red"] . ";";
                 if ($f_log_filter_1 == "1") : $logDisplayRow = true; endif;
                 if ($logDisplayRow == true && $f_log_filter_1 == "2") : $logDisplayRow = false; endif;
              endif;
              $currRowStr .= "  <td class=\"f8np1\" style=\"text-align:right;" . $logBgCol . "\"><b>" . $data_09 . "&nbsp;</b></td>\n";
              
              $currRowStr .= "</tr>\n";
              
              if ($logDisplayRow) :
                 $outLogArray[] = $currRowStr;
                 $numOfRowsLOG++;
              endif;
           endif;

           // Compute probability for the next service
           if ($mode == "0" || $mode == "2") :
              if ($rem_data_04 != "") :    // Important to avoid the usage of the first row of the list. Do NOT use "0" to "value of an element of the first row".
                 if ($data_05 != "" && $rem_data_05 != "" && $data_05 < $rem_data_05) :
                    if ($lastServiceDate_05 != "") :
                       $daysSinceLastService_05[] = mcDateDiff($lastServiceDate_05, $row["atih_data_04"]);
                    endif;
                    $lastServiceDate_05 = $row["atih_data_04"];
                 endif;
                 if ($data_06 != "" && $rem_data_06 != "" && $data_06 < $rem_data_06) :
                    if ($lastServiceDate_06 != "") :
                       $daysSinceLastService_06[] = mcDateDiff($lastServiceDate_06, $row["atih_data_04"]);
                    endif;
                    $lastServiceDate_06 = $row["atih_data_04"];
                 endif;
                 if ($data_07 != "" && $rem_data_07 != "" && $data_07 > $rem_data_07) :
                    if ($lastServiceDate_07 != "") :
                       $daysSinceLastService_07[] = mcDateDiff($lastServiceDate_07, $row["atih_data_04"]);
                    endif;
                    $lastServiceDate_07 = $row["atih_data_04"];
                 endif;
                 if ($data_08 != "" && $rem_data_08 != "" && $data_08 > $rem_data_08) :
                    if ($lastServiceDate_08 != "") :
                       $daysSinceLastService_08[] = mcDateDiff($lastServiceDate_08, $row["atih_data_04"]);
                    endif;
                    $lastServiceDate_08 = $row["atih_data_04"];
                 endif;
                 if ($data_09 != "" && $rem_data_09 != "" && $data_09 > $rem_data_09) :
                    if ($lastServiceDate_09 != "") :
                       $daysSinceLastService_09[] = mcDateDiff($lastServiceDate_09, $row["atih_data_04"]);
                    endif;
                    $lastServiceDate_09 = $row["atih_data_04"];
                 endif;
              endif;
              $rem_data_04 = $row["atih_data_04"];
              $rem_data_05 = $data_05; $rem_data_06 = $data_06; $rem_data_07 = $data_07; $rem_data_08 = $data_08; $rem_data_09 = $data_09; 
           endif;
     endwhile;
     $result->free();

     // Compute probability for the next service
     if ($mode == "0" || $mode == "2") :
        $tmpSum_05 = 0; $tmpSum_06 = 0; $tmpSum_07 = 0; $tmpSum_08 = 0; $tmpSum_09 = 0;
        $daysSinceLastServiceLen_05 = count($daysSinceLastService_05);
        for ($i = 0; $i < $daysSinceLastServiceLen_05; $i++) :
            $tmpSum_05 += $daysSinceLastService_05[$i];
        endfor;
        $daysSinceLastServiceLen_06 = count($daysSinceLastService_06);
        for ($i = 0; $i < $daysSinceLastServiceLen_06; $i++) :
            $tmpSum_06 += $daysSinceLastService_06[$i];
        endfor;
        $daysSinceLastServiceLen_07 = count($daysSinceLastService_07);
        for ($i = 0; $i < $daysSinceLastServiceLen_07; $i++) :
            $tmpSum_07 += $daysSinceLastService_07[$i];
        endfor;
        $daysSinceLastServiceLen_08 = count($daysSinceLastService_08);
        for ($i = 0; $i < $daysSinceLastServiceLen_08; $i++) :
            $tmpSum_08 += $daysSinceLastService_08[$i];
        endfor;
        $daysSinceLastServiceLen_09 = count($daysSinceLastService_09);
        for ($i = 0; $i < $daysSinceLastServiceLen_09; $i++) :
            $tmpSum_09 += $daysSinceLastService_09[$i];
        endfor;

        // Compute average values of each component
        $currentTime = getDateTime("0");
        $daySinceLastService_05 = mcDateDiff($lastServiceDate_05, $currentTime);
        $daySinceLastService_06 = mcDateDiff($lastServiceDate_06, $currentTime);
        $daySinceLastService_07 = mcDateDiff($lastServiceDate_07, $currentTime);
        $daySinceLastService_08 = mcDateDiff($lastServiceDate_08, $currentTime);
        $daySinceLastService_09 = mcDateDiff($lastServiceDate_09, $currentTime);

        $probabilityToNextService_05 = 0; $probabilityToNextService_06 = 0; $probabilityToNextService_07 = 0; $probabilityToNextService_08 = 0; $probabilityToNextService_09 = 0;
        if ($daysSinceLastServiceLen_05 > 0 && $tmpSum_05 > 0) :
           $averageTimeForServiceInterval = ($tmpSum_05 / $daysSinceLastServiceLen_05);
           $probabilityToNextService_05 = round(($daySinceLastService_05 / $averageTimeForServiceInterval) * 100);
        endif;
        if ($daysSinceLastServiceLen_06 > 0 && $tmpSum_06 > 0) :
           $averageTimeForServiceInterval = ($tmpSum_06 / $daysSinceLastServiceLen_06);
           $probabilityToNextService_06 = round(($daySinceLastService_06 / $averageTimeForServiceInterval) * 100);
        endif;
        if ($daysSinceLastServiceLen_07 > 0 && $tmpSum_07 > 0) :
           $averageTimeForServiceInterval = ($tmpSum_07 / $daysSinceLastServiceLen_07);
           $probabilityToNextService_07 = round(($daySinceLastService_07 / $averageTimeForServiceInterval) * 100);
        endif;
        if ($daysSinceLastServiceLen_08 > 0 && $tmpSum_08 > 0) :
           $averageTimeForServiceInterval = ($tmpSum_08 / $daysSinceLastServiceLen_08);
           $probabilityToNextService_08 = round(($daySinceLastService_08 / $averageTimeForServiceInterval) * 100);
        endif;
        if ($daysSinceLastServiceLen_09 > 0 && $tmpSum_09 > 0) :
           $averageTimeForServiceInterval = ($tmpSum_09 / $daysSinceLastServiceLen_09);
           $probabilityToNextService_09 = round(($daySinceLastService_09 / $averageTimeForServiceInterval) * 100);
        endif;

        // Compute maximum of all prababilities
        $probabilityToNextServiceMax = max($probabilityToNextService_05, $probabilityToNextService_06, $probabilityToNextService_07, $probabilityToNextService_08, $probabilityToNextService_09);

        // Output probabilities in the last row of the table
        if ($mode == "0") :
            // Probability threshold values
            $probability_tv_yellow = getParameterValue("0", "MASK_ATIH_PROBABILITY_VALUE_YELLOW", $hq_id);
            if ($probability_tv_yellow == "") : $probability_tv_yellow = 70; endif;
            $probability_tv_red = getParameterValue("0", "MASK_ATIH_PROBABILITY_VALUE_RED", $hq_id);
            if ($probability_tv_red == "") : $probability_tv_red = 90; endif;

            $currRowStr = "<tr>\n";

            // Major probability
            $logBgCol = "background-color:" . $colArray["green"] . ";";
            if ($probabilityToNextServiceMax >= $probability_tv_yellow) :
               $logBgCol = "background-color:" . $colArray["yellow"] . ";";
            endif;
            if ($probabilityToNextServiceMax >= $probability_tv_red) :
               $logBgCol = "background-color:" . $colArray["red"] . ";";
            endif;
            $currRowStr .= "  <td class=\"f8np1\" style=\"text-align:center;" . $logBgCol . "\"><b>" . getLngt("Gesamtservicewahrscheinlichkeit nur auf Basis der Serviceintervalle:") . "&nbsp;" . $probabilityToNextServiceMax . "&nbsp;%</b></td>\n";
  
            // Probability in "$probabilityToNextService_05"
            $logBgCol = "background-color:" . $colArray["green"] . ";";
            if ($probabilityToNextService_05 >= $probability_tv_yellow) :
               $logBgCol = "background-color:" . $colArray["yellow"] . ";";
            endif;
            if ($probabilityToNextService_05 >= $probability_tv_red) :
               $logBgCol = "background-color:" . $colArray["red"] . ";";
            endif;
            $currRowStr .= "  <td class=\"f8np1\" style=\"text-align:center;" . $logBgCol . "\"><b>" . $probabilityToNextService_05 . "&nbsp;%</b></td>\n";
            
            // Probability in "$probabilityToNextService_06"
            $logBgCol = "background-color:" . $colArray["green"] . ";";
            if ($probabilityToNextService_06 >= $probability_tv_yellow) :
               $logBgCol = "background-color:" . $colArray["yellow"] . ";";
            endif;
            if ($probabilityToNextService_06 >= $probability_tv_red) :
               $logBgCol = "background-color:" . $colArray["red"] . ";";
            endif;
            $currRowStr .= "  <td class=\"f8np1\" style=\"text-align:center;" . $logBgCol . "\"><b>" . $probabilityToNextService_06 . "&nbsp;%</b></td>\n";
            
            // Probability in "$probabilityToNextService_07"
            $logBgCol = "background-color:" . $colArray["green"] . ";";
            if ($probabilityToNextService_07 >= $probability_tv_yellow) :
               $logBgCol = "background-color:" . $colArray["yellow"] . ";";
            endif;
            if ($probabilityToNextService_07 >= $probability_tv_red) :
               $logBgCol = "background-color:" . $colArray["red"] . ";";
            endif;
            $currRowStr .= "  <td class=\"f8np1\" style=\"text-align:center;" . $logBgCol . "\"><b>" . $probabilityToNextService_07 . "&nbsp;%</b></td>\n";

            // Probability in "$probabilityToNextService_08"
            $logBgCol = "background-color:" . $colArray["green"] . ";";
            if ($probabilityToNextService_08 >= $probability_tv_yellow) :
               $logBgCol = "background-color:" . $colArray["yellow"] . ";";
            endif;
            if ($probabilityToNextService_08 >= $probability_tv_red) :
               $logBgCol = "background-color:" . $colArray["red"] . ";";
            endif;
            $currRowStr .= "  <td class=\"f8np1\" style=\"text-align:center;" . $logBgCol . "\"><b>" . $probabilityToNextService_08 . "&nbsp;%</b></td>\n";

            // Probability in "$probabilityToNextService_09"
            $logBgCol = "background-color:" . $colArray["green"] . ";";
            if ($probabilityToNextService_09 >= $probability_tv_yellow) :
               $logBgCol = "background-color:" . $colArray["yellow"] . ";";
            endif;
            if ($probabilityToNextService_09 >= $probability_tv_red) :
               $logBgCol = "background-color:" . $colArray["red"] . ";";
            endif;
            $currRowStr .= "  <td class=\"f8np1\" style=\"text-align:center;" . $logBgCol . "\"><b>" . $probabilityToNextService_09 . "&nbsp;%</b></td>\n";

            $currRowStr .= "</tr>\n";
            
            if ($logDisplayRow) :
               $outLogArray[] = $currRowStr;
            endif;
        endif;

        return $probabilityToNextServiceMax;
     endif;
  endif;
}


// Get log data
function getLogData ($whereClause = "", $orderByClause = "") {
	global $db, $PHP_SELF;
	global $hq_id, $rootStockSU, $numOfRowsLOG, $f_search, $f_log_sort_sequence, $f_log_orderByCol, $outLogArray, $f_log_filter_1;
  global $f_tv_01, $f_tv_02, $f_tv_03, $f_tv_04, $f_tv_05, $f_tv_06, $f_tv_07, $f_tv_08, $f_tv_09, $f_tv_10;
  global $f_tv_11, $f_tv_12, $f_tv_13, $f_tv_14, $f_tv_15, $f_tv_16, $f_tv_17, $f_tv_18, $f_tv_19, $f_tv_20;
  global $f_tv_21, $f_tv_22, $f_tv_23, $f_tv_24, $f_tv_25;
  global $colArray;

  $fieldClause = "log.log_createtime, log.hq_id, log.jb_id, log.usr_id, log.cr_id, log.cr_sid, log.cs_id, log.at_id, log.stk_id, log.id_01, log.logo_description";
  $fromClause = "phoenix_log.log AS log";
  // if ($whereClause != "") : $whereClause = "log.logo_id = '1000' AND " . $whereClause; endif;

  // Sort sequence of the log data
  $sortseq = "";
  if ($f_log_sort_sequence == "1") : $sortseq = " DESC"; endif;   // ASC or DESC
  $orderByColArray = array("log.log_createtime" . $sortseq);
  if ($f_log_orderByCol == "") : $f_log_orderByCol = "0"; endif;  // Contains the number of the current column to be sorted
  $orderByClause = $orderByColArray[$f_log_orderByCol];
  $sqlStmt = generateStatement($fieldClause,$fromClause,$whereClause,$orderByClause);
  // echo $sqlStmt . "<br>";
  if ($sqlStmt != "") :
     $result = $db->query($sqlStmt);
     if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
     $numOfRowsLOG = 0;
     $lineToggler = 0;
     while ($row = $result->fetch_assoc()):
           // Init according to row filter
           if ($f_log_filter_1 == "1") :
              $logDisplayRow = false;
           elseif ($f_log_filter_1 == "2") :
              $logDisplayRow = true;
           else :
              $logDisplayRow = true;
           endif;
           if ($lineToggler == 0) : $lineToggler = 1; else : $lineToggler = 0; endif;
           // $cellColor = getListColorGeneric($numOfRowsLOG, $lineToggler, "#88FF88", "#88FF88", "#BBFFBB", "#BBFFBB");
           // $logBgCol = "background-color:" . $cellColor . ";";

           $tmpFieldsArray = spliti(";", $row["logo_description"]);
           $tmpField_01 = $tmpFieldsArray[0];    if ($tmpField_01 == "0") : $tmpField_01 = ""; endif;
           $tmpField_02 = $tmpFieldsArray[1];    if ($tmpField_02 == "0") : $tmpField_02 = ""; endif;
           $tmpField_03 = $tmpFieldsArray[2];    if ($tmpField_03 == "0") : $tmpField_03 = ""; endif;
           $tmpField_04 = $tmpFieldsArray[3];    if ($tmpField_04 == "0") : $tmpField_04 = ""; endif;
           $tmpField_05 = $tmpFieldsArray[4];    if ($tmpField_05 == "0") : $tmpField_05 = ""; endif;

           $logBgCol = "background-color:" . $colArray["green"] . ";";
           $currRowStr = "<tr>\n";
           $currRowStr .= "  <td class=\"f8np1\" style=\"width:120;text-align:center;" . $logBgCol . "\"><b>" . $row["log_createtime"] . "&nbsp;</b></td>\n";

           if ($tmpField_01 != "" && $tmpField_01 >= $f_tv_04) : 
              $logBgCol = "background-color:" . $colArray["red"] . ";";
              if ($f_log_filter_1 == "1") : $logDisplayRow = true; endif;
              if ($logDisplayRow == true && $f_log_filter_1 == "2") : $logDisplayRow = false; endif;
           endif;
           $currRowStr .= "  <td class=\"f8np1\" style=\"text-align:center;" . $logBgCol . "\"><b>" . $tmpField_01 . "</b></td>\n";

           $logBgCol = "background-color:" . $colArray["green"] . ";";
           if ($tmpField_02 != "" && $tmpField_02 >= $f_tv_02) :
              $logBgCol = "background-color:" . $colArray["red"] . ";";
              if ($f_log_filter_1 == "1") : $logDisplayRow = true; endif;
              if ($logDisplayRow == true && $f_log_filter_1 == "2") : $logDisplayRow = false; endif;
           endif;
           $currRowStr .= "  <td class=\"f8np1\" style=\"text-align:center;" . $logBgCol . "\"><b>" . $tmpField_02 . "</b></td>\n";

           $logBgCol = "background-color:" . $colArray["green"] . ";";
           if ($tmpField_03 != "" && $tmpField_03 <= $f_tv_05) :
              $logBgCol = "background-color:" . $colArray["red"] . ";";
              if ($f_log_filter_1 == "1") : $logDisplayRow = true; endif;
              if ($logDisplayRow == true && $f_log_filter_1 == "2") : $logDisplayRow = false; endif;
           endif;
           $currRowStr .= "  <td class=\"f8np1\" style=\"text-align:center;" . $logBgCol . "\"><b>" . $tmpField_03 . "</b></td>\n";

           $logBgCol = "background-color:" . $colArray["green"] . ";";
           if ($tmpField_04 != "" && $tmpField_04 <= $f_tv_06) :
              $logBgCol = "background-color:" . $colArray["red"] . ";";
              if ($f_log_filter_1 == "1") : $logDisplayRow = true; endif;
              if ($logDisplayRow == true && $f_log_filter_1 == "2") : $logDisplayRow = false; endif;
           endif;
           $currRowStr .= "  <td class=\"f8np1\" style=\"text-align:center;" . $logBgCol . "\"><b>" . $tmpField_04 . "</b></td>\n";

           $logBgCol = "background-color:" . $colArray["green"] . ";";
           if ($tmpField_05 != "" && $tmpField_05 <= $f_tv_07) :
              $logBgCol = "background-color:" . $colArray["red"] . ";";
              if ($f_log_filter_1 == "1") : $logDisplayRow = true; endif;
              if ($logDisplayRow == true && $f_log_filter_1 == "2") : $logDisplayRow = false; endif;
           endif;
           $currRowStr .= "  <td class=\"f8np1\" style=\"text-align:center;" . $logBgCol . "\"><b>" . $tmpField_05 . "</b></td>\n";

           $currRowStr .= "</tr>\n";
           
           if ($logDisplayRow) :
              $outLogArray[] = $currRowStr;
              $numOfRowsLOG++;
           endif;
     endwhile;
     $result->free();
  endif;
}

// Get articleitem message data
function getSuMessageData ($serialNoSU) {
	global $db, $PHP_SELF;
	global $hq_id, $rootStockSU, $numOfRowsMsg, $outMessageArray;
  global $colArray;

  $tmpAtId = getFieldValueFromId("phoenix.articleitem", "ati_serialno", $serialNoSU, "at_id");
  $tmpSuMsgCodes = getFieldValueFromId("phoenix.articleitem", "ati_serialno", $serialNoSU, "ati_data_17");
  $tmpSuMsgCodesArray = spliti(",", $tmpSuMsgCodes);
  $tmpSuMsgCodes = "'" . implode("','", $tmpSuMsgCodesArray) . "'";

  $displayedListColsTypes = getParameterValue("0", "MASK_ATM_LIST_COLS_FIELDTYPES", $hq_id);
  if ($displayedListColsTypes == "") :
     $fieldClause = "atm.atm_code, atm.atm_desc, atm.atm_text, atm.atm_prio, atm.atm_critical";
  endif;
  $fromClause = "phoenix.articlemessage AS atm";
  $whereClause = "atm.at_id = '" . $tmpAtId . "' AND atm.atm_code IN (" . $tmpSuMsgCodes . ")";
  $orderByClause = "atm.at_id, atm.atm_code";

  $sqlStmt = generateStatement($fieldClause,$fromClause,$whereClause,$orderByClause);
  // echo $sqlStmt . "<br>";
  if ($sqlStmt != "") :
     $result = $db->query($sqlStmt);
     if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
     $numOfRowsMsg = 0;
     $lineToggler = 0;
     while ($row = $result->fetch_assoc()):

           $logDisplayRow = true;
           if ($lineToggler == 0) : $lineToggler = 1; else : $lineToggler = 0; endif;

           $msgBgCol = "background-color:" . $colArray["yellow"] . ";";
           if ($row["atm_critical"] == "1") :
              $msgBgCol = "background-color:" . $colArray["red"] . ";";
           endif;

           $currRowStr = "<tr>\n";

           $currRowStr .= "  <td class=\"f8np1\" style=\"width:100;text-align:center;" . $msgBgCol . "\"><b>" . $row["atm_code"] . "</b>&nbsp;</td>\n";
           $currRowStr .= "  <td class=\"f8np1\" style=\"text-align:left;" . $msgBgCol . "\">" . $row["atm_desc"] . "&nbsp;</td>\n";
           $currRowStr .= "  <td class=\"f8np1\" style=\"text-align:left;" . $msgBgCol . "\">" . $row["atm_text"] . "&nbsp;</td>\n";
           // $currRowStr .= "  <td class=\"f8np1\" style=\"width:40;text-align:right;" . $msgBgCol . "\">" . $row["atm_prio"] . "&nbsp;</td>\n";

           $currRowStr .= "</tr>\n";

           if ($logDisplayRow) :
              $outMessageArray[] = $currRowStr;
              $numOfRowsMsg++;
           endif;
     endwhile;
     $result->free();
  endif;
}

// Get current persistent states of the serviceunits
function getGlobalStateData () {
	global $db, $PHP_SELF;
	global $f_act, $hq_id, $rootStockSU, $outGlobalStateArray, $maxNumOfAtiDataFields;
  global $colArray;

  $displayedListColsTypes = getParameterValue("0", "MASK_ATI_LIST_COLS_FIELDTYPES", $hq_id);
  if ($displayedListColsTypes == "") :
     $fieldClause = "at.at_eid, at.at_name, ati.at_id, ati.ati_serialno, ati.stk_id, stk.stk_name, "
                  . "ati.ati_data_01, CAST(ati.ati_data_02 AS DECIMAL(10,7)) AS ati_data_02, CAST(ati.ati_data_03 AS DECIMAL(10,7)) AS ati_data_03, ati.ati_data_04, "
                  . "CAST(ati.ati_data_05 AS DECIMAL(8,2)) AS ati_data_05, CAST(ati.ati_data_06 AS DECIMAL(8,2)) AS ati_data_06, CAST(ati.ati_data_07 AS DECIMAL(8,2)) AS ati_data_07, "
                  . "CAST(ati.ati_data_08 AS DECIMAL(8,2)) AS ati_data_08, CAST(ati.ati_data_09 AS DECIMAL(8,2)) AS ati_data_09, "
                  . "ati.ati_data_10, ati.ati_data_11, ati.ati_data_12, ati.ati_data_13, ati.ati_data_14, ati.ati_data_15, "
                  . "ati.ati_data_16, ati.ati_data_17, ati.ati_data_18, ati.ati_data_19, ati.ati_data_20, "
                  . "ati.ati_data_21, ati.ati_data_22, ati.ati_data_23, ati.ati_data_24, ati.ati_data_25, "
                  . "stk.stk_name, stk.stk_hsno, stk.ad_id, ad.ad_street, ad.ad_zipcode, ad.ad_city, ad.ad_country";
  endif;
  $whereClause = "ati.ati_data_25 != '1'";  // Not "deleted" serviceunits only
  $orderByClause = "";

  $sqlStmt = getStmtGenericStockArticleItems("0", $rootStockSU, "", "1", $whereClause, $fieldClause, $suOrderByClause, "");
  // echo $sqlStmt . "<br>";
  if ($sqlStmt != "") :  
     $result = $db->query($sqlStmt);     
     if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
     
     // Init global fields
     $outGlobalStateArray["numOfRowsSU"] = 0;
     $outGlobalStateArray["numOfCriticalRowsSU"] = 0;
     $outGlobalStateArray["numOfSemiCriticalRowsSU"] = 0;
     for ($i = 1; $i <= $maxNumOfAtiDataFields; $i++) :
         $outGlobalStateArray["ati_data_" . pad($i, 2)] = "";
         if ($i >= 5 && $i <= 9) :
            $outGlobalStateArray["ati_data_" . pad($i, 2)] = 0;
         endif;
     endfor;
     
     while ($row = $result->fetch_assoc()):

           // Init ALL elements
           for ($i = 0; $i <= $maxNumOfAtiDataFields; $i++) :
               $dataSU[$i] = "";
           endfor;
           // Set elements
           for ($i = 1; $i <= $maxNumOfAtiDataFields; $i++) :
               $dataSU[$i] = $row["ati_data_" . pad($i, 2)];
           endfor;

           // All service units (not deleted)
           $outGlobalStateArray["numOfRowsSU"]++;

           // Sum up the values of the numeric fields
           for ($i = 5; $i <= 9; $i++) :
               $outGlobalStateArray["ati_data_" . pad($i, 2)] += $row["ati_data_" . pad($i, 2)];
           endfor;
           
           // Check for critical state 
           $criticalStateArray = getCriticalLevelOfSU($row["ati_serialno"], $dataSU);
           
           // All CRITICAL service units (not deleted)
           if ($criticalStateArray[1]) :
              $outGlobalStateArray["numOfCriticalRowsSU"]++;
           endif;
           
           // All SEMI CRITICAL service units (not deleted)
           // Attention: Do not count a critical row !!!
           if (!$criticalStateArray[1] && $criticalStateArray[2]) :
              $outGlobalStateArray["numOfSemiCriticalRowsSU"]++;
           endif;
     endwhile;
     $result->free();
  endif;
}
?>
