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

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


$httpVars = array("f_act", "articleId", "orderClause", "statusMessage", "printVersion");

$httpVisualVars = array("f_at_eid", "f_at_name", "f_at_match", "f_at_description", "f_at_barcode", "f_searchmode", 
                        "f_show_invisible", "f_at_authenticated", "f_at_visible", "f_at_bundlequantity", "f_at_bundlecode",
                        "f_bundlearticle_remove", "f_at_eid_new", "f_atb_bundlequantity_new", "f_at_serialno", "f_at_mountable",
                        "f_at_stk_itemquantity", "f_at_stk_areaquantity", "g_atg_id", "deactivateMenu", "objecttypemode");

$httpVarsArray = array_merge ($httpVars, $httpVisualVars);
                         
getSecHttpVars("1", $httpVarsArray);                         


// Select user-type for mode of security check 
$userType = getFieldValueFromId("user","usr_id",$usr_id,"usr_type");
$userTypeName = getUserTypeName($userType);

if ($userTypeName == "stk") :
   $maskStkArticleAccess = getParameterValue($emp_id, "MASK_STK_ARTICLE_ACCESS");
   if ($maskStkArticleAccess != "1") :
      gotoReferer("1");
   endif;
else :
   $usrAccessArray["hq"] = "1";
   authCheckForAccess($hq_id, $usr_id, $emp_id, "1", $customerId, $cscIdRoot, $cscIdActual);
   authCheckEmployeeRights($emp_id, "14", "1");
endif;

getLanguage(__FILE__);

$deactivateMenuStatic = "1";
$pageTitel = getLngt(wrapPhrase("ARTIKEL", $objecttypemode));
include_once ("../admin/menu.php");
include_once ("../include/html.inc.php");
include_once ("../include/inc_article.inc.php");
include_once ("../include/inc_stock.inc.php");
getCurrentScript(__FILE__);

// No operation if print version requested
if ($printVersion == "1") : $f_act = ""; endif;

$dbOperationCompleted = "0";

// Init parameters:
// Single Checkbox => Flag
if ($f_at_serialno == "" || count($f_at_serialno) == 0) :
   $f_at_serialno = "0";
else: 
   $f_at_serialno = "1";
endif;
if ($f_at_mountable == "" || count($f_at_mountable) == 0) :
   $f_at_mountable = "0";
else: 
   $f_at_mountable = "1";
endif;

// Init package factor if empty
if ($f_at_stk_itemquantity == "") : $f_at_stk_itemquantity = "1"; endif;
if ($f_at_stk_areaquantity == "") : $f_at_stk_areaquantity = "1"; endif;

// Get EID prefix and reset EID only if equals prefix
$constAtEidPrefix = getParameterValue("0", "AT_EID_PREFIX", $hq_id);
if ($f_at_eid == $constAtEidPrefix) : $f_at_eid = ""; endif;    


   // *******************************
   // * Operations for the articles *   
   // *******************************

   // Generate log string
   if ($f_act != "") :
      $logString = makeLogString(array($f_at_eid,$f_at_name,$f_at_authenticated,$f_at_visible,$g_atg_id,$f_at_match,$f_at_description,$f_at_barcode,$f_at_bundlequantity,$f_at_bundlecode,$f_at_stk_itemquantity,$f_at_stk_areaquantity,$f_at_serialno,$f_at_mountable), ";", "0");
   endif;

   // Insert new article
   if ($f_act == "newArticle") :
      
      if ($f_at_eid != "" && $f_at_name != "") :

         // Check existence of the article (all data)
         if ($db->getOne("SELECT at_eid FROM article WHERE at_eid = '" . $f_at_eid . "'")) :
            $statusMessage = getLngt("Die eindeutige " . wrapPhrase("Artikelnummer", $objecttypemode) . " (ExtID) ist bereits vergeben! Bitte wählen Sie eine andere");
                
         elseif ($f_at_barcode != "" && $db->getOne("SELECT at_barcode FROM article WHERE at_barcode = '" . $f_at_barcode . "'")) :
            $statusMessage = getLngt("Der eindeutige Barcode ist bereits vergeben! Bitte prüfen Sie, ob der " . wrapPhrase("Artikel", $objecttypemode) . " schon existiert! Es erfolgte keine Änderung!");
            
         elseif ($db->getOne("SELECT at_name FROM article WHERE at_name = '" . $f_at_name . "'")) :
            $statusMessage = getLngt("Die " . wrapPhrase("Artikelbezeichnung", $objecttypemode) . " existiert schon! Eine Identität scheint sehr wahrscheinlich, deshalb wird der Artikel unter dieser Bezeichnung nicht angelegt!");

         else:
             TA("B");

             $currentTime = getDateTime("0");

             // Insert article
             // $f_at_discount = str_replace (",", ".", $f_at_discount);
             // $f_at_prov = str_replace (",", ".", $f_at_prov);
             insertStmt("article", array("at_eid", $f_at_eid, "at_name", $f_at_name, "hq_id", $hq_id, "at_match", $f_at_match, "at_description", $f_at_description, "at_barcode", $f_at_barcode, "at_createtime", $currentTime,
                                         "atg_id", $g_atg_id, "at_bundlequantity", $f_at_bundlequantity, "at_bundlecode", $f_at_bundlecode, "at_stk_itemquantity", $f_at_stk_itemquantity, "at_stk_areaquantity", $f_at_stk_areaquantity, "at_serialno", $f_at_serialno, "at_mountable", $f_at_mountable));
             $at_id_new = getLastInsertId();

             // Set special article group like a customer relation et al.
             if ($g_atg_id != "" && is_numeric($g_atg_id) && $g_atg_id > "0") :
                if (existsEntry("articlegroupitem",array("md_id", $md_id, "hq_id", "0", "at_id", $g_atg_id))) :
                   insertStmt("articlegroupitem", array("md_id", $md_id, "hq_id", '0', "atg_id", $g_atg_id, "at_id", $at_id_new));
                else :
                   insertStmt("articlegroupitem", array("md_id", $md_id, "hq_id", $hq_id, "atg_id", $g_atg_id, "at_id", $at_id_new));
                endif;
                $g_atg_id = "";
             endif;

             // Write logdata into log database
             writeToLogDB("61",$hq_id,"",$usr_id,"","","","STATUS_NEW=" . $logString,$at_id_new);

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

             // Reset fields of form-parameters
             // clearParameters($httpVisualVars);   // <= Moved to the end of the php-part of this script...
             $dbOperationCompleted = "1";
         endif;
      else :
         $statusMessage = getLngt("Bitte geben Sie alle mit * gekennzeichneten Felder ein!");
      endif;
   endif;            

   // Modify article
   if ($f_act == "modifyArticle" && $articleId != "") :
      
      if ($f_at_eid != "" && $f_at_name != "") :

         if ($db->getOne("SELECT at_eid FROM article WHERE at_eid = '" . $f_at_eid . "' AND NOT (at_id = '" . $articleId . "')")) :
            $statusMessage = getLngt("Die eindeutige " . wrapPhrase("Artikelnummer", $objecttypemode) . " (ExtID) ist bereits vergeben! Bitte wählen Sie eine andere!");

         elseif ($f_at_barcode != "" && $db->getOne("SELECT at_barcode FROM article WHERE at_barcode = '" . $f_at_barcode . "' AND NOT (at_id = '" . $articleId . "')")) :
            $statusMessage = getLngt("Der eindeutige Barcode ist bereits vergeben! Bitte prüfen Sie, ob " . wrapPhrase("der Artikel", $objecttypemode) . " schon existiert! Es erfolgte keine Änderung!");

         else :
            // Get current state of the serial number
            $currAtSerialno = getFieldValueFromId("article", "at_id", $articleId, "at_serialno");
         
            // Only check if state of the serial number will be changed !!!
            if ($currAtSerialno != $f_at_serialno) :
            
               // Check for switched flag for serial number ...
               if ($f_at_serialno == "1") :
                  // 1. Check for existing quantity on any stockarticle
                  if (quantityOfSpecialStockArticleOnAnyStock($articleId) > 0) :
                     $f_at_serialno = "0";
                     $statusMessage = getLngt(wrapPhrase("Dieser Artikel", $objecttypemode) . " weist Lagerbestände aus (evtl. auch in einer anderen Niederlassung)! Das Kennzeichen kann deshalb zur Zeit leider nicht gesetzt werden!");
                  endif;
                  // 2. Check for article being a bundle
                  if (isBundledArticle($articleId)) :
                     $f_at_serialno = "0";
                     $statusMessage = getLngt("Solange " . wrapPhrase("dieser Artikel", $objecttypemode) . " ein Gebinde ist, kann keine Seriennummer geführt werden!");
                  endif;
                  // 3. Check for article being in any bundle
                  if (existsEntry("articlebundle",array("at_id2",$articleId))) :
                     $f_at_serialno = "0";
                     $statusMessage = getLngt("Solange " . wrapPhrase("dieser Artikel", $objecttypemode) . " Bestandteil eines Gebindes ist (evtl. auch in einer anderen Niederlassung), kann keine Seriennummer geführt werden!");
                  endif;
               else :
                  // Check for existence of serial numbers
                  if (existsEntry("articleitem",array("at_id",$articleId))) :
                     $f_at_serialno = "1";
                     $statusMessage = getLngt(wrapPhrase("Dieser Artikel", $objecttypemode) . " besitzt noch eine eingetragene Seriennummern! Der Status bzgl. Seriennummer wurde nicht verändert!");
                  endif;
               endif;
            endif;

            TA("B");

            // Get current state in at_modify_status because it is equal to "1" then do NOT change                        
            $modifyStatus = getFieldValueFromId("article", "at_id", $articleId, "at_modify_status");
            if ($modifyStatus != "1") : $modifyStatus = "2"; endif;

            // Update article
            // $f_at_discount = str_replace (",", ".", $f_at_discount);
            // $f_at_prov = str_replace (",", ".", $f_at_prov);
            $defaultFields = array("at_eid", $f_at_eid, "at_name", $f_at_name, "at_match", $f_at_match, "at_description", $f_at_description, "at_barcode", $f_at_barcode, "at_bundlequantity", $f_at_bundlequantity, "at_bundlecode", $f_at_bundlecode, "at_stk_itemquantity", $f_at_stk_itemquantity, "at_stk_areaquantity", $f_at_stk_areaquantity, "at_serialno", $f_at_serialno, "at_mountable", $f_at_mountable);
            updateStmt("article","at_id",$articleId,$defaultFields);

            // Set special article group like a customer relation et al.
            if ($g_atg_id != "" && is_numeric($g_atg_id) && $g_atg_id > "0") :
               if (existsEntry("articlegroupitem",array("md_id", $md_id, "hq_id", "0", "at_id", $articleId))) :
                  updateStmt("articlegroupitem","at_id",$articleId,array("atg_id",$g_atg_id), "md_id = '" . $md_id . "' AND hq_id = '0'");
               elseif (existsEntry("articlegroupitem",array("hq_id",$hq_id,"at_id",$articleId))) :
                  updateStmt("articlegroupitem","at_id",$articleId,array("atg_id",$g_atg_id), "md_id = '" . $md_id . "' AND hq_id = '" . $hq_id . "'");
               else :
                  insertStmt("articlegroupitem", array("md_id", $md_id, "hq_id", $hq_id, "atg_id", $g_atg_id, "at_id", $articleId));
               endif;
            else :
               deleteStmt("articlegroupitem","md_id = '" . $md_id . "' AND hq_id = '" . $hq_id . "' AND at_id = '" . $articleId . "'");
            endif;

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

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

            $dbOperationCompleted = "1";
         endif;               
      else :
         $statusMessage = getLngt("Bitte geben Sie alle mit * gekennzeichneten Felder ein!");
      endif;                                                            
   endif;

   // Delete article
   if ($f_act == "removeArticle" && $articleId != "") :
      if (existsEntry("article",array("at_id",$articleId))) :
         //   TA("B");
         //   deleteStmt("article","at_id = '".$articleId."'");
        
         // Write logdata into log database
         // writeToLogDB("65",$hq_id,"",$usr_id,"","","","STATUS_DELETED",$articleId);
         
         //   TA("C");
         //   TA("E");
      else :
         $statusMessage = getLngt(wrapPhrase("Der Artikel", $objecttypemode) . " kann nicht entfernt werden!");
      endif;
   endif;  

   // Set status of authentication of the article
   if ($f_act == "setAuthentication") :

      // Check for company
      if ($articleId != "") :

         if (existsEntry("article",array("at_id",$articleId))) :

            // Update authentication-status
            updateStmt("article","at_id",$articleId,array("at_authenticated",$f_at_authenticated));
            
            // Write logdata into log database
            writeToLogDB("63",$hq_id,"",$usr_id,"","","","STATUS_AUTHENTICATION=".$f_at_authenticated,$articleId);
         else :               
            $statusMessage = getLngt(wrapPhrase("Der spezifizierte Artikel", $objecttypemode) . " ist nicht im Datenbestand erhalten!");
         endif;      
      else :
         $statusMessage = getLngt("Sie haben " . wrapPhrase("keinen Artikel", $objecttypemode) . " spezifiziert!");
      endif;
   endif;
   
   // Set status of visibility of the article
   if ($f_act == "setVisibility") :

      // Check for company
      if ($articleId != "") :

         if (existsEntry("article",array("at_id",$articleId))) :

            // Update authentication-status
            updateStmt("article","at_id",$articleId,array("at_visible",$f_at_visible));

            // Write logdata into log database
            writeToLogDB("64",$hq_id,"",$usr_id,"","","","STATUS_VISIBILITY=".$f_at_visible,$articleId);
         else :               
            $statusMessage = getLngt(wrapPhrase("Der spezifizierte Artikel", $objecttypemode) . " ist nicht im Datenbestand erhalten!");
         endif;      
      else :
         $statusMessage = getLngt("Sie haben " . wrapPhrase("keinen Artikel", $objecttypemode) . " spezifiziert!");
      endif;
   endif;
   
   // Remove bundle article
   if ($f_act == "removeBundleArticle") :

      // Check for company
      if ($articleId != "") :

         // Check for existence of a subarticle of the article to be removed
         if (!isBundledArticle($f_bundlearticle_remove)) :

            if (existsEntry("articlebundle",array("at_id",$articleId, "at_id2", $f_bundlearticle_remove))) :
            
               // Delete bundle article out of the bundle
               deleteStmt("articlebundle","at_id = '".$articleId."' AND at_id2 = '" . $f_bundlearticle_remove . "'");
            
               // Write logdata into log database
               // writeToLogDB("64",$hq_id,"",$usr_id,"","","","STATUS_VISIBILITY=".$f_at_visible,$articleId);
            else :               
               $statusMessage = getLngt(wrapPhrase("Der zu löschende Artikel") . " ist nicht im Gebinde erhalten!");
            endif;
         else :               
            $statusMessage = getLngt(wrapPhrase("Der zu löschende Artikel") . " ist ein Gebindeartikel! Bitte zuerst die ihm zugeordneten " . wrapPhrase("Artikel", $objecttypemode) . " entfernen!");
         endif;
      else :
         $statusMessage = getLngt("Sie haben " . wrapPhrase("keinen Artikel", $objecttypemode) . " spezifiziert!");
      endif;
   endif;

   // New bundle article
   if ($f_act == "newBundleArticle") :

      // Check for company
      if ($articleId != "") :

         if (existsEntry("article",array("at_id",$articleId)) && existsEntry("article",array("at_eid", $f_at_eid_new))) :
         
            // Perhaps it is possible to check existing item quantity on any stock before changing to bundled article ...?!
            // $tmpArticleItemQuantity = getStockArticleQuantitySubtree ($stkIdRoot, "0", stkat.stkat_itemquantity, "at.at_id = " . $tmpAtId . "'");

            if ($f_atb_bundlequantity_new > 0) :

               // Get at_id of the EID in f_at_eid_new
               $atIdTmp = getFieldValueFromId("article", "at_eid", $f_at_eid_new, "at_id");

               if ($atIdTmp != "") :
                  $storeArticle = true;

                  // Check for switch for serial numbers for the CURRENT article
                  $tmpAtSerialNo = getFieldValueFromId("article", "at_id", $articleId, "at_serialno");
                  if ($storeArticle && $tmpAtSerialNo == "1") :
                     $storeArticle = false;
                     $statusMessage = getLngt(wrapPhrase("Dem Artikel", $objecttypemode) . " dürfen " . wrapPhrase("keine Artikel", $objecttypemode) . " oder Gebinde zugefügt werden, da " . wrapPhrase("für diesen Artikel", $objecttypemode) . " Seriennummern erfasst werden müssen!");
                  endif;
                  
                  // Check for switch for serial numbers for the CURRENT article
                  $tmpAtSerialNo = getFieldValueFromId("article", "at_id", $atIdTmp, "at_serialno");
                  if ($storeArticle && $tmpAtSerialNo == "1") :
                     $storeArticle = false;
                     $statusMessage = getLngt(wrapPhrase("Der Artikel", $objecttypemode) . " darf nicht als Gebindebestandteil zugefügt werden, da " . wrapPhrase("für diesen Artikel", $objecttypemode) . " Seriennummern erfasst werden müssen!");
                  endif;

                  // Check for identity
                  if ($storeArticle && $articleId == $atIdTmp) :
                     $storeArticle = false;
                     $statusMessage = getLngt(wrapPhrase("Ein Artikel", $objecttypemode) . " darf nicht sich selbst zugefügt werden, also ein Gebinde kann nicht aus sich selbst bestehen!");
                  endif;

                  // Check for cycle if article is a bundeled article
                  if ($storeArticle && isBundledArticle($atIdTmp)) :
                     $noCycle = true;
                     $recurseCount = "0";
                     checkForCycle($articleId, $atIdTmp);
                     if (!$noCycle) :
                        // Cycle detected
                        $storeArticle = false;
                        $statusMessage = getLngt(wrapPhrase("Der Gebindeartikel", $objecttypemode) . " kann nicht zugefügt werden, da nach der Ausführung eine zyklische Abhängigkeit bestünde!");
                     endif;
                  endif;

                  // If current article in $articleId is NOT a bundle and shall become a bundle by association of an article in $atIdTmp
                  // then check whether $articleId has currently a quantity on any stock!
                  // Do NOT execute transformation from "item article" to "bundle article" if at least one item does exist on any stock!
                  // ATTENTION: This has to be done on ALL stocks and therefore on all root stocks, too. The administration of articles is independent of a specisal headquarters!!!
                  if ($storeArticle && !isBundledArticle($articleId)) :
                     // Check for quantity on any stock
                     if (quantityOfSpecialStockArticleOnAnyStock($articleId) > 0) :
                        $storeArticle = false;
                        $statusMessage = getLngt("Bitte buchen Sie vor der Umwandlung " . wrapPhrase("in einen Gebindeartikel", $objecttypemode) . " die bestehenden Stückmengen aus!");
                     endif;
                  endif;

                  // Insert new bundled article or update quantity of an existing bundled article
                  if ($storeArticle) :
                     // Check existence of a parent-child pair
                     if (existsEntry("articlebundle",array("at_id",$articleId, "at_id2",$atIdTmp))) :
                        updateQuantityOfExistingBundledArticle($articleId, $atIdTmp, $f_atb_bundlequantity_new);
                     else :
                        insertStmt("articlebundle", array("at_id", $articleId, "at_id2", $atIdTmp, "atb_bundlequantity", $f_atb_bundlequantity_new));
                     endif;
                  endif;

                  // Write logdata into log database
                  // writeToLogDB("64",$hq_id,"",$usr_id,"","","","STATUS_VISIBILITY=".$f_at_visible,$articleId);
               else :
                  $statusMessage = getLngt(wrapPhrase("Der Artikel", $objecttypemode) . " ist nicht bekannt!");
               endif;
            else :
               $statusMessage = getLngt("Die Gebindemenge muss größer Null sein!");
            endif;
         else :               
            $statusMessage = getLngt(wrapPhrase("Der Artikel", $objecttypemode) . " existiert nicht!");
         endif;      
      else :
         $statusMessage = getLngt("Sie haben " . wrapPhrase("keinen Artikel", $objecttypemode) . " spezifiziert!");
      endif;
   endif;



   // *********************************
   // * Selection of the article-data *
   // *********************************
   if ($articleId != "") :
      $sqlquery = "SELECT at.at_id, at.hq_id, at.at_eid, at.at_name, atgi.atg_id, at.at_match, at.at_description,"
                   . "    at.at_barcode, at.at_authenticated, at.at_visible, at.at_serialno, at.at_mountable,"
                   . "    at.at_bundlequantity, at.at_bundlecode, at.at_stk_itemquantity, at.at_stk_areaquantity"
                   . " FROM article AS at LEFT JOIN articlegroupitem AS atgi ON at.at_id = atgi.at_id AND atgi.md_id = '" . $md_id . "' AND atgi.hq_id IN ('0','" . $hq_id . "')"
                   . " WHERE at.at_id = '" . $articleId . "'"
                   .         getSQLMandatorPhrase($emp_id, " AND at.hq_id = '" . $hq_id . "' ");

      $result = $db->query($sqlquery);

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

      while ($row = $result->fetch_assoc()):
            $f_articleId       = $row["at_id"];
            $f_at_eid          = $row["at_eid"];
            $f_at_name         = $row["at_name"];
            $f_at_match        = $row["at_match"];
            $f_at_description  = $row["at_description"];
            $f_at_barcode      = $row["at_barcode"];
            $f_at_hq_id        = $row["hq_id"];

            $f_at_authenticated = $row["at_authenticated"];
            $f_at_authenticated2 = 0;
            if ($f_at_authenticated != "1") :
               $f_at_authenticated = 0; 
               $f_at_authenticated2 = 1;
            endif;
            $f_at_visible = $row["at_visible"];
            $f_at_visible2 = 0;
            if ($f_at_visible != "1") :
               $f_at_visible = 0; 
               $f_at_visible2 = 1;
            endif;

            $f_at_bundlequantity    = $row["at_bundlequantity"];
            $f_at_bundlecode        = $row["at_bundlecode"];
            $f_at_stk_itemquantity  = $row["at_stk_itemquantity"];
            $f_at_stk_areaquantity  = $row["at_stk_areaquantity"];
            $f_at_serialno          = $row["at_serialno"];
            $f_at_mountable         = $row["at_mountable"];

            $g_atg_id = $row["atg_id"];
      endwhile;
      $result->free();


      // *** BUNDLE ***

      // If the currrent article represents a bundle, there are one or more associated articles belonging to this bundle
      // The bundle is an article by itself !!!
      $sqlquery = "SELECT atb.at_id, atb.at_id2, at.at_eid, at.at_name, at2.at_eid AS at_eid2, at2.at_name AS at_name2,"
                   . "    atb.atb_bundlequantity"
                   . " FROM articlebundle AS atb, article AS at, article AS at2"
                   . " WHERE atb.at_id = '" . $articleId . "' AND"
                   . "       atb.at_id = at.at_id AND"
                   . "       atb.at_id2 = at2.at_id";

      $result = $db->query($sqlquery);

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

      $f_articlebundle = "";      
      $atCount = 0;
      $f_articlebundle .= "<div style=\"float:left\">";
      while ($row = $result->fetch_assoc()):
            $atCount++;
            $f_articlebundle .= "<div>";
            $f_articlebundle .= "  <br>";
            $f_articlebundle .= "  <input class=\"smaller\" type=\"text\" name=\"f_at_eid_" . $count . "\" value=\"" . $row["at_eid2"] . "\" size=\"10\" maxlength=\"10\" readonly>&nbsp;&nbsp;";
            $f_articlebundle .= "  <input class=\"smaller\" type=\"text\" name=\"f_at_name_" . $count . "\" value=\"" . $row["at_name2"] . "\" size=\"20\" maxlength=\"50\" readonly>&nbsp;&nbsp;";
            $f_articlebundle .= "  <input class=\"smaller\" type=\"text\" name=\"f_atb_bundlequantity_" . $count . "\" value=\"" . $row["atb_bundlequantity"] . "\" size=\"3\" maxlength=\"5\" readonly>&nbsp;&nbsp;";
            $f_articlebundle .= "  <a href=\"javascript:clearBundleArticle('" . $row["at_id2"] . "');\"><img src=\"../images/waste.png\" border=\"0\" height=\"15\" width=\"12\"></a>";
            $f_articlebundle .= "</div>";
      endwhile;
      $result->free();

      if ($atCount == 0) :
         $f_articlebundle .= "<div style=\"width:20; height:10;\"></div>";
         $f_articlebundle .= "<div>";
         $f_articlebundle .= getLngt("- Zur Zeit sind noch keine Gebindebestandteile eingetragen -");
         $f_articlebundle .= "</div>";
      endif;

      $f_articlebundle .= "<div style=\"width:20; height:15;\"></div>";
      $f_articlebundle .= "<div style=\"float:left\">";
      $f_articlebundle .= getLngt("EID:") . "&nbsp;<input class=\"smaller\" type=\"text\" name=\"f_at_eid_new\" value=\"\" size=\"10\" maxlength=\"10\">&nbsp;&nbsp;";
      // $f_articlebundle .= "  <input class=\"smaller\" type=\"text\" name=\"f_at_name_new\" value=\"\" size=\"20\" maxlength=\"50\" readonly>&nbsp;&nbsp;";
      $f_articlebundle .= getLngt("Menge:") . "&nbsp;<input class=\"smaller\" type=\"text\" name=\"f_atb_bundlequantity_new\" value=\"\" size=\"3\" maxlength=\"5\">&nbsp;&nbsp;";
      $f_articlebundle .= "</div>";
      $f_articlebundle .= defineButtonType08(getLngt("Hinzufügen"), "action_new_bundlearticle", "newBundleArticle();", "90", "left", "3");
   endif;

   // Get the data of the article group
   if ($g_atg_id != "") :
       // $g_atg_key = getFieldValueFromId("articlegroup", "atg_id", "$g_atg_id", "atg_key");
       // $g_atg_name = getFieldValueFromId("articlegroup", "atg_id", "$g_atg_id", "atg_name");
       $g_atg_key = getFieldValueFromClause("articlegroup","atg_key","md_id = '" . $md_id . "' AND atg_id = '" . $g_atg_id . "'");
       $g_atg_name = getFieldValueFromClause("articlegroup","atg_name","md_id = '" . $md_id . "' AND atg_id = '" . $g_atg_id . "'");
   endif;

   // Get max-value of the EID of the current article for inserting a new row
   // The constant value "AT_EID_GENERATION" contains the prefix of the SID [SPECIAL TREATMENT]
   $f_eid_maxval = "";
   // $atEidGeneration = getParameterValue("0", "AT_EID_GENERATION");
   if (AT_EID_GENERATION != "") :
      $f_eid_maxval = getMaxOfField("article", "at_eid", "at_eid < '" . AT_EID_GENERATION . "'");
      // Check existence of at least one EID with requested prefix
      if (substr($f_eid_maxval, 0, strlen(AT_EID_PREFIX)) != AT_EID_PREFIX) :
         $f_eid_maxval = AT_EID_PREFIX . "100000";
      endif;
      if (is_numeric($f_eid_maxval)) :
         ++$f_eid_maxval;   // Increment because of the next free EID (Attention: Not TA-safe!)
      else :
        // Remove alphanumeric chars (e.g "HTHB123456" => "123456")
        $prefixChars = ereg_replace("[^[:alpha:]+]","",$f_eid_maxval);
        $f_eid_maxval = ereg_replace("[^[:digit:]+]","",$f_eid_maxval);
        ++$f_eid_maxval;
        $f_eid_maxval = $prefixChars . $f_eid_maxval;
      endif;
   endif;

   // Only for output
   $title = getLngt(wrapPhrase("NEUER ARTIKEL", $objecttypemode));
   $buttonAuthentication = "";
   $buttonVisibility = "";
   $displayTextAuthentication = "";
   $displayTextVisibility = "";
   $confirmTextAuthentication = "";
   $confirmTextVisibility = "";
 
   if ($articleId != "") :
      $title = getLngt(wrapPhrase("ARTIKEL", $objecttypemode)) . ": &nbsp;" . substr($f_at_name, 0, 100);
      
      // Check for being a bundled article
      if (isBundledArticle($articleId)) :
         $title .= "&nbsp;&nbsp;&nbsp;<span class=\"f10bp1_red\">[" . getLngt("GEBINDE") . "]</span>&nbsp;&nbsp;&nbsp;";
      endif;

      // Show mandator
      /*
      if (authCheckEmployeeRights($emp_id, "10")) :

         // Name of the headquarter
         $hq_name = getFieldValueFromId("headquarters", "hq_id", $f_at_hq_id, "hq_name");
         $title .= "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
         $title .= "[" . $hq_name . "]";

         $title .= "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
      endif;
      */

      $buttonAuthentication = defineButtonType08(getLngt("Sperren"), "action_lock", "authenticationFinishPage();", "90", "left", "3");
      $confirmTextAuthentication = getLngt("Möchten Sie den Eintrag wirklich sperren?");
      if ($f_at_authenticated != "1") : 
         $buttonAuthentication = defineButtonType08(getLngt("Freischalten"), "action_lock", "authenticationFinishPage();", "90", "left", "3");
         $displayTextAuthentication = getLngt("(gesperrt)");
         $confirmTextAuthentication = getLngt("Möchten Sie den Eintrag wirklich freischalten?");
      endif;
      
      $buttonVisibility = defineButtonType08(getLngt("Ausblenden"), "action_visible", "visibilityFinishPage();", "90", "left", "3");
      $confirmTextVisibility = getLngt("Möchten Sie den Eintrag wirklich ausblenden?");
      if ($f_at_visible != "1") : 
         $buttonVisibility = defineButtonType08(getLngt("Einblenden"), "action_visible", "visibilityFinishPage();", "90", "left", "3");
         $displayTextVisibility = getLngt("(ausgeblendet)");
         $confirmTextVisibility = getLngt("Möchten Sie den Eintrag wirklich einblenden?");
      endif;
   endif;
   
   // Only for output:
   // Check for updating the list
   $javaScriptOut = "";
   if ($statusMessage == "" && $f_act != "" && $dbOperationCompleted == "1" && MASK_ARTICLE_SHOW_LIST == "1") :
      $javaScriptOut .= "opener.finishPage('".strWrapJs($f_at_eid)."','".strWrapJs($f_at_name)."','".strWrapJs($f_at_match)."','".strWrapJs($f_at_description)."','".strWrapJs($f_at_barcode)."');";
   endif;   
   if ($f_act == "newArticle" && $dbOperationCompleted == "1") :
      // Reset fields of form-parameters
      clearParameters($httpVisualVars);
      // Init package factor
      if ($f_at_stk_itemquantity == "") : $f_at_stk_itemquantity = "1"; endif;
      if ($f_at_stk_areaquantity == "") : $f_at_stk_areaquantity = "1"; endif;
   endif;
   

   // ******************************************************************************************************************

   
   $f_at_eid = strWrapHtml($f_at_eid);
   $f_at_name = strWrapHtml($f_at_name);
   $f_at_match = strWrapHtml($f_at_match);
   $f_at_description = strWrapHtml($f_at_description);

   if ($articleId != "" || AT_EID_GENERATION == "") :
        $f_at_eid_out = "<input class=\"smaller\" type=\"text\" name=\"f_at_eid\" value=\"" . $f_at_eid . "\" tabindex=\"30\" size=\"10\" maxlength=\"10\" " . (AT_EID_EDITABLE != "1" ? "readonly" : "") . ">";
   else :
        if ($f_at_eid == "") :
           $f_at_eid = $constAtEidPrefix;
        endif;
   
        $f_at_eid_out = "<div style=\"float:left\"><input class=\"smaller\" type=\"text\" name=\"f_at_eid\" value=\"" . $f_at_eid . "\" tabindex=\"30\" size=\"10\" maxlength=\"10\">&nbsp;</div>";
        $f_at_eid_out .= defineButtonType08("...", "action_eid", "searchMaxEID();", "20", "left", "2");
   endif;
   
   // Generate Output
   if ($articleId != "") : 
       $f_actText = "modifyArticle";
   else :
       $f_actText = "newArticle";
   endif;

   $f_at_id = $articleId;

   // Serial number
   $f_at_serialno_0 = "";
   if ($f_at_serialno == "1") :
      $f_at_serialno_0 = "checked";
   endif;
   // Article mountable
   $f_at_mountable_0 = "";
   if ($f_at_mountable == "1") :
      $f_at_mountable_0 = "checked";
   endif;


   /*
   $f_at_fixprice_discount_0 = "";
   if ($f_at_fixprice_discount == "1") : $f_at_fixprice_discount_0 = "checked"; endif;

   $f_at_xxx_0 = "";
   $f_at_xxx_1 = "";
   if ($f_at_xxx == "1" || $f_at_xxx == "3") : $f_at_xxx_0 = "checked"; endif;
   if ($f_at_xxx == "2" || $f_at_xxx == "3") : $f_at_xxx_1 = "checked"; endif;

   $f_at_commission_no_0 = "";
   $f_at_commission_no_1 = "";
   if ($f_at_commission_no == "0" || $f_at_commission_no == "") : $f_at_commission_no_0 = "checked"; endif;
   if ($f_at_commission_no == "1") : $f_at_commission_no_1 = "checked"; endif;
   */
?>

<html>

<head>
<title><?php echo $pageTitel . " " . $f_at_name ?></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 src="../include/searchLists.js" type="text/javascript"></script>

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

var f_at_id = '<?php echo $f_at_id ?>';

function clearAllFields() {
  document.location.href = "article_special.php";
};

function authenticationFinishPage() {
  if (confirm('<?php echo $confirmTextAuthentication ?>')) {	
     document.forms[0].f_at_authenticated.value='<?php echo $f_at_authenticated2 ?>';
     document.forms[0].f_act.value='setAuthentication';
     document.forms[0].submit();
  }
};

function visibilityFinishPage() {
  if (confirm('<?php echo $confirmTextVisibility ?>')) {	
     document.forms[0].f_at_visible.value='<?php echo $f_at_visible2 ?>';
     document.forms[0].f_act.value='setVisibility';
     document.forms[0].submit();
  }
};

function finishPage() {
  var ok = true;
  /*
  if (!checkIsNaNIgnoreSpace(document.forms[0].f_at_bundlequantity.value, '<?php echo getLngt("Bitte tragen Sie eine Zahl bei der Verpackungsmenge ein!") ?>')) {ok = false;};
  */
  if (!checkIsNaNIgnoreSpace(document.forms[0].f_at_stk_itemquantity.value, '<?php echo getLngt("Bitte tragen Sie eine Zahl bei der Lagerartikelmenge ein!") ?>')) {ok = false;};
  if (!checkIsNaNIgnoreSpace(document.forms[0].f_at_stk_areaquantity.value, '<?php echo getLngt("Bitte tragen Sie eine Zahl bei der Lagerstellplatzbedarfsmenge ein!") ?>')) {ok = false;};

  if (ok) {
     document.forms[0].submit();
  }
};

function clearParent() {	
  document.forms[0].g2_at_id.value='';
  document.forms[0].g2_at_name.value='';
};

function searchAtg() {
  var f_act = 'search';
  
  var widthPopupWin = 500;
  var heightPopupWin = 700;
  var leftPopupWin = (screen.width / 2) - (widthPopupWin / 2) - 12;
  var topPopupWin = (screen.height / 2) - (heightPopupWin / 2) - 50;
  var popupWin;
  popupWin = window.open("../stock/atg_list.php?f_act=" + f_act + "&generic=1111",
    "","dependent=yes,width=" + widthPopupWin + ",height=" +
    heightPopupWin +",left=" + leftPopupWin + ",top=" + topPopupWin +
    ",scrollbars=yes");
};

function clearAtg() {	
  document.forms[0].g_atg_id.value='';
  document.forms[0].g_atg_key.value='';
  document.forms[0].g_atg_name.value='';
};

function searchMaxEID() {
  var maxvalue = document.forms[0].f_eid_maxval.value;
  if (confirm('<?php echo getLngt("Soll der Wert") ?> ' + maxvalue + ' <?php echo getLngt("übernommen werden?") ?>')) {
     document.forms[0].f_at_eid.value = maxvalue;
  };
};

function openPrintLayout() {
  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("../stock/article_special.php?articleId=" + f_at_id + "&printVersion=1","","dependent=yes,width=" + widthPopupWin + ",height=" + heightPopupWin +",left=" + leftPopupWin + ",top=" + topPopupWin + ",scrollbars=yes");
};

function openGroups(articleId) {
  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=at&itemId=" + articleId,"","dependent=yes,width=" + widthPopupWin + ",height=" + heightPopupWin +",left=" + leftPopupWin + ",top=" + topPopupWin + ",scrollbars=yes");
};

function clearBundleArticle(atId) {
  document.forms[0].f_bundlearticle_remove.value = atId;
  document.forms[0].f_act.value = 'removeBundleArticle';
  document.forms[0].submit();
};

function newBundleArticle(atId) {
  document.forms[0].f_act.value = 'newBundleArticle';
  document.forms[0].submit();
};
-->
</script>

</head>

<body class="menu_bgcol" onLoad="<?php echo $phpCurrentNavigationOnLoad ?><?php echo $javaScriptOut ?>displayStatusMessage();">

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

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

<form action="../stock/article_special.php" method="post">
  <input type="hidden" name="f_act" value="">
  <input type="hidden" name="articleId" value="<?php echo $articleId ?>">
  <input type="hidden" name="f_at_authenticated" value="<?php echo $f_at_authenticated ?>">
  <input type="hidden" name="f_at_visible" value="<?php echo $f_at_visible ?>">
  <input type="hidden" name="g_atg_id" value="<?php echo $g_atg_id ?>">
  <input type="hidden" name="f_eid_maxval" value="<?php echo $f_eid_maxval ?>">
  <?php echo $phpCurrentNavigationInputHidden ?>
  <input type="hidden" name="deactivateMenu" value="<?php echo ec($deactivateMenu) ?>">  
  <input type="hidden" name="f_bundlearticle_remove" value="">
  <input type="hidden" name="objecttypemode" value="<?php echo ec($objecttypemode) ?>">
  
  <?php echo htmlDivLineSpacer("10px"); ?>

  <div class="f10bp1_blue">
    <?php echo $title ?>&nbsp;&nbsp;&nbsp;<span class="f10bp1_red"><?php echo $displayTextAuthentication ?></span>
  </div>
  <?php echo htmlDivLineSpacer("20px"); ?>

  <div>
    <div <?php echo setStyleHtmlDiv("110px","left"); ?>><?php echo getLngt("Bezeichnung") ?>*:</div>
    <div>
      <div style="float:left">
        <input class="smaller" type="text" name="f_at_name" value="<?php echo $f_at_name ?>" maxlength="35" size="50" tabindex="10">
        <!-- <input class="smaller" type="text" name="f_at_name2" value="..." maxlength="35"  size="50" tabindex="20"> -->
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <?php echo getLngt("ExtID") ?>*:&nbsp;
      </div>
      <?php echo $f_at_eid_out ?>
    </div>
  </div>
  <?php echo htmlDivLineSpacer("5px", "", "left"); ?>
  
  <div>
    <div <?php echo setStyleHtmlDiv("110px","left"); ?>><?php echo getLngt("Zusatz:") ?></div>
    <div>
    	<input class="smaller" type="text" name="f_at_match" value="<?php echo $f_at_match ?>" maxlength="100" size="50" tabindex="10">
    </div>
  </div>
  <?php echo htmlDivLineSpacer("5px", "", "left"); ?>
  
  <div>
    <div <?php echo setStyleHtmlDiv("110px","left"); ?>><?php echo getLngt("Beschreibung:") ?></div>
    <div>
      <textarea class="smaller" name="f_at_description" cols="90" rows="1" tabindex="420"><?php echo $f_at_description ?></textarea>
    </div>
  </div>
  <?php echo htmlDivLineSpacer("5px", "", "left"); ?>
  
  <div>
    <div <?php echo setStyleHtmlDiv("110px","left"); ?>><?php echo getLngt(wrapPhrase("Warengruppe:", $objecttypemode)); ?></div>
    <div>
      <div style="float:left">
        <input class="smaller" type="text" name="g_atg_key" value="<?php echo $g_atg_key ?>" size="4" disabled >
        <input class="smaller" type="text" name="g_atg_name" value="<?php echo $g_atg_name ?>" size="15" disabled >
        &nbsp;
      </div>
      <?php echo defineButtonType08("...", "action_atg", "searchAtg();", "20", "left"); ?>
      <div style="float:left">
        &nbsp;
        <a href="javascript:clearAtg();" tabindex="330"><img src="../images/waste.png" border="0" height="15" width="12"></a>
      </div>
    </div>
  </div>
  <?php echo htmlDivLineSpacer("20px", "", "left"); ?>

  <div>
    <div <?php echo setStyleHtmlDiv("110px","left"); ?>><?php echo getLngt("Barcode:") ?></div>
    <div>
      <div style="float:left">
        <input class="smaller" type="text" name="f_at_barcode" value="<?php echo $f_at_barcode ?>" size="50">&nbsp;&nbsp;
      </div>
      <div>
      	<?php if ($f_at_barcode != "") : ?>
          <img src="../include/barcode_BCGcode39.php?text=<?php echo $f_at_barcode ?>">
        <?php endif; ?>
      </div>
    </div>
  </div>
  <?php echo htmlDivLineSpacer("20px", "", "left"); ?>

  <div>
    <div <?php echo setStyleHtmlDiv("110px","left"); ?>><?php echo getLngt("Seriennummern:") ?></div>
    <div>
      <div>
      	<input class="f8np1" type="checkbox" name="f_at_serialno[]" value="1" <?php echo $f_at_serialno_0 ?>>
      </div>
    </div>
  </div>
  <?php echo htmlDivLineSpacer("20px", "", "left"); ?>

  <div>
    <div <?php echo setStyleHtmlDiv("110px","left"); ?>><?php echo getLngt("Montierbar:") ?></div>
    <div>
      <div>
      	<input class="f8np1" type="checkbox" name="f_at_mountable[]" value="1" <?php echo $f_at_mountable_0 ?>>
      </div>
    </div>
  </div>
  <?php echo htmlDivLineSpacer("20px", "", "left"); ?>

  <div>
    <div <?php echo setStyleHtmlDiv("110px","left"); ?>><?php echo getLngt("Gebinde:") ?></div>
    <div>
      <div>
      	<?php echo getLngt("Anzahl Verpackungsstücke:") ?>&nbsp;
        <input class="smaller" type="text" name="f_at_bundlequantity" value="<?php echo $f_at_bundlequantity ?>" size="4" >
        &nbsp;&nbsp;
        <?php /*
        <?php echo getLngt("Gebindecode:") ?>&nbsp;
        <input class="smaller" type="text" name="f_at_bundlecode" value="<?php echo $f_at_bundlecode ?>" size="30" >
        */ ?>
      </div>
    </div>
  </div>
  <?php echo htmlDivLineSpacer("5px", "", "left"); ?>

  <div>
    <div <?php echo setStyleHtmlDiv("110px","left"); ?>>&nbsp;</div>
    <div>    	
      <?php echo $f_articlebundle ?>
    </div>
  </div>
  <?php echo htmlDivLineSpacer("20px", "", "left"); ?>


  <div>
    <div <?php echo setStyleHtmlDiv("110px","left"); ?>><?php echo getLngt("Lagereinheit:") ?></div>
    <div>
      <div style="float:left">
      	<?php getLngt(wrapPhrase("Anzahl Artikelstücke", $objecttypemode)); ?>*&nbsp;
        <input class="smaller" type="text" name="f_at_stk_itemquantity" value="<?php echo $f_at_stk_itemquantity ?>" size="4" >

        <?php if (false) : ?>
           <?php if ($f_at_bundlequantity > 1) : ?>
             &nbsp;(<?php echo round(($f_at_stk_itemquantity / $f_at_bundlequantity), 2); ?>&nbsp;<?php echo getLngt("Gebinde") ?>)
           <?php endif; ?>
        <?php endif; ?>

        &nbsp;&nbsp;
        <?php echo getLngt("benötigen Lagerplätze") ?>*
        &nbsp;&nbsp;
        <input class="smaller" type="text" name="f_at_stk_areaquantity" value="<?php echo $f_at_stk_areaquantity ?>" size="4" >
        &nbsp;&nbsp;<?php echo getLngt("(Stückzahl pro Lagerplätze)") ?>
      </div>
    </div>
  </div>
  <?php echo htmlDivLineSpacer("20px", "", "left"); ?>

  <div>
    <?php echo defineButtonType08(getLngt("Speichern"), "action_save", "document.forms[0].f_act.value='" . $f_actText . "';finishPage();", "90", "left", "3"); ?>
    <?php echo defineButtonType08(getLngt("Zurücksetzen"), "action_reset", "clearAllFields();", "90", "left", "3"); ?>
    <?php echo defineButtonType08(getLngt("Schließen"), "action_close", "window.close();", "90", "left", "3"); ?>
    <?php echo $buttonAuthentication ?>
    <?php echo $buttonVisibility ?>
    <?php echo defineButtonType08(getLngt("Gruppen"), "action_grp", "openGroups('" . ec($f_at_id) . "');", "90", "left", "3"); ?>
  </div>  


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

</html>
