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

include_once ("../include/mcglobal.inc.php");
include_once ("../include/auth.inc.php");


// Check HTTP-Parameters
getSecHttpVars("1",array("f_act", "customerId", "cscIdRoot", "cscIdActual", "statusMessage",
                         "emp_id_act", "userListOfType", "usr_id_curr", "tableSort", "deactivateMenu", "f_hq_id", "par_stock_access",
                         "f_usr_name", "f_usr_firstname", "f_usr_birthdate_day", "f_usr_birthdate_month", "f_usr_birthdate_year",
                         "f_usr_email", "f_usr_phone", "f_usr_phone2", "f_usr_fax", "f_usr_account", "f_usr_password", "f_usr_password2",
                         "f_selectRootStock", "rootStkIdForSubstkPar", "rootStkOpForSubstkPar", "f_substocks_readonly", "f_stk_article_access"));

getLanguage(__FILE__);

// Set current menu navigation element
$pageTitel = getLngt("BENUTZER");
if ($userListOfType == "4") :
   $menuElement = "lagerist";
   $pageTitel = getLngt("LAGERMITARBEITER");
endif;
if ($userListOfType == "5") :
   $menuElement = "rampenmanager";
   $pageTitel = getLngt("RAMPENMANAGER");
endif;

include_once ("../admin/menu.php");
include_once ("../include/html.inc.php");
include_once ("../include/inc_stock.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);
if (!authCheckEmployeeRights($emp_id, "3")) : 
   $userListOfType = ""; 
endif;
// Check for user list type to be administrated NOT being in [0 .. 3]
if ($userListOfType == "0" || $userListOfType == "1" || $userListOfType == "2" || $userListOfType == "3") :
   $userListOfType = ""; 
endif;

// Birthdate
$f_usr_birthdate = "";
if ($f_usr_birthdate_year != "" && $f_usr_birthdate_month != "" && $f_usr_birthdate_day != "") :
  $f_usr_birthdate = $f_usr_birthdate_year . "-" . pad($f_usr_birthdate_month, 2, "0") . "-" . pad($f_usr_birthdate_day, 2, "0");
endif;

// Triggers javascript to clear the input fields to edit a user
$clearUserFields = false;
if ($userListOfType != "") :

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

   if ($userTypeName == "hq") :
   
      // Insert new user
      if ($f_act == "newUser") :
      
         // Generate log string
         $logString = makeLogString(array($userListOfType,$f_usr_name,$f_usr_firstname,$f_usr_email,$f_usr_phone,$f_usr_phone2,$f_usr_fax,$f_usr_account,$f_usr_birthdate), ";", "0");

         $sqlquery = "SELECT usr.usr_id FROM user AS usr"
                   . " WHERE usr.usr_account = '" . $f_usr_account . "' ";
                   
         $result = $db->query($sqlquery);
         if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
         $insertFlag = TRUE;
         while ($row = $result->fetch_assoc()):
               $insertFlag = FALSE;
         endwhile;
         $result->free();

         if ($insertFlag) :
            if (checkPasswordValidation($f_usr_password,$f_usr_password2)) : 
            
               TA("B");
            
               $sqlStmtPwd = "INSERT INTO user (hq_id,usr_type,usr_name,usr_firstname,usr_email,usr_phone,usr_phone2,usr_fax,usr_account,usr_password,usr_birthdate)" .
                                 " VALUES ($hq_id,'$userListOfType','$f_usr_name','$f_usr_firstname','$f_usr_email','$f_usr_phone','$f_usr_phone2','$f_usr_fax','$f_usr_account',PASSWORD('$f_usr_password'),'$f_usr_birthdate')";

               $res = $db->query($sqlStmtPwd);
               if (DB::isError($res)) : die ("$PHP_SELF: " . $res->getMessage()); endif;
               
               $usr_id_new = getLastInsertId();

               $sqlStmtEmp = "INSERT INTO employee (usr_id,csc_id,emp_rights)" .
                                    " VALUES ($usr_id_new,'$cscIdActual','00000000000000000000000000000000000000000000000000')";

               $res = $db->query($sqlStmtEmp);                  
               if (DB::isError($res)) : die ("$PHP_SELF: " . $res->getMessage()); endif; 
               $emp_id_new = getLastInsertId();


               // Automatischer E-Mail-Versand eines systemgenerierten Passwortes ???

               // *** Special treatment ***
               if ($userListOfType == "4") :
                  if ($f_selectRootStock != "") :
                     // Insert the stock associated to the warehouseman
                     insertStmt("stockuser", array("stk_id", $f_selectRootStock, "usr_id", $usr_id_new));
                  endif;

                  // Set state of accessibility to substocks to readonly by default
                  insertStmt("parameter", array("par_key", "MASK_STK_READONLY_WHERE_DEFINED_WRITEACCESS", "emp_id", $emp_id_new, "par_value", "1", "hq_id", $hq_id));

                  $f_act = "setAccessRootStocks";
               endif;

               // Write logdata into log database
               writeToLogDB("73",$hq_id,"",$usr_id,"","","","STATUS_NEW=" . $logString,"","","");
               
               TA("C");
               TA("E");
	       
               $clearUserFields = true;
            endif;
         else :
            $statusMessage = getLngt("Der Benutzername existiert schon! Bitte wählen Sie einen anderen!");
         endif;
      endif;

      // Modify user
      if ($f_act == "modifyUser" && $usr_id_curr != "") :

         // Check the user-account except the current to be modified in $usr_id_curr
         $sqlquery = "SELECT usr.usr_id FROM user AS usr"
                   . " WHERE usr.usr_account = '" . $f_usr_account . "' AND"
                   . "       usr.usr_id != '" . $usr_id_curr . "'";

         $result = $db->query($sqlquery);
         if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
         $updateFlag = TRUE;
         while ($row = $result->fetch_assoc()):
               $updateFlag = FALSE;
         endwhile;
         $result->free();            

         if ($updateFlag) :

            $tmpUsrName = getFieldValueFromId("user", "usr_id", $usr_id_curr, "usr_name");
            $tmpUsrFirstName = getFieldValueFromId("user", "usr_id", $usr_id_curr, "usr_firstname");
            $tmpUsrAccount = getFieldValueFromId("user", "usr_id", $usr_id_curr, "usr_firstname");
            $tmpUsrPassword = getFieldValueFromId("user", "usr_id", $usr_id_curr, "usr_password");
            $tmpUsrBirthdate = getFieldValueFromId("user", "usr_id", $usr_id_curr, "usr_birthdate");
            $tmpUsrPhone = getFieldValueFromId("user", "usr_id", $usr_id_curr, "usr_phone");
            $tmpUsrPhone2 = getFieldValueFromId("user", "usr_id", $usr_id_curr, "usr_phone2");
            $tmpUsrFax = getFieldValueFromId("user", "usr_id", $usr_id_curr, "usr_fax");
            $logString = makeLogString(array($tmpUsrName,$tmpUsrFirstName,$tmpUsrAccount,$tmpUsrPassword,$tmpUsrBirthdate,$tmpUsrPhone,$tmpUsrPhone2,$tmpUsrFax), ";", "0");

            $defaultFields = array("usr_name",$f_usr_name,"usr_firstname",$f_usr_firstname,"usr_email",$f_usr_email,"usr_phone",$f_usr_phone,"usr_phone2",$f_usr_phone2,"usr_fax",$f_usr_fax,"usr_account",$f_usr_account,"usr_birthdate",$f_usr_birthdate);
            updateStmt("user","usr_id",$usr_id_curr,$defaultFields);

            // *** Special treatment ***
            if ($userListOfType == "4" && $f_selectRootStock != "") :
               if (existsEntry("stockuser",array("usr_id",$usr_id_curr))) :
                  // Update the stock associated to the warehouseman
                  updateStmt("stockuser","usr_id",$usr_id_curr,array("stk_id",$f_selectRootStock));
               else :
                  // Insert the stock associated to the warehouseman
                  insertStmt("stockuser", array("stk_id", $f_selectRootStock, "usr_id", $usr_id_curr));
               endif;

               $f_act = "setAccessRootStocks";
            endif;

            // Write logdata into log database
            writeToLogDB("74",$hq_id,"",$usr_id,"","","","STATUS_MODIFIED=" . $logString,"","","");

            // $clearUserFields = true;
         else :
            $statusMessage = getLngt("Der Benutzername existiert schon! Bitte wählen Sie einen anderen!");
         endif;                                                        
      endif;

      // Remove user
      if ($f_act == "removeUser" && $usr_id_curr != "") :
   
         TA("B");
   
         $tmpUsrName = getFieldValueFromId("user", "usr_id", $usr_id_curr, "usr_name");
         $tmpUsrFirstName = getFieldValueFromId("user", "usr_id", $usr_id_curr, "usr_firstname");
         $tmpUsrAccount = getFieldValueFromId("user", "usr_id", $usr_id_curr, "usr_firstname");
         $tmpUsrPassword = getFieldValueFromId("user", "usr_id", $usr_id_curr, "usr_password");
         $tmpUsrType = getFieldValueFromId("user", "usr_id", $usr_id_curr, "usr_type");
         $logString = makeLogString(array($tmpUsrName,$tmpUsrFirstName,$tmpUsrAccount,$tmpEmpRigths,$tmpUsrPassword), ";", "0");

         // *** Special treatment ***
         if ($userListOfType == "4") :
            deleteStmt("stockuser","usr_id = ".$usr_id_curr);
         endif;

         deleteStmt("user","usr_id = ".$usr_id_curr);
         deleteStmt("employee","usr_id = ".$usr_id_curr);

         // Write logdata into log database
         writeToLogDB("75",$hq_id,"",$usr_id,"","","","STATUS_DELETED=" . $logString . "|TYPE=" . $tmpUsrType,"","",$usr_id_curr);

         TA("C");
         TA("E");

         $clearUserFields = true;
      endif;

      // Stock employee (warehousemen)
      if ($userListOfType == "4") :

         // Change access to root stocks
         $allRootStocksArray = getColVectorFromDB2ArrayByClause("stock", "stk_id", "stk_pre_id = '0' AND stk_path = ''", "", "");
         if ($f_act == "setAccessRootStocks" && $usr_id_curr != "" && $emp_id_act != "") :
            
            // Get the emp_id of the root admin because he/she is allowed to change a password of an employee
            $empIdRootAdmin = getEmpIdOfRootAdmin($userTypeName);
         
            if ($emp_id_act != $empIdRootAdmin) :
            
               if ($emp_id_act != $emp_id) :
         
                  if (!is_array($par_stock_access) || $par_stock_access == "") : $par_stock_access = array(); endif;
                  $stkRootAccessIDsEmpIdArray = array();
                  $stkRootAccessIDsActEmpIdArray = array();
                  
                  // Currrent user logged in
                  if ($emp_id == $empIdRootAdmin) :
                     $stkRootAccessIDsEmpIdArray = $allRootStocksArray;
                     $stkRootAccessIDsEmpId = implode(",", $stkRootAccessIDsEmpIdArray);
                  else :
                     $stkRootAccessIDsEmpId = getParameterValue($emp_id, "MASK_STK_ROOT_ACCESS");
                     if ($stkRootAccessIDsEmpId != "") :
                        $stkRootAccessIDsEmpIdArray = explode(",",$stkRootAccessIDsEmpId);
                     endif;
                  endif;
         
                  // Current user to be viewed or edited
                  $stkRootAccessIDsActEmpId = getParameterValue($emp_id_act, "MASK_STK_ROOT_ACCESS");
                  if ($stkRootAccessIDsActEmpId != "") :
                     $stkRootAccessIDsActEmpIdArray = explode(",",$stkRootAccessIDsActEmpId);
                  endif;
         
                  if (count($par_stock_access) > 0) :
                     $tmpEmpIdRestArray = array_diff($stkRootAccessIDsEmpIdArray, $par_stock_access);
                     $tmpEmpIdActUnionArray = array_unique(array_merge($stkRootAccessIDsActEmpIdArray, $par_stock_access));
                  else :
                     $tmpEmpIdRestArray = $stkRootAccessIDsEmpIdArray;
                     $tmpEmpIdActUnionArray = $stkRootAccessIDsActEmpIdArray;
                  endif;
         
                  $storeArray = array_diff($tmpEmpIdActUnionArray, $tmpEmpIdRestArray);
                  $storeString = implode(",", $storeArray);
         
                  if (existsEntry("parameter",array("par_key","MASK_STK_ROOT_ACCESS","emp_id",$emp_id_act,"hq_id",$hq_id))) :
                     updateStmt("parameter", "emp_id", $emp_id_act, array("par_value", $storeString), " par_key = 'MASK_STK_ROOT_ACCESS' AND hq_id = '" . $hq_id . "'");
                  else:
                     insertStmt("parameter", array("par_key", "MASK_STK_ROOT_ACCESS", "emp_id", $emp_id_act, "par_value", $storeString, "hq_id", $hq_id));
                  endif;
                  
                  // Switch access state between readonly and writeable substocks if possible (only the changing employee is NOT readonly by himself!)
                  $tmpStkReadonlyEmpId = getParameterValue($emp_id, "MASK_STK_READONLY_WHERE_DEFINED_WRITEACCESS");
                  if ($tmpStkReadonlyEmpId == "") : $tmpStkReadonlyEmpId = "0"; endif;
                  if ($emp_id == $empIdRootAdmin || $tmpStkReadonlyEmpId == "0") :
                     if (existsEntry("parameter",array("par_key","MASK_STK_READONLY_WHERE_DEFINED_WRITEACCESS","emp_id",$emp_id_act,"hq_id",$hq_id))) :
                        updateStmt("parameter", "emp_id", $emp_id_act, array("par_value", $f_substocks_readonly), " par_key = 'MASK_STK_READONLY_WHERE_DEFINED_WRITEACCESS' AND hq_id = '" . $hq_id . "'");
                     else:
                        insertStmt("parameter", array("par_key", "MASK_STK_READONLY_WHERE_DEFINED_WRITEACCESS", "emp_id", $emp_id_act, "par_value", $f_substocks_readonly, "hq_id", $hq_id));
                     endif;
                  endif;

                  // Switch access state for article master data
                  $tmpStkArticleAccessEmpId = getParameterValue($emp_id, "MASK_STK_ARTICLE_ACCESS");
                  if ($tmpStkArticleAccessEmpId == "") : $tmpStkArticleAccessEmpId = "0"; endif;
                  if ($emp_id == $empIdRootAdmin || $tmpStkArticleAccessEmpId == "0") :
                     if (existsEntry("parameter",array("par_key","MASK_STK_ARTICLE_ACCESS","emp_id",$emp_id_act,"hq_id",$hq_id))) :
                        updateStmt("parameter", "emp_id", $emp_id_act, array("par_value", $f_stk_article_access), " par_key = 'MASK_STK_ARTICLE_ACCESS' AND hq_id = '" . $hq_id . "'");
                     else:
                        insertStmt("parameter", array("par_key", "MASK_STK_ARTICLE_ACCESS", "emp_id", $emp_id_act, "par_value", $f_stk_article_access, "hq_id", $hq_id, "md_id", $md_id));
                     endif;
                  endif;
               else :
                  $statusMessage = getLngt("Ihre eigenen Lagerzugänge können Sie nicht verändern!");
               endif;
            else :
               $statusMessage = getLngt("Sie sind leider nicht autorisiert!");
            endif;
         endif;
// -------------------------------------------------------------------------------------         
         // Right management of substocks
         if ($f_act == "setAccessSubtocks" && $usr_id_curr != "" && $emp_id_act != "") :

            // Get the emp_id of the root admin because he/she is allowed to change a password of an employee
            $empIdRootAdmin = getEmpIdOfRootAdmin($userTypeName);

            if ($emp_id_act != $empIdRootAdmin) :

               if ($emp_id_act != $emp_id) :

   	             // Get parameter of the viewed or edited emloyee to check the right for substock level
                  $parMaskStkSubstockActEmpIdAccess = getParameterValue($emp_id_act, "MASK_STK_SUBSTOCK_ACCESS");
// echo "PARAMETER EMP_ACT: " . $parMaskStkSubstockActEmpIdAccess . "<br>";
                  $parMaskStkSubstockActEmpIdAccess = str_replace("|", "--", $parMaskStkSubstockActEmpIdAccess);
                  $tmpPairsActEmpIdArray = explode("--", $parMaskStkSubstockActEmpIdAccess);
                  $tmpPairsActEmpIdArrayLen = count($tmpPairsActEmpIdArray);
// echo "rootStkIdForSubstkPar: " . $rootStkIdForSubstkPar . " &nbsp; " . getFieldValueFromId("stock","stk_id", $rootStkIdForSubstkPar,"stk_name") . "<br>";
   	             // Get all HTTP-POST parameters for the substocks
                  if ($rootStkIdForSubstkPar > 0 && is_numeric($rootStkIdForSubstkPar)) :
   
                     $allRootStocksArray = getColVectorFromDB2ArrayByClause("stock", "stk_id", "stk_pre_id = '0' AND stk_path = ''", "", "");
   
                     list ($currStock) = getSecHttpVars("1",array("par_stock_access_subtree_" . $rootStkIdForSubstkPar));
// echo "currStock: " . $currStock . " &nbsp; " . getFieldValueFromId("stock","stk_id", $currStock,"stk_name") . "<br>";
                     // Check parameter being a root stock or a substock or it is empty
                     if ($currStock == "") :
// echo "DRIN 1 <br><br>";
                        // Current stock is empty, no parameter change
                        // ...
                     elseif (in_array($currStock, $allRootStocksArray)) :
// echo "DRIN 2 <br><br>";
                        // Current stock is a root stock
                        // Check restriction of the viewed or edited employee according to the current root stock
                        for ($j = 0; $j < $tmpPairsActEmpIdArrayLen; $j++) :
                            $tmpSubStockTupel = explode(",", $tmpPairsActEmpIdArray[$j]);
                            if ($tmpSubStockTupel[0] == $rootStkIdForSubstkPar) :                                
                               unset($tmpPairsActEmpIdArray[$j]);
                            endif;
                        endfor;
                     else :
// echo "DRIN 3 <br><br>";
                        // Check restriction of the viewed or edited employee according to the current root stock
                        $tmpFound = false;
                        for ($j = 0; $j < $tmpPairsActEmpIdArrayLen; $j++) :
                            $tmpSubStockTupel = explode(",", $tmpPairsActEmpIdArray[$j]);  // E.g. "3,7,4,12,26" <=> (3 = root stock, the others substocks)
                            if ($tmpSubStockTupel[0] == $rootStkIdForSubstkPar) :
// echo $tmpSubStockTupel[0] . "&nbsp;=>&nbsp;";
                               // Update ...
                               $newSubstockIds = $tmpSubStockTupel;
                               $tmpSubStockTupelLen = count($tmpSubStockTupel);
                               $opDone = false;
                               for ($k = 1; $k < $tmpSubStockTupelLen; $k++) :
                                   if ($currStock == $tmpSubStockTupel[$k]) :
                                      if ($rootStkOpForSubstkPar == "add") :
                                         // It does exist, do nothing ...
                                         $opDone = true;
                                      endif;
                                      if ($rootStkOpForSubstkPar == "sub") :
                                         unset($newSubstockIds[$k]);
                                         $opDone = true;
                                      endif;
                                   endif;
                                   if (isStkChild($currStock, $tmpSubStockTupel[$k])) :
                                      if ($rootStkOpForSubstkPar == "add") :
                                         $newSubstockIds[$k] = $currStock;
                                         $opDone = true;
                                      endif;
                                   endif;
                               endfor;
                               if (!$opDone) :
                                  // Add new resriction
                                  if ($rootStkOpForSubstkPar == "add") :
                                     $newSubstockIds[] = $currStock;
                                  endif;
                               endif;
   
                               // Check for removement of all substock rights but the root stock
                               $newSubstockIdsStr = "";
                               if (count($newSubstockIds) > 1) :
                                  $newSubstockIdsStr = implode(",", $newSubstockIds);
                               endif;
                               $tmpPairsActEmpIdArray[$j] = $newSubstockIdsStr;
// echo "tmpPairsActEmpIdArray: " . $tmpPairsActEmpIdArray[$j] . "<br>";
                               $tmpFound = true;
                            endif;
                        endfor;
                        if (!$tmpFound) :
                           // Insert ...
                           $tmpPairsActEmpIdArray[] = $rootStkIdForSubstkPar . "," . $currStock;
                        endif;
                     endif;
                     
                     // Implode updated parameter value to store
                     $tmpPairsActEmpId = implode("|", $tmpPairsActEmpIdArray);
                     if (substr($tmpPairsActEmpId, 0, 1) == "|") : $tmpPairsActEmpId = substr($tmpPairsActEmpId, 1); endif;
                     if (substr($tmpPairsActEmpId, -1) == "|") : $tmpPairsActEmpId = substr($tmpPairsActEmpId, 0, -1); endif;
// echo "tmpPairsActEmpId: " . $tmpPairsActEmpId . "<br>";
                     if (existsEntry("parameter",array("par_key","MASK_STK_SUBSTOCK_ACCESS","emp_id",$emp_id_act,"hq_id",$hq_id))) :
                        updateStmt("parameter", "emp_id", $emp_id_act, array("par_value", $tmpPairsActEmpId), " par_key = 'MASK_STK_SUBSTOCK_ACCESS' AND hq_id = '" . $hq_id . "'");
                     else:
                        insertStmt("parameter", array("par_key", "MASK_STK_SUBSTOCK_ACCESS", "emp_id", $emp_id_act, "par_value", $tmpPairsActEmpId, "hq_id", $hq_id));
                     endif;
                  endif;               
   
               else :
                  $statusMessage = getLngt("Ihre eigenen Lagerzugänge können Sie nicht verändern!");
               endif;
            else :
               $statusMessage = getLngt("Sie sind leider nicht autorisiert!");
            endif;
         endif;
// -------------------------------------------------------------------------------------
      endif;

      // ***********************************************************************
      // * Selection of all users of the requested user type ($userListOfType) *
      // ***********************************************************************

      if ($tableSort == "") : $tableSort = "usr_name"; endif;

      // Stock employee (warehousemen)
      if ($userListOfType == "4") :
         $sqlquery = "SELECT usr.usr_id, usr.usr_name, usr.usr_firstname, usr.usr_email, usr.usr_phone,"
                      . "    usr.usr_phone2, usr.usr_fax, usr.usr_account, hq.hq_mnemonic, emp.emp_id AS emp_id_act, par.par_value, par2.par_value AS par2_value, par3.par_value AS par3_value, par4.par_value AS par4_value"
                      . " FROM user AS usr, headquarters AS hq, employee AS emp LEFT JOIN parameter AS par ON par.par_key = 'MASK_STK_ROOT_ACCESS' AND par.hq_id = '" . $hq_id . "' AND par.emp_id = emp.emp_id"
                      . "                                                       LEFT JOIN parameter AS par2 ON par2.par_key = 'MASK_STK_SUBSTOCK_ACCESS' AND par2.hq_id = '" . $hq_id . "' AND par2.emp_id = emp.emp_id"
                      . "                                                       LEFT JOIN parameter AS par3 ON par3.par_key = 'MASK_STK_READONLY_WHERE_DEFINED_WRITEACCESS' AND par3.hq_id = '" . $hq_id . "' AND par3.emp_id = emp.emp_id"
                      . "                                                       LEFT JOIN parameter AS par4 ON par4.par_key = 'MASK_STK_ARTICLE_ACCESS' AND par4.hq_id = '" . $hq_id . "' AND par4.emp_id = emp.emp_id"
                      . " WHERE emp.usr_id = usr.usr_id AND usr.hq_id = hq.hq_id AND hq.hq_id IN " . getSQLMandatorArray($f_hq_id) . " AND usr.usr_type = '" . $userListOfType . "'"
                      . " ORDER BY $tableSort";
      else :
         $sqlquery = "SELECT usr.usr_id, usr.usr_name, usr.usr_firstname, usr.usr_email, usr.usr_phone,"
                      . "    usr.usr_phone2, usr.usr_fax, usr.usr_account, hq.hq_mnemonic, emp.emp_id AS emp_id_act"
                      . " FROM user AS usr, headquarters AS hq, employee AS emp"
                      . " WHERE emp.usr_id = usr.usr_id AND usr.hq_id = hq.hq_id AND hq.hq_id IN " . getSQLMandatorArray($f_hq_id) . " AND usr.usr_type = '" . $userListOfType . "'"
                      . " ORDER BY $tableSort";
      endif;
// echo "<br><br>" . $sqlquery . "<br><br>";
      $result = $db->query($sqlquery);
      if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());

      // Maintable with header
      $numOfUser = 0;   
      $tableOfUsers = "<table border=\"0\" cellpadding=\"5\">\n";
      $tableOfUsers .= "<tr class=\"f8bp1\">";
      // if (authCheckEmployeeRights($emp_id, "10")) :
         $tableOfUsers .= "<td>&nbsp;<a href=\"javascript:document.forms[0].tableSort.value='usr_name';document.forms[0].submit();\">" . getLngt("Name") . "</a></td>";
         $tableOfUsers .= "<td>&nbsp;<a href=\"javascript:document.forms[0].tableSort.value='usr_firstname';document.forms[0].submit();\">" . getLngt("Vorname") . "</a></td>";
         if ($userTypeName == "hq" && authCheckEmployeeRights($emp_id, "10")) :
            $tableOfUsers .= "<td>&nbsp;<a href=\"javascript:document.forms[0].tableSort.value='hq_mnemonic';document.forms[0].submit();\">" . getLngt("Niederlassung") . "</a></td>";
         endif;
         $tableOfUsers .= "<td>&nbsp;<a href=\"javascript:document.forms[0].tableSort.value='usr_email';document.forms[0].submit();\">" . getLngt("E-Mail") . "</a></td>";
         $tableOfUsers .= "<td>&nbsp;<a href=\"javascript:document.forms[0].tableSort.value='usr_phone';document.forms[0].submit();\">" . getLngt("Telefon") . "</a></td>";
         $tableOfUsers .= "<td>&nbsp;<a href=\"javascript:document.forms[0].tableSort.value='usr_phone2';document.forms[0].submit();\">" . getLngt("Mobil") . "</a></td>";
         $tableOfUsers .= "<td>&nbsp;<a href=\"javascript:document.forms[0].tableSort.value='usr_account';document.forms[0].submit();\">" . getLngt("Anmeldename") . "</a></td>";      
         $tableOfUsers .= "<td>&nbsp;" . getLngt("Löschen") . "</td>";
         $tableOfUsers .= "<td>&nbsp;" . getLngt("Bearbeiten") . "</td>";
      // endif;
      $tableOfUsers .= "</tr>\n";

      $rowCounter = 0;
      $lineToggler = 0;   
      while ($row = $result->fetch_assoc()):
            $numOfUser++;

            $cellColor = getListColor($numOfUser, $lineToggler);

            $tableOfUsers .= "<tr>";
            $tableOfUsers .= "<td bgcolor=\"" . $cellColor ."\">&nbsp;" . $row["usr_name"] . "</td>";
            $tableOfUsers .= "<td bgcolor=\"" . $cellColor ."\">&nbsp;" . $row["usr_firstname"] . "</td>";
            if ($userTypeName == "hq" && authCheckEmployeeRights($emp_id, "10")) :
               $tableOfUsers .= "<td bgcolor=\"" . $cellColor ."\">&nbsp;" . $row["hq_mnemonic"] . "</td>";
            endif;
            $tableOfUsers .= "<td bgcolor=\"" . $cellColor ."\">&nbsp;" . $row["usr_email"] . "</td>";
            $tableOfUsers .= "<td bgcolor=\"" . $cellColor ."\">&nbsp;" . $row["usr_phone"] . "</td>";
            $tableOfUsers .= "<td bgcolor=\"" . $cellColor ."\">&nbsp;" . $row["usr_phone2"] . "</td>";
   
            $tableOfUsers .= "<td bgcolor=\"" . $cellColor ."\">&nbsp;" . $row["usr_account"] . "</td>";
   
            $tableOfUsers .= "<td align=\"center\" bgcolor=\"" . $cellColor ."\"><a href=\"javascript:removeUser('removeUser','".ec($row["usr_id"])."','".$row["usr_account"]."');\">"
                                          . "<img src=\"../images/trash.jpg\" border=\"0\" height=\"13\" width=\"8\">" 
                                          . "</a>" . "</td>";
            if ($userListOfType == "4") :

               $currStkId = getFieldValueFromId("stockuser","usr_id",$row["usr_id"],"stk_id");
               $tableOfUsers .= "<td bgcolor=\"" . $cellColor ."\">&nbsp;" . "<a href=\"javascript:editStockUser('" . ec($row["usr_id"]) . "','" . $row["emp_id_act"] . "','" . $row["usr_account"] . "','" . $row["usr_name"] . "','" . $row["usr_firstname"] . "','" . $row["usr_birthdate"] . "','" . $row["usr_email"] . "','" . $row["usr_phone"] . "','" . $row["usr_phone2"] . "','" . $row["usr_fax"] . "','" . $currStkId . "', '" . $row["par_value"] . "', '" . $row["par2_value"] . "', '" . $row["par3_value"] . "', '" . $row["par4_value"] . "')\" >" . "<img src=\"../images/arrow_right.png\" border=\"0\" height=\"10\" width=\"25\">" . "</a>" . "</td>";
            else :
               $tableOfUsers .= "<td bgcolor=\"" . $cellColor ."\">&nbsp;" . "<a href=\"javascript:editUser('" . ec($row["usr_id"]) . "','" . $row["emp_id_act"] . "','" . $row["usr_account"] . "','" . $row["usr_name"] . "','" . $row["usr_firstname"] . "','" . $row["usr_birthdate"] . "','" . $row["usr_email"] . "','" . $row["usr_phone"] . "','" . $row["usr_phone2"] . "','" . $row["usr_fax"] . "')\" >" . "<img src=\"../images/arrow_right.png\" border=\"0\" height=\"10\" width=\"25\">" . "</a>" . "</td>";
            endif;
            $tableOfUsers .= "</tr>\n";

            $usrName = $row["usr_name"];
            $usrFirstname = $row["usr_firstname"];
      endwhile;
      $tableOfUsers .= "</table>\n";
      $result->free();   
      

      
      // ********************************************************************
      // * Special fields and operations according to the current user type *
      // ********************************************************************
      
      $specialOutput = "";
      // $allRootStocksArray = getColVectorFromDB2ArrayByClause("stock", "stk_id", "stk_pre_id = '0' AND stk_path = ''", "", "");

      // Stock employee (warehousemen)
      if ($userListOfType == "4") :
         
         $specialOutput .= "<div>";
         $specialOutput .= "  <div style=\"width:200px; float:left;\">" . getLngt("Hauptlager") . ":</div>";
         $specialOutput .= "  <div>";
         $specialOutput .= "    <select name=\"f_selectRootStock\">";
         $specialOutput .= "      <option value=\"\">---</option>";
         $specialOutput .=        addOptionsFromTable("stock","stk_id","stk_name","stk_name","stk_pre_id = '0' AND stk_path = ''",($usr_id_curr != "" ? $f_selectRootStock : ""));
         $specialOutput .= "    </select>";
         $specialOutput .= "  </div>";
         $specialOutput .= "</div>";

         // Manage access to root stocks
         $changeParametersAccessStk = "";
         if ($userTypeName == "hq") :
         
            // if ($emp_id_act != $empIdRootAdmin) :
         
               // Init
               if (count($allRootStocksArray) > 0) :
                  $stkRootAccessIDsEmpIdArray = array();
                  $stkRootAccessIDsEmpId = "";
                  $stkRootAccessIDsActEmpIdArray = array();
                  $stkRootAccessIDsActEmpId = "";
                  
                  // Check for being admin to get access to all root stocks
                  if (existsEntry("headquarters",array("hq_admin",$emp_id))) :
                     // Get all root stock IDs
                     $stkRootAccessIDsEmpIdArray = $allRootStocksArray;
                     if (count($stkRootAccessIDsEmpIdArray) > 0) :
                        $stkRootAccessIDsEmpId = implode(",",$stkRootAccessIDsEmpIdArray);
                     endif;
                  else :
                     // Currrent user logged in
                     $stkRootAccessIDsEmpId = getParameterValue($emp_id, "MASK_STK_ROOT_ACCESS");
                     if ($stkRootAccessIDsEmpId != "") :
                        $stkRootAccessIDsEmpIdArray = explode(",",$stkRootAccessIDsEmpId);
                     endif;
                  endif;
         
                  // Current user to be viewed or edited
                  $stkRootAccessIDsActEmpId = getParameterValue($emp_id_act, "MASK_STK_ROOT_ACCESS");
                  if ($stkRootAccessIDsActEmpId != "") :
                     $stkRootAccessIDsActEmpIdArray = explode(",",$stkRootAccessIDsActEmpId);
                  endif;
         
                  $stkRootAccessIDsArray = array_diff($allRootStocksArray, $stkRootAccessIDsEmpIdArray);
                  $stkRootAccessIDs = implode(",", $stkRootAccessIDsArray);
         
                  // Output         
                  if ($emp_id == $emp_id_act) :
                     $stkRootAccessIDsArray = $allRootStocksArray;
                  endif;

                  $changeParametersAccessStk .= "<div style=\"width:200px; height:100%; float:left;\">";
                  $changeParametersAccessStk .= "<div>" . getLngt("Zugang Hauptläger:") . "</div>\n";
                  // $changeParametersAccessStk .= "<div>" . addCheckboxesFromTable("par_stock_access", "stock", "stk_id", "stk_name", "stk_name", "stk_pre_id = '0' AND stk_path = ''", $stkRootAccessIDsActEmpIdArray, "<br>", $stkRootAccessIDsArray) . "</div>\n";
                  // $changeParametersAccessStk .= "<div><br></div>\n";
                  // $changeParametersAccessStk .= defineButtonType10(getLngt("Lagerzugänge&nbsp;setzen"), "action_rights", "finishPage('" . ec("setAccessRootStocks") . "');", "150", "");


                  // RIGHT MANAGEMENT OF SUBSTOCKS (BEGIN)
                  $changeParametersAccessStk .= "<div>" . addCheckboxesFromTable("par_stock_access", "stock", "stk_id", "stk_name", "stk_name", "stk_pre_id = '0' AND stk_path = ''", $stkRootAccessIDsActEmpIdArray, "<br>", $stkRootAccessIDsArray) . "</div>\n";
                  if ($f_substocks_readonly == "") : $f_substocks_readonly = "1"; endif;
                  $changeParametersAccessStk .= "<br>" . getLngt("Nur Leseberechtigung<br>auf definierte Unterläger:") . "<br><select name=\"f_substocks_readonly\">" . addOptionsGenericText(array(getLngt("Nein"),getLngt("Ja")),$f_substocks_readonly,"") . "</select>\n";
                  if ($f_stk_article_access == "") : $f_stk_article_access = "0"; endif;
                  $changeParametersAccessStk .= "<br><br>" . getLngt("Berechtigung zur Artikelverwaltung:") . "<br><select name=\"f_stk_article_access\">" . addOptionsGenericText(array(getLngt("Nein"),getLngt("Ja")),$f_stk_article_access,"") . "</select>\n";
                  $changeParametersAccessStk .= "</div>\n";

                  $changeParametersAccessStk .= "<div>\n";
                  $changeParametersAccessStk .= "<div>" . getLngt("Einschränkung auf Unterläger:") . "</div>\n";
                  
	                // Get parameter of the currrent executing emloyee logged in to check the right for substock level
                  $parMaskStkSubstockEmpIdAccess = getParameterValue($emp_id, "MASK_STK_SUBSTOCK_ACCESS");   // => E.G.:  "10,11|13,17|21,23" <=> Pairs of "...|root stock, substock|..."
                  $parMaskStkSubstockEmpIdAccess = str_replace("|", "--", $parMaskStkSubstockEmpIdAccess);
                  $tmpPairsEmpIdArray = explode("--", $parMaskStkSubstockEmpIdAccess);
                  $tmpPairsEmpIdArrayLen = count($tmpPairsEmpIdArray);
         
	                // Get parameter of the viewed or edited emloyee to check the right for substock level
                  $parMaskStkSubstockActEmpIdAccess = getParameterValue($emp_id_act, "MASK_STK_SUBSTOCK_ACCESS");   // => E.G.:  "10,11|13,17|21,23" <=> Pairs of "...|root stock, substock|..."
                  $parMaskStkSubstockActEmpIdAccess = str_replace("|", "--", $parMaskStkSubstockActEmpIdAccess);
                  $tmpPairsActEmpIdArray = explode("--", $parMaskStkSubstockActEmpIdAccess);
                  $tmpPairsActEmpIdArrayLen = count($tmpPairsActEmpIdArray);

                  $stkRootAccessIDsEmpIdArrayLen = count($stkRootAccessIDsEmpIdArray);
                  for ($i = 0; $i < $stkRootAccessIDsEmpIdArrayLen; $i++) :
	                    // Init with root stock id 
		                  $stkIdToGetTheSubtreeFor = array($stkRootAccessIDsEmpIdArray[$i]);
		                  $stkIdToGetTheSubtreeFor2 = array($stkRootAccessIDsEmpIdArray[$i]);
         
                      // Check restriction of the executing employee according to the current root stock
                      for ($j = 0; $j < $tmpPairsEmpIdArrayLen; $j++) :
                          $tmpSubStockTupel = explode(",", $tmpPairsEmpIdArray[$j]);
                          if ($tmpSubStockTupel[0] == $stkRootAccessIDsEmpIdArray[$i]) :
                             $stkIdToGetTheSubtreeFor = array();
                             $tmpSubStockTupelLen = count($tmpSubStockTupel);
                             for ($k = 1; $k < $tmpSubStockTupelLen; $k++) :
                                 $stkIdToGetTheSubtreeFor[] = $tmpSubStockTupel[$k];
                             endfor;
                          endif;
                      endfor;
         
                      // Check restriction of the viewed or edited employee according to the current root stock
                      for ($j = 0; $j < $tmpPairsActEmpIdArrayLen; $j++) :
                          $tmpSubStockTupel = explode(",", $tmpPairsActEmpIdArray[$j]);
                          if ($tmpSubStockTupel[0] == $stkRootAccessIDsEmpIdArray[$i]) :
                             $stkIdToGetTheSubtreeFor2 = array();
                             $tmpSubStockTupelLen = count($tmpSubStockTupel);
                             for ($k = 1; $k < $tmpSubStockTupelLen; $k++) :
                                 $stkIdToGetTheSubtreeFor2[] = $tmpSubStockTupel[$k];
                             endfor;
                          endif;
                      endfor;

                      // Check for relation between both sub stock access values of executing and viewed employee
                      // VERY IMPORTANT:
                      // 1. The <select>-field appears if the right of the viewed employee is less than the right of the executing employee AND
                      //    the right of the stock id of the executing employee does exist in the path of the stock id of the edited employee
                      // 2. The <select>-field appears if the rights of both (executing and viewed employee) are equal
                      // 3. The <select>-field appears if the viewed employee has NO access to the stock but the executing employee
                      
                      $stkIdToGetTheSubtreeForLen = count($stkIdToGetTheSubtreeFor);
                      $stkIdToGetTheSubtreeFor2Len = count($stkIdToGetTheSubtreeFor2);

                      // Check these points:
                      $tmpCheckA = false;
                      $tmpCheckB = false;

                      for ($j = 0; $j < $stkIdToGetTheSubtreeForLen; $j++) :
                          for ($k = 0; $k < $stkIdToGetTheSubtreeFor2Len; $k++) :
                              if (isStkChild($stkIdToGetTheSubtreeFor[$j], $stkIdToGetTheSubtreeFor2[$k], "1")) :
                                 $tmpCheckA = true;
                              endif;
                              if (isStkChild($stkIdToGetTheSubtreeFor2[$j], $stkIdToGetTheSubtreeFor[$k], "1")) :
                                 $tmpCheckB = true;
                              endif;
                          endfor;
                      endfor;                

                      if ($tmpCheckA || ($tmpCheckB && in_array($stkRootAccessIDsEmpIdArray[$i], array_diff($stkRootAccessIDsEmpIdArray, $stkRootAccessIDsActEmpIdArray)))  ) :
         
                         $stkIdTreeArray = array();
                         for ($j = 0; $j < $stkIdToGetTheSubtreeForLen; $j++) :
                             getTreeStockData($stkIdToGetTheSubtreeFor[$j]);
                             
                             // Add current stock
                             $stkIdTreeArray[$stkIdToGetTheSubtreeFor[$j]] = getFieldValueFromId("stock","stk_id", $stkIdToGetTheSubtreeFor[$j],"stk_name");
                         endfor;
         
                         $changeParametersAccessStk .= "<div>\n";
                         $changeParametersAccessStk .= getFieldValueFromId("stock","stk_id", $stkRootAccessIDsEmpIdArray[$i],"stk_name")  . ":";
                         $changeParametersAccessStk .= "</div>\n";
                         
                         for ($j = 0; $j < $stkIdToGetTheSubtreeFor2Len; $j++) :
                             if (!in_array($stkIdToGetTheSubtreeFor2[$j], $allRootStocksArray)) :
                                $changeParametersAccessStk .= "<div>\n";
                                $changeParametersAccessStk .= "-&nbsp;" . getFieldValueFromId("stock","stk_id", $stkIdToGetTheSubtreeFor2[$j],"stk_name");
                                $changeParametersAccessStk .= "</div>\n";
                             endif;
                         endfor;
                         
                         $changeParametersAccessStk .= defineButtonType08("+", "action_substk_add", "changeSubStock('" . $stkRootAccessIDsEmpIdArray[$i] . "','add');", "10", "left", "2");
                         $changeParametersAccessStk .= defineButtonType08("-", "action_substk_sub", "changeSubStock('" . $stkRootAccessIDsEmpIdArray[$i] . "','sub');", "10", "left", "2");
                         
                         $changeParametersAccessStk .= "<div>\n";
                         $changeParametersAccessStk .= "<select name=\"par_stock_access_subtree_" . $stkRootAccessIDsEmpIdArray[$i] . "\">\n";
                         $changeParametersAccessStk .= addOptionsFromAssociativeArray($stkIdTreeArray, $stkIdToGetTheSubtreeFor2, "1", "", "");
                         $changeParametersAccessStk .= "</select>";
                         $changeParametersAccessStk .= "</div>\n";
                      endif;
                  endfor;
                  $changeParametersAccessStk .= "</div>\n";
                  // RIGHT MANAGEMENT OF SUBSTOCKS (END)
               endif;
            // endif;
         endif;
	 
      endif;
   endif;
endif;
?>

<html>

<head>
<title><?php echo $pageTitel ?></title>

<link rel="stylesheet" type="text/css" href="../css/phoenix.css">
<style type="text/css">
  <?php include_once ("../css/navigation.css.php"); ?>
</style>

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

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

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

function removeUser(f_act,usr_id_curr,usr_account) {
  if (confirm('Benutzer ' + usr_account + ' entfernen?')) {
  	 document.forms[0].usr_id_curr.value = usr_id_curr;
     finishPage(f_act);
  };
};

function finishPage(f_act) {
	frm = document.forms[0];
  frm.f_act.value = f_act;
  frm.currentNavigationItem.value = '<?php echo $menuElement ?>';
  frm.submit();
};

function clearUser() {
	frm = document.forms[0];
  frm.usr_id_curr.value = '';
  frm.emp_id_act.value = '';
  frm.f_usr_account.value = '';
  frm.f_usr_name.value = '';
  frm.f_usr_firstname.value = '';
  frm.f_usr_birthdate.value = '';
  frm.f_usr_birthdate_day.value = '';
  frm.f_usr_birthdate_month.value = '';
  frm.f_usr_birthdate_year.value = '';
  frm.f_usr_email.value = '';
  frm.f_usr_phone.value = '';
  frm.f_usr_phone2.value = '';
  frm.f_usr_fax.value = '';
  frm.f_usr_password.value = '';
  frm.f_usr_password2.value = '';
};

function clearStockUser() {
	frm = document.forms[0];
  clearUser();
  frm.f_selectRootStock.options[0].selected = true;
  frm.f_substocks_readonly.options[1].selected = true;
  frm.f_stk_article_access.options[0].selected = true;
  var rootIDs = new Array(<?php echo implode(",", $allRootStocksArray);?>);
  var tmpLen = rootIDs.length;
  for (i = 0; i < tmpLen; i++) {
      document.getElementsByName('par_stock_access[]')[i].checked = false;
  }
  for (i = 0; i < tmpLen; i++) {
      elem = eval('frm.par_stock_access_subtree_' + rootIDs[i]);
      if (elem) {
      	 elem.options[0].selected = true;
      }
  }
};

function pageReset() {
	<?php if ($userListOfType == "4") : ?>
	  clearStockUser();
	<?php else : ?>
    clearUser();
  <?php endif; ?>
  finishPage('');
};


function setUserFormFields(usr_id_curr,emp_id_act,usr_account,usr_name,usr_firstname,usr_birthdate,usr_email,usr_phone,usr_phone2,usr_fax) {
	frm = document.forms[0];
  frm.usr_id_curr.value = usr_id_curr;
  frm.emp_id_act.value = emp_id_act;
  frm.f_usr_account.value = usr_account;
  frm.f_usr_name.value = usr_name;
  frm.f_usr_firstname.value = usr_firstname;
  frm.f_usr_birthdate_day.value = usr_birthdate.substr(8, 2);  
  frm.f_usr_birthdate_month.value = usr_birthdate.substr(5, 2);
  frm.f_usr_birthdate_year.value = usr_birthdate.substr(0, 4);
  frm.f_usr_email.value = usr_email;
  frm.f_usr_phone.value = usr_phone;
  frm.f_usr_phone2.value = usr_phone2;
  frm.f_usr_fax.value = usr_fax;
};


function editUser(usr_id_curr,emp_id_act,usr_account,usr_name,usr_firstname,usr_birthdate,usr_email,usr_phone,usr_phone2,usr_fax) {
	frm = document.forms[0];
	clearUser();
  setUserFormFields(usr_id_curr,emp_id_act,usr_account,usr_name,usr_firstname,usr_birthdate,usr_email,usr_phone,usr_phone2,usr_fax)
  finishPage('');
};

function editStockUser(usr_id_curr,emp_id_act,usr_account,usr_name,usr_firstname,usr_birthdate,usr_email,usr_phone,usr_phone2,usr_fax,stk_id,par_value,par2_value,par3_value,par4_value) {
	frm = document.forms[0];
	clearStockUser();
  setUserFormFields(usr_id_curr,emp_id_act,usr_account,usr_name,usr_firstname,usr_birthdate,usr_email,usr_phone,usr_phone2,usr_fax)
  for(i=0;i<frm.f_selectRootStock.length;++i) {
    if (frm.f_selectRootStock.options[i].value == stk_id) {
       frm.f_selectRootStock.options[i].selected = true;
    }
  }
  var rootIDs = new Array(<?php echo implode(",", $allRootStocksArray);?>);
  var tmpLen = rootIDs.length;
  var parValueArray = par_value.split(",");
  var tmp2Len = parValueArray.length;
  for (i = 0; i < tmpLen; i++) {
      for (j = 0; j < tmp2Len; j++) {
	        if (document.getElementsByName('par_stock_access[]')[i].value == parValueArray[j]) {
                   document.getElementsByName('par_stock_access[]')[i].checked = true;
	        }
      }
  }
  if (par3_value == '1') {
     frm.f_substocks_readonly.options[1].selected = true;
  } else {
     frm.f_substocks_readonly.options[0].selected = true;
  }
  if (par4_value == '1') {
     frm.f_stk_article_access.options[1].selected = true;
  } else {
     frm.f_stk_article_access.options[0].selected = true;
  }
  finishPage('');
};

function checkDate(checkObj,mode) {
  var resetValue = checkDateFields(checkObj,mode);
  if (resetValue) {
     checkObj.value = '';
     checkObj.focus();
  };
};

function saveUser() {	
	var ok = true;
	frm = document.forms[0];
	
	if (frm.f_usr_name.value == '') {
     ok = false;
     alert('<?php echo getLngt("Bitte tragen Sie einen Namen ein!") ?>');
  }
	if (frm.f_usr_firstname.value == '') {
     ok = false;
     alert('<?php echo getLngt("Bitte tragen Sie einen Vornamen ein!") ?>');
  }
	if (frm.f_usr_account.value == '') {
     ok = false;
     alert('<?php echo getLngt("Bitte vergeben Sie einen Benutzernamen (Konto) ein!") ?>');
  }
  if (frm.usr_id_curr.value == '') {
	   if (frm.f_usr_password.value == '') {
        ok = false;
        alert('<?php echo getLngt("Bitte vergeben Sie ein Passwort!") ?>');
     }
	   if (frm.f_usr_password2.value.length == 0 && frm.f_usr_password.value.length != 0) {
        ok = false;
        alert('<?php echo getLngt("Bitte bestätigen Sie das Passwort im Wiederholungsfeld!") ?>');
     }
	   if (frm.f_usr_password.value == '' && frm.f_usr_password.value != '') {
        ok = false;
        alert('<?php echo getLngt("Bitte bestätigen Sie das Passwort!") ?>');
     }
  }
	
  if (frm.f_usr_email.value.length != 0) {
     // if e-mail has content then check syntax
     if (!checkMailAddress(frm.f_usr_email, '<?php echo getLngt("Bitte tragen Sie eine gültige Email-Adresse ein!") ?>')) {ok = false;};
  }
  if (ok && frm.f_usr_email.value.length == 0) {
     alert('<?php echo getLngt("Um Auftragsbestätigungs-Emails zu verschicken, tragen Sie bitte eine gültige Email-Adresse ein!") ?>');
     ok = false;
  }
  if (!checkIsNaNIgnoreSpace(frm.f_usr_phone.value, '<?php echo getLngt("Bitte tragen Sie eine Nummer bei Telefon ein!") ?>')) {ok = false;};
  if (!checkIsNaNIgnoreSpace(frm.f_usr_phone2.value, '<?php echo getLngt("Bitte tragen Sie eine Nummer bei Mobil ein!") ?>')) {ok = false;};
  if (!checkIsNaNIgnoreSpace(frm.f_usr_fax.value, '<?php echo getLngt("Bitte tragen Sie eine Nummer bei Fax ein!") ?>')) {ok = false;};

  if (frm.f_usr_birthdate_year.value != '' && frm.f_usr_birthdate_month.value != '' && frm.f_usr_birthdate_day.value != '')	 {
	   frm.f_usr_birthdate.value = frm.f_usr_birthdate_year.value + '-' + frm.f_usr_birthdate_month.value + '-' + frm.f_usr_birthdate_day;
	};
	
	if (ok) {
	   if (frm.usr_id_curr.value == '') {
        finishPage('newUser');
     } else {
        finishPage('modifyUser');
     };
  };
};

function changeSubStock(rootStockId ,op) {
	frm = document.forms[0];
	frm.rootStkIdForSubstkPar.value = rootStockId;
	frm.rootStkOpForSubstkPar.value = op;
	// frm.emp_id_act.value = '';
	// frm.usr_id_curr.value = '';
	finishPage("setAccessSubtocks");
}
-->
</script>
</head>

<body onLoad="<?php echo $phpCurrentNavigationOnLoad ?><?php if ($clearUserFields) : echo "clearUser();"; endif; ?>displayStatusMessage();">

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

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

<form action="../admin/user_list.php" method="post">
  <input type="hidden" name="f_act" value="">  
  <input type="hidden" name="customerId" value="<?php echo ec($customerId) ?>">
  <input type="hidden" name="cscIdRoot" value="<?php echo ec($cscIdRoot) ?>">
  <input type="hidden" name="cscIdActual" value="<?php echo ec($cscIdActual) ?>">  
  <?php echo $phpCurrentNavigationInputHidden ?>
  <input type="hidden" name="deactivateMenu" value="<?php echo ec($deactivateMenu) ?>">
  <input type="hidden" name="tableSort" value="<?php echo $tableSort ?>">
  
  <input type="hidden" name="userListOfType" value="<?php echo $userListOfType ?>">
  <input type="hidden" name="usr_id_curr" value="<?php echo $usr_id_curr ?>">
  <input type="hidden" name="emp_id_act" value="<?php echo $emp_id_act ?>">
  <input type="hidden" name="f_usr_birthdate" value="">
  
  <input type="hidden" name="rootStkIdForSubstkPar" value="">
  <input type="hidden" name="rootStkOpForSubstkPar" value="">

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

  <!-- Headquarters checkboxes -->
  <?php if ($userTypeName == "hq" && authCheckEmployeeRights($emp_id, "10")) : ?>
    <?php echo getHeadquartersCheckboxes($f_hq_id); ?>
    <?php echo htmlDivLineSpacer("10px", "", "left"); ?>
  <?php endif; ?>

  <?php echo defineButtonType10(getLngt("Speichern"), "action_save", "saveUser();", "140", "left", "15") ?>
  <?php echo defineButtonType10(getLngt("Zurücksetzen"), "action_reset", "pageReset();", "140", "left", "15") ?>
  <?php // echo defineButtonType10(getLngt("Aktualisieren"), "action_reload", "finishPage('');", "140", "left", "15"); ?>

  <?php echo htmlDivLineSpacer("20px", "", "left"); ?>

  <div>
    <table border="0">
      <tr>
        <td class="f10np1">
          <?php echo $tableOfUsers ?>
          <br><br>
          <?php echo getLngt("Anzahl Benutzer:") . " " . $numOfUser; ?>
        </td>
      </tr>                  
    </table>
  </div>

  <!-- Basic data (name, firstname, etc.) -->
  <div style="width:500px; float:left;">
    <div>
      <div <?php echo setStyleHtmlDiv("200px","left"); ?>><?php echo getLngt("Name*") ?>:</div>
      <div><input type="text" name="f_usr_name" value="<?php echo $f_usr_name ?>"></div>
    </div>
    <?php echo htmlDivLineSpacer("5px"); ?>
    <div>
      <div <?php echo setStyleHtmlDiv("200px","left"); ?>><?php echo getLngt("Vorname*") ?>:</div>
      <div><input type="text" name="f_usr_firstname" value="<?php echo $f_usr_firstname ?>"></div>
    </div>
    <?php echo htmlDivLineSpacer("5px"); ?>
    <div>
      <div <?php echo setStyleHtmlDiv("200px","left"); ?>><?php echo getLngt("E-Mail*") ?>:</div>
      <div><input type="text" name="f_usr_email" value="<?php echo $f_usr_email ?>"></div>
    </div>
    <?php echo htmlDivLineSpacer("5px"); ?>
    <div>
      <div <?php echo setStyleHtmlDiv("200px","left"); ?>><?php echo getLngt("Telefon") ?>:</div>
      <div><input type="text" name="f_usr_phone" value="<?php echo $f_usr_phone ?>"></div>
    </div>
    <?php echo htmlDivLineSpacer("5px"); ?>
    <div>
      <div <?php echo setStyleHtmlDiv("200px","left"); ?>><?php echo getLngt("Mobil") ?>:</div>
      <div><input type="text" name="f_usr_phone2" value="<?php echo $f_usr_phone2 ?>"></div>
    </div>
    <?php echo htmlDivLineSpacer("5px"); ?>
    <div>
      <div <?php echo setStyleHtmlDiv("200px","left"); ?>><?php echo getLngt("Fax") ?>:</div>
      <div><input type="text" name="f_usr_fax" value="<?php echo $f_usr_fax ?>"></div>
    </div>
    <?php echo htmlDivLineSpacer("5px"); ?>

    <div>
      <div <?php echo setStyleHtmlDiv("200px","left"); ?>><?php echo getLngt("Geburtstag") ?>:<?php echo getLngt("[TT-MM-JJJJ]") ?></div>
      <div>
        <?php 
          // Birthdate
          if ($f_usr_birthdate != "") :
            $f_usr_birthdate_year = substr($f_usr_birthdate,0,4);
            $f_usr_birthdate_month = substr($f_usr_birthdate,5,2);
            $f_usr_birthdate_day = substr($f_usr_birthdate,8,2);
          endif;
        ?>
        <input type="text" name="f_usr_birthdate_day" value="<?php echo $f_usr_birthdate_day ?>" size="2" maxlength="2" onBlur="checkDate(this,'day')">&nbsp;
        <input type="text" name="f_usr_birthdate_month" value="<?php echo $f_usr_birthdate_month ?>" size="2" maxlength="2" onBlur="checkDate(this,'month')">&nbsp;
        <input type="text" name="f_usr_birthdate_year" value="<?php echo $f_usr_birthdate_year ?>" size="4" maxlength="4">
      </div>
    </div>
    <?php echo htmlDivLineSpacer("5px"); ?>
    
    <div>
      <div <?php echo setStyleHtmlDiv("200px","left"); ?>><?php echo getLngt("Anmeldename*") ?>:</div>
      <div><input type="text" name="f_usr_account" value="<?php echo $f_usr_account ?>"></div>
    </div>
    <?php echo htmlDivLineSpacer("5px"); ?>
    <div>
      <div <?php echo setStyleHtmlDiv("200px","left"); ?>><?php echo getLngt("Passwort*") ?>:</div>
      <div><input type="password" name="f_usr_password" value=""></div>
    </div>
    <?php echo htmlDivLineSpacer("5px"); ?>
    <div>
      <div <?php echo setStyleHtmlDiv("200px","left"); ?>><?php echo getLngt("Wiederholung*") ?>:</div>
      <div><input type="password" name="f_usr_password2" value=""></div>
    </div>
    <?php echo htmlDivLineSpacer("5px"); ?>
    
    <?php echo $specialOutput; ?>
    <?php if ($specialOutput != "") : echo htmlDivLineSpacer("5px"); endif; ?>
  </div>

  <?php echo $changeParametersAccessStk; ?>

  <?php echo htmlDivLineSpacer("10px","","left"); ?>
  
</form>
</div>
</body>

</html>