<?php
/*=======================================================================
 *
 * stock_move.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", "cscIdCurrent", "statusMessage", "deactivateMenu",
                         "stkIdRoot", "stkIdCurrent", "f_mv_at", "f_mv_stk_itemquantity", 
                         "f_mv_stk_from", "f_mv_stk_to", "f_mv_tan", "f_mv_remark", 
                         "f_mv_serialno", "f_mv_jb_id",
                         "f_count", "f_count2",
                         "f_mv_search_stk_name_from", "f_mv_search_stk_name_to"));

// Id of the current employee and the costcenter (individual root-node) logged in
if ($cscIdRoot == ""): $cscIdRoot = getFieldValueFromId("employee","emp_id",$emp_id,"csc_id"); endif;
if ($customerId == ""): $customerId = getFieldValueFromId("costcenter","csc_id",$cscIdRoot,"cs_id"); endif;

// Get the rights of the employee logged in
$empRights = getRights($emp_id);

// Init
if ($cscIdCurrent == ""): $cscIdCurrent = $cscIdRoot; endif;
if ($hqId == ""): $hqId = $hq_id; endif;
if ($customerId == ""): $customerId = "0"; endif;

getLanguage(__FILE__);

// Attention: Definition AFTER definitions of $customerId, $cscIdRoot and $cscIdCurrent
$pageTitel = getLngt("GESAMMELTE LAGERBEWEGUNG");
$deactivateMenuStatic = "1";
include_once ("../admin/menu.php");
include_once ("../include/html.inc.php");
include_once ("../include/inc_stock.inc.php");
include_once ("../include/inc_article.inc.php");
getCurrentScript(__FILE__);

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

// Parameters have to exist for both: customer and headquarter
if (($userTypeName != "stk") && ($customerId == "" || $cscIdRoot == "" || $cscIdCurrent == "")) :
   die ("$PHP_SELF: Parameter fehlen!");
endif;

// Check authentication verifying emmployee an his/her costcenter- and customer-association
if ( !( ($userType == "1") || ($userType == "4") || authCheck($hq_id,$usr_id,$emp_id,$cscIdRoot,$customerId,$cscIdActual) ) ) :
   gotoReferer("1");
endif;


// Get right status of the current employee
$stockRight = false;
if ($userTypeName == "hq") :
   if (substr($empRights,14,1) == "1") : $stockRight = true; endif;
endif;

// Display area configuration for planning the stock capacities
if ($f_stk_planning == "" || count($f_stk_planning) == 0) :
   $f_stk_planning = "0";
else: 
   $f_stk_planning = "1";
endif;

// Enter the max quantity of the current stock
if ($f_stk_maxquantity == "") : $f_stk_maxquantity = "0"; endif;

// Name of the root stock
$stkNameRoot = getFieldValueFromId("stock","stk_id",$stkIdRoot,"stk_name");

// Name of the current bundle article
$atNameBundle = getFieldValueFromId("article","at_id",$f_mv_at,"at_name");

// Quantity of the bundle article (equals to the factor of each article bundled ...)
if ($f_mv_stk_itemquantity == "") :
   $f_mv_stk_itemquantity = 0;
endif;

// Check for incoming goods according to capacities if stock planning is active
$incoming = false;
$f_stk_planning = getFieldValueFromId("stock","stk_id",$stkIdRoot,"stk_planning");
if ($f_stk_planning == "1" && $f_mv_stk_to != "0") :
   $incoming = true;
endif;

// Check for outgoing goods according to existing quantities
$outgoing = false;
if ($f_mv_stk_from != "0") :
   $outgoing = true;
endif;

// Close current window automatically
$autoClose = "0";

/*
echo "customerId: " . $customerId . "<br><br>" . "stkIdRoot: " . $stkIdRoot . "<br>" . "stkIdCurrent: " . $stkIdCurrent . "<br>";
echo "stkNameCurrent: " . $stkNameCurrent . "<br>" . "stkPathCurrent: " . $stkPathCurrent . "<br>" . "nameStock: " . $nameStock . "<br><br>";
echo "Date range: " . $fromDateRange . " - " . $toDateRange . "<br>";
echo "f_act: " . $f_act . "<br>";
*/

if (true) :

   // Only it is possible to enable/disable the stock area planning for the whole tree
   $f_stk_planning = getFieldValueFromId("stock","stk_id",$stkIdRoot,"stk_planning");

   // *** Save the stock article movement (Begin) ***
   if ($f_act == "moveArticle") :

      if ($f_count > 0 && $f_count2 >= 0) :

         TA("B");                   
         $currentTime = getDateTime("0");
         $statusMessage = "";

         for ($i = 0; $i <= $f_count; $i++) :
           for ($j = 0; $j <= $f_count2; $j++) :
               getSecHttpVars("1",array("f_mv_stk_from_" . $i . "_" . $j, "f_mv_at_id_" . $i . "_" . $j, "f_mv_stk_itemquantity_" . $i . "_" . $j, "f_mv_stk_to_" . $i . "_" . $j, "f_mv_tan_" . $i . "_" . $j, "f_mv_remark_" . $i . "_" . $j, "f_mv_serialno_" . $i . "_" . $j, "f_mv_jb_id_" . $i . "_" . $j));

               $tmpQuantity = ${("f_mv_stk_itemquantity_" . $i . "_" . $j)};
               if ($tmpQuantity > 0) :
                  $tmpStkFrom  = ${("f_mv_stk_from_" . $i . "_" . $j)};
                  $tmpAtId     = ${("f_mv_at_id_" . $i . "_" . $j)};
                  $tmpStkTo    = ${("f_mv_stk_to_" . $i . "_" . $j)};
                  $tmpTan      = ${("f_mv_tan_" . $i . "_" . $j)};
                  $tmpRemark   = ${("f_mv_remark_" . $i . "_" . $j)};
                  $tmpSerialNo = ${("f_mv_serialno_" . $i . "_" . $j)};
                  $tmpJbId     = ${("f_mv_jb_id_" . $i . "_" . $j)};

                  $moveResult = stockMoveTA ($tmpStkFrom, $tmpStkTo, $tmpAtId, $tmpQuantity, $tmpTan, $tmpRemark, $tmpSerialNo, $tmpJbId, $usr_id, $f_mv_at, $currentTime);

                  if ($moveResult[0]) :
                      // TA executed
                      $f_mv_stk_itemquantity = 0;   // Reset quantity value (only for display)
                      $f_mv_tan = "";
                      $f_mv_remark = "";
                      $f_mv_serialno = "";
                  endif;
                  if (trim($moveResult[1]) != "") :
                     $tmpAtEid = getFieldValueFromId("article","at_id",$tmpAtId,"at_eid");
                     if ($statusMessage != "") : $statusMessage .= " / "; endif;
                     $statusMessage .= $tmpAtEid . ": " . $moveResult[1] . "  ";
                  endif;
               endif;
           endfor;
         endfor;
         
         $autoClose = "1";
         
         TA("C");
         TA("E");
      endif;
   endif;
   // *** Save the stock article movement (End) ***
   

   if ($autoClose == "0") :

      // **************************************************
      // * Get all articles of the current bundle article *
      // **************************************************
      
      // Get all articles by top-down recursion
      getTreeOfBundledArticles($f_mv_at, 0, 1);

      // --- DEBUG START --------------------------------------------------------------------------------
      if (false) :
         echo "<br>";
         echo "recurseCount: " . $recurseCount . "<br><br>";
         
         echo "atArray:<br>";
         $keys = array_keys($atArray);
         $keysLen = count($keys);
         for ($i = 0; $i < $keysLen; $i++) :
             $tmpAtId = $keys[$i];
             echo $tmpAtId . " : " .  $atArray[$tmpAtId] . "<br>";
         endfor;
         
         echo "----------------<br>";
      endif;
      // --- DEBUG END -----------------------------------------------------------------------------------

      // Iterate all item articles beeing in the bundle   
      $stockArticles = array();
      $out = "";
      $count = 0;
      $count2 = 0;
      $quantityStockSumNeeded = 0;
      $displayBacklog = false;
      $keys = array_keys($atArray);
      $keysLen = count($keys);   
      for ($i = 0; $i < $keysLen; $i++) :
          $tmpAtId = $keys[$i];
          $tmpQuantityOneBundle = $atArray[$tmpAtId];
          
          // ATTENTION: Multiply quantity of 1 bundled article by quantity of the whole bundle
          $tmpQuantity = $tmpQuantityOneBundle * $f_mv_stk_itemquantity;
      
          $atEid = getFieldValueFromId("article","at_id",$tmpAtId,"at_eid");
          $atName = getFieldValueFromId("article","at_id",$tmpAtId,"at_name");

          $tmpStockArticles = showStockArticles($stkIdCurrent, "1", "at.at_id = '" . $tmpAtId . "'", "stkat.stkat_itemquantity DESC");
          $stockArticles[] = $tmpStockArticles;

          $out .= "<div>\n";
          $out .= $tmpStockArticles;
          $out .= "</div>\n";
          $out .= "<div style=\"width:100%; height:5px;\"> </div>";
          $out .= "<div>\n";

          $stmtStockArticles = getStmtStockArticles ($stkIdCurrent, "1", "at.at_id ='" . $tmpAtId . "'", "stkat.stkat_itemquantity DESC") ;
          $result = $db->query($stmtStockArticles);     
          if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());       

          // Only if the current article has to go out of the stock then split per stocks and check for quantities !!!
          $tmpCount = 0;   // Count number of stock areas the current article will be found
          if ($outgoing) :
             // Iterate all stocks having this current article of the whole bundle
             // $tmpAtLeastOneStockHasEnoughQuantityOfRequestedQuantity = false;
             // $tmpSumOfStkatItemQuantity = 0;
             $tmpStockArticleArray = array();
             while ($row = $result->fetch_assoc()):
                $tmpStockArticleArray["stk_id"][$tmpCount] = $row["stk_id"];
         	      $tmpStockArticleArray["stk_name"][$tmpCount] = $row["stk_name"];
	              $tmpStockArticleArray["stkat_itemquantity"][$tmpCount] = $row["stkat_itemquantity"];

	              // $tmpSumOfStkatItemQuantity += $row["stkat_itemquantity"];

	              // if (!$tmpAtLeastOneStockHasEnoughQuantityOfRequestedQuantity && $row["stkat_itemquantity"] >= $tmpQuantity) :
                //    $tmpAtLeastOneStockHasEnoughQuantityOfRequestedQuantity = true;
	              // endif;

                $tmpCount++;
             endwhile;
             $result->free();
          endif;

          if ($incoming) :
             // Get the free places of the target stock according to the current article
             $stkQuantityFree = getFreeStkQuantity ($f_mv_stk_to, $tmpAtId, 0, "1");
      
             // Number of articles matching number of stock areas
             $atStkItemQuantity = getFieldValueFromId("article", "at_id", $tmpAtId, "at_stk_itemquantity");
             $atStkAreaQuantity = getFieldValueFromId("article", "at_id", $tmpAtId, "at_stk_areaquantity");
          endif;

          // Iterate until the whole requested quantity can be disposed          
          $restOfItemQuantity = $tmpQuantity;
          $count2 = max($count2, $tmpCount);
          for ($j = 0; $j <= $tmpCount; $j++) :

	            $tmpStockFromForDispose = $f_mv_stk_from;
	            if ($outgoing) :
	               $tmpStockFromForDispose = $tmpStockArticleArray["stk_id"][$j];
	            endif;

	            $out .= "<div>\n";

              $out .= "<select name=\"f_mv_stk_from_" . $i . "_" . $j . "\">";
              $out .= "  <option value=\"0\">" . getLngt("Eingangslieferung") . "</option>";
              $out .= addOptionsFromTable("stock","stk_id","stk_name","stk_name","stk_id = '" . $stkIdRoot . "' OR stk_path LIKE '%//" . $stkIdRoot . "//%'",$tmpStockFromForDispose);
              $out .= "</select>&nbsp;";

              $out .= "<select name=\"f_mv_stk_to_" . $i . "_" . $j . "\">";
              $out .= "  <option value=\"0\">" . getLngt("Ausgangslager") . "</option>";
              $out .= addOptionsFromTable("stock","stk_id","stk_name","stk_name","stk_id = '" . $stkIdRoot . "' OR stk_path LIKE '%//" . $stkIdRoot . "//%'",$f_mv_stk_to);
              $out .= "</select>&nbsp;";

              $out .= "<input type=\"hidden\" name=\"f_mv_at_id_" . $i . "_" . $j . "\" value=\"" . $tmpAtId . "\">&nbsp;";
              // $out .= "<input type=\"text\" name=\"f_mv_at_eid_" . $i . "\" value=\"" . $atEid . "\" size=\"10\" readonly disabled>&nbsp;";
              $out .= "<input type=\"text\" name=\"f_mv_at_name_" . $i . "_" . $j . "\" value=\"" . $atName . "\" size=\"20\" readonly disabled>&nbsp;";

	            $quantityToBeDisposed = $tmpQuantity;
	            if ($outgoing):
	               $quantityToBeDisposed = $tmpStockArticleArray["stkat_itemquantity"][$j];
	               if ($j < $tmpCount):
	                  $quantityToBeDisposed = min($restOfItemQuantity, $tmpStockArticleArray["stkat_itemquantity"][$j]);
	               endif;
              endif;

	            if ($incoming) :
                 // Get the free places of the target stock according to the current article
                 $stkItemQuantityFree = getFreeStkQuantity($f_mv_stk_to, $tmpAtId, $quantityToBeDisposed, "2");
                                  
                 $stkQuantityNeeded = ceil(($quantityToBeDisposed * $atStkAreaQuantity) / $atStkItemQuantity);
                 
                 // Sum up all quantities
                 $quantityStockSumNeeded += $stkQuantityNeeded;

                 if ($stkQuantityFree < $quantityStockSumNeeded) :
                    $quantityToBeDisposed = 0;
                    $displayBacklog = true;
                 endif;
	            endif;

	            if ($quantityToBeDisposed == "") : $quantityToBeDisposed = 0; endif;
              $out .= "<input type=\"text\" name=\"f_mv_stk_itemquantity_" . $i . "_" . $j . "\" value=\"" . $quantityToBeDisposed . "\" size=\"5\">&nbsp;";

	            $restOfItemQuantity = $restOfItemQuantity - $tmpStockArticleArray["stkat_itemquantity"][$j];

              // If stock movement is an outgoing transaction then display available quantity (sum of stocks)
              if ($outgoing && $j == $tmpCount) :
	               if ($restOfItemQuantity > 0) :
	                  $out .= "<span class=\"f8np1_red\">" . getLngt("nicht verfügbar:") . "&nbsp;" . $restOfItemQuantity . "</span>&nbsp;&nbsp;";
	                  $out .= "<span class=\"f8np1_red\">" . getLngt("von:") . "&nbsp;" . $tmpQuantity . "</span>&nbsp;&nbsp;";
	                  $out .= "<span class=\"f8np1_red\">(" . $tmpQuantityOneBundle . "&nbsp;x&nbsp;" . $f_mv_stk_itemquantity . ")</span>&nbsp;&nbsp;";
	               endif;
              endif;
              
              if ($incoming && $displayBacklog) :
                 $out .= "<span class=\"f8np1_red\">" . getLngt("Überhang auf dem Ziellager:") . "&nbsp;" . abs($stkQuantityFree - $quantityStockSumNeeded) . "&nbsp;" . getLngt("Stellplätze") . "</span>&nbsp;&nbsp;";
              endif;

              $out .= "</div>\n";
              $out .= "<div style=\"width:100%; height:15px;\"> </div>";

	            if ($restOfItemQuantity <= 0) :
	               break;
	            endif;
          endfor;
          $out .= "<div style=\"width:100%; height:20px;\"> </div>"; 

          $count++;
      endfor;
   endif;  // $autoClose == "0"
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/lib_global.js" type="text/javascript"></script>
<script src="../include/searchLists.js" type="text/javascript"></script>
<script src="../include/checkFormTags.js" type="text/javascript"></script>

<script type="text/javascript">
<!--
var autoClose = '<?php echo $autoClose ?>';
if (autoClose == '1') {
	opener.document.forms[0].statusMessage.value = '<?php echo $statusMessage ?>';
	opener.stkFinishPage('journalSearch');
	this.window.close();
};

// NAVIGATION
<?php echo $jsMenuOut; ?>

function stkFinishPage(f_act) {
  document.forms[0].f_act.value=f_act;
  if (document.forms[0].currentNavigationItem) {
     document.forms[0].currentNavigationItem.value='lager';
  }
  document.forms[0].submit();
}

function articleMoveFinishPage() {
  stkFinishPage('moveArticle');
}


// ********
// * AJAX *
// ********

// Init
var stkIdRoot = '<?php echo $stkIdRoot ?>';
var listLenth;
var stkIdList;
var stkNameList;
var stkBarcodeList;
var scanCodeIsSerialNo = false;
var scanCodeIsArticleBarcode = false;
var scanCodeIsStockBarcode = false;
var stkMvData = new textlist ();
var stkMvArticleData = new textlist ();
var stkMvStockData = new textlist ();

// Init global JS-parameters
function initGlobals () {
  scanCodeIsSerialNo = false;
  scanCodeIsArticleBarcode = false;
  scanCodeIsStockBarcode = false;
  stkMvData = new textlist ();
  stkMvArticleData = new textlist ();
  stkMvStockData = new textlist ();
}

function scan_request(specificURL, parms) {
    var myAjax = new Ajax.Request(
        specificURL,        
        {method: 'get', asynchronous: false, parameters: parms}
    );
    eval(myAjax.transport.responseText);
}

function executeScanCode() {
	frm = document.forms[0];
  var elem = document.forms[0].f_scan;
  var ev = elem.value;

  // Init Ajax call ...
  scan_request('../stock/ajaxReqScanExecution.php', 'mode=0');

  // Check command
  if (ev == '') {
  	 return;
  } else if (ev == 'MV-IN') {
  	 // Incoming goods
  	 frm.f_stkat_scanmode[0].checked = true;
  } else if (ev == 'MV-OUT') {
  	 // Outgoing goods
  	 frm.f_stkat_scanmode[1].checked = true;
  } else if (ev == 'MV-DISPOSAL') {
  	 // Disposal
     articleMoveFinishPage();
  } else if (ev == 'MV-QUANTITY') {
  	 // Set quantity field (source f_store)
     frm.f_mv_stk_itemquantity.value = frm.f_store.value;
     frm.f_store.value = '';
  } else if (ev == 'MV-TAN') {
  	 // Set tan field (source f_store)
     frm.f_mv_tan.value = frm.f_store.value;
     frm.f_store.value = '';
  } else if (ev == 'MV-REMARK') {
  	 // Set remark field (source f_store)
     frm.f_mv_remark.value = frm.f_store.value;
     frm.f_store.value = '';
  } else if (ev == 'MV-SERNO') {
  	 // Set serial number field (source f_store)
     frm.f_mv_serialno.value = frm.f_store.value;
     frm.f_store.value = '';
  } else if (ev == 'MV-JOB') {
  	 // Set serial number field (source f_store)
     frm.f_mv_jb_id.value = frm.f_store.value;
     frm.f_store.value = '';
     if (frm.f_mv_jb_id.value.length > 0) {
        $('mvJobId').setStyle({borderColor: '#FF0000', borderWidth: '2px', borderStyle: 'solid', padding: '4px'});
     };
  } else if (ev == 'MV-OPENJOBS') {
  	 frm.f_store.value = '';
     openCurrentListOfStockJobs();
  } else if (ev == '-0-' || ev == '-1-' || ev == '-2-' || ev == '-3-' || ev == '-4-' ||
             ev == '-5-' || ev == '-6-' || ev == '-7-' || ev == '-8-' || ev == '-9-') {
  	 // Number
	 var numCmd = ev.substr(1, 1);
	 frm.f_store.value = frm.f_store.value + numCmd;
  } else if (ev == '-BACK-') {
  	 // Remove last character
     var tmpLen = frm.f_store.value.length;
     tmpLen = tmpLen - 1;
     frm.f_store.value = frm.f_store.value.substr(0, tmpLen);
  } else if (ev == '-CLR-') {
  	 // Remove last character
     frm.f_store.value = '';
  } else {

  	 // **********************
     // *** INCOMING GOODS ***
     // **********************

     if (frm.f_stkat_scanmode[0].checked == true) {
  	    // First check scan value is an article barcode
	      scan_request('../stock/ajaxReqScanExecution.php', 'mode=2&scanCode=' + ev);

  	    if (!scanCodeIsArticleBarcode) {  	    	  	    	
  	       // Check scan value is a stock barcode.
	         scan_request('../stock/ajaxReqScanExecution.php', 'mode=3&scanCode=' + ev + '&stkIdRoot=' + stkIdRoot);
  	    }

  	    if (!scanCodeIsArticleBarcode && !scanCodeIsStockBarcode) {
  	       // Check scan value is a serial no.
	         scan_request('../stock/ajaxReqScanExecution.php', 'mode=1&scanCode=' + ev);
  	    }
  	    
  	    if (!scanCodeIsArticleBarcode && !scanCodeIsStockBarcode && !scanCodeIsSerialNo) {
  	       // Store unknown scanned barcode to storage
	         frm.f_store.value = frm.f_scan.value;
  	    }

  	    // Execute if an article does exist according to the barcode
  	    if (scanCodeIsArticleBarcode) {
  	    	  // Prepare article search in all stocks
  	    	  // Execute after reload
  	    	  frm.js_execute_cmd.value = '2';
  	    	  frm.js_execute_data.value = stkMvArticleData[0];  // Article ID
  	    	  
  	    	  // Display the stock articles, filtered accorting to this specified article
  	    	  frm.maskDisplayArticleSwitch.value = '1';
  	    	  
  	    	  // Set current stock to root stock (top level)
  	    	  frm.stkIdCurrent.value = stkIdRoot;
  	    	  
  	    	  // Show ALL stocks (whole tree)
            for(i=0;i<frm.f_displayModeStockArticle.length;++i) {
               if (frm.f_displayModeStockArticle.options[i].value == '1') {
                  frm.f_displayModeStockArticle.options[i].selected = true;
               }
            }

            if (stkMvArticleData[0]!= '') {
               for(i=0;i<frm.f_mv_at.length;++i) {
                 if (frm.f_mv_at.options[i].value == stkMvArticleData[0]) {
                    frm.f_mv_at.options[i].selected = true;
                 }
               }
            }

  	    	  // Reload page
  	    	  stkFinishPage('');
        }

        // Execute if a stock does exist according to the barcode
        if (scanCodeIsStockBarcode) {
  	    	  // Prepare stock search
  	    	  // Execute after reload
  	    	  frm.js_execute_cmd.value = '3';
  	    	  frm.js_execute_data.value = stkMvArticleData[0];  // Stock ID
  	    	  
            if (stkMvStockData[0]!= '') {
               for(i=0;i<frm.f_mv_stk_to.length;++i) {
                 if (frm.f_mv_stk_to.options[i].value == stkMvStockData[0]) {
                    frm.f_mv_stk_to.options[i].selected = true;
                 }
               }
            }

  	    	  // Set current stock to the selected stock
  	    	  frm.stkIdCurrent.value = stkMvStockData[0];
  	    	  
  	    	  // Show ONLY current stock
            for(i=0;i<frm.f_displayModeStockArticle.length;++i) {
               if (frm.f_displayModeStockArticle.options[i].value == '0') {
                  frm.f_displayModeStockArticle.options[i].selected = true;
               }
            }
  	    	  
  	    	  // Reload page
  	    	  stkFinishPage('');
        }
     }
     
     // **********************
     // *** OUTGOING GOODS ***
     // **********************
     
     if (frm.f_stkat_scanmode[1].checked == true) {
  	    // First check scan value is a serial no.  	 
	      scan_request('../stock/ajaxReqScanExecution.php', 'mode=1&scanCode=' + ev);

  	    if (!scanCodeIsSerialNo) {
  	       // Check scan value is an article barcode
	         scan_request('../stock/ajaxReqScanExecution.php', 'mode=2&scanCode=' + ev);
  	    }

  	    if (!scanCodeIsSerialNo && !scanCodeIsArticleBarcode) {
  	       // Check scan value is a serial no.
	         scan_request('../stock/ajaxReqScanExecution.php', 'mode=3&scanCode=' + ev + '&stkIdRoot=' + stkIdRoot);
  	    }

  	    if (!scanCodeIsArticleBarcode && !scanCodeIsStockBarcode && !scanCodeIsSerialNo) {
  	       // Store unknown scanned barcode to storage
	         frm.f_store.value = frm.f_scan.value;
  	    }

  	    // Execute if a serial number does exist
  	    if (scanCodeIsSerialNo) {
  	    	 // *** Fill fields for the article movement ***
  	    	  
  	    	 // Execute after reload
  	    	 frm.js_execute_cmd.value = '1';
  	    	 frm.js_execute_data.value = stkMvData[5];  // Serial number
  	    	  
           // Switch incoming journal stock (stk_to) to the outgoing stock of the new movement (stk_from)
  	    	 if (stkMvData[3]!= '') {
              for(i=0;i<frm.f_mv_stk_from.length;++i) {
                if (frm.f_mv_stk_from.options[i].value == stkMvData[3]) {
                   frm.f_mv_stk_from.options[i].selected = true;
                }
              }
           }
           if (stkMvData[2]!= '') {
              for(i=0;i<frm.f_mv_at.length;++i) {
                if (frm.f_mv_at.options[i].value == stkMvData[2]) {
                   frm.f_mv_at.options[i].selected = true;
                }
              }
           }
           // if (stkMvData[3]!= '') {
              for(i=0;i<frm.f_mv_stk_to.length;++i) {
                if (frm.f_mv_stk_to.options[i].value == '0') {
                   frm.f_mv_stk_to.options[i].selected = true;
                }
              }
           // }
           // frm.f_mv_stk_itemquantity.value = '';
           frm.f_mv_tan.value = stkMvData[4];
           // frm.f_mv_remark.value = '';
           frm.f_mv_serialno.value = stkMvData[5];
        
  	    	  // Reload page
  	    	  stkFinishPage('');
  	    }

  	    // Execute if an article does exist according to the barcode
  	    if (scanCodeIsArticleBarcode) {
  	    	  // Prepare article search in all stocks
  	    	  // Execute after reload
  	    	  frm.js_execute_cmd.value = '2';
  	    	  frm.js_execute_data.value = stkMvArticleData[0];  // Article ID
  	    	  
  	    	  // Display the stock articles, filtered accorting to this specified article
  	    	  frm.maskDisplayArticleSwitch.value = '1';
  	    	  
  	    	  // Set current stock to root stock (top level)
  	    	  frm.stkIdCurrent.value = stkIdRoot;
  	    	  
  	    	  // Show ALL stocks (whole tree)
            for(i=0;i<frm.f_displayModeStockArticle.length;++i) {
              if (frm.f_displayModeStockArticle.options[i].value == '1') {
                 frm.f_displayModeStockArticle.options[i].selected = true;
              }
            }

           // Set outgoing stock of the new movement (stk_from = '0')
  	    	 // if () {
              for(i=0;i<frm.f_mv_stk_to.length;++i) {
                if (frm.f_mv_stk_to.options[i].value == '0') {
                   frm.f_mv_stk_to.options[i].selected = true;
                }
              }
           // }

           if (stkMvArticleData[0]!= '') {
              for(i=0;i<frm.f_mv_at.length;++i) {
                if (frm.f_mv_at.options[i].value == stkMvArticleData[0]) {
                   frm.f_mv_at.options[i].selected = true;
                }
              }
           }
  	    	  
  	    	  // Reload page
  	    	  stkFinishPage('');
        }
        
        // Execute if a stock does exist according to the barcode
        if (scanCodeIsStockBarcode) {
  	    	  // Prepare stock search
  	    	  // Execute after reload
  	    	  frm.js_execute_cmd.value = '3';
  	    	  frm.js_execute_data.value = stkMvArticleData[0];  // Stock ID
  	    	  
            if (stkMvStockData[0]!= '') {
               for(i=0;i<frm.f_mv_stk_from.length;++i) {
                 if (frm.f_mv_stk_from.options[i].value == stkMvStockData[0]) {
                    frm.f_mv_stk_from.options[i].selected = true;
                 }
               }
            }

  	    	  // Set current stock to the selected stock
  	    	  frm.stkIdCurrent.value = stkMvStockData[0];
  	    	  
  	    	  // Show ONLY current stock
            for(i=0;i<frm.f_displayModeStockArticle.length;++i) {
               if (frm.f_displayModeStockArticle.options[i].value == '0') {
                  frm.f_displayModeStockArticle.options[i].selected = true;
               }
            }
  	    	  
  	    	  // Reload page
  	    	  stkFinishPage('');
        }
     }
/*
  } else if (stkIdRoot != '') {
  	 evuc = ev.toUpperCase();
     scan_request('../stock/ajaxReqScanExecution.php?stkIdRoot=' + stkIdRoot, '');
     if (listLenth && listLenth > 0) {
        for(i=0; i<listLenth; ++i) {
          if (evuc == stkBarcodeList[i]) {
          	 frm.f_stk_id.value = stkIdList[i];
          	 frm.f_stk_name.value = stkNameList[i];
          }
        }
     }
*/     
  }
  // Init global JS
  initGlobals();
  
  elem.value = '';  
  $('f_scan').focus();
}

function setScanFocus() {
  if ($('f_scan')) {
     $('f_scan').focus();
  }
}


// *** Handling of jobs ***

function openCurrentListOfStockJobs() {
  var widthPopupWin = 900;
  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/stock_jobs.php?stkIdRoot=" + stkIdRoot + "&deactivateMenu=1",
    "","dependent=yes,width=" + widthPopupWin + ",height=" +
    heightPopupWin +",left=" + leftPopupWin + ",top=" + topPopupWin +
    ",scrollbars=yes");
};

function clearJob() {	
  document.forms[0].f_mv_jb_id.value='';
};
-->
</script>

<?php echo $js_date ?>

</head>

<body onLoad="<?php echo $phpCurrentNavigationOnLoad ?>displayStatusMessage();setScanFocus();">

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

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

<form name="stock" action="../stock/stock_move.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="cscIdCurrent" value="<?php echo ec($cscIdCurrent) ?>">
  <input type="hidden" name="cscNameCurrent" value="<?php echo $cscNameCurrent ?>">
  <input type="hidden" name="stkIdRoot" value="<?php echo ec($stkIdRoot) ?>">
  <?php echo $phpCurrentNavigationInputHidden ?>
  <input type="hidden" name="deactivateMenu" value="<?php echo ec($deactivateMenu) ?>">
  <input type="hidden" name="js_execute_cmd" value="">
  <input type="hidden" name="js_execute_data" value="">  
  <input type="hidden" name="f_mv_at" value="<?php echo ec($f_mv_at) ?>">
  <input type="hidden" name="f_count" value="<?php echo ec($count) ?>">
  <input type="hidden" name="f_count2" value="<?php echo ec($count2) ?>">
  
  <?php echo htmlDivLineSpacer("10px"); ?>
  
  <div class="f10bp1_blue">
    <div style="float:left">
       <?php echo getLngt("Aktuelles Lager:") ?>&nbsp;<span class="f10bp1_red"><?php echo $stkNameRoot ?></span>
       &nbsp;&nbsp;&nbsp;&nbsp;
       <?php echo getLngt("Aktueller Gebindeartikel:") ?>&nbsp;<span class="f10bp1_red"><?php echo $atNameBundle ?></span>
       &nbsp;&nbsp;&nbsp;&nbsp;
       <?php echo getLngt("Angeforderte Gebindebuchungsmenge:") ?>&nbsp;<span class="f10bp1_red"><?php echo $f_mv_stk_itemquantity ?></span>
    </div>

  <?php echo htmlDivLineSpacer("5px", "", "left"); ?>
  <?php echo htmlDivLineSpacer("1px","100%","","1"); ?>
  <?php echo htmlDivLineSpacer("5px"); ?>
  
  <?php echo htmlDivLineSpacer("10px"); ?>

    
  <!-- STOCK ARTICLES AND STOCKMOVES -->
  
  <?php echo $out; ?>
  
  <?php echo htmlDivLineSpacer("20px"); ?>
    
  <?php echo defineButtonType10(getLngt("Disponieren"), "action_move", "articleMoveFinishPage();", "150", "left", "10") ?>
  
  <?php echo defineButtonType10(getLngt("Schließen"), "action_close", "window.close();", "155"); ?>

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

  <!-- BARCODE SCAN -->
  <?php echo htmlDivLineSpacer("20px", "", "left"); ?> 
  <div style="width:600px; border: 3px;border-color:#FF0000; border-style:solid; padding: 10px; margin: 0px;"> 
      <div class="f10bp1_blue" style="float:left; vertical-align:middle;" valign="center">
        <?php echo getLngt("BARCODE-SCAN:") ?>&nbsp;<input type="text" id="f_scan" name="f_scan" value="" size="20" onblur="javascript:executeScanCode();" border="2">&nbsp;&nbsp;&nbsp;
      </div>
      <div class="f10bp1" style="vertical-align:middle;" valign="center">
        <?php echo getLngt("Zwischenspeicher:") ?>&nbsp;<input type="text" id="f_store" name="f_store" value="" size="20" onfocus="javascript:setScanFocus();">&nbsp;&nbsp;
      </div>
  </div> 
  <?php echo htmlDivLineSpacer("10px", "", "left"); ?> 


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

</html>