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

include_once ("../include/global.inc.php");
include_once ("../include/auth.inc.php");
include_once ("../include/services_func.inc.php");
include_once ("../include/caglobal.inc.php");


// Check HTTP-Parameters
getSecHttpVars("1",array("f_act","mode","csId","opener","orderByService","orderByServiceType","orderByServiceCustomer",
                         "day_from", "month_from", "year_from",
                         "statusMessage", "serviceMode", "f_service_id", "f_service_change", "f_service_new", 
                         "f_servicetype_id", "f_servicetype_change", "f_servicetype_new", "f_future_date_existing", "deactivateMenu",
                         "pageFirstCall", "f_chkbx_toggle", "f_chkbx_toggle_cr"));

getLanguage(__FILE__);

$pageTitel = getLngt("PREISE");
if ($mode == "discount") : $pageTitel = getLngt("RABATTE"); endif;
include_once ("../admin/menu.php");
include_once ("../include/html.inc.php");
getCurrentScript(__FILE__);

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

// Check authentication access for managing global prices
if ($csId == "" || $csId == "0") :
   authCheckEmployeeRights($emp_id, "29", "1");
endif;

// Debug
$srvDebug = false;

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

// Set the current timestamp to store the data
$currentTime = getDateTime("0");
$currentDate = getDateTime("3");

// Service-mode
if ($serviceMode == "") :
   $constServiceMode = getParameterValue("0", "SERVICE_DISPLAY_MODE_DEFAULT", $hq_id);
   if ($constServiceMode == "" || $constServiceMode == "0") :
      $serviceMode = "0";
   else :
      $serviceMode = "1";
   endif;
endif;

// Init future date
if (!isset($f_future_date_existing)) : $f_future_date_existing = ""; endif;

// Check range of date. All fields have to be set
if ($day_from == "" || $month_from == "" || $year_from == "") :
    // Initialize date-ranges to the current date
    $day_from = getDateTime("day");
    $month_from = getDateTime("month");
    $year_from = getDateTime("year");
endif;
$selDate = $year_from . "-" . pad($month_from,2) . "-" . pad($day_from,2);

// Init store times
if ($selDate > $currentDate) :
   $f_future_date_existing = $selDate;
elseif ($selDate < $currentDate) :
   $f_act = "";
   $f_future_date_existing = "";
   $day_from = getDateTime("day");
   $month_from = getDateTime("month");
   $year_from = getDateTime("year");
   $statusMessage = getLngt("Das Datum muss in der Zukunft liegen!");
endif;

// Presently future dates are enabled for service mode "0" only (!!!!)
// HARDCODED !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
$futureDatesEnabled = true;
if ($serviceMode != "0") :
   $futureDatesEnabled = false;
   $f_future_date_existing = "";
endif;

// Restrictions regarding access rights
$whereClauseRightsService = "";
if ($serviceMode == "0") :
   $parServiceRights = getParameterValue("0", "RIGHTS_TABLE_SERVICE", $hq_id);
   if ($parServiceRights == "") : $parServiceRights = getParameterValue("0", "RIGHTS_TABLE_SERVICE", "0"); endif;
   if ($parServiceRights != "") : 
      $rightArr = getKeyValueArrayFromString($parServiceRights);
      $tmpKeys = array_keys($rightArr);
      $tmpKeysLen = count($tmpKeys);
      for ($i = 0; $i < $tmpKeysLen; $i++) :
          if (!authCheckEmployeeRights($emp_id, $rightArr[$tmpKeys[$i]])) :
             $whereClauseRightsService .= " AND srv_name != '" . $tmpKeys[$i] . "' ";
          endif;
      endfor;
   endif;
endif;

if ($srvDebug) :
   echo "serviceMode = " . $serviceMode . "<br>";
   echo "futureDatesEnabled = " . $futureDatesEnabled . "<br>";
   echo "day_from = " . $day_from . "<br>";
   echo "month_from = " . $month_from . "<br>";
   echo "year_from = " . $year_from . "<br>";
   echo "selDate = " . $selDate . "<br>";
   echo "currentDate = " . $currentDate . "<br>";
   echo "currentTime = " . $currentTime . "<br>";
endif;

if ($pageFirstCall == "" || ($f_chkbx_toggle == "" && $f_chkbx_toggle_cr == "")) :
   $pageFirstCall = 1;
   $f_chkbx_toggle = "service";
   $f_chkbx_toggle_cr = "";
endif;
$f_chkbx_toggle_checked = "";
if ($f_chkbx_toggle == "service") : $f_chkbx_toggle_checked = "checked"; endif;
$f_chkbx_toggle_cr_checked = "";
if ($f_chkbx_toggle_cr == "service_cr") : $f_chkbx_toggle_cr_checked = "checked"; endif;

// Price-mode or discount-mode
if ($mode == "") : $mode = "price" ; endif;

// General price/discount for all customers
if ($csId == "") : $csId = "0" ; endif;

// Check opener ONLY for output in target
$htmlFormTarget = "target=\"\"";
if ($opener == "1") : $htmlFormTarget = ""; endif;

$cmpComp = "";
$cmpComp2 = "";
if ($csId != "0") :    
   $cmpId = getFieldValueFromId("customer","cs_id",$csId,"cmp_id");
   $tmpFields = getFieldsValueFromId("company","cmp_id",$cmpId,array("cmp_comp","cmp_comp2"));
   $cmpComp = $tmpFields[0];
   $cmpComp2 = $tmpFields[1];
endif;

// ORDER BY to be displayed
if ($orderByService == "") : $orderByService = "srv_group, srv_sort" ; endif;
if ($orderByServiceType == "") : $orderByServiceType = "srvt_group, srvt_name" ; endif;
if ($orderByServiceCustomer == "") : $orderByServiceCustomer = "srvt.srvt_group, srvt.srvt_name" ; endif;


// Check mandator state; if enabled (= 1) then differ between mandators, else set HQ_ID = 0 => same values for ALL mandators
$currentHqId = $hq_id;
if ($serviceMode >= "1") :
   $constHqId = getParameterValue("0", "MANDATOR_SERVICE2_ENABLED", $hq_id);
else :
   $constHqId = getParameterValue("0", "MANDATOR_SERVICE_ENABLED", $hq_id);
endif;   
if ($constHqId == "" || $constHqId == "0") : $currentHqId = "0"; endif;


// *** Storing-processes ***
// *** BEGIN ***************

// Change name of a service
if ($f_act == "save_service_change") :
   if ($f_service_id != "") :
      TA("B");
      updateStmt("service", "srv_id", $f_service_id, array("srv_name", $f_service_change));
      writeToLogDB("57",$hq_id,"",$usr_id,"","","","DBOP=Update_service|SRV_MODE=".$serviceMode);
      TA("C");
      TA("E");
   else :
      $statusMessage = getLngt("Der gewünschte Name existiert leider schon!");
   endif;
endif;

// Insert new service
if ($f_act == "save_service_new") :
   if ($f_service_new != "") :
      TA("B");
      $tmpFields = array("srv_mode",$serviceMode,"hq_id",$currentHqId,"cs_id",$csId,"srv_name",$f_service_new);
      insertStmt("service",$tmpFields);
      writeToLogDB("58",$hq_id,"",$usr_id,"","","","DBOP=Insert_service|SRV_MODE=".$serviceMode);
      TA("C");
      TA("E");
   else :
      $statusMessage = getLngt("Vergeben Sie bitte einen Namen!");
   endif;
endif;

// Change name of a servicetype
if ($f_act == "save_servicetype_change") :
   if ($f_servicetype_id != "") :
      TA("B");
      updateStmt("servicetype", "srvt_id", $f_servicetype_id, array("srvt_name", $f_servicetype_change));
      writeToLogDB("59",$hq_id,"",$usr_id,"","","","DBOP=Update_servicetype|SRV_MODE=".$serviceMode);
      TA("C");
      TA("E");
   else :
      $statusMessage = getLngt("Der gewünschte Name existiert leider schon!");
   endif;
endif;

// Insert new servicetype
if ($f_act == "save_servicetype_new") :
   if ($f_servicetype_new != "") :
      TA("B");
      $tmpFields = array("srvt_mode",$serviceMode,"hq_id",$currentHqId,"cs_id",$csId,"srvt_name",$f_servicetype_new);
      insertStmt("servicetype",$tmpFields);
      writeToLogDB("60",$hq_id,"",$usr_id,"","","","DBOP=Insert_servicetype|SRV_MODE=".$serviceMode);
      TA("C");
      TA("E");
   else :
      $statusMessage = getLngt("Vergeben Sie bitte einen Namen!");
   endif;
endif;

// Removal of a service
if ($f_act == "remove_service_single") :
   if ($f_service_id != "") :
      TA("B");
      $tmpSrvName = getFieldValueFromId("service", "srv_id", $f_service_id, "srv_name");
      deleteStmt("service","srv_id = " . $f_service_id);
      writeToLogDB("131",$hq_id,"",$usr_id,"","","","DBOP=Delete_service|SRV_MODE=".$serviceMode."|SRV_ID=".$f_service_id."|SRV_NAME=".$tmpSrvName);
      TA("C");
      TA("E");
   else :
      $statusMessage = getLngt("Eine Löschung konnte nicht erfolgen!");
   endif;
endif;

// Removal of a service type
if ($f_act == "remove_service_type_single") :
   if ($f_servicetype_id != "") :
      TA("B");
      $tmpSrvtName = getFieldValueFromId("servicetype", "srvt_id", $f_servicetype_id, "srvt_name");
      deleteStmt("servicetype","srvt_id = " . $f_servicetype_id);
      writeToLogDB("132",$hq_id,"",$usr_id,"","","","DBOP=Delete_servicetype|SRV_MODE=".$serviceMode."|SRVT_ID=".$f_servicetype_id."|SRVT_NAME=".$tmpSrvtName);
      TA("C");
      TA("E");
   else :
      $statusMessage = getLngt("Eine Löschung konnte nicht erfolgen!");
   endif;
endif;

// *** END ***************


// *****************************
// * Selection of all services *
// *****************************
if ($csId > "0" && $serviceMode >= "1") :
   $sqlquery = "SELECT srv.srv_id, srv.srv_name, srv.srv_sort, srv.srv_group, srv.cs_id"
               . " FROM service AS srv, customerservice AS cssrv"
               . " WHERE srv.hq_id = '" . $currentHqId . "' AND srv.cs_id = '0' AND srv.srv_mode = '" . $serviceMode . "' AND"
               . "       srv.srv_id = cssrv.srv_id AND cssrv.cs_id = '" . $csId . "'";
   
   $sqlquery2 = "SELECT srv_id, srv_name, srv_sort, srv_group, cs_id"
                . " FROM service"
                . " WHERE hq_id = '" . $currentHqId . "' AND cs_id = '" . $csId . "' AND srv_mode = '" . $serviceMode . "'";
   
   $sqlquery = "(" . $sqlquery . ") UNION (" . $sqlquery2 . ") ORDER BY " . $orderByService;
else :
   // Default
   $sqlquery = "SELECT srv_id, srv_name, srv_sort, srv_group, cs_id"
               . " FROM service"
               . " WHERE hq_id = '" . $currentHqId . "' AND cs_id = '0' AND srv_mode = '" . $serviceMode . "'" . $whereClauseRightsService
               . " ORDER BY " . $orderByService;
endif;

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

$services = array();
$count = 0;
while ($row = $result->fetch_assoc()):
      $count++;
      $services["id"][$count] = $row["srv_id"];
      $services["name"][$count] = $row["srv_name"];
      $services["sort"][$count] = $row["srv_sort"];
      $services["group"][$count] = $row["srv_group"];
      $services["cs_id"][$count] = $row["cs_id"];
endwhile;
$result->free();


// *********************************
// * Selection of all servicetypes *
// *********************************
if ($csId > "0" && $serviceMode >= "1") :
   $sqlquery = "SELECT srvt.srvt_id, srvt.srvt_name, srvt.srvt_group, srvt.cs_id"
               . " FROM servicetype AS srvt, customerservicetype AS cssrvt"
               . " WHERE srvt.hq_id = '" . $currentHqId . "' AND srvt.cs_id = '0' AND srvt.srvt_mode = '" . $serviceMode . "' AND"
               . "       srvt.srvt_id = cssrvt.srvt_id AND cssrvt.cs_id = '" . $csId . "'";
               
   $sqlquery2 = "SELECT srvt_id, srvt_name, srvt_group, cs_id"
                . " FROM servicetype"
                . " WHERE hq_id = '" . $currentHqId . "' AND cs_id = '" . $csId . "' AND srvt_mode = '" . $serviceMode . "'";
                
   // $sqlquery = "(" . $sqlquery . ") UNION (" . $sqlquery2 . ")";
   $sqlquery = "(" . $sqlquery . ") UNION ALL (" . $sqlquery2 . ") ORDER BY " . $orderByServiceType;
else :
   // Default
   $sqlquery = "SELECT srvt_id, srvt_name, srvt_group, cs_id"
               . " FROM servicetype"
               . " WHERE hq_id = '" . $currentHqId . "' AND cs_id = '0' AND srvt_mode = '" . $serviceMode . "'"
               . " ORDER BY " . $orderByServiceType;
endif;

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

$serviceTypes = array();
$count = 0;
while ($row = $result->fetch_assoc()):
      $count++;
      $serviceTypes["id"][$count] = $row["srvt_id"];
      $serviceTypes["name"][$count] = $row["srvt_name"];
      $serviceTypes["group"][$count] = $row["srvt_group"];
      $serviceTypes["cs_id"][$count] = $row["cs_id"];
endwhile;
$result->free();


// Check for moving future data in "servicehistory" being current now to "servicecustomer", depending on "hq_id"
function moveSrvh2Srvc () {
	global $db, $PHP_SELF, $srvDebug;
	global $currentTime, $currentDate, $services, $serviceTypes, $hq_id, $csId, $vhtId;
	global $srvc_price, $srvc_discount, $srvc_cr_price, $srvc_cr_discount;
	$srvIdArr = $services["id"];
	$srvtIdArr = $serviceTypes["id"];
	$srvIdArrLen = count($srvIdArr);
	$srvtIdArrLen = count($srvtIdArr);
  if ($srvDebug) :
     echo "servicesLen = " . $srvIdArrLen . "<br>";
     echo "serviceTypesLen = " . $srvtIdArrLen . "<br>";	
     echo "</br>"; print_r($srvIdArr); echo "</br>"; 
     echo "</br>"; print_r($srvtIdArr); echo "</br></br>";
  endif;

  for ($i = 1; $i <= $srvIdArrLen; $i++) :
       $srvId = $srvIdArr[$i];
       for ($j = 1; $j <= $srvtIdArrLen; $j++) :
           $srvtId = $srvtIdArr[$j];
           // Check existence of the row in "servicecustomer"
           if (!existsEntry("servicecustomer",array("srv_id",$srvId,"srvt_id",$srvtId,"hq_id",$hq_id,"cs_id",$csId))) :
              // Generate empty row
              insertStmt("servicecustomer",array("srv_id",$srvId,"srvt_id",$srvtId,"hq_id",$hq_id,"cs_id",$csId));
           endif;
           // Get youngest "servicehistory" value
           // Call with "4" returns array($price, $crPrice, $discount, $crDiscount)
           $currSrvhVal = getServiceValues($srvId, $srvtId, $csId, $hq_id, $currentTime, "4", $vhtId);
           if ($currSrvhVal[0] == "" || $currSrvhVal[0] == "0") : $currSrvhVal[0] = "0.00"; endif;
           if ($currSrvhVal[1] == "" || $currSrvhVal[1] == "0") : $currSrvhVal[1] = "0.00"; endif;
           if ($currSrvhVal[2] == "" || $currSrvhVal[2] == "0") : $currSrvhVal[2] = "0.00"; endif;
           if ($currSrvhVal[3] == "" || $currSrvhVal[3] == "0") : $currSrvhVal[3] = "0.00"; endif;
           $srvhValidFromDate = $currSrvhVal[4];
           // Get "servicecustomer" value
           $srvc_price = ""; $srvc_discount = ""; $srvc_cr_price = ""; $srvc_cr_discount = "";  // Init globals
           getDbFieldValues("servicecustomer",array("srvc_price","srvc_cr_price","srvc_discount","srvc_cr_discount","srvc_modify"),array("srv_id",$srvId,"srvt_id",$srvtId,"hq_id",$hq_id,"cs_id",$csId));
           if ($srvc_price == "" || $srvc_price == "0") : $srvc_price = "0.00"; endif;
           if ($srvc_cr_price == "" || $srvc_cr_price == "0") : $srvc_cr_price = "0.00"; endif;
           if ($srvc_discount == "" || $srvc_discount == "0") : $srvc_discount = "0.00"; endif;
           if ($srvc_cr_discount == "" || $srvc_cr_discount == "0") : $srvc_cr_discount = "0.00"; endif;

           if ($srvDebug) :
              if ($srvc_price != $currSrvhVal[0] || $srvc_cr_price != $currSrvhVal[1] || $srvc_discount != $currSrvhVal[2] || $srvc_cr_discount != $currSrvhVal[3]) : echo "<span style=\"color:red\">"; else : echo "<span style=\"color:green\">"; endif;
              echo "[".$srvId."][".$srvtId."] = [".$srvc_price." / ".$srvc_cr_price." / ".$srvc_discount." / ".$srvc_cr_discount . "][".$currSrvhVal[0]." / ".$currSrvhVal[1]." / ".$currSrvhVal[2]." / ".$currSrvhVal[3] . "]";
              echo "</span>";
              echo "<br><br>";
           endif;

           // Move current values from "servicehistory" to "servicecustomer"
           $whereClause = "srv_id = '" . $srvId . "' AND srvt_id = '" . $srvtId . "' AND hq_id = '" . $hq_id . "' AND cs_id = '" . $csId . "'";
           if ($srvc_price != $currSrvhVal[0]) :
              $sqlStmt = "UPDATE servicecustomer SET srvc_price = '" . $currSrvhVal[0] . "' WHERE " . $whereClause;
              if ($srvDebug) : echo $sqlStmt . "<br>"; endif;
              $res = $db->query($sqlStmt);
              if (DB::isError($res)) : die ("$PHP_SELF: " . $res->getMessage()); endif;
           endif;
           if ($srvc_cr_price != $currSrvhVal[1]) :
              $sqlStmt = "UPDATE servicecustomer SET srvc_cr_price = '" . $currSrvhVal[1] . "' WHERE " . $whereClause;
              if ($srvDebug) : echo $sqlStmt . "<br>"; endif;
              $res = $db->query($sqlStmt);
              if (DB::isError($res)) : die ("$PHP_SELF: " . $res->getMessage()); endif;
           endif;
           if ($srvc_discount != $currSrvhVal[2]) :
              $sqlStmt = "UPDATE servicecustomer SET srvc_discount = '" . $currSrvhVal[2] . "' WHERE " . $whereClause;
              if ($srvDebug) : echo $sqlStmt . "<br>"; endif;
              $res = $db->query($sqlStmt);
              if (DB::isError($res)) : die ("$PHP_SELF: " . $res->getMessage()); endif;
           endif;
           if ($srvc_cr_discount != $currSrvhVal[3]) :
              $sqlStmt = "UPDATE servicecustomer SET srvc_cr_discount = '" . $currSrvhVal[3] . "' WHERE " . $whereClause;
              if ($srvDebug) : echo $sqlStmt . "<br>"; endif;
              $res = $db->query($sqlStmt);
              if (DB::isError($res)) : die ("$PHP_SELF: " . $res->getMessage()); endif;
           endif;
           if ($srvDebug) : echo "<br>"; endif;
       endfor;
  endfor;
}

// Check for (future) values to be moved from "servicehistory" to "servicecustomer" because future date becomes current date
if ($f_future_date_existing == "") :  // REMOVE IF MORE THAN ONE FUTURE DATE WILL EXIST !!!!
   moveSrvh2Srvc();
endif;


// ***************************************
// * Selection of servicecustomer-values *
// ***************************************
if ($f_future_date_existing == "") :
   $sqlquery = "SELECT srvc.srv_id, srvc.srvt_id, srvc.cs_id, srvc.srvc_price, srvc.srvc_discount, srvc.srvc_cr_price, srvc.srvc_cr_discount"
               . " FROM service AS srv, servicetype AS srvt, servicecustomer AS srvc"
               . " WHERE srvc.srv_id = srv.srv_id"
               . "   AND srv.srv_mode = '" . $serviceMode . "'"
               . "   AND srvc.srvt_id = srvt.srvt_id"
               . "   AND srvt.srvt_mode = '" . $serviceMode . "'"
               . "   AND srvc.cs_id = " . $csId
               . "   AND srvc.hq_id = " . $currentHqId
               . " ORDER BY " . $orderByServiceCustomer;
   
   $result = $db->query($sqlquery);
   if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
   
   $servicePrices = array();
   $serviceDiscounts = array();
   $serviceCrPrices = array();
   $serviceCrDiscounts = array();
   while ($row = $result->fetch_assoc()):
         $servicePrices[$row["srv_id"]][$row["srvt_id"]] = $row["srvc_price"];
         $serviceDiscounts[$row["srv_id"]][$row["srvt_id"]] = $row["srvc_discount"];
         $serviceCrPrices[$row["srv_id"]][$row["srvt_id"]] = $row["srvc_cr_price"];
         $serviceCrDiscounts[$row["srv_id"]][$row["srvt_id"]] = $row["srvc_cr_discount"];
   endwhile;
   $result->free();
else :
   // Get values for the selected future date
   $sqlqueryHistory = "SELECT srvh.srv_id, srvh.srvt_id, srvh.cs_id, srvh.srvh_price, srvh.srvh_discount, srvh.srvh_cr_price, srvh.srvh_cr_discount"
                    . " FROM service AS srv, servicetype AS srvt, servicehistory AS srvh"
                    . " WHERE srvh.srv_id = srv.srv_id"
                    . "   AND srv.srv_mode = '" . $serviceMode . "'"
                    . "   AND srvh.srvt_id = srvt.srvt_id"
                    . "   AND srvt.srvt_mode = '" . $serviceMode . "'"
                    . "   AND srvh.cs_id = " . $csId
                    . "   AND srvh.hq_id = " . $currentHqId
                    . "   AND LEFT(srvh.srvh_validfrom, 10) = '" . $f_future_date_existing . "'"
                    . " ORDER BY " . $orderByServiceCustomer;

   $result = $db->query($sqlqueryHistory);
   if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
   
   $servicePrices = array();
   $serviceDiscounts = array();
   $serviceCrPrices = array();
   $serviceCrDiscounts = array();
   while ($row = $result->fetch_assoc()):
         $servicePrices[$row["srv_id"]][$row["srvt_id"]] = $row["srvh_price"];
         $serviceDiscounts[$row["srv_id"]][$row["srvt_id"]] = $row["srvh_discount"];
         $serviceCrPrices[$row["srv_id"]][$row["srvt_id"]] = $row["srvh_cr_price"];
         $serviceCrDiscounts[$row["srv_id"]][$row["srvt_id"]] = $row["srvh_cr_discount"];
   endwhile;
   $result->free();
endif;


// Number of entries
$lenServices = count($services["id"]);
$lenServiceTypes = count($serviceTypes["id"]);


// *************************************************
// * Storing prices and discounts if requested     *
// * Using the results of the statements before!!! *
// *************************************************
if ($f_act != "" && $f_act == "save") :

   TA("B");

   for ($i = 1; $i <= $lenServiceTypes; $i++) :

       for ($j = 1; $j <= $lenServices; $j++) :    

           // Define current service-id and service-type-id
           $srvCur = $services["id"][$j];
           $srvtCur = $serviceTypes["id"][$i];

           // Get current input-type-text-field with price-/dicount-value
           list ($newValueToBeStored) = getHttpVars(array("service_". $srvCur ."_" . $srvtCur));
           if ($newValueToBeStored == "") : $newValueToBeStored = "0"; endif;
           list ($newCrValueToBeStored) = getHttpVars(array("service_cr_". $srvCur ."_" . $srvtCur));
           if ($newCrValueToBeStored == "") : $newCrValueToBeStored = "0"; endif;

           // Allow float data with "." and ","
           $newValueToBeStored = str_replace (",", ".", $newValueToBeStored);
           $newCrValueToBeStored = str_replace (",", ".", $newCrValueToBeStored);

           if ($servicePrices[$srvCur][$srvtCur] == "") : $servicePrices[$srvCur][$srvtCur] = "0"; endif;
           if ($serviceDiscounts[$srvCur][$srvtCur] == "") : $serviceDiscounts[$srvCur][$srvtCur] = "0"; endif;
           if ($serviceCrPrices[$srvCur][$srvtCur] == "") : $serviceCrPrices[$srvCur][$srvtCur] = "0"; endif;
           if ($serviceCrDiscounts[$srvCur][$srvtCur] == "") : $serviceCrDiscounts[$srvCur][$srvtCur] = "0"; endif;

           if ($f_future_date_existing == "") :

              if ($mode == "price") :
              
                 // Check for necessity to update or insert
                 if ($servicePrices[$srvCur][$srvtCur] != $newValueToBeStored || $serviceCrPrices[$srvCur][$srvtCur] != $newCrValueToBeStored) :
              
                    if (existsEntry("servicecustomer",array("srv_id",$srvCur,"srvt_id",$srvtCur,"hq_id",$currentHqId,"cs_id",$csId))) :
              
                       $sqlStmt = "UPDATE servicecustomer SET srvc_price = $newValueToBeStored, srvc_cr_price = $newCrValueToBeStored"
                                  . " WHERE srv_id = $srvCur AND srvt_id = $srvtCur AND hq_id = $currentHqId AND cs_id = $csId";
                       $res = $db->query($sqlStmt);
                       if (DB::isError($res)) : die ("$PHP_SELF: " . $res->getMessage()); endif;
                    else :                
                       if ($newValueToBeStored != "0" || $newCrValueToBeStored != "0") :
                          // Insert the new price
                          $tmpFields = array("srv_id",$srvCur,"srvt_id",$srvtCur,"hq_id",$currentHqId,"cs_id",$csId,"srvc_price",$newValueToBeStored,"srvc_discount",$serviceDiscounts[$srvCur][$srvtCur],"srvc_cr_price",$newCrValueToBeStored,"srvc_cr_discount",$serviceCrDiscounts[$srvCur][$srvtCur]);
                          insertStmt("servicecustomer",$tmpFields);
                       endif;
                    endif;
                    
                    // Insert current prices AND (!) discounts into the servicehistory
                    $tmpFields = array("srv_id",$srvCur,"srvt_id",$srvtCur,"hq_id",$currentHqId,"cs_id",$csId,"usr_id",$currentSessionUsrId,"srvh_validfrom",$currentTime,"srvh_price",$newValueToBeStored,"srvh_discount",$serviceDiscounts[$srvCur][$srvtCur],"srvh_cr_price",$newCrValueToBeStored,"srvh_cr_discount",$serviceCrDiscounts[$srvCur][$srvtCur]);
                    insertStmt("servicehistory",$tmpFields);
                    
                    $servicePrices[$srvCur][$srvtCur] = $newValueToBeStored;
                    $serviceCrPrices[$srvCur][$srvtCur] = $newCrValueToBeStored;
                 endif;
              
              else :
              
                 // Check for necessity to update or insert
                 if ($serviceDiscounts[$srvCur][$srvtCur] != $newValueToBeStored || $serviceCrDiscounts[$srvCur][$srvtCur] != $newCrValueToBeStored) :
              
                    if (existsEntry("servicecustomer",array("srv_id",$srvCur,"srvt_id",$srvtCur,"hq_id",$currentHqId,"cs_id",$csId))) :
                       // Update the new discount              
                       $sqlStmt = "UPDATE servicecustomer SET srvc_discount = $newValueToBeStored, srvc_cr_discount = $newCrValueToBeStored"
                                  . " WHERE srv_id = $srvCur AND srvt_id = $srvtCur AND hq_id = $currentHqId AND cs_id = $csId";
                       $res = $db->query($sqlStmt);
                       if (DB::isError($res)) : die ("$PHP_SELF: " . $res->getMessage()); endif;
                    else :                
                       if ($newValueToBeStored != "0" || $newCrValueToBeStored != "0") :
                          // Insert the new discount
                          $tmpFields = array("srv_id",$srvCur,"srvt_id",$srvtCur,"hq_id",$currentHqId,"cs_id",$csId,"srvc_price",$servicePrices[$srvCur][$srvtCur],"srvc_discount",$newValueToBeStored,"srvc_cr_price",$serviceCrPrices[$srvCur][$srvtCur],"srvc_cr_discount",$newCrValueToBeStored);
                          insertStmt("servicecustomer",$tmpFields);
                       endif;
                    endif;
                    
                    // Insert current prices AND (!) discounts into the servicehistory
                    $tmpFields = array("srv_id",$srvCur,"srvt_id",$srvtCur,"hq_id",$currentHqId,"cs_id",$csId,"usr_id",$currentSessionUsrId,"srvh_validfrom",$currentTime,"srvh_price",$servicePrices[$srvCur][$srvtCur],"srvh_discount",$newValueToBeStored,"srvh_cr_price",$serviceCrPrices[$srvCur][$srvtCur],"srvh_cr_discount",$newCrValueToBeStored);
                    insertStmt("servicehistory",$tmpFields);
                    
                    $serviceDiscounts[$srvCur][$srvtCur] = $newValueToBeStored;
                    $serviceCrDiscounts[$srvCur][$srvtCur] = $newCrValueToBeStored;
                 endif;           
              endif;

           else :  // Update values for selected future date in "servicehistory" only (!!!!)
           
              if ($mode == "price") :

                 if (existsEntry("servicehistory",array("srv_id",$srvCur,"srvt_id",$srvtCur,"hq_id",$currentHqId,"cs_id",$csId,"srvh_validfrom",$f_future_date_existing . " 00:00:00"))) :

                    $sqlStmt = "UPDATE servicehistory SET srvh_price = $newValueToBeStored, srvh_cr_price = $newCrValueToBeStored"
                               . " WHERE srv_id = $srvCur AND srvt_id = $srvtCur AND hq_id = $currentHqId AND cs_id = $csId AND srvh_validfrom = '" . $f_future_date_existing . " 00:00:00'";
                    $res = $db->query($sqlStmt);
                    if (DB::isError($res)) : die ("$PHP_SELF: " . $res->getMessage()); endif;
                 else :                
                    if ($newValueToBeStored != "0" || $newCrValueToBeStored != "0") :
                       // Insert the new price
                       $tmpFields = array("srv_id",$srvCur,"srvt_id",$srvtCur,"hq_id",$currentHqId,"cs_id",$csId,"usr_id",$currentSessionUsrId,"srvh_price",$newValueToBeStored,"srvh_discount",$serviceDiscounts[$srvCur][$srvtCur],"srvh_cr_price",$newCrValueToBeStored,"srvh_cr_discount",$serviceCrDiscounts[$srvCur][$srvtCur],"srvh_validfrom",$f_future_date_existing . " 00:00:00");
                       insertStmt("servicehistory",$tmpFields);
                    endif;
                 endif;

              else :

                 if (existsEntry("servicehistory",array("srv_id",$srvCur,"srvt_id",$srvtCur,"hq_id",$currentHqId,"cs_id",$csId,"srvh_validfrom",$f_future_date_existing . " 00:00:00"))) :

                    $sqlStmt = "UPDATE servicehistory SET srvh_discount = $newValueToBeStored, srvh_cr_discount = $newCrValueToBeStored"
                               . " WHERE srv_id = $srvCur AND srvt_id = $srvtCur AND hq_id = $currentHqId AND cs_id = $csId AND srvh_validfrom = '" . $f_future_date_existing . " 00:00:00'";
                    $res = $db->query($sqlStmt);
                    if (DB::isError($res)) : die ("$PHP_SELF: " . $res->getMessage()); endif;
                 else:
                    if ($newValueToBeStored != "0" || $newCrValueToBeStored != "0") :
                       // Insert the new discount
                       $tmpFields = array("srv_id",$srvCur,"srvt_id",$srvtCur,"hq_id",$currentHqId,"cs_id",$csId,"usr_id",$currentSessionUsrId,"srvh_price",$servicePrices[$srvCur][$srvtCur],"srvh_discount",$newValueToBeStored,"srvh_cr_price",$serviceCrPrices[$srvCur][$srvtCur],"srvh_cr_discount",$newCrValueToBeStored,"srvh_validfrom",$f_future_date_existing . " 00:00:00");
                       insertStmt("servicehistory",$tmpFields);
                    endif;
                 endif;
              endif;              
           endif;  // $f_future_date_existing
       endfor;
   endfor;
   
   TA("C");
   TA("E");   
endif;


// Get values of the selected future date AFTER storing AGAIN (!!!)
if ($f_future_date_existing != "") :
   // Get values for the selected future date
   // sqlqueryHistory = .... Statement see above ....

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

   while ($row = $result->fetch_assoc()):
         $servicePrices[$row["srv_id"]][$row["srvt_id"]] = $row["srvh_price"];
         $serviceDiscounts[$row["srv_id"]][$row["srvt_id"]] = $row["srvh_discount"];
         $serviceCrPrices[$row["srv_id"]][$row["srvt_id"]] = $row["srvh_cr_price"];
         $serviceCrDiscounts[$row["srv_id"]][$row["srvt_id"]] = $row["srvh_cr_discount"];
   endwhile;
   $result->free();
endif;


// *****************************************************
// * Generation of the price-matrix or discount-matrix *
// *****************************************************

// Table-header
$serviceOutput = "<tr>\n";
$serviceOutput .= "<td>&nbsp;</td>\n";   // because of the following row-names
for ($j = 1; $j <= $lenServices; $j++) :
    $serviceOutput .= "<td>" . $services["name"][$j] . "</td>\n";
endfor;
$serviceOutput .= "</tr>\n";

// Table-data
$remServiceTypeGroup = "";
for ($i = 1; $i <= $lenServiceTypes; $i++) :
    if ($remServiceTypeGroup != $serviceTypes["group"][$i]) :
       $remServiceTypeGroup = $serviceTypes["group"][$i];
       $tmpGroupIdArray = spliti(",", substr($serviceTypes["group"][$i], 1, -1));
       $tmpGroupIdArrayLen = count($tmpGroupIdArray);
       $tmpGroupName = "";
       for ($k = 0; $k < $tmpGroupIdArrayLen; $k++) :
           if ($tmpGroupName != "") : $tmpGroupName .= "&nbsp;&nbsp;/&nbsp;&nbsp;"; endif;
           $tmpGroupName .= getFieldValueFromId("groups", "grp_id", $tmpGroupIdArray[$k], "grp_name");
       endfor;
       $serviceOutput .= "<tr><td colspan=\"" . $lenServices . "\"><b>" . $tmpGroupName . "</b></td></tr>\n";   // "$lenServices" because of number of cols
    endif;
    $serviceOutput .= "<tr>\n";
    $serviceOutput .= "<td>" . $serviceTypes["name"][$i] . "</td>\n";
    for ($j = 1; $j <= $lenServices; $j++) :    
    
        // Define current service-id and service-type-id
        $srvCur = $services["id"][$j];
        $srvtCur = $serviceTypes["id"][$i];    

        if ($mode == "price") :
           if ($servicePrices[$srvCur][$srvtCur] == "") : $servicePrices[$srvCur][$srvtCur] = "0"; endif;
           if ($serviceCrPrices[$srvCur][$srvtCur] == "") : $serviceCrPrices[$srvCur][$srvtCur] = "0"; endif;
           $serviceOutput .= "<td>\n";
           $serviceOutput .= "<div class=\"service\"><input type=\"text\" class=\"cell_attr\" name=\"service_" . $srvCur . "_" . $srvtCur . "\" value=\"" . $servicePrices[$srvCur][$srvtCur] . "\" size=\"7\" align=\"right\"></div>\n";
           $serviceOutput .= "<div class=\"service_cr\"><input type=\"text\" class=\"cell_attr_cr\" name=\"service_cr_" . $srvCur . "_" . $srvtCur . "\" value=\"" . $serviceCrPrices[$srvCur][$srvtCur] . "\" size=\"7\" align=\"right\"></div>\n";
           $serviceOutput .= "</td>\n";
        else :
           if ($serviceDiscounts[$srvCur][$srvtCur] == "") : $serviceDiscounts[$srvCur][$srvtCur] = "0"; endif;
           if ($serviceCrDiscounts[$srvCur][$srvtCur] == "") : $serviceCrDiscounts[$srvCur][$srvtCur] = "0"; endif;
           $serviceOutput .= "<td>\n";
           $serviceOutput .= "<div class=\"service\"><input type=\"text\" class=\"cell_attr\" name=\"service_" . $srvCur . "_" . $srvtCur . "\" value=\"" . $serviceDiscounts[$srvCur][$srvtCur] . "\" size=\"7\" align=\"right\"></div>\n";
           $serviceOutput .= "<div class=\"service_cr\"><input type=\"text\" class=\"cell_attr_cr\" name=\"service_cr_" . $srvCur . "_" . $srvtCur . "\" value=\"" . $serviceCrDiscounts[$srvCur][$srvtCur] . "\" size=\"7\" align=\"right\"></div>\n";
           $serviceOutput .= "</td>\n";
        endif;
    endfor;
    $serviceOutput .= "</tr>\n";
endfor;

// Future dates with prices and discounts
$futureDatesArr = getColVectorFromDB2ArrayByClause("servicehistory", "LEFT(srvh_validfrom,10) AS srvh_validfrom", "hq_id = '" . $currentHqId . "' AND cs_id = '" . $csId . "' AND LEFT(srvh_validfrom,10) > '" . $currentDate . "'", "", "srvh_validfrom", "DISTINCT");
$futureDatesArrLen = count($futureDatesArr);
if ($srvDebug) :
   // print_r($futureDatesArr); echo "<br>";
   echo "futureDatesArrLen = " . $futureDatesArrLen . "<br>";
   echo "f_future_date_existing = " . $f_future_date_existing . "<br>";
endif;

// Output
if ($mode == "price") : 
   $title = getLngt("Allgemeine Preise");
else :    
   $title = getLngt("Allgemeine Rabatte [in %]");
endif;   
if ($csId != "0") :   
   if ($mode == "price") : 
      $title = getLngt("Preise speziell für den Kunden") . " " . $cmpComp . " " . $cmpComp2;
   else :    
      $title = getLngt("Rabatte speziell für den Kunden") . " " . $cmpComp . " " . $cmpComp2;
   endif;   
endif;


$currentFrameName = "";  // Empty string for "main frame"

// Date-ranges
$filter_dateranges = "<select class=\"dateFields\" id=\"day_from\" name=\"day_from\" class=\"f8np1\" onchange=\"fillDateFields(0, '" . $currentFrameName . "', 'services', 'day_from', 'day_from', 'month_from', 'year_from', '', '', ''); setCssDateFields();\"></select>\n"
                   . "<select class=\"dateFields\" id=\"month_from\" name=\"month_from\" class=\"f8np1\" onchange=\"fillDateFields(0, '" . $currentFrameName . "', 'services', 'month_from', 'day_from', 'month_from', 'year_from', '', '', ''); setCssDateFields();\"></select>\n"
                   . "<select class=\"dateFields\" id=\"year_from\" name=\"year_from\" class=\"f8np1\" onchange=\"fillDateFields(0, '" . $currentFrameName . "', 'services', 'year_from', 'day_from', 'month_from', 'year_from', '', '', ''); setCssDateFields();\"></select>\n";

// Javascript-function as template only for
$js_date = "<script type=\"text/javascript\">\n"
         . "<!--\n"
         . "function initForm() {\n"
         . "  fillDateFields(1,\"" . $currentFrameName . "\",\"services\",\"\",\"day_from\",\"month_from\",\"year_from\",\"\",\"\",\"\");\n"
         . "  setDateTimeFields(\"" . $currentFrameName . "\",\"services\",".$day_from.",".$month_from.",".$year_from.", \"\", \"\", \"day_from\", \"month_from\", \"year_from\", \"\", \"\", \"\");\n"
         . "}\n"
         . "-->\n"
         . "</script>\n";
?>


<html lang="de">
<head>
<title><?php echo $pageTitel; ?></title>

<style type="text/css">
  <?php include_once ("../css/phoenix.css.php"); ?>
  <?php include_once ("../css/navigation.css.php"); ?>
  <?php include_once ("../css/mc.css.php"); ?>
</style>

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

<script src="../include/checkFormTags.js" type="text/javascript"></script>
<script src="../include/lib_global.js" type="text/javascript"></script>

<?php echo $js_date ?>

<script type="text/javascript">
<!--
// NAVIGATION
<?php echo $jsMenuOut; ?>

var currentTime = new Date();
FILLDATEFIELDSSTARTYEAR = currentTime.getFullYear();

function searchCustomerPopup() {
  var widthPopupWin = 800;
  var heightPopupWin = 600;
  var leftPopupWin = (screen.width / 2) - (widthPopupWin / 2) - 12;
  var topPopupWin = (screen.height / 2) - (heightPopupWin / 2) - 50;
  var popupWin;
  popupWin=window.open("../admin/impressum.html", "","dependent=yes,width=" + widthPopupWin + ",height=" + heightPopupWin +",left=" + leftPopupWin + ",top=" + topPopupWin);  	
};	

function finishPage(f_act) { 
 // for(i=0;i<document.forms[0].jb_costcenter_select.length;++i) {
 //   if (document.forms[0].jb_costcenter_select.options[i].selected == true) {   
 //      document.forms[0].jb_costcenter.value=document.forms[0].jb_costcenter_select.options[i].value;
 //   }
 // };
 if (f_act == 'save') {
    if (!confirm('<?php echo getLngt("Preisbereichsmatrix speichern?") ?>')) {
       return false;
    }
 }
 if (f_act == 'changeMode') {
    if (confirm('<?php echo getLngt("Möchten Sie den Modus wechseln?") ?>')) {
    	 if (document.forms[0].serviceMode.value == '1') {
    	 	  document.forms[0].serviceMode.value = '0'
    	 } else {
    	 	  document.forms[0].serviceMode.value = '1'
    	 }	    	        
    }
 }
 document.forms[0].f_act.value = f_act;
 document.forms[0].submit();
};

function finishPageServiceRemove(f_act) { 
 var service_removed = getSelectedValue('f_service_id');
 if (service_removed != '') {
    if (confirm('<?php echo getLngt("Den Preistyp wirklich entfernen?") ?>')) {
    	 if (confirm('<?php echo getLngt("Wirklich entfernen? Alle zugehörigen Preisinformationen werden entfernt!") ?>')) {
          finishPage(f_act);
       };
    };
 } else {
    alert('<?php echo getLngt("Es wurde kein Preistyp zum Entfernen ausgewählt!") ?>');
 }
};

function finishPageServiceTypeRemove(f_act) { 
 var service_type_removed = getSelectedValue('f_servicetype_id');
 if (service_type_removed != '') {
    if (confirm('<?php echo getLngt("Den Leistungstyp wirklich entfernen?") ?>')) {
    	 if (confirm('<?php echo getLngt("Wirklich entfernen? Alle zugehörigen Preisinformationen werden entfernt!") ?>')) {
          finishPage(f_act);
       };
    };
 } else {
    alert('<?php echo getLngt("Es wurde kein Leistungstyp zum Entfernen ausgewählt!") ?>');
 }
};

function finishPageServiceChange(f_act) { 
 var service_change = document.forms[0].f_service_change.value;
 if (service_change != '') {
    if (confirm('<?php echo getLngt("Den Preistyp wirklich umbenennen?") ?>')) {
       finishPage(f_act);
    };
 } else {
    alert('<?php echo getLngt("Bitte geben Sie einen Bezeichner ein!") ?>');
 }
};

function finishPageServiceNew(f_act) {
 var service_new = document.forms[0].f_service_new.value;
 if (service_new != '') {
    if (confirm('<?php echo getLngt("Neuen Preistyp anlegen?") ?>')) {
       finishPage(f_act);
    };
 } else {
    alert('<?php echo getLngt("Bitte geben Sie einen Bezeichner ein!") ?>');
 }
};

function finishPageServiceTypeChange(f_act) { 
 var servicetype_change = document.forms[0].f_servicetype_change.value;
 if (servicetype_change != '') {
    if (confirm('<?php echo getLngt("Den Leistungstyp wirklich umbenennen?") ?>')) {
       finishPage(f_act);
    };
 } else {
    alert('<?php echo getLngt("Bitte geben Sie einen Bezeichner ein!") ?>');
 }
};

function finishPageServiceTypeNew(f_act) {
 var servicetype_new = document.forms[0].f_servicetype_new.value;
 if (servicetype_new != '') {
    if (confirm('<?php echo getLngt("Neuen Leistungstyp anlegen?") ?>')) {
       finishPage(f_act);
    };
 } else {
    alert('<?php echo getLngt("Bitte geben Sie einen Bezeichner ein!") ?>');
 }
};

function openGroups(itemType) {
	var itemId = 0;
	var elem = '';
  if (itemType == 'srv') {elem = document.forms[0].f_service_id;};
  if (itemType == 'srvt') {elem = document.forms[0].f_servicetype_id;};
	var optLen = elem.length;
  for (i = 0; i < optLen; ++i) {
    if (elem.options[i].selected == true) {
    	 itemId = elem.options[i].value;
    };
  }
  if (itemType != '' && itemId > 0) {
     var widthPopupWin = 800;
     var heightPopupWin = 700;
     var leftPopupWin = (screen.width / 2) - (widthPopupWin / 2) - 12;
     var topPopupWin = (screen.height / 2) - (heightPopupWin / 2) - 50;
     var popupWin;
     popupWin = window.open("../admin/groupmembers.php?itemType=" + itemType + "&itemId=" + itemId,"","dependent=yes,width=" + widthPopupWin + ",height=" + heightPopupWin +",left=" + leftPopupWin + ",top=" + topPopupWin + ",scrollbars=yes");
  }
};

function initCells() {
	// Show or hide cells
  if ('<?php echo $f_chkbx_toggle_checked ?>' == 'checked') { $(".service").show(); } else { $(".service").hide(); };
  if ('<?php echo $f_chkbx_toggle_cr_checked ?>' == 'checked') { $(".service_cr").show(); } else { $(".service_cr").hide(); };
  // Common checkbox attributes
  $(".chkbox_attr").css("display", "inline-block");
  $(".chkbox_attr").css("height", "20px");
  <?php if ($mode == "discount") : ?>
    $(".chkbox_attr").css("width", "200px");
  <?php else : ?>
  	$(".chkbox_attr").css("width", "160px");
  <?php endif; ?>
  // Special checkbox attributes
  $(".chkbox_attr_special").css("background-color", "#FFFFFF");
  $(".chkbox_attr_special_cr").css("background-color", "#F7F8E0");
  // Special cell attributes
  $(".cell_attr").css("background-color", "#FFFFFF");
  $(".cell_attr_cr").css("background-color", "#F7F8E0");
}

function toggleCells() {
	// Check at least one checkbox has to be set
	if (!$('#f_chkbx_toggle').prop('checked') && !$('#f_chkbx_toggle_cr').prop('checked')) {
		 $('#f_chkbx_toggle').val('service');
		 $('#f_chkbx_toggle').prop('checked',true);
		 alert('<?php echo getLngt("Mindestens eine der Checkboxen muss gesetzt sein!") ?>');
	}
  if ($('#f_chkbx_toggle').prop('checked')) { $(".service").show(); } else { $(".service").hide(); };
  if ($('#f_chkbx_toggle_cr').prop('checked')) { $(".service_cr").show(); } else { $(".service_cr").hide(); };
}

<?php if ($futureDatesEnabled) : ?>
// Date fields
function setCssDateFields() {
  var currDate = '<?php echo $currentDate ?>';
  var selDate;
  var selYear = $('#year_from').val();
  var selMonth = $('#month_from').val();
  var selDay = $('#day_from').val();
  if (selYear != '' && selMonth != '' && selDay != '') {
  	 selDate = selYear + '-' + padl(selMonth, 2) + "-" + padl(selDay, 2);
  	 $(".dateFields").css("background-color", "#EEEEEE");
  	 if (selDate < currDate) {
  	 	  $('#year_from').val('<?php echo $year_from ?>');
  	 	  $('#month_from').val('<?php echo $month_from ?>');
  	 	  $('#day_from').val('<?php echo $day_from ?>');
  	 	  alert('<?php echo getLngt("Das Datum kann nur in ein zukünftiges geändert werden!") ?>');
  	 }
  	 if (selDate > currDate) {
  	 	  $(".dateFields").css("background-color", "#FF0000");
  	 }
  }
}

// Date selection box
function setCssDateSelectionBox() {
	var futureDateExisting = $('#f_future_date_existing').val();
	if (futureDateExisting == '') {
		 $('#f_future_date_existing').css("background-color", "#EEEEEE");
	} else {
		 $('#f_future_date_existing').css("background-color", "#FF0000");
	}
}
<?php endif; ?>
-->
</script>
<noscript>
  <center>
  <b><br>JavaScript ist nicht verf&uuml;gbar. Bitte aktivieren Sie JavaScript<br><br>
        in Ihrem Browser, damit diese Seite ordnungsgem&auml;&szlig; funktioniert!</b><br><br>
  </center>
</noscript>
</head>
                                                                    
<body onLoad="<?php echo $phpCurrentNavigationOnLoad ?>initCells();<?php echo ($futureDatesEnabled ? ($futureDatesArrLen > 0 ? "setCssDateSelectionBox();" : "initForm();") : "") ?>displayStatusMessage();">

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

<div class="mc_page-header">
  <?php echo $title ?>
</div>

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

<?php // echo htmlDivLineSpacer("5px", "", "left"); ?>
<div>
	<?php echo defineButtonType10(getLngt("Speichern"), "action_save", "finishPage('save');", "120", "left", "3"); ?>
  <?php echo defineButtonType10(getLngt("Modus&nbsp;wechseln"), "action_reset", "finishPage('changeMode');", "120", "left", "0"); ?>
</div> 
<?php echo htmlDivLineSpacer("20px", "", "left"); ?>

<form name="services" action="../admin/services.php" method="post" <?php echo $htmlFormTarget ?>>
  
  <input type="hidden" name="f_act" value="">
  <input type="hidden" name="mode" value="<?php echo ec($mode) ?>">
  <input type="hidden" name="orderByService" value="<?php echo $orderByService ?>">
  <input type="hidden" name="orderByServiceType" value="<?php echo $orderByServiceType ?>">
  <input type="hidden" name="orderByServiceCustomer" value="<?php echo $orderByServiceCustomer ?>">
  <input type="hidden" name="csId" value="<?php echo ec($csId) ?>">
  <input type="hidden" name="opener" value="<?php echo $opener ?>">
  <input type="hidden" name="serviceMode" value="<?php echo $serviceMode ?>">
  <?php echo $phpCurrentNavigationInputHidden ?>
  <input type="hidden" name="deactivateMenu" value="<?php echo ec($deactivateMenu) ?>">
  <input type="hidden" name="pageFirstCall" value="<?php echo $pageFirstCall ?>">

  <?php echo htmlDivLineSpacer("30px"); ?>

  <div>
    <span class="chkbox_attr chkbox_attr_special"><input type="checkbox"  id="f_chkbx_toggle" name="f_chkbx_toggle" value="service" onChange="toggleCells();" <?php echo $f_chkbx_toggle_checked ?>> <?php echo ($mode == "price" ? getLngt("Preise") : getLngt("Rabatte")); ?></span>
    &nbsp;&nbsp;
    <span class="chkbox_attr chkbox_attr_special_cr"><input type="checkbox" id="f_chkbx_toggle_cr" name="f_chkbx_toggle_cr" value="service_cr" onChange="toggleCells();" <?php echo $f_chkbx_toggle_cr_checked ?>> <?php echo ($mode == "price" ? getLngt("Frachtvergütungen") : getLngt("Frachtvergütungsrabatte")); ?></span>
    &nbsp;&nbsp;&nbsp;&nbsp;

    <?php if ($futureDatesEnabled) : ?>
      <?php if ($futureDatesArrLen > 0) : ?>
        <select class="f8np1" id="f_future_date_existing" name="f_future_date_existing" onchange="finishPage('');">
          <?php echo addOptionsFromArray($futureDatesArr, $f_future_date_existing, $emptyItem = "YES", $lf = "\n") ?>
        </select>
      <?php else : ?>
        <?php echo $filter_dateranges ?>
      <?php endif; ?>
    <?php endif; ?>
  </div>
  <?php echo htmlDivLineSpacer("15px", "", "left"); ?>

  <div>
    <table>
      <?php echo $serviceOutput ?>
    </table>    
  </div>
  <?php echo htmlDivLineSpacer("20px", "", "left"); ?>

  <div>
    <?php 
      // echo defineButtonType10(getLngt("Speichern"), "action_save", "finishPage('save');", "100", "left", "3"); 
      // echo htmlDivLineSpacer("20px", "", "left");
    ?>
  </div>
  <?php echo htmlDivLineSpacer("20px", "", "left"); ?>

  <?php if ($csId != "0") : ?>
     <div class="f12bp1_blue">
       <?php echo getLngt("Kundenspezifische Preis-/Leistungstypen:") ?>
     </div>
    <?php echo htmlDivLineSpacer("20px", "", "left"); ?>
  <?php endif; ?>  

  <?php if ($serviceMode == "1") : ?>
    <div>
      <div <?php echo setStyleHtmlDiv("130px","left"); ?>><span class="f10bp1_blue"><?php echo getLngt("Preistypen") ?>:</span></div>
      <div>
        <div <?php echo setStyleHtmlDiv("210px","left"); ?>>
          <select name="f_service_id">
          	<option value="">---</option>
            <?php 
              for ($j = 1; $j <= $lenServices; $j++) :
                  if ($csId == "0" || ($csId != "0" && $services["cs_id"][$j])) :
                     $is_selected = "";
                     if ($f_service_id == $services["id"][$j]) : $is_selected = " selected"; endif;
                     echo "<option value=\"" . $services["id"][$j] . "\" " . $is_selected . ">" . $services["name"][$j] . "</option>\n";
                  endif;
              endfor;
            ?>
          </select>
          <?php
            // Check for authorisation to remove single service
            if ($serviceMode >= "1" && authCheckEmployeeRights($emp_id, "31")) :
               echo "&nbsp;<a href=\"javascript:finishPageServiceRemove('remove_service_single');\"><img src=\"../images/waste.png\" border=\"0\" height=\"15\" width=\"12\"></a>";
            endif;
          ?>
        </div>
        <?php 
          if ($csId == "0") :
             echo defineButtonType10(getLngt("Gruppen"), "action_srvgroup", "openGroups('srv');", "90", "left", "5"); 
          endif;
        ?>
        <div <?php echo setStyleHtmlDiv("150px","left"); ?>>
          <input type="text" name="f_service_change" value="" size="20" maxlength="50">&nbsp;&nbsp;
        </div>
        <?php echo defineButtonType10(getLngt("Preistyp&nbsp;umbenennen"), "action_rename", "finishPageServiceChange('save_service_change');", "180", "left", "5"); ?>
        <div <?php echo setStyleHtmlDiv("140px","left"); ?>>
          Neuer&nbsp;Preistyp:
        </div>
        <div <?php echo setStyleHtmlDiv("150px","left"); ?>>
          <input type="text" name="f_service_new" value="" size="20" maxlength="50">&nbsp;&nbsp;&nbsp;
        </div>
        <?php echo defineButtonType10(getLngt("Preistyp&nbsp;anlegen"), "action_new", "finishPageServiceNew('save_service_new');", "180", "left", "3"); ?>
      </div>
    </div>
    <?php echo htmlDivLineSpacer("15px", "", "left"); ?>

    <div>
      <div <?php echo setStyleHtmlDiv("130px","left"); ?>><span class="f10bp1_blue"><?php echo getLngt("Leistungstypen") ?>:</span></div>
      <div>
        <div <?php echo setStyleHtmlDiv("210px","left"); ?>>
          <select name="f_servicetype_id">
          	<option value="">---</option>
            <?php 
              for ($j = 1; $j <= $lenServiceTypes; $j++) :
                  if ($csId == "0" || ($csId != "0" && $serviceTypes["cs_id"][$j])) :
                     $is_selected = "";
                     if ($f_servicetype_id == $serviceTypes["id"][$j]) : $is_selected = " selected"; endif;
                     echo "<option value=\"" . $serviceTypes["id"][$j] . "\" " . $is_selected . ">" . $serviceTypes["name"][$j] . "</option>\n";
                  endif;
              endfor;
            ?>
          </select>
          <?php
            // Check for authorisation to remove single service
            if ($serviceMode >= "1" && authCheckEmployeeRights($emp_id, "31")) :
               echo "&nbsp;<a href=\"javascript:finishPageServiceTypeRemove('remove_service_type_single');\"><img src=\"../images/waste.png\" border=\"0\" height=\"15\" width=\"12\"></a>";
            endif;
          ?>
        </div>
        <?php 
          if ($csId == "0") :
             echo defineButtonType10(getLngt("Gruppen"), "action_srvtgroup", "openGroups('srvt');", "90", "left", "5"); 
          endif;
        ?>
        <div <?php echo setStyleHtmlDiv("150px","left"); ?>>          
          <input type="text" name="f_servicetype_change" value="" size="20" maxlength="50">&nbsp;&nbsp;
          </div>
        <?php echo defineButtonType10(getLngt("Leistungstyp&nbsp;umbenennen"), "action_rename", "finishPageServiceTypeChange('save_servicetype_change');", "180", "left", "5"); ?>
        <div <?php echo setStyleHtmlDiv("140px","left"); ?>>
          Neuer&nbsp;Leistungstyp:
        </div>
        <div <?php echo setStyleHtmlDiv("150px","left"); ?>>
          <input type="text" name="f_servicetype_new" value="" size="20" maxlength="50">&nbsp;&nbsp;&nbsp;
        </div>
        <?php echo defineButtonType10(getLngt("Leistungstyp&nbsp;anlegen"), "action_new", "finishPageServiceTypeNew('save_servicetype_new');", "180", "left", "3"); ?>
      </div>
    </div>
    <?php echo htmlDivLineSpacer("15px", "", "left"); ?>
  <?php endif; ?>

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