<?php
/*=======================================================================
 *
 * inc_filters.inc.php
 *
 * Autor: Marc Vollmann
 *
 * Functions for filters displayed in "courier vehicle", "job", "customer", ...
 *
 =======================================================================*/   


// Gets the (courier) filters
// $filterString          : Contains the filter string to be parsed to check if filter is set
// $modeStatus            : Filters filtered by crf_status ("" = all filters / "0" = only info / "1" = only mandatory)
// $modeVhtId             : Filters filtered by vehicle type (e.g. "5" = all vehicles up to "Bus", but e.g. no "LKW" (eq. to "7"))
// $cols                  : Number of columns to be displayed; overrules automatic computation according to number of requested entries
// $showMandatoryAsterisk : An asterisk will be displayed if filter is mandatory
// $showTableBorder       : Displaying border of the table enabled/disabled
function getFilters ($filterString, $filterType = "", $modeStatus = "", $modeVhtId = "0", $cols = "1", $showMandatoryAsterisk = "1", $showTableBorder = "0", $crfTextShow = "0", $crfModifyEnabled = "0", $crfOrderBy = "0") {
   global $db, $PHP_SELF;

   getLanguage(__FILE__);

   if ($showTableBorder == "" || !is_numeric($showTableBorder)) : $showTableBorder = "0"; endif;
   if ($cols == "" || !is_numeric($cols)) : $cols = "2"; endif;

   // Filter type
   $whereClause = "";
   if ($filterType != "" && is_numeric($filterType)) : 
      $whereClause .= "crf_type = '" . $filterType . "' AND ";
   endif;

   // Number of (mandatory) entries
   if ($modeStatus != "" && is_numeric($modeStatus)) : 
      $whereClause .= "crf_status = '" . $modeStatus . "' AND ";
   endif;
   $whereClause .= "(vht_id = '0' OR vht_id <= '" . $modeVhtId . "')";

   $rowLen = getCountOfTable("courierfilter", $whereClause);
   $crfSortMax = getMaxOfField("courierfilter", "crf_sort");
   $crfSortMax = $crfSortMax + 10;

   // Get mandatory rows
   $fromClause = "";
   if ($crfTextShow == "1") :
      $fromClause = ", crf.crf_longtext";
   endif;
   $orderByClause = "crf.crf_short";
   if ($crfOrderBy == "1") :
      $orderByClause = "crf.crf_text";
   elseif ($crfOrderBy == "2") :
      $orderByClause = "crf.crf_sort";
   endif;
   $sqlquery = "SELECT crf.crf_id, crf.crf_type, crf.crf_short, crf.crf_text, crf.crf_status, crf.crf_sort" . $fromClause
                      . " FROM courierfilter AS crf"
                      . " WHERE " . $whereClause
                      . " ORDER BY " . $orderByClause;

   $result = $db->query($sqlquery);
   if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());

   // Generate output with checkboxes
   $output = "<table><tr><td valign=\"top\"><table border=\"" . $showTableBorder . "\">\n";
   $partTextLen = 100;
   $count = 0;
   $lineToggler = 0;
   while ($row = $result->fetch_assoc()):
   	     if ($lineToggler == 0) : $lineToggler = 1; else : $lineToggler = 0; endif;                
         // $cellColor = getListColor($count, $lineToggler);
         if ($row["crf_type"] == 1) :
            $cellColor = getListColorGeneric($count, $lineToggler, "#AAFFAA", "#AAFFAA", "#CCFFCC", "#CCFFCC");
         else :
            $cellColor = getListColor($count, $lineToggler);
         endif;
         $isChecked = "";
         if (!(strpos($filterString, "," . $row["crf_short"] . ",") === FALSE)) : $isChecked = " checked "; endif;
         $output .= "<tr>";
         if ($crfModifyEnabled == "1") :
            $output .= "<td bgcolor=\"" . $cellColor ."\">&nbsp;<a href=\"javascript:removeCrf('" . $row["crf_id"] . "','" . $row["crf_short"] . "','" . $row["crf_text"] . "');\" tabindex=\"\"><img src=\"../images/waste.png\" border=\"0\" height=\"15\" width=\"12\"></a>&nbsp;</td>";
         else :
            $output .= "<td bgcolor=\"" . $cellColor ."\"><input type=\"checkbox\" name=\"f_crvh_filter[]\" value=\"" . $row["crf_short"] . "\"" . $isChecked . "></td>";
         endif;
         $output .= "<td bgcolor=\"" . $cellColor ."\">" . $row["crf_short"] . ($showMandatoryAsterisk == "1" && $row["crf_status"] == "1" ? "*" : "") . "</td>";
         $output .= "<td bgcolor=\"" . $cellColor ."\">" . getLngt($row["crf_text"]) . "</td>";

         if ($crfTextShow == "1") :
             if ($crfModifyEnabled == "1") :
                // name=\"f_crf_sort[" . $row["crf_id"] . "]\"
                $output .= "<td bgcolor=\"" . $cellColor ."\">"
                         . "<select class=\"f8np1\" onChange=\"javascript:crfSortUpdate('" . $row["crf_id"] . "', $(this).val())\">"
                         . addOptionsFromRange("0", $crfSortMax, $row["crf_sort"])
                         . "</select>"
                         . "</td>";
             else :
                $output .= "<td bgcolor=\"" . $cellColor ."\" align=\"right\">&nbsp;" . getLngt($row["crf_sort"]) . "&nbsp;</td>";
             endif;
         endif;

         if ($crfTextShow == "1") :
            $output .= '<td bgcolor="' . $cellColor . '" width="200" height="50">' 
                     . '  <div id="crf_lt_part_' . $row["crf_id"] . '">' 
                     .      substr(getLngt($row["crf_longtext"]),0,$partTextLen) . (strlen($row["crf_longtext"]) < $partTextLen ? '' : '....') . '&nbsp;&nbsp;' 
                     .      ($crfModifyEnabled == "1" ? '<input type="button" style="width: 10px; height: 10px; vertical-align: middle;" id="crf_' . $row["crf_id"] . '" value="" onClick="containerAction(\'crf_lt_part_' . $row["crf_id"] . '\', \'hide\'); containerAction(\'crf_lt_edit_' . $row["crf_id"] . '\', \'show\');">' : '')
                     . '  </div>'
                     . '  <div class="class_crf_lt_edit" id="crf_lt_edit_' . $row["crf_id"] . '">'
                     .       defineButtonType08("Speichern", "action_crf_save", "saveCrfLongtext(" . $row["crf_id"] . ", document.forms[0].crf_lt_ta_" . $row["crf_id"] . ", " . $partTextLen . "); containerAction('crf_lt_edit_" . $row["crf_id"] . "', 'hide');", "90", "left", "0")
                     .       defineButtonType08("Schließen", "action_crf_close", "containerAction('crf_lt_edit_" . $row["crf_id"] . "', 'hide'); containerAction('crf_lt_part_" . $row["crf_id"] . "', 'show');", "90", "", "")
                     . '    <div>'
                     . '      <textarea class="f8np1 class_crf_lt_textarea" id="crf_lt_ta_' . $row["crf_id"] . '" name="crf_lt_ta_' . $row["crf_id"] . '" cols="30" rows="3">' . getLngt($row["crf_longtext"]) . '</textarea>'
                     . '    </div>'
                     . '  </div>'                     
                     . '</td>';
         endif;

         $output .= "</tr>";
         $count++;
         if ($count >= ($rowLen / $cols)) :
             $output .= "</table></td><td valign=\"top\"><table border=\"" . $showTableBorder . "\">\n";
             $count = 0;
             $lineToggler = 0;
         endif;
   endwhile;
   $output .= "</table></td></tr></table>\n";
   $result->free();   

   return $output;
}

// Implodes checked filters from the array and returns a comma seperated string
function getImplodedFilterstring ($filterArray) {
   $retString = "";
   if (!is_array($filterArray)) : $filterArray = array(); endif;
   $filterLen = count($filterArray);
   if ($filterLen > 0 && $filterArray[0] != "") :
      $retString .= ",";
      for ($i = 0; $i < $filterLen; $i++) :
          $retString .= $filterArray[$i];
          $retString .= ",";
      endfor;   
   endif;
   return $retString;
}

// Remove element from (filter) string
function removeItemFromFilterstring ($filterString, $itemToRemove) {
	 if ($filterString != "" && $itemToRemove != "") :
      if (substr($filterString, 0, 2) == "," . $itemToRemove) :
         $filterString = substr($filterString, 2);
      elseif (substr($filterString, -2, 2) == $itemToRemove . ",") :
         $filterString = substr($filterString, 0, strlen($filterString) - 2);
      elseif (!strpos($filterString, "," . $itemToRemove . ",") === FALSE) :
         $filterString = str_replace("," . $itemToRemove, "", $filterString);
      endif;
      // Remove comma if no item is left
      if (strlen($filterString) < "3") : $filterString = ""; endif;
	 endif;
   return $filterString;
}

// Remove delimiter separated elemnts of a special string regarding elemnts to be excludes also separated by second delimiter
function removeItemsFromString ($specialString, $itemsToBeRemovedStr, $delimiter = ",", $delimiter2 = ",") {
	 if ($specialString != "" && $itemsToBeRemovedStr != "") :
	    // Items to be removed
      $itemsStrToBeRemovedArr = explode(",", $itemsToBeRemovedStr);
      $itemsStrToBeRemovedArrLen = count($itemsStrToBeRemovedArr);
	    // Remove items from special string
      $specialArr = explode($delimiter2, $specialString);
      for ($e = 0; $e < $itemsStrToBeRemovedArrLen; $e++) :
          if (in_array($itemsStrToBeRemovedArr[$e], $specialArr)) :
             $specialString = str_replace($itemsStrToBeRemovedArr[$e], "", $specialString);
             if (substr($specialString, 0, 1) == $delimiter) : $specialString = substr($specialString, 1); endif;
             if (substr($specialString, -1) == $delimiter) : $specialString = substr($specialString, 0, -1); endif;
             $specialString = str_replace($delimiter . $delimiter, $delimiter, $specialString);
          endif;
      endfor;
	 endif;
   return $specialString;
}

// Remove element from (filter) string with leading and ending commata
function removeItemFromFilterstringWithCommata ($filterString, $itemToRemove) {
	 $itemToRemove = trim($itemToRemove);
	 if ($filterString != "" && $itemToRemove != "") :
	    $itemToRemoveLen = strlen($itemToRemove);
	    $itemToRemoveLen++;
      if (substr($filterString, 0, $itemToRemoveLen) == "," . $itemToRemove) :
         $filterString = substr($filterString, $itemToRemoveLen);
      elseif (substr($filterString, -$itemToRemoveLen) == $itemToRemove . ",") :
         $filterString = substr($filterString, 0, strlen($filterString) - $itemToRemoveLen);
      elseif (!strpos($filterString, "," . $itemToRemove . ",") === FALSE) :
         $filterString = str_replace("," . $itemToRemove, "", $filterString);
      endif;
      // Remove comma if no item is left
      if (strlen($filterString) < "3") : $filterString = ""; endif;
	 endif;
   return $filterString;
}
?>