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


include_once ("../include/mcglobal.inc.php");
include_once ("../include/caglobal.inc.php");    // For pricing and invoice-text only
// include_once ('../include/email/htmlMimeMail.php');
include_once ("../include/services_func.inc.php");
include_once ("../include/inc_parseXML.inc.php");
include_once ("../include/inc_mtf_func.inc.php");
include_once ("../include/inc_customer.inc.php");
include_once ("../include/inc_job.inc.php");
include_once ("../include/inc_vehicle.inc.php");
include_once ("../include/inc_disposition.inc.php");
// include_once ("../include/inc_disposition_DEV.inc.php");
// include_once ("../geo/geocode.inc.php");


// Write logdata into log file
$currentTime = getDateTime("0");
$currentDate = getDateTime("3");

$debug = false;
$debugOut = "";

// $orderReq = file_get_contents('php://input');

// Check HTTP-Parameters
getSecHttpVars("1",array("f_act", "orderReq", "selectedLanguage"));


function orderRequestLogFile ($msg, $logLevel = 0) {
  XMLRequestLogFile($msg, $logLevel, $logFile = "orderReq.log");
}


$orderReq = urldecode($orderReq);
$orderReq = mcEncode($orderReq);
// echo $orderReq . "<br><br>";

orderRequestLogFile($currentTime);
orderRequestLogFile($orderReq);


if ($selectedLanguage == "" || !is_numeric($selectedLanguage)) : $selectedLanguage = "1"; endif;  // Default in English
$languageSelected = $selectedLanguage;

getLanguage(__FILE__);
getCurrentScript(__FILE__);

$err = array();
$outResponse = "";
$acceptOrder = true;

// ---------------------------------------------------------------------------

// GLOBAL MODE OF USAGE
$globalParUseRelatedCustomer = getParameterValue("0", "GLOBAL_USE_RELATED_CUSTOMER", "0");

// *** Init ***
$maxNumOfOrdersPerDay = 200;
$maxNumOfRunningOrders = 1000;
$hqId = "";
$usr_id = "";
$jbStatus = "9";
$jbType = "";
$jbTourname = "";
$fixprice = 0;
$cmpPostage = 0;
$csInvmode = "";
$jbService = 1;
$jbTimeUnits = 2;
$txId = "4";
$txValue = getFieldValueFromId("tax","tx_id",$txId,"tx_value");
$txSign = getFieldValueFromId("tax","tx_id",$txId,"tx_sign");
if ($globalParUseRelatedCustomer == "1") :
   $txValue = $txId;
   $txSign = "";
endif;
$trServicesArray = array();             // All station services and prices of all tour stations for calling price function
$trArticleArray = array();              // All articles (per station)
$trCalcFunctionsArray = array();        // All calculator functions (per station)
$trCalcFunctionsResultArray = array();  // All calculator function results (per station)
$gHqId = true;                          // Needed for calculator functions

// *** Parse request ***
$orderArray = xml2array($orderReq);
if ($debug) :
   // print_r($orderArray); echo "<br><br><br>";
endif;

// *** Convert result array to usable parameters ***
// Authentication data
$csEid          = convertSpecial($orderArray["xml"]["order"]["auth"]["customer"]);
$csId           = getFieldValueFromId("customer","cs_eid",$csEid,"cs_id");
$usrAccount     = convertSpecial($orderArray["xml"]["order"]["auth"]["account"]);
$usrPassword    = convertSpecial($orderArray["xml"]["order"]["auth"]["password"]);
$sessionId      = convertSpecial($orderArray["xml"]["order"]["auth"]["session_id"]);
// Optional customer group data (needed to find e.g. an article price automatically). Has to be set explicitly, because a customer could belong to more groups !!!!
$csGroupId      = convertSpecial($orderArray["xml"]["order"]["auth"]["group_no"]);
$csGroupName    = convertSpecial($orderArray["xml"]["order"]["auth"]["group_name"]);
if ($csGroupId != "" && is_numeric($csGroupId)) :
   $csGroupName = getFieldValueFromId("groups","grp_id",$csGroupId,"grp_name");
elseif ($csGroupName != "") :
   $csGroupId = getFieldValueFromId("groups","grp_name",$csGroupName,"grp_id");
endif;
// Reset customer group data if it could not be identified
if ($csGroupId == "" || $csGroupName == "") :
   $csGroupId = "";
   $csGroupName = "";
endif;

$debugOut .= "usrAccount: " . $usrAccount . "<br>\n";
$debugOut .= "usrPassword: " . $usrPassword . "<br>\n";
$debugOut .= "usrPassword: " . $usrPassword . "<br>\n";
$debugOut .= "sessionId: " . $sessionId . "<br>\n";

if (checkRequestAuthenticationData($usrAccount, $usrPassword, $sessionId, $csId)) :
   $debugOut .= "Authentication okay!<br><br>\n";

   // Data
   $hqId            = getFieldValueFromId("customer","cs_id",$csId,"hq_id");
   $cscName         = convertSpecial($orderArray["xml"]["order"]["auth"]["costcenter_name"]);
   $cscId = "";
   if ($cscName != "") :
      $cscId        = getFieldValueFromClause("costcenter","csc_id","cs_id = '" . $csId . "' AND csc_name = '" . $cscName . "'");
   endif;
   if ($cscId == "" || !is_numeric($cscId)) :
      $cscId        = getFieldValueFromClause("costcenter","csc_id","cs_id = '" . $csId . "' AND isnull(csc_pre_id)");   // Root costcenter
   endif;

   // Get current headquarters instance
   $parHqInstance = getParameterValue("0", "HQ_INSTANCE", $hqId);

   // Check disposition mode related to the vehicle state. If enabled then "jb_status" will be set to "0" if vehicle is blocked for the vehicle for the day.
   $dispositionJbStatusMode = getParameterValue("0", "DISPOSITION_JB_STATUS_MODE", $hqId);
   if ($dispositionJbStatusMode == "") : $dispositionJbStatusMode = getParameterValue("0", "DISPOSITION_JB_STATUS_MODE", "0"); endif;
   if ($dispositionJbStatusMode == "") : $dispositionJbStatusMode = "0"; endif;

   // Payer versus related
   $cscIdPayer = $cscId;
   $cscIdRelated = "0";
   $csIdRelated = "0";
   $jbRelevantCostcenterField = "csc_id_payer";
   if ($globalParUseRelatedCustomer == "1") :
      $cscIdPayer = "0";       // Set below by inserting the new customer costcenter
      $cscIdRelated = $cscId;  // The authenticated customer will be the related customer and the end customer will be the payer (look below) !!!!
      $csIdRelated = getFieldValueFromId("costcenter","csc_id",$cscIdRelated,"cs_id");
      $jbRelevantCostcenterField = "csc_id_related";
   endif;

   $operationMode = convertSpecial($orderArray["xml"]["order"]["operation"]);  // "UPD" = UPDATE, "DEL" = DELETE, "INS" (or empty or any value) = INSERT
   $debugOn       = convertSpecial($orderArray["xml"]["order"]["debug_on"]);
   $commissionNo  = convertSpecial($orderArray["xml"]["order"]["no"]);
   $commNoRelated = convertSpecial($orderArray["xml"]["order"]["no_related"]);
   if ($commNoRelated == $commissionNo) :
      $commNoRelated = "";  // No cycle "jb_id == jb_id_parent" !!!!
   endif;
   $commNoMerged  = convertSpecial($orderArray["xml"]["order"]["no_merged"]);
   $commNoService = convertSpecial($orderArray["xml"]["order"]["no_service"]);

   // Check commission number regarding existence
   $checkExistenceCommissionNo = getParameterValue("0", "ORDER_REQUEST_CHECK_EXISTENCE_COMMISSION_NO", $hqId);
   if ($checkExistenceCommissionNo == "") : $checkExistenceCommissionNo = getParameterValue("0", "ORDER_REQUEST_CHECK_EXISTENCE_COMMISSION_NO", "0"); endif;

if (!$debug && $debugOn == "ON" || $debugOn == "YES") :
   $debug = true;
endif;

   // Check existence of commission number
   if ($checkExistenceCommissionNo == "1") :
       // Get num of stations the commission number is associated to
       $numOfRows = getCountOfTable("tour", "tr_commission_no = '" . $commissionNo . "'");

       // If the sender does not know the order is an "INS" or "UPD" operation then always "UPD" will be sent.
       // If the (unique) commission number check for existence is activated then the decision will be made here for the order to be an "UPD" or "INS"
       $checkOperationForExistingCommissionNo = getParameterValue("0", "ORDER_REQUEST_CHECK_OPERATION_EXISTENCE_COMMISSION_NO", $hqId);
       if ($checkOperationForExistingCommissionNo == "") : $checkOperationForExistingCommissionNo = getParameterValue("0", "ORDER_REQUEST_CHECK_OPERATION_EXISTENCE_COMMISSION_NO", "0"); endif;

       if ($checkOperationForExistingCommissionNo == "1") :
          // The commission number does exist, wrap "UPD" to "INS" 
          if ($operationMode == "UPD" || $operationMode == "UPDATE") :
             if ($numOfRows == "0") :
                $operationMode = "INS";
             endif;
          endif;
       else :
          // Standard check for existing commission number
          if ($operationMode == "" || $operationMode == "INS" || $operationMode == "INSERT") :
             if ($numOfRows != "" && $numOfRows > 0) :
                $err[] = array("100", getLngt("Die eindeutige Kommissionsnummer existiert schon. Der neue Auftrag kann nicht geschrieben werden."));
                $acceptOrder = false;
             endif;
          endif;
       endif;
   endif;

   // Get related (parent/delivery) job ID by order number
   $jbIdParent = "";
   if ($commNoRelated != "") :
      $parNoRelated = getObjectBasedParameterValue("ORDER_REQUEST_NO_RELATED_MODE", $csId, $hqId);
      if ($parNoRelated == "1") :
         // Overrule with related order number from GDC field "info_0" because <no> (<=> $commissionNo) contains the shipment NO
         $jbIdParent = getOneStmt("SELECT jb.jb_id AS jb_id FROM genericdatacontainer AS gdc, job AS jb, costcenter AS csc WHERE gdc.gdc_obj_type = 'jb' AND gdc.gdc_gen_fieldname = 'info_0' AND gdc.gdc_content = '" . $commNoRelated . "' AND gdc.gdc_obj_id = jb.jb_id AND jb." . $jbRelevantCostcenterField . " = csc.csc_id AND csc.cs_id = '" . $csId . "' ORDER BY jb.jb_id DESC", "jb_id");
      elseif ($parNoRelated == "2") :
         $jbIdParent = $commNoRelated;
      else :
         // DEFAULT: Remote order number equals commission number
         $jbIdParent = getOneStmt("SELECT jb.jb_id AS jb_id FROM tour AS tr, job AS jb, costcenter AS csc WHERE tr.tr_commission_no = '" . $commNoRelated . "' AND tr.jb_id = jb.jb_id AND jb." . $jbRelevantCostcenterField . " = csc.csc_id AND csc.cs_id = '" . $csId . "'", "jb_id");
      endif;
   endif;

   // Get merged job ID by merged order number
   $jbIdMerged = "";
   if ($commNoMerged != "") :
      $parNoMerged = getObjectBasedParameterValue("ORDER_REQUEST_NO_MERGED_MODE", $csId, $hqId);
      if ($parNoMerged == "1") :
         $jbIdMerged = getOneStmt("SELECT jb.jb_id AS jb_id FROM genericdatacontainer AS gdc, job AS jb, costcenter AS csc WHERE gdc.gdc_obj_type = 'jb' AND gdc.gdc_gen_fieldname = 'info_0' AND gdc.gdc_content = '" . $commNoMerged . "' AND gdc.gdc_obj_id = jb.jb_id AND jb." . $jbRelevantCostcenterField . " = csc.csc_id AND csc.cs_id = '" . $csId . "' ORDER BY jb.jb_id DESC", "jb_id");
      elseif ($parNoMerged == "2") :
         $jbIdMerged = $commNoMerged;
      else :
         $jbIdMerged = getOneStmt("SELECT jb.jb_id AS jb_id FROM tour AS tr, job AS jb, costcenter AS csc WHERE tr.tr_commission_no = '" . $commNoMerged . "' AND tr.jb_id = jb.jb_id AND jb." . $jbRelevantCostcenterField . " = csc.csc_id AND csc.cs_id = '" . $csId . "'", "jb_id");
      endif;
   endif;

   // Get job ID to be UPDATED by order number
   $jbIdUpdate = "";
   $parNoUpdate = getObjectBasedParameterValue("ORDER_REQUEST_NO_UPDATE", $csId, $hqId);
   if ($operationMode == "UPD" || $operationMode == "UPDATE") :
      if ($parNoUpdate == "1") :
         $jbIdUpdate = getOneStmt("SELECT jb.jb_id AS jb_id FROM genericdatacontainer AS gdc, job AS jb, costcenter AS csc WHERE gdc.gdc_obj_type = 'jb' AND gdc.gdc_gen_fieldname = 'info_0' AND gdc.gdc_content = '" . $commissionNo . "' AND gdc.gdc_obj_id = jb.jb_id AND jb." . $jbRelevantCostcenterField . " = csc.csc_id AND csc.cs_id = '" . $csId . "'", "jb_id");
      elseif ($parNoUpdate == "2") :
         $jbIdUpdate = $commissionNo;
      else :
         // DEFAULT: Remote order number equals commission number
         $jbIdUpdate = getOneStmt("SELECT jb.jb_id AS jb_id FROM tour AS tr, job AS jb, costcenter AS csc WHERE tr.tr_commission_no = '" . $commissionNo . "' AND tr.jb_id = jb.jb_id AND jb." . $jbRelevantCostcenterField . " = csc.csc_id AND csc.cs_id = '" . $csId . "'", "jb_id");
      endif;
   endif;

   // Get job ID to be CANCELLED by order number
   $jbIdCancellation = "";
   $jbIdArrayWithParentOfCancellation = array();  // If a job will be cancelled then move "jb_parent" of all jobs refering to the cancelled job to the new job [Here init only]
   $parNoCancellation = getObjectBasedParameterValue("ORDER_REQUEST_NO_CANCELLATION", $csId, $hqId);
   if ($operationMode == "DEL" || $operationMode == "DELETE") :
      if ($parNoCancellation == "1") :
         $jbIdCancellation = getOneStmt("SELECT jb.jb_id AS jb_id FROM genericdatacontainer AS gdc, job AS jb, costcenter AS csc WHERE gdc.gdc_obj_type = 'jb' AND gdc.gdc_gen_fieldname = 'info_0' AND gdc.gdc_content = '" . $commissionNo . "' AND gdc.gdc_obj_id = jb.jb_id AND jb." . $jbRelevantCostcenterField . " = csc.csc_id AND csc.cs_id = '" . $csId . "'", "jb_id");
      elseif ($parNoCancellation == "2") :
         $jbIdCancellation = $commissionNo;
      else :
         // DEFAULT: Remote order number equals commission number
         $jbIdCancellation = getOneStmt("SELECT jb.jb_id AS jb_id FROM tour AS tr, job AS jb, costcenter AS csc WHERE tr.tr_commission_no = '" . $commissionNo . "' AND tr.jb_id = jb.jb_id AND jb." . $jbRelevantCostcenterField . " = csc.csc_id AND csc.cs_id = '" . $csId . "'", "jb_id");
      endif;
   endif;

$debugOut .= "---- OP ---------<br>\n";
$debugOut .= "operationMode: " . $operationMode . "<br>\n";
$debugOut .= "jbIdParent: " . $jbIdParent . "<br>\n";
$debugOut .= "jbIdMerged: " . $jbIdMerged . "<br>\n";
$debugOut .= "jbIdUpdate: " . $jbIdUpdate . "<br>\n";
$debugOut .= "jbIdCancellation: " . $jbIdCancellation . "<br>\n";
$debugOut .= "---- OP ---------<br>\n";

   $jbType         = convertSpecial($orderArray["xml"]["order"]["type"]);
   $hqMnemonic     = convertSpecial($orderArray["xml"]["order"]["hq"]);
   $hqId_XML       = getFieldValueFromId("headquarters","hq_mnemonic",$hqMnemonic,"hq_id");
   if ($hqMnemonic == "" && $hqId != "" && is_numeric($hqId) && $hqId > "0") :
      $hqMnemonic  = getFieldValueFromId("headquarters","hq_id",$hqId,"hq_mnemonic");
   endif;
   $vhtId          = convertSpecial($orderArray["xml"]["order"]["vehicle"]["type_no"]);
   $vhtType        = convertSpecial($orderArray["xml"]["order"]["vehicle"]["type_name"]);
   if ($vhtId != "" && is_numeric($vhtId)) :
      $vhtType = getFieldValueFromClause("metatype","mt_value","mt_type = 'vehicletype' AND mt_sort = '" . $vhtId . "'");
   elseif ($vhtType != "") :
      $vhtId = getFieldValueFromClause("metatype","mt_sort","mt_type = 'vehicletype' AND mt_value = '" . $vhtType . "'");
   endif;
   $jbCrvhWeight   = convertSpecial($orderArray["xml"]["order"]["vehicle"]["weight"],"intval");
   $jbCrvhLength   = convertSpecial($orderArray["xml"]["order"]["vehicle"]["length"],"intval");
   $jbCrvhWidth    = convertSpecial($orderArray["xml"]["order"]["vehicle"]["width"],"intval");
   $jbCrvhHeight   = convertSpecial($orderArray["xml"]["order"]["vehicle"]["height"],"intval");
   $jbCrvhPosition = convertSpecial($orderArray["xml"]["order"]["vehicle"]["position"],"intval");
   $jbOrdertime    = convertSpecial($orderArray["xml"]["order"]["ordertime"]);
   $jbOrdertimeUTC = convertSpecial($orderArray["xml"]["order"]["ordertimeUTC"]);
   $jbWarningtime  = convertSpecial($orderArray["xml"]["order"]["warningtime"]);
   $jbWarningtimeUTC  = convertSpecial($orderArray["xml"]["order"]["warningtimeUTC"]);
   $jbAcquisitiontime = convertSpecial($orderArray["xml"]["order"]["acquisition_time"]);
   $jbReserv       = 0;

   // Order time
   if ($jbOrdertime == "" || $jbOrdertime == "0000-00-00 00:00:00") :
      // Check for UTC
      if ($jbOrdertimeUTC == "" || $jbOrdertimeUTC == "0000-00-00 00:00:00") :
         $jbOrdertime = $currentTime;
      else :
         $gmtDT = substr($jbOrdertimeUTC, 0,19);
         $checkGmtdatetimeIsValid = strtotime($gmtDT);
         if ($checkGmtdatetimeIsValid != "" && is_int($checkGmtdatetimeIsValid)):
            $jbOrdertime = date("Y-m-d H:i:s", gmmktime(substr($gmtDT,11,2), substr($gmtDT,14,2), substr($gmtDT,17,2), substr($gmtDT,5,2), substr($gmtDT,8,2), substr($gmtDT,0,4)));
         else :
            $err[] = array("112", getLngt("Das Datum wurde nicht erwartungsgemäß übergeben."));
            $acceptOrder = false;
         endif;
         $jbReserv = 1;
      endif;
   else :
      // $jbOrdertime = checkDateTimeFormat($jbOrdertime);    // DISABLED BECAUSE OF PHP VERSION ONLY !!! ACTIVATE AFTER MIGRATION !!!
      $checkGmtdatetimeIsValid = strtotime($jbOrdertime);
      if ($checkGmtdatetimeIsValid != "" && is_int($checkGmtdatetimeIsValid)):
         $jbReserv = 1;
      else :
         $err[] = array("113", getLngt("Die Auftragszeit wurde nicht erwartungsgemäß übergeben."));
         $acceptOrder = false;
      endif;
   endif;
   // Check ordertime being in the future
   $parCheckOrdertime = getObjectBasedParameterValue("ORDER_REQUEST_CHECK_ORDERTIME", $csId, $hqId);
   if ($parCheckOrdertime == "1") :
      if ($jbOrdertime < $currentTime) :
         $err[] = array("116", getLngt("Die Auftragszeit liegt in der Vergangenheit."));
         $acceptOrder = false;
      endif;
   endif;

   // Warning time
   if ($jbWarningtime == "" || $jbWarningtime == "0000-00-00 00:00:00") :
      // Check for UTC
      if ($jbWarningtimeUTC != "" && $jbWarningtimeUTC != "0000-00-00 00:00:00") :
         $gmtDT = substr($jbWarningtimeUTC, 0,19);
         $checkGmtdatetimeIsValid = strtotime($gmtDT);
         if ($checkGmtdatetimeIsValid != "" && is_int($checkGmtdatetimeIsValid)):
            $jbWarningtime = date("Y-m-d H:i:s", gmmktime(substr($gmtDT,11,2), substr($gmtDT,14,2), substr($gmtDT,17,2), substr($gmtDT,5,2), substr($gmtDT,8,2), substr($gmtDT,0,4)));
         else :
            $err[] = array("114", getLngt("Die späteste Erledigungszeit wurde nicht erwartungsgemäß übergeben."));
            $acceptOrder = false;
         endif;
      endif;
   else :
      // $jbWarningtime = checkDateTimeFormat($jbWarningtime);    // DISABLED BECAUSE OF PHP VERSION ONLY !!! ACTIVATE AFTER MIGRATION !!!
      $checkGmtdatetimeIsValid = strtotime($jbWarningtime);
      if ($checkGmtdatetimeIsValid == "" || !is_int($checkGmtdatetimeIsValid)):
         $err[] = array("114", getLngt("Die späteste Erledigungszeit wurde nicht erwartungsgemäß übergeben."));
         $acceptOrder = false;
      endif;
   endif;

   $crSid = convertSpecial($orderArray["xml"]["order"]["courier"]);
   $crIdOrder = "";
   if ($crSid != "") :
      $crIdOrder = getFieldValueFromId("couriervehicle","crvh_sid",$crSid,"cr_id");
      if ($crIdOrder == "") : $crSid = ""; endif;
   endif;
   $jbCrFilter = convertSpecial($orderArray["xml"]["order"]["filter"]);
   
   $jbRemark = convertSpecial($orderArray["xml"]["order"]["remark"]);
   $parJbRemarkMode = getObjectBasedParameterValue("ORDER_REQUEST_JB_REMARK_MODE", $csId, $hqId);
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!   
   if ($parJbRemarkMode == "1") :
      // Overrule invoice text with customer date and daytime
      $jbRemark = "";  // <= !!!!!!!!!!!! HERE !!!!!!!!!!!!!!!!!!!
   endif;
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
   $jbCrRemark = convertSpecial($orderArray["xml"]["order"]["courier_remark"]);

   // Special informations inserted into GDC structure
   $jbGdcArray = array();
/*   
   $numOfGdcEntries = count($orderArray["xml"]["order"]["gdc"]["val"]);
   for ($k = 0; $k < $numOfGdcEntries; $k++) :
       $jbGdcArray[$k] = convertSpecial($orderArray["xml"]["order"]["gdc"]["val"][$k]);
   endfor;
*/
   $numOfGdcEntries = count($orderArray["xml"]["order"]["gdc"]["val"]);
   if ($numOfGdcEntries > 0) :
      for ($k = 0; $k < $numOfGdcEntries; $k++) :
          if ($numOfGdcEntries == 1) : 
             $jbGdcArray[0] = convertSpecial($orderArray["xml"]["order"]["gdc"]["val"]);
          else :
             $jbGdcArray[$k] = convertSpecial($orderArray["xml"]["order"]["gdc"]["val"][$k]);
          endif;
     endfor;
   endif;

   // Get customized ("tourarticle") added service infos (for invoicing etc.)
   // Structure: key_01=val_01_german,val_01_english,....|key_02=val_02_german,val_02_english,....|key_03=val_03_german,val_03_english,....|key_04=val_04_german,val_04_english,....|....
   // (E.g.: 100=Montage aller Art/Montagezusatzkosten,ADDITIONAL_INSTALL_SERVICE|101=Möbelmontage,FURNITURE_ASSEMBLY|102=Polstermöbelmontage,LEGS_FURNITURE_ASSEMBLY|103=Möbelmontage/Monteur vor Ort,FURNITURE_ASSEMBLY_EXPRESS|104=KuSe Möbelnachmontage,AFTER_SALES_FURNITURE_ASSEMBLY|....)
   $csAddedServiceInfos = getFieldValueFromClause("genericdatacontainer", "gdc_content", "gdc_obj_type = 'cs' AND gdc_gen_fieldname = 'add_service_info' AND gdc_obj_id = '" . $csId . "'");
   $csAddedServiceInfosArray = getKeyValueArrayFromString($csAddedServiceInfos);
   $csAddedServiceInfosArrayLen = count($csAddedServiceInfosArray);
   // Generate both reverse arrays depending on the language selected:
   // 1. $arr[100] = "ADDITIONAL_INSTALL_SERVICE", ....
   // 2. $arr["ADDITIONAL_INSTALL_SERVICE"] = "Montage aller Art/Montagezusatzkosten";
   $csAddedServiceReverseInfosArray1 = array();
   $csAddedServiceReverseInfosArray2 = array();
   $csAddSrvKeysArray = array_keys($csAddedServiceInfosArray);
   $csAddSrvKeysArrayLen = count($csAddSrvKeysArray);
   for ($l = 0; $l < $csAddSrvKeysArrayLen; $l++) :
       $tmpValArray = spliti(",", $csAddedServiceInfosArray[$csAddSrvKeysArray[$l]]);                // "Montage aller Art/Montagezusatzkosten,ADDITIONAL_INSTALL_SERVICE" => array("ADDITIONAL_INSTALL_SERVICE","Montage aller Art/Montagezusatzkosten")
       $csAddedServiceReverseInfosArray1[$tmpValArray[$languageSelected]] = $csAddSrvKeysArray[$l];  // $csAddedServiceReverseInfosArray1["ADDITIONAL_INSTALL_SERVICE"] = 100;
       $csAddedServiceReverseInfosArray2[$tmpValArray[$languageSelected]] = $tmpValArray[0];         // $csAddedServiceReverseInfosArray2["ADDITIONAL_INSTALL_SERVICE"] = "Montage aller Art/Montagezusatzkosten";
   endfor;
   $csAddedServiceReverseInfosArray1Len = count($csAddedServiceReverseInfosArray1);
   $csAddedServiceReverseInfosArray2Len = count($csAddedServiceReverseInfosArray2);
if ($debug) :
   echo "---- ADDED SERVICE INFOS --------------------------------------------------------------- <br>";
   echo "BASE VALUES IN csAddedServiceInfos: " . $csAddedServiceInfos . "<br><br>";
   echo "csAddedServiceInfosArray:<br>";
   print_r($csAddedServiceInfosArray);
   echo "---------------------------------------------------------------------------------------- <br><br>";
   echo "---- ADDED SERVICE INFOS REVERSE --------------------------------------------------------<br>";
   echo "csAddedServiceReverseInfosArray1:<br>";
   print_r($csAddedServiceReverseInfosArray1);
   echo "csAddedServiceReverseInfosArray2:<br>";
   print_r($csAddedServiceReverseInfosArray2);
   echo "---------------------------------------------------------------------------------------- <br>";
endif;


   // Init
   $jbTourdata = "";
   $jbTourdataZipcode = "";
   $jbTourdataCity = "";
   $jbTourdataCountry = "";

   // "TOUR" data
   $numOfStations = count($orderArray["xml"]["order"]["stations"]["station"]);

   if ($numOfStations > 0) :

      // Station arrays
      $trWareFromTo = array(); $trCommissionNo = array(); $trCostcenter = array(); $trCompany = array(); $trCompany2 = array(); $trScanCodeMandatory = array();
      $trStreet = array(); $trHouseno = array(); $trFloor = array(); $trZipcode = array(); $trCity = array(); $trAdId = array();
      $trSpecialRemark = array(); $trPerson = array(); $trPhone = array(); $trEmail = array();
      $trAdSupplement_1 = array(); $trAdSupplement_2 = array(); $trAdSupplement_3 = array(); $trAdSupplement_4 = array(); $trAdSupplement_5 = array();
      $trInvCompany = array(); $trInvCompany2 = array();
      $trInvStreet = array(); $trInvHouseno = array(); $trInvFloor = array(); $trInvZipcode = array(); $trInvCity = array(); $trInvAdId = array();
      $trInvSpecialRemark = array(); $trInvPerson = array(); $trInvPhone = array(); $trInvEmail = array();
      $trInvAdSupplement_1 = array(); $trInvAdSupplement_2 = array(); $trInvAdSupplement_3 = array(); $trInvAdSupplement_4 = array(); $trInvAdSupplement_5 = array();
      $trInvPaymentMethod = array(); $trInvVoucher = array(); $trInvpartialPayment = array(); $trInvPriceMode = array();
      $trGdcArray = array();

      // Station services
      $trServices = array(); $trTimeslots = array(); $trTimesunits = array(); $trShipmentMode = array(); $trOrderType = array();
      $trDeliveryInfo = array(); $trFlagServiceDoc = array(); $trDocumentsURL = array();

      // Arrays for summarized article fields OR maximum values
      $trSumWeight = array(); $trSumPositions = array(); $trSumPieces = array(); $trSumPrices = array(); $trSumVolume = array();
      $trMaxHeight = array(); $trMaxLength = array(); $trMaxWidth = array(); $trMaxDimension = array();

      for ($i = 0; $i < $numOfStations; $i++) :
          $trSort = $i + 1;

          $trWareFromTo[$i]   = convertSpecial($orderArray["xml"]["order"]["stations"]["station"][$i]["ware_from_to"]);
          $trCommissionNo[$i] = convertSpecial($orderArray["xml"]["order"]["stations"]["station"][$i]["commission_no"]);
          $trCostcenter[$i]   = convertSpecial($orderArray["xml"]["order"]["stations"]["station"][$i]["costcenter"]);
          $trCscId[$i] = "";
          if ($trCostcenter[$i] != "") :
             $trCscId[$i] = getFieldValueFromClause("costcenter","csc_id","cs_id = '" . $csId . "' AND csc_name = '" . $trCostcenter[$i] . "'");
          endif;
$debugOut .= "trCostcenter[$i]: " . $trCostcenter[$i] . "<br>\n";
$debugOut .= "trCscId[$i]: " . $trCscId[$i] . "<br>\n";
$debugOut .= "<br>\n";
          // Mandatory scan (bar)code
          $trScanCodeMandatory[$i] = convertSpecial($orderArray["xml"]["order"]["stations"]["station"][$i]["scan_code_mandatory"]);

          // Invoice address       
          $trInvCompany[$i]        = convertSpecial($orderArray["xml"]["order"]["stations"]["station"][$i]["invoice"]["company"]);
          $trInvCompany2[$i]       = convertSpecial($orderArray["xml"]["order"]["stations"]["station"][$i]["invoice"]["company2"]);
          $trInvStreet[$i]         = convertSpecial($orderArray["xml"]["order"]["stations"]["station"][$i]["invoice"]["street"]);
          $trInvHouseno[$i]        = convertSpecial($orderArray["xml"]["order"]["stations"]["station"][$i]["invoice"]["houseno"]);
          $trInvZipcode[$i]        = convertSpecial($orderArray["xml"]["order"]["stations"]["station"][$i]["invoice"]["zipcode"]);
          $trInvCity[$i]           = convertSpecial($orderArray["xml"]["order"]["stations"]["station"][$i]["invoice"]["city"]);
          $trInvSpecialRemark[$i]  = convertSpecial($orderArray["xml"]["order"]["stations"]["station"][$i]["invoice"]["special_remark"]);
          $trInvPerson[$i]         = convertSpecial($orderArray["xml"]["order"]["stations"]["station"][$i]["invoice"]["person"]);
          $trInvPhone[$i]          = convertSpecial($orderArray["xml"]["order"]["stations"]["station"][$i]["invoice"]["phone"]);
          $trInvEmail[$i]          = convertSpecial($orderArray["xml"]["order"]["stations"]["station"][$i]["invoice"]["email"]);

          $trInvAdSupplement_1[$i] = convertSpecial($orderArray["xml"]["order"]["stations"]["station"][$i]["invoice"]["ad_supplement_1"]);
          $trInvAdSupplement_2[$i] = convertSpecial($orderArray["xml"]["order"]["stations"]["station"][$i]["invoice"]["ad_supplement_2"]);
          $trInvAdSupplement_3[$i] = convertSpecial($orderArray["xml"]["order"]["stations"]["station"][$i]["invoice"]["ad_supplement_3"]);
          $trInvAdSupplement_4[$i] = convertSpecial($orderArray["xml"]["order"]["stations"]["station"][$i]["invoice"]["ad_supplement_4"]);
          $trInvAdSupplement_5[$i] = convertSpecial($orderArray["xml"]["order"]["stations"]["station"][$i]["invoice"]["ad_supplement_5"]);

$debugOut .= "INVOICE ADDRESS BY XML-TAGS<br>\n";
$debugOut .= "trInvCompany[$i]: " . $trInvCompany[$i] . "<br>\n";
$debugOut .= "trInvCompany2[$i]: " . $trInvCompany2[$i] . "<br>\n";
$debugOut .= "trInvAdId[$i]: " . $trInvAdId[$i] . "<br>\n";
$debugOut .= "trInvStreet[$i]: " . $trInvStreet[$i] . "<br>\n";
$debugOut .= "trInvHouseno[$i]: " . $trInvHouseno[$i] . "<br>\n";
$debugOut .= "trInvFloor[$i]: " . $trInvFloor[$i] . "<br>\n";
$debugOut .= "trInvZipcode[$i]: " . $trInvZipcode[$i] . "<br>\n";
$debugOut .= "trInvCity[$i]: " . $trInvCity[$i] . "<br>\n";
$debugOut .= "trInvSpecialRemark[$i]: " . $trInvSpecialRemark[$i] . "<br>\n";
$debugOut .= "trInvPerson[$i]: " . $trInvPerson[$i] . "<br>\n";
$debugOut .= "trInvPhone[$i]: " . $trInvPhone[$i] . "<br>\n";
$debugOut .= "trInvEmail[$i]: " . $trInvEmail[$i] . "<br>\n";
$debugOut .= "trInvAdSupplement_1[$i]: " . $trInvAdSupplement_1[$i] . "<br>\n";
$debugOut .= "trInvAdSupplement_2[$i]: " . $trInvAdSupplement_2[$i] . "<br>\n";
$debugOut .= "trInvAdSupplement_3[$i]: " . $trInvAdSupplement_3[$i] . "<br>\n";
$debugOut .= "trInvAdSupplement_4[$i]: " . $trInvAdSupplement_4[$i] . "<br>\n";
$debugOut .= "trInvAdSupplement_5[$i]: " . $trInvAdSupplement_5[$i] . "<br>\n";
$debugOut .= "<br>\n";

          $trInvAdId[$i] = "";
          if ($trInvStreet[$i] != "" && $trInvZipcode[$i] != "" && $trInvCity[$i] != "") :
             $sqlStmt = "SELECT ad_id FROM address WHERE ad_street = '" . $trInvStreet[$i] . "' AND ad_zipcode = '" . $trInvZipcode[$i] . "' AND ad_city = '" . $trInvCity[$i] . "' AND ad_country = 'DE'";
             $trInvAdId[$i] = $db->getOne($sqlStmt);
             if (DB::isError($ad_id)) die ("$PHP_SELF: <br>$sqlStmt<br>" . $ad_id->getMessage());
             if ($trInvAdId[$i] == ""):
                insertStmt("address", array("ad_street", $trInvStreet[$i], "ad_zipcode", $trInvZipcode[$i], "ad_city", $trInvCity[$i], "ad_country", "DE"));
                $trInvAdId[$i] = getLastInsertID();
             endif;
             // $tmpArray = insertAddress($trInvStreet[$i], $trInvZipcode[$i], $trInvCity[$i], "", "DE", true);
             // $trAdId[$i] = $tmpArray[0];
          endif;

          if ($trCscId[$i] != "" && $trCscId[$i] != "0") :
$debugOut .= "trCostcenter[$i] does exist: YES<br><br>\n";
             // Delivery address
             $trCompany[$i]          = getFieldValueFromClause("costcenteraddress","cscad_comp","adt_id = '4' AND csc_id = '" . $trCscId[$i] . "'");
             $trCompany2[$i]         = getFieldValueFromClause("costcenteraddress","cscad_comp2","adt_id = '4' AND csc_id = '" . $trCscId[$i] . "'");
             $trAdId[$i]             = getFieldValueFromClause("costcenteraddress","ad_id","adt_id = '4' AND csc_id = '" . $trCscId[$i] . "'");
             $trStreet[$i]           = getFieldValueFromId("address","ad_id",$trAdId[$i],"ad_street");
             $trHouseno[$i]          = getFieldValueFromClause("costcenteraddress","cscad_hsno","adt_id = '4' AND csc_id = '" . $trCscId[$i] . "'");
             $trFloor[$i]            = getFieldValueFromClause("costcenteraddress","cscad_floor","adt_id = '4' AND csc_id = '" . $trCscId[$i] . "'");
             $trZipcode[$i]          = getFieldValueFromId("address","ad_id",$trAdId[$i],"ad_zipcode");
             $trCity[$i]             = getFieldValueFromId("address","ad_id",$trAdId[$i],"ad_city");
             $trSpecialRemark[$i]    = getFieldValueFromClause("costcenteraddress","cscad_remark","adt_id = '4' AND csc_id = '" . $trCscId[$i] . "'");
             $trPerson[$i]           = getFieldValueFromClause("costcenteraddress","cscad_person","adt_id = '4' AND csc_id = '" . $trCscId[$i] . "'");
             $trPhone[$i]            = getFieldValueFromClause("costcenteraddress","cscad_phone","adt_id = '4' AND csc_id = '" . $trCscId[$i] . "'");
             $trEmail[$i]            = getFieldValueFromClause("costcenteraddress","cscad_email","adt_id = '4' AND csc_id = '" . $trCscId[$i] . "'");

             $tmpAddressSupplement = getFieldValueFromClause("genericdatacontainer", "gdc_content", "gdc_obj_type = 'csc' AND gdc_gen_fieldname = 'ad_supplement' AND gdc_context = '" . $trSort . "' AND gdc_obj_id = '" . $trCscId[$i] . "'");
             $tmpAddressSupplement = str_replace("|", "-,-", $tmpAddressSupplement);
             $tmpAddressSupplementArray = spliti("-,-",$tmpAddressSupplement);
             $trAdSupplement_1[$i]   = $tmpAddressSupplementArray[0];
             $trAdSupplement_2[$i]   = $tmpAddressSupplementArray[1];
             $trAdSupplement_3[$i]   = $tmpAddressSupplementArray[2];
             $trAdSupplement_4[$i]   = $tmpAddressSupplementArray[3];
             $trAdSupplement_5[$i]   = $tmpAddressSupplementArray[4];

$debugOut .= "PICKUP/DELIVERY ADDRESS BY EXISTING COSTCENTER<br>\n";
$debugOut .= "trCompany[$i]: " . $trCompany[$i] . "<br>\n";
$debugOut .= "trCompany2[$i]: " . $trCompany2[$i] . "<br>\n";
$debugOut .= "trAdId[$i]: " . $trAdId[$i] . "<br>\n";
$debugOut .= "trStreet[$i]: " . $trStreet[$i] . "<br>\n";
$debugOut .= "trHouseno[$i]: " . $trHouseno[$i] . "<br>\n";
$debugOut .= "trFloor[$i]: " . $trFloor[$i] . "<br>\n";
$debugOut .= "trZipcode[$i]: " . $trZipcode[$i] . "<br>\n";
$debugOut .= "trCity[$i]: " . $trCity[$i] . "<br>\n";
$debugOut .= "trSpecialRemark[$i]: " . $trSpecialRemark[$i] . "<br>\n";
$debugOut .= "trPerson[$i]: " . $trPerson[$i] . "<br>\n";
$debugOut .= "trPhone[$i]: " . $trPhone[$i] . "<br>\n";
$debugOut .= "trEmail[$i]: " . $trEmail[$i] . "<br>\n";
$debugOut .= "trAdSupplement_1[$i]: " . $trAdSupplement_1[$i] . "<br>\n";
$debugOut .= "trAdSupplement_2[$i]: " . $trAdSupplement_2[$i] . "<br>\n";
$debugOut .= "trAdSupplement_3[$i]: " . $trAdSupplement_3[$i] . "<br>\n";
$debugOut .= "trAdSupplement_4[$i]: " . $trAdSupplement_4[$i] . "<br>\n";
$debugOut .= "trAdSupplement_5[$i]: " . $trAdSupplement_5[$i] . "<br>\n";
$debugOut .= "<br>\n";

             // Invoice address
             if ($trInvAdId[$i] == "") :
                $trInvCompany[$i]        = getFieldValueFromClause("costcenteraddress","cscad_comp","adt_id = '2' AND csc_id = '" . $trCscId[$i] . "'");
                $trInvCompany2[$i]       = getFieldValueFromClause("costcenteraddress","cscad_comp2","adt_id = '2' AND csc_id = '" . $trCscId[$i] . "'");
                $trInvAdId[$i]           = getFieldValueFromClause("costcenteraddress","ad_id","adt_id = '2' AND csc_id = '" . $trCscId[$i] . "'");
                $trInvStreet[$i]         = getFieldValueFromId("address","ad_id",$trInvAdId[$i],"ad_street");
                $trInvHouseno[$i]        = getFieldValueFromClause("costcenteraddress","cscad_hsno","adt_id = '2' AND csc_id = '" . $trCscId[$i] . "'");
                $trInvFloor[$i]          = getFieldValueFromClause("costcenteraddress","cscad_floor","adt_id = '2' AND csc_id = '" . $trCscId[$i] . "'");
                $trInvZipcode[$i]        = getFieldValueFromId("address","ad_id",$trInvAdId[$i],"ad_zipcode");
                $trInvCity[$i]           = getFieldValueFromId("address","ad_id",$trInvAdId[$i],"ad_city");
                $trInvSpecialRemark[$i]  = getFieldValueFromClause("costcenteraddress","cscad_remark","adt_id = '2' AND csc_id = '" . $trCscId[$i] . "'");
                $trInvPerson[$i]         = getFieldValueFromClause("costcenteraddress","cscad_person","adt_id = '2' AND csc_id = '" . $trCscId[$i] . "'");
                $trInvPhone[$i]          = getFieldValueFromClause("costcenteraddress","cscad_phone","adt_id = '2' AND csc_id = '" . $trCscId[$i] . "'");
                $trInvEmail[$i]          = getFieldValueFromClause("costcenteraddress","cscad_email","adt_id = '2' AND csc_id = '" . $trCscId[$i] . "'");
                $tmpInvAddressSupplement = getFieldValueFromClause("genericdatacontainer", "gdc_content", "gdc_obj_type = 'csc' AND gdc_gen_fieldname = 'ad_inv_supplement' AND gdc_context = '" . $trSort . "' AND gdc_obj_id = '" . $trCscId[$i] . "'");
                $tmpInvAddressSupplement = str_replace("|", "-,-", $tmpInvAddressSupplement);
                $tmpInvAddressSupplementArray = spliti("-,-",$tmpInvAddressSupplement);
                $trInvAdSupplement_1[$i]   = $tmpInvAddressSupplementArray[0];
                $trInvAdSupplement_2[$i]   = $tmpInvAddressSupplementArray[1];
                $trInvAdSupplement_3[$i]   = $tmpInvAddressSupplementArray[2];
                $trInvAdSupplement_4[$i]   = $tmpInvAddressSupplementArray[3];
                $trInvAdSupplement_5[$i]   = $tmpInvAddressSupplementArray[4];
                
$debugOut .= "INVOICE ADDRESS BY EXISTING COSTCENTER<br>\n";
$debugOut .= "trInvCompany[$i]: " . $trInvCompany[$i] . "<br>\n";
$debugOut .= "trInvCompany2[$i]: " . $trInvCompany2[$i] . "<br>\n";
$debugOut .= "trInvAdId[$i]: " . $trInvAdId[$i] . "<br>\n";
$debugOut .= "trInvStreet[$i]: " . $trInvStreet[$i] . "<br>\n";
$debugOut .= "trInvHouseno[$i]: " . $trInvHouseno[$i] . "<br>\n";
$debugOut .= "trInvFloor[$i]: " . $trInvFloor[$i] . "<br>\n";
$debugOut .= "trInvZipcode[$i]: " . $trInvZipcode[$i] . "<br>\n";
$debugOut .= "trInvCity[$i]: " . $trInvCity[$i] . "<br>\n";
$debugOut .= "trInvSpecialRemark[$i]: " . $trInvSpecialRemark[$i] . "<br>\n";
$debugOut .= "trInvPerson[$i]: " . $trInvPerson[$i] . "<br>\n";
$debugOut .= "trInvPhone[$i]: " . $trInvPhone[$i] . "<br>\n";
$debugOut .= "trInvEmail[$i]: " . $trInvEmail[$i] . "<br>\n";
$debugOut .= "trInvAdSupplement_1[$i]: " . $trInvAdSupplement_1[$i] . "<br>\n";
$debugOut .= "trInvAdSupplement_2[$i]: " . $trInvAdSupplement_2[$i] . "<br>\n";
$debugOut .= "trInvAdSupplement_3[$i]: " . $trInvAdSupplement_3[$i] . "<br>\n";
$debugOut .= "trInvAdSupplement_4[$i]: " . $trInvAdSupplement_4[$i] . "<br>\n";
$debugOut .= "trInvAdSupplement_5[$i]: " . $trInvAdSupplement_5[$i] . "<br>\n";
$debugOut .= "<br>\n";
             endif;
          else :
$debugOut .= "trCostcenter[$i] does exist: NO<br><br>\n";
             // Delivery address
             $trCompany[$i]        = convertSpecial($orderArray["xml"]["order"]["stations"]["station"][$i]["company"]);
             $trCompany2[$i]       = convertSpecial($orderArray["xml"]["order"]["stations"]["station"][$i]["company2"]);
             $trStreet[$i]         = convertSpecial($orderArray["xml"]["order"]["stations"]["station"][$i]["street"]);
             $trHouseno[$i]        = convertSpecial($orderArray["xml"]["order"]["stations"]["station"][$i]["houseno"]);
             $trFloor[$i]          = convertSpecial($orderArray["xml"]["order"]["stations"]["station"][$i]["floorno"]);
             $trZipcode[$i]        = convertSpecial($orderArray["xml"]["order"]["stations"]["station"][$i]["zipcode"]);
             $trCity[$i]           = convertSpecial($orderArray["xml"]["order"]["stations"]["station"][$i]["city"]);
             $trSpecialRemark[$i]  = convertSpecial($orderArray["xml"]["order"]["stations"]["station"][$i]["special_remark"]);
             $trPerson[$i]         = convertSpecial($orderArray["xml"]["order"]["stations"]["station"][$i]["person"]);
             $trPhone[$i]          = convertSpecial($orderArray["xml"]["order"]["stations"]["station"][$i]["phone"]);
             $trEmail[$i]          = convertSpecial($orderArray["xml"]["order"]["stations"]["station"][$i]["email"]);

             $trAdSupplement_1[$i] = convertSpecial($orderArray["xml"]["order"]["stations"]["station"][$i]["ad_supplement_1"]);
             $trAdSupplement_2[$i] = convertSpecial($orderArray["xml"]["order"]["stations"]["station"][$i]["ad_supplement_2"]);
             $trAdSupplement_3[$i] = convertSpecial($orderArray["xml"]["order"]["stations"]["station"][$i]["ad_supplement_3"]);
             $trAdSupplement_4[$i] = convertSpecial($orderArray["xml"]["order"]["stations"]["station"][$i]["ad_supplement_4"]);
             $trAdSupplement_5[$i] = convertSpecial($orderArray["xml"]["order"]["stations"]["station"][$i]["ad_supplement_5"]);

             $trAdId[$i] = "";
             if ($trStreet[$i] != "" && $trZipcode[$i] != "" && $trCity[$i] != "") :
                $sqlStmt = "SELECT ad_id FROM address WHERE ad_street = '" . $trStreet[$i] . "' AND ad_zipcode = '" . $trZipcode[$i] . "' AND ad_city = '" . $trCity[$i] . "' AND ad_country = 'DE'";
                $trAdId[$i] = $db->getOne($sqlStmt);
                if (DB::isError($ad_id)) die ("$PHP_SELF: <br>$sqlStmt<br>" . $ad_id->getMessage());
                if ($trAdId[$i] == ""):
                   insertStmt("address", array("ad_street", $trStreet[$i], "ad_zipcode", $trZipcode[$i], "ad_city", $trCity[$i], "ad_country", "DE"));
                   $trAdId[$i] = getLastInsertID();
                endif;
                // $tmpArray = insertAddress($trStreet[$i], $trZipcode[$i], $trCity[$i], "", "DE", true);
                // $trAdId[$i] = $tmpArray[0];
             endif;
             // Get "EXTERN" costcenter of the current headquarters
             if ($globalParUseRelatedCustomer != "1") :
                $trCscId[$i] = getParameterValue("0", "CSC_ID_PAYER_EXTERN", $hqId);
             endif;
             
$debugOut .= "PICKUP/DELIVERY ADDRESS BY XML-TAGS<br>\n";
$debugOut .= "trCompany[$i]: " . $trCompany[$i] . "<br>\n";
$debugOut .= "trCompany2[$i]: " . $trCompany2[$i] . "<br>\n";
$debugOut .= "trAdId[$i]: " . $trAdId[$i] . "<br>\n";
$debugOut .= "trStreet[$i]: " . $trStreet[$i] . "<br>\n";
$debugOut .= "trHouseno[$i]: " . $trHouseno[$i] . "<br>\n";
$debugOut .= "trFloor[$i]: " . $trFloor[$i] . "<br>\n";
$debugOut .= "trZipcode[$i]: " . $trZipcode[$i] . "<br>\n";
$debugOut .= "trCity[$i]: " . $trCity[$i] . "<br>\n";
$debugOut .= "trSpecialRemark[$i]: " . $trSpecialRemark[$i] . "<br>\n";
$debugOut .= "trPerson[$i]: " . $trPerson[$i] . "<br>\n";
$debugOut .= "trPhone[$i]: " . $trPhone[$i] . "<br>\n";
$debugOut .= "trEmail[$i]: " . $trEmail[$i] . "<br>\n";
$debugOut .= "trAdSupplement_1[$i]: " . $trAdSupplement_1[$i] . "<br>\n";
$debugOut .= "trAdSupplement_2[$i]: " . $trAdSupplement_2[$i] . "<br>\n";
$debugOut .= "trAdSupplement_3[$i]: " . $trAdSupplement_3[$i] . "<br>\n";
$debugOut .= "trAdSupplement_4[$i]: " . $trAdSupplement_4[$i] . "<br>\n";
$debugOut .= "trAdSupplement_5[$i]: " . $trAdSupplement_5[$i] . "<br>\n";
$debugOut .= "<br>\n";
          endif;

          // Invoice data
          // Presently store data into "tr_remark" !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
          /*          
          $trInvPaymentMethod[$i] = convertSpecial($orderArray["xml"]["order"]["stations"]["station"][$i]["invoice"]["payment_method"]);  // Payment method
          if ($trSpecialRemark[$i] != "") : $trSpecialRemark[$i] .= "<br>" . "------------------------"; endif;
          if ($trInvPaymentMethod[$i] != "") : $trSpecialRemark[$i] .= "<br>" . getLngt("Bezahlart") . ":" . $trInvPaymentMethod[$i]; endif;
          $trInvPriceMode[$i] = convertSpecial($orderArray["xml"]["order"]["stations"]["station"][$i]["invoice"]["price_mode"]);  // Price mode (e.g. "family card")
          if ($trInvPriceMode[$i] != "") : $trSpecialRemark[$i] .= "<br>" . getLngt("Spezialpreis") . ":" . $trInvPriceMode[$i]; endif;
          $trInvPartialPayment[$i] = convertSpecial($orderArray["xml"]["order"]["stations"]["station"][$i]["invoice"]["partial_payment"]);  // Partial payment
          if ($trInvPartialPayment[$i] != "") : $trSpecialRemark[$i] .= "<br>" . getLngt("Bereits bezahlt") . ":" . $trInvPartialPayment[$i]; endif;
          $trInvVoucher[$i] = convertSpecial($orderArray["xml"]["order"]["stations"]["station"][$i]["invoice"]["voucher_no"]);   // Voucher
          if ($trInvVoucher[$i] != "") : $trSpecialRemark[$i] .= "<br>" . getLngt("Voucher") . ":" . $trInvVoucher[$i]; endif;
          // if ($trInvAdId[$i] == "") : $trInvAdId[$i] = $trAdId[$i]; endif;   // No invoice address specified => take delivery address
          if ($trInvAdId[$i] != "") : 
             $trSpecialRemark[$i] .= "<br>" . "------------------------";
             if ($trInvCompany[$i] != "") : $trSpecialRemark[$i] .= "<br>" . $trInvCompany[$i] . "<br>" . $trInvCompany2[$i]; endif;
             $trSpecialRemark[$i] .= "<br>" . $trInvCompany[$i] . "<br>" . $trInvCompany2[$i];
             $trSpecialRemark[$i] .= "<br>" . getLngt("Adresse") . ":" . "<br>" . $trInvStreet[$i] . " " . $trInvHouseno[$i] . "<br>" . $trInvZipcode[$i] . " " . $trInvCity[$i];
          endif;
          if ($trInvPerson[$i] != "") : $trSpecialRemark[$i] .= "<br>" . $trInvPerson[$i]; endif;
          if ($trInvPhone[$i] != "") : $trSpecialRemark[$i] .= "<br>" . $trInvPhone[$i]; endif;
          if ($trInvEmail[$i] != "") : $trSpecialRemark[$i] .= "<br>" . $trInvEmail[$i]; endif;
          if ($trInvSpecialRemark[$i] != "") : $trSpecialRemark[$i] .= "<br>" . $trInvSpecialRemark[$i]; endif;
          */

          // Articles
          $numOfArticles = 0;
          if ($orderArray["xml"]["order"]["stations"]["station"][$i]["articles"]["article"]["no"] != "" || $orderArray["xml"]["order"]["stations"]["station"][$i]["articles"]["article"]["description"] != "") :
             $numOfArticles = 1;
          else :
             $numOfArticles = count($orderArray["xml"]["order"]["stations"]["station"][$i]["articles"]["article"]);
          endif;

          // Mode of tour article service to be handled per station
          $tratModeArray = array();  // Init

          if ($numOfArticles > 0) :
             for ($j = 0; $j < $numOfArticles; $j++) :

                 if ($numOfArticles == 1) : 
                    $trArticleArray[$i][0] = $orderArray["xml"]["order"]["stations"]["station"][$i]["articles"]["article"];
                 else :
                    $trArticleArray[$i][$j] = $orderArray["xml"]["order"]["stations"]["station"][$i]["articles"]["article"][$j];
                 endif;
                 if ($trSpecialRemark[$i] != "") : $trSpecialRemark[$i] .= "\n" . "------------------------"; endif;

                 $tmpAtMode = $trArticleArray[$i][$j]["mode"];
                 // $csAddedServiceReverseInfosArray1[$tmpValArray[$languageSelected]] = $csAddSrvKeysArray[$l];  // $csAddedServiceReverseInfosArray1["ADDITIONAL_INSTALL_SERVICE"] = 100;
                 // $csAddedServiceReverseInfosArray2[$tmpValArray[$languageSelected]] = $tmpValArray[0];  // $csAddedServiceReverseInfosArray2["ADDITIONAL_INSTALL_SERVICE"] = "Montage aller Art/Montagezusatzkosten";
                 if ($csAddedServiceReverseInfosArray1[$tmpAtMode] != "") :
                    array_push($tratModeArray, $csAddedServiceReverseInfosArray1[$tmpAtMode]);
                 endif;
                 /*
                 if ($tmpAtMode == "1") : 
                    $trSpecialRemark[$i] .= "\n" . getLngt("WARE RETOURE");
                 elseif ($tmpAtMode == "2") :
                    $trSpecialRemark[$i] .= "\n" . getLngt("WARE MONTIEREN");
                 elseif ($tmpAtMode == "3") :
                    $trSpecialRemark[$i] .= "\n" . getLngt("WARE DEMONTIEREN");
                 elseif ($tmpAtMode == "4") :
                    $trSpecialRemark[$i] .= "\n" . getLngt("WARE ENTSORGEN");
                 else :
                    $trSpecialRemark[$i] .= "\n" . getLngt("WARE AUSLIEFERN");
                 endif;
                 */

                 $tmpAtNo          = convertSpecial($trArticleArray[$i][$j]["no"]);
                 $tmpAtSerialno    = convertSpecial($trArticleArray[$i][$j]["serialno"]);
                 $tmpAtDescription = convertSpecial($trArticleArray[$i][$j]["description"]);
                 $tmpAtQuantity    = convertSpecial($trArticleArray[$i][$j]["quantity"]);
                 if ($tmpAtQuantity == "" || !is_numeric($tmpAtQuantity)) : 
                    // Default quantity "= 1"
                    $tmpAtQuantity = 1; 
                    $trArticleArray[$i][$j]["quantity"] = "1";
                 endif;
                 $tmpAtPrice       = convertNumSpecial($trArticleArray[$i][$j]["price"]);
                 $tmpAtGroup       = convertSpecial($trArticleArray[$i][$j]["articlegroup_no"]);
                 $tmpAtWeight      = convertNumSpecial($trArticleArray[$i][$j]["weight"]);
                 $tmpAtPositions   = convertNumSpecial($trArticleArray[$i][$j]["positions"]);
                 $tmpAtPieces      = convertNumSpecial($trArticleArray[$i][$j]["pieces"]);
                 if ($tmpAtPieces == "" || !is_numeric($tmpAtPieces)) : 
                    // Default number of pieces "= 1"
                    $tmpAtPieces = 1; 
                    $trArticleArray[$i][$j]["pieces"] = "1";
                  endif;
                 $tmpAtLength      = convertNumSpecial($trArticleArray[$i][$j]["length"]);
                 $tmpAtWidth       = convertNumSpecial($trArticleArray[$i][$j]["width"]);
                 $tmpAtHeight      = convertNumSpecial($trArticleArray[$i][$j]["height"]);
                 if ($tmpAtLength != "" || $tmpAtWidth != "" || $tmpAtHeight != "") : 
                    $trSpecialRemark[$i] .= "\n" . getLngt("LxBxH") . ": " . $tmpAtLength . "x" . $tmpAtWidth . "x" . $tmpAtHeight;
                 endif;
                 $tmpAtVolume      = convertNumSpecial($trArticleArray[$i][$j]["volume"]);

                 // Try to get an existing article ID from table "article"
                 $tmpAtId = getFieldValueFromId("article", "at_name", $tmpAtNo, "at_id");

                 // Store data into "tr_remark"
                 /*
                 if ($tmpAtNo != "") : $trSpecialRemark[$i] .= "\n" . getLngt("NR.") . ": " . $tmpAtNo; endif;                   
                 if ($tmpAtSerialno != "") : $trSpecialRemark[$i] .= "\n" . getLngt("SN") . ": " . $tmpAtSerialno; endif;        
                 if ($tmpAtDescription != "") : $trSpecialRemark[$i] .= "\n" . $tmpAtDescription; endif;                         
                 if ($tmpAtQuantity != "") : $trSpecialRemark[$i] .= "\n" . getLngt("STK.") . ": " . $tmpAtQuantity; endif;      
                 if ($tmpAtPrice != "") : $trSpecialRemark[$i] .= "\n" . getLngt("PREIS") . ": " . $tmpAtPrice; endif;           
                 if ($tmpAtGroup != "") : $trSpecialRemark[$i] .= "\n" . getLngt("WGRP") . ": " . $tmpAtGroup; endif;            
                 if ($tmpAtWeight != "") : $trSpecialRemark[$i] .= "\n" . getLngt("GEWICHT") . ": " . $tmpAtWeight; endif;       
                 if ($tmpAtPositions != "") : $trSpecialRemark[$i] .= "\n" . getLngt("STELLPL.") . ": " . $tmpAtPositions; endif;
                 if ($tmpAtPieces != "") : $trSpecialRemark[$i] .= "\n" . getLngt("PACKSTK.") . ": " . $tmpAtPieces; endif;
                 if ($tmpAtVolume != "") : $trSpecialRemark[$i] .= "\n" . getLngt("VOLUMEN") . ": " . $tmpAtVolume; endif;
                 */

                 // * Cumulated fields *
                 // Weight
                 if ($trSumWeight[$i] == "") : $trSumWeight[$i] = 0; endif;
                 if ($tmpAtWeight != "" && is_numeric($tmpAtWeight)) :
                    $trSumWeight[$i] += ($tmpAtQuantity * $tmpAtWeight);
                 endif;
                 // Positions
                 if ($trSumPositions[$i] == "") : $trSumPositions[$i] = 0; endif;
                 if ($tmpAtPositions != "" && is_numeric($tmpAtPositions)) :
                    $trSumPositions[$i] += $tmpAtPositions;
                 endif;
                 // Pieces
                 if ($trSumPieces[$i] == "") : $trSumPieces[$i] = 0; endif;
                 if ($tmpAtPieces != "" && is_numeric($tmpAtPieces)) :
                    $trSumPieces[$i] += $tmpAtPieces;
                 endif;
                 // Volume
                 if ($trSumVolume[$i] == "") : $trSumVolume[$i] = 0; endif;
                 if ($tmpAtVolume != "" && is_numeric($tmpAtVolume)) :
                    $trSumVolume[$i] += $tmpAtVolume;
                 endif;
                 // Total price
                 if ($trSumPrices[$i] == "") : $trSumPrices[$i] = 0; endif;
                 if ($tmpAtId != "" && ($tmpAtPrice == "" || !is_numeric($tmpAtPrice))) :
                    // Try to get price from "articleprice" for this article
                    // Check for special customer price ($trInvPriceMode[$i] <=> "mt_sort" ("disposition_mode"))
                    $tmpAtPrice = getArticleServiceValues($tmpAtId, $currentTime, "", $csId, $trInvPriceMode[$i], 0);         // Check for article SPECIAL price of the SPECIAL customer
                    if ($tmpAtPrice == "" && $csGroupId == "" && $csGroupName == "") :
                       $tmpAtPrice = getArticleServiceValues($tmpAtId, $currentTime, $csGroupId, "", $trInvPriceMode[$i], 0); // Check for article SPECIAL group price
                    endif;
                    if ($tmpAtPrice == "") :
                       $tmpAtPrice = getArticleServiceValues($tmpAtId, $currentTime, "", $csId, "", 0);                       // Check for article STANDARD price of the SPECIAL customer
                    endif;
                    if ($tmpAtPrice == "" && $csGroupId == "" && $csGroupName == "") :
                       $tmpAtPrice = getArticleServiceValues($tmpAtId, $currentTime, $csGroupId, "", $csId, "", 0);           // Check for article STANDARD group price
                    endif;
                 endif;
                 if ($tmpAtPrice != "" && is_numeric($tmpAtPrice)) :
                    $trSumPrices[$i] += ($tmpAtQuantity * $tmpAtPrice);
                 endif;
                 // Maximum of height
                 if ($trMaxHeight[$i] == "") : $trMaxHeight[$i] = 0; endif;
                 if ($tmpAtHeight != "" && is_numeric($tmpAtHeight)) :
                    $trMaxHeight[$i] = max($trMaxHeight[$i], $tmpAtHeight);
                 endif;
                 // Maximum of length
                 if ($trMaxLength[$i] == "") : $trMaxLength[$i] = 0; endif;
                 if ($tmpAtLength != "" && is_numeric($tmpAtLength)) :
                    $trMaxLength[$i] = max($trMaxLength[$i], $tmpAtLength);
                 endif;
                 // Maximum of width
                 if ($trMaxWidth[$i] == "") : $trMaxWidth[$i] = 0; endif;
                 if ($tmpAtWidth != "" && is_numeric($tmpAtWidth)) :
                    $trMaxWidth[$i] = max($trMaxWidth[$i], $tmpAtWidth);
                 endif;
                 // Maximum of any dimension
                 if ($trMaxDimension[$i] == "") : $trMaxDimension[$i] = 0; endif;
                 $trMaxDimension[$i] = max($trMaxHeight[$i], $trMaxLength[$i], $trMaxWidth[$i]);
             endfor;
          endif;

          // If ARTICLE TOTAL VALUES are sent within the request overwrite existing conputed values
          $tmpTotalWeight = convertNumSpecial($orderArray["xml"]["order"]["stations"]["station"][$i]["articles"]["total_weight"]);
          if ($tmpTotalWeight != "" && is_numeric($tmpTotalWeight) && $tmpTotalWeight > 0) :
             $trSumWeight = $tmpTotalWeight;
          endif;
          $tmpTotalPieces = convertNumSpecial($orderArray["xml"]["order"]["stations"]["station"][$i]["articles"]["total_pieces"]);
          if ($tmpTotalPieces != "" && is_numeric($tmpTotalPieces) && $tmpTotalPieces > 0) :
             $trSumPieces = $tmpTotalPieces;
          endif;
          $tmpTotalVolume = convertNumSpecial($orderArray["xml"]["order"]["stations"]["station"][$i]["articles"]["total_volume"]);
          if ($tmpTotalVolume != "" && is_numeric($tmpTotalVolume) && $tmpTotalVolume > 0) :
             $trSumVolume = $tmpTotalVolume;
          endif;
          $tmpTotalMeters = convertNumSpecial($orderArray["xml"]["order"]["stations"]["station"][$i]["articles"]["total_meter"]);
          // if ($tmpTotalMeters != "" && is_numeric($tmpTotalMeters) && $tmpTotalMeters > 0) :
          $trSumMeters = $tmpTotalMeters;
          // endif;


          // Station services
          $trServices[$i]       = $orderArray["xml"]["order"]["stations"]["station"][$i]["services"];
          $trTimeslots[$i]      = $trServices[$i]["timeslots"];
          $trTimesunits[$i]     = $trServices[$i]["timeunits"];
          $trShipmentMode[$i]   = $trServices[$i]["shipment_mode"];
          $trOrderType[$i]      = $trServices[$i]["order_type"];
          $trDeliveryInfo[$i]   = $trServices[$i]["delivery_info"];
          $trFlagServiceDoc[$i] = $trServices[$i]["flag_service_doc"];
          $trDocumentsURL[$i]   = $trServices[$i]["documents_URL"];

          // Write some service infos into "tr_remark"
          // if ($trTimeslots[$i] != "")       : $trSpecialRemark[$i]  .= "\nTageszeit: " . $trTimeslots[$i]    . "\n----------"; endif;
          if ($trOrderType[$i] != "")       : $trSpecialRemark[$i]  .= "\nOrder-Typ: " . $trOrderType[$i]    . "\n----------"; endif;
          if ($trDeliveryInfo[$i] != "")    : $trSpecialRemark[$i]  .= "\nAuslieferinformationen: " . $trDeliveryInfo[$i] . "\n----------"; endif;
          if ($trFlagServiceDoc[$i] == "1") : $trSpecialRemark[$i]  .= "\nINSTRUKTIONEN EXISTIEREN! "        . "\n----------"; endif;
          if ($trDocumentsURL[$i] != "")    : $trSpecialRemark[$i] .= "\nOrder-Typ: " . $trDocumentsURL[$i] . "\n----------"; endif;

$debugOut .= "STATION SERVICES<br>\n";
$debugOut .= "trTimeslots[$i]: " . $trTimeslots[$i] . "<br>\n";
$debugOut .= "trTimesunits[$i]: " . $trTimesunits[$i] . "<br>\n";
$debugOut .= "trShipmentMode[$i]: " . $trShipmentMode[$i] . "<br>\n";
$debugOut .= "trOrderType[$i]: " . $trOrderType[$i] . "<br>\n";
$debugOut .= "trDeliveryInfo[$i]: " . $trDeliveryInfo[$i] . "<br>\n";
$debugOut .= "trFlagServiceDoc[$i]: " . $trFlagServiceDoc[$i] . "<br>\n";
$debugOut .= "trDocumentsURL[$i]: " . $trDocumentsURL[$i] . "<br>\n";
$debugOut .= "<br>\n";

          // Calculator prices per functions
          $numOfCalcFunctions = count($orderArray["xml"]["order"]["stations"]["station"][$i]["services"]["calculator"]["func_item"]);
          if ($numOfCalcFunctions > 0) :
             for ($j = 0; $j < $numOfCalcFunctions; $j++) :
                 $trCalcFunctionsArray[$i][$j] = $orderArray["xml"]["order"]["stations"]["station"][$i]["services"]["calculator"]["func_item"][$j];
                 $trCalcFunctionsResultArray[$i][$j] = 0;

                 $tmpFuncNo = $orderArray["xml"]["order"]["stations"]["station"][$i]["services"]["calculator"]["func_item"][$j]["no"];
                 if ($tmpFuncNo != "" && is_numeric($tmpFuncNo)) :
                    if (substr($tmpFuncNo, 0, 1) == "2") :
                       $tmpFuncNo = "ident_" . substr($tmpFuncNo, 1);
                    else :
                       $tmpFuncNo = substr($tmpFuncNo, 1);
                    endif;
                    $tmpPar1 = $orderArray["xml"]["order"]["stations"]["station"][$i]["services"]["calculator"]["func_item"][$j]["par_1"];
                    $tmpPar2 = $orderArray["xml"]["order"]["stations"]["station"][$i]["services"]["calculator"]["func_item"][$j]["par_2"];
                    $tmpPar3 = $orderArray["xml"]["order"]["stations"]["station"][$i]["services"]["calculator"]["func_item"][$j]["par_3"];
                    $tmpPar4 = $orderArray["xml"]["order"]["stations"]["station"][$i]["services"]["calculator"]["func_item"][$j]["par_4"];
                    $tmpPar5 = $orderArray["xml"]["order"]["stations"]["station"][$i]["services"]["calculator"]["func_item"][$j]["par_5"];
                    $tmpQuantity = $orderArray["xml"]["order"]["stations"]["station"][$i]["services"]["calculator"]["func_item"][$j]["quantity"];
                    if ($tmpQuantity == "" || !is_numeric($tmpQuantity)) : $tmpQuantity = 1; endif;
                    $trCalcFunctionsResultArray[$i][$j] = getMtfFunctionResult($hqId, $csId, "20", $tmpFuncNo, $tmpPar1, $tmpPar2, $tmpPar3, $tmpPar4, $tmpPar5);
                    if ($trCalcFunctionsResultArray[$i][$j] == "" || !is_numeric($trCalcFunctionsResultArray[$i][$j])) : $trCalcFunctionsResultArray[$i][$j] = 0; endif;
                    $trCalcFunctionsResultArray[$i][$j] = $tmpQuantity * $trCalcFunctionsResultArray[$i][$j];
                    // Totalprice of the job
                    $fixprice += $trCalcFunctionsResultArray[$i][$j];
                 endif;
             endfor;
          endif;

          // Special informations inserted into GDC structure
          $numOfGdcEntries = count($orderArray["xml"]["order"]["stations"]["station"][$i]["gdc"]["val"]);
          for ($k = 0; $k < $numOfGdcEntries; $k++) :
              $trGdcArray[$i][$k] = convertSpecial($orderArray["xml"]["order"]["stations"]["station"][$i]["gdc"]["val"][$k]);
          endfor;

          // Generation parts of the field "jb_tourdata" (e.g.: "04109;04316|Leipzig;Leipzig/Mölkau|DE;DE")
          if ($i > 0) :
             $jbTourdataZipcode .= ";";
             $jbTourdataCity .= ";";
             $jbTourdataCountry .= ";";
          endif;
          $jbTourdataZipcode .= $trZipcode[$i];
          $jbTourdataCity .= $trCity[$i];
          $jbTourdataCountry .= "DE";

          // Error handling
          if ($jbRemark == "" && $parJbRemarkMode == "") :
             $err[] = array("105", getLngt("Es wurde kein Rechnungstext übergeben."));
             $acceptOrder = false;
          endif;
          if ($trAdId[$i] == "") :
             $err[] = array("110", getLngt("Die Adressdaten sind nicht vollständig."));
             $acceptOrder = false;
          endif;
      endfor;

      // Generation of the field "jb_tourdata" (e.g.: "04109;04316|Leipzig;Leipzig/Mölkau|DE;DE")
      $jbTourdata = $jbTourdataZipcode . "|" . $jbTourdataCity . "|" . $jbTourdataCountry;
   else :
      $err[] = array("111", getLngt("Es konnten keine Stationen generiert werden."));
      $acceptOrder = false;
   endif;
   

   // Store into the database
if ($debug) :
   echo "csEid:" . $csEid . "<br>";
   echo "csId:" . $csId . "<br>";
   echo "usrAccount:" . $usrAccount . "<br>";
   echo "usrPassword:" . $usrPassword . "<br>";
   echo "cscName:" . $cscName . "<br>";
   echo "cscId:" . $cscId . "<br>";
   echo "hqMnemonic:" . $hqMnemonic . "<br>";
   echo "hqId:" . $hqId . "<br>";
   echo "hqId_XML:" . $hqId_XML . "<br>";
   echo "vhtId:" . $vhtId . "<br>";
   echo "vhtType:" . $vhtType . "<br>";
   echo "jbCrvhWeight:" . $jbCrvhWeight . "<br>";
   echo "jbCrvhLength:" . $jbCrvhLength . "<br>";
   echo "jbCrvhWidth:" . $jbCrvhWidth . "<br>";
   echo "jbCrvhHeight:" . $jbCrvhHeight . "<br>";
   echo "jbCrvhPosition:" . $jbCrvhPosition . "<br>";
   echo "jbOrdertime:" . $jbOrdertime . "<br>";
   echo "jbOrdertimeUTC:" . $jbOrdertimeUTC . "<br>";
   echo "jbWarningtime:" . $jbWarningtime . "<br>";
   echo "jbWarningtimeUTC:" . $jbWarningtimeUTC . "<br>";
   echo "crSid:" . $crSid . "<br>";
   echo "crIdOrder:" . $crIdOrder . "<br>";
   echo "jbCrFilter:" . $jbCrFilter . "<br>";
   echo "jbCrRemark:" . $jbCrRemark . "<br>";
   echo "jbTourdata:" . $jbTourdata . "<br>";
   echo "numOfStations:" . $numOfStations . "<br>";
   for ($i = 0; $i < $numOfStations; $i++) :
       echo "<br>";
       echo "* STATION " . $i . " * : <br>";
       echo "DELIVERY:"            . "<br>";
       echo $trWareFromTo[$i]      . "<br>";
       echo $trCostcenter[$i]      . "<br>";
       echo $trCscId[$i]           . "<br>";
       echo $trCompany[$i]         . "<br>";
       echo $trCompany2[$i]        . "<br>";
       echo $trAdId[$i]            . "<br>";
       echo $trStreet[$i]          . "<br>";
       echo $trHouseno[$i]         . "<br>";
       echo $trFloor[$i]           . "<br>";
       echo $trZipcode[$i]         . "<br>";
       echo $trCity[$i]            . "<br>";
       echo $trSpecialRemark[$i]   . "<br>";
       echo $trPerson[$i]          . "<br>";
       echo $trPhone[$i]           . "<br>";
       echo $trEmail[$i]           . "<br>";
       echo "INVOICE:"             . "<br>";
       echo $trInvCompany[$i]      . "<br>";
       echo $trInvCompany2[$i]     . "<br>";
       echo $trInvAdId[$i]         . "<br>";
       echo $trInvStreet[$i]       . "<br>";
       echo $trInvHouseno[$i]      . "<br>";
       echo $trInvZipcode[$i]      . "<br>";
       echo $trInvCity[$i]         . "<br>";
       echo $trInvSpecialRemark[$i]. "<br>";
       echo $trInvPerson[$i]       . "<br>";
       echo $trInvPhone[$i]        . "<br>";
       echo $trInvEmail[$i]        . "<br>";
       print_r($trServices[$i]); echo "<br>";
       echo "trInvVoucher:" . $trInvVoucher[$i] . "<br>";
       echo "trInvPaymentMethod:" . $trInvPaymentMethod[$i] . "<br>";
       echo "trArticleArray:"; print_r($trArticleArray[$i]); echo "<br>";
       print_r($trCalcFunctionsArray[$i]); echo "<br>";
       print_r($trCalcFunctionsResultArray[$i]); echo "<br>";
   endfor;
endif;

   $cscIdList = array();

   if ($csId != "" && $csId > "0") :
      $sqlquery = "SELECT csc.csc_id FROM costcenter AS csc WHERE csc.cs_id = '" . $csId . "'";
      $result = $db->query($sqlquery);
      if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
      while ($row = $result->fetch_assoc()):
            $cscIdList[] = $row["csc_id"];
      endwhile;
      $result->free();
   endif;
   if (count($cscIdList) > 0) :
      // Check for maximum number of jobs per day
      $numOfOrdersOfTheCurrentDay = getCountOfTable("job", "jb_modify >= '" . $currentDate . " 00:00:00' AND csc_id_payer IN (" . implode(",", $cscIdList) . ")");
      if ($numOfOrdersOfTheCurrentDay == "" || (is_numeric($numOfOrdersOfTheCurrentDay) && $numOfOrdersOfTheCurrentDay > $maxNumOfOrdersPerDay)) :
         $acceptOrder = false;
         $err[] = array("102", getLngt("Das Limit der Aufträge pro Tag wurde überschritten. Derzeit sind dies") . " " . $maxNumOfOrdersPerDay . " " . getLngt("Aufträge"));
      endif;
      // Check for maximum number of running jobs
      $numOfRunningOrders = getCountOfTable("job", "jb_status != '2' AND csc_id_payer IN (" . implode(",", $cscIdList) . ")");
      if ($numOfRunningOrders > $maxNumOfRunningOrders) :
         $acceptOrder = false;
         $err[] = array("103", getLngt("Das Limit insgesamt laufender Aufträge wurde überschritten. Derzeit sind dies") . " " . $maxNumOfRunningOrders . " " . getLngt("Aufträge"));
      endif;
   endif;   


   // Check existence of at least one error
   $errLen = count($err);

   if ($errLen == 0 && $acceptOrder) :

      // **********
      // * UPDATE *
      // **********

      if ($operationMode == "UPD" || $operationMode == "UPDATE") :

         // There are two options for updates:
         // [1.] All order data will be updated => Cancellation of the existing job and insert a new one
         // [2.] Partial update => All atomic tags being not be empty have to be updated
         $updateMode = "1";  // Option [1.]

         if ($jbIdUpdate != "" && is_numeric($jbIdUpdate) && $jbIdUpdate > "0") :

            if ($updateMode == "1") :
            
               $jbIdCancellation = $jbIdUpdate;  // Important for cancellation
               
               // Get ALL job IDs having $jbIdCancellation in "jb_parent_id"
               // $jbIdWithParentOfCancellation = getFieldValueFromId("job", "jb_id_parent", $jbIdCancellation, "jb_id");  // ONE JOB ONLY
               $jbIdArrayWithParentOfCancellation = getColVectorFromDB2ArrayByClause("job", "jb_id", "jb_id_parent = '" . $jbIdCancellation . "'", "", "", "");
            else :

               // Delta update
               // ............
            endif;

         else :
            $acceptOrder = false;
            $err[] = array("105", getLngt("Es wurde keine Auftragsnummer für ein Update übergeben!"));
         endif;

      endif;


      // **********
      // * DELETE *
      // **********

      $opCancellationExecuted = false;

      if ($operationMode == "DEL" || $operationMode == "DELETE" || $updateMode == "1") :

         if ($jbIdCancellation != "" && is_numeric($jbIdCancellation) && $jbIdCancellation > "0") :

            // Update job data
            $res = updateStmt("job", "jb_id", $jbIdCancellation, array("jb_storno", "1", "jb_status", "2", "jb_finishtime", $currentTime, "cr_sid", "", "jb_autoranking", "1"), "(jb_status = '8' OR jb_status = '9' OR jb_status = '0' OR jb_status = '1') AND (isnull(jb_storno) OR jb_storno = '0')");
            if ($db->affected_rows > 0) :

               // Remove existing commission number not to be found again in the future
               if ($parNoCancellation == "1") :
                  // Remove related order number from GDC (field "info_0")
                  updateStmt("genericdatacontainer", "gdc_obj_id", $jbIdCancellation, array("gdc_content", "XX" . $commissionNo . "XX"), "gdc_obj_type = 'jb' AND gdc_gen_fieldname = 'info_0' AND gdc_content = '" . $commissionNo . "'");
               elseif ($parNoCancellation == "2") :
                  // Do nothing because $jbIdCancellation =!= $commissionNo;
               else :
                  // DEFAULT: Remote order number equals commission number
                  updateStmt("tour", "jb_id", $jbIdCancellation, array("tr_commission_no", ""), "tr_commission_no = '" . $commissionNo . "'");
               endif;

               $opCancellationExecuted = true;

               // Remove job from FDS
               removeAssocCrvhJb($jbIdCancellation, $csId);
            else :
               $acceptOrder = false;
               $err[] = array("107", getLngt("Der Stornovorgang konnte nicht abgeschlossen werden, weil entweder der Auftrag schon storniert wurde oder sich in der Ausführung befindet!"));
            endif;
         else :
            $acceptOrder = false;
            $err[] = array("106", getLngt("Es wurde keine Auftragsnummer für ein Storno übergeben!"));
         endif;
         
      endif;


      // **********
      // * INSERT *
      // **********

      if ($operationMode == "" || $operationMode == "INS" || $operationMode == "INSERT" || ($updateMode == "1" && $opCancellationExecuted)) :

         TA("B");

         if ($globalParUseRelatedCustomer == "1") :

            // **** INSERT CUSTOMER DATA ****

            $tmpStation = "1";  // End customer data in second station by delivery and installation
            $orderIsRetour = false;
            $orderIsExchange = false;
            // Check for "Retoure" <=> customer data in the first station
            if (((int)$trShipmentMode[0] & 128) == 128 || ((int)$trShipmentMode[1] & 128) == 128) :
               $orderIsRetour = true;
               $tmpStation = "0";
            endif;
            // Check for "Exchange" <=> Normal order with added station with retour state
            if (((int)$trShipmentMode[0] & 256) == 256 || ((int)$trShipmentMode[1] & 256) == 256) :
               $orderIsExchange = true;
            endif;


            // SPECIAL WRAPPER TO CHANGE PLACES OF FIRST STATION AND SECOND STATION BECAUSE OF CURRENT APP
            // WRAPPER START
            if (true && $orderIsRetour) :
               $tmpStation = "1";  // End customer data in second station by delivery and installation IN EVERY CASE !!!!

               $tmpVal = $trCscId[1];                 $trCscId[1] = $trCscId[0];                           $trCscId[0] = $tmpVal;
               $tmpVal = $trWareFromTo[1];            $trWareFromTo[1] = $trWareFromTo[0];                 $trWareFromTo[0] = $tmpVal;
               $tmpVal = $trCommissionNo[1];          $trCommissionNo[1] = $trCommissionNo[0];             $trCommissionNo[0] = $tmpVal;
               $tmpVal = $trCostcenter[1];            $trCostcenter[1] = $trCostcenter[0];                 $trCostcenter[0] = $tmpVal;
               $tmpVal = $trCompany[1];               $trCompany[1] = $trCompany[0];                       $trCompany[0] = $tmpVal;
               $tmpVal = $trCompany2[1];              $trCompany2[1] = $trCompany2[0];                     $trCompany2[0] = $tmpVal;
               $tmpVal = $trScanCodeMandatory[1];     $trScanCodeMandatory[1] = $trScanCodeMandatory[0];   $trScanCodeMandatory[0] = $tmpVal;
               $tmpVal = $trStreet[1];                $trStreet[1] = $trStreet[0];                         $trStreet[0] = $tmpVal;
               $tmpVal = $trHouseno[1];               $trHouseno[1] = $trHouseno[0];                       $trHouseno[0] = $tmpVal;
               $tmpVal = $trFloor[1];                 $trFloor[1] = $trFloor[0];                           $trFloor[0] = $tmpVal;
               $tmpVal = $trZipcode[1];               $trZipcode[1] = $trZipcode[0];                       $trZipcode[0] = $tmpVal;
               $tmpVal = $trCity[1];                  $trCity[1] = $trCity[0];                             $trCity[0] = $tmpVal;
               $tmpVal = $trAdId[1];                  $trAdId[1] = $trAdId[0];                             $trAdId[0] = $tmpVal;
               $tmpVal = $trSpecialRemark[1];         $trSpecialRemark[1] = $trSpecialRemark[0];           $trSpecialRemark[0] = $tmpVal;
               $tmpVal = $trPerson[1];                $trPerson[1] = $trPerson[0];                         $trPerson[0] = $tmpVal;
               $tmpVal = $trPhone[1];                 $trPhone[1] = $trPhone[0];                           $trPhone[0] = $tmpVal;
               $tmpVal = $trEmail[1];                 $trEmail[1] = $trEmail[0];                           $trEmail[0] = $tmpVal;
               $tmpVal = $trAdSupplement_1[1];        $trAdSupplement_1[1] = $trAdSupplement_1[0];         $trAdSupplement_1[0] = $tmpVal;
               $tmpVal = $trAdSupplement_2[1];        $trAdSupplement_2[1] = $trAdSupplement_2[0];         $trAdSupplement_2[0] = $tmpVal;
               $tmpVal = $trAdSupplement_3[1];        $trAdSupplement_3[1] = $trAdSupplement_3[0];         $trAdSupplement_3[0] = $tmpVal;
               $tmpVal = $trAdSupplement_4[1];        $trAdSupplement_4[1] = $trAdSupplement_4[0];         $trAdSupplement_4[0] = $tmpVal;
               $tmpVal = $trAdSupplement_5[1];        $trAdSupplement_5[1] = $trAdSupplement_5[0];         $trAdSupplement_5[0] = $tmpVal;
               $tmpVal = $trInvCompany[1];            $trInvCompany[1] = $trInvCompany[0];                 $trInvCompany[0] = $tmpVal;
               $tmpVal = $trInvCompany2[1];           $trInvCompany2[1] = $trInvCompany2[0];               $trInvCompany2[0] = $tmpVal;
               $tmpVal = $trInvStreet[1];             $trInvStreet[1] = $trInvStreet[0];                   $trInvStreet[0] = $tmpVal;
               $tmpVal = $trInvHouseno[1];            $trInvHouseno[1] = $trInvHouseno[0];                 $trInvHouseno[0] = $tmpVal;
               $tmpVal = $trInvFloor[1];              $trInvFloor[1] = $trInvFloor[0];                     $trInvFloor[0] = $tmpVal;
               $tmpVal = $trInvZipcode[1];            $trInvZipcode[1] = $trInvZipcode[0];                 $trInvZipcode[0] = $tmpVal;
               $tmpVal = $trInvCity[1];               $trInvCity[1] = $trInvCity[0];                       $trInvCity[0] = $tmpVal;
               $tmpVal = $trInvAdId[1];               $trInvAdId[1] = $trInvAdId[0];                       $trInvAdId[0] = $tmpVal;
               $tmpVal = $trInvSpecialRemark[1];      $trInvSpecialRemark[1] = $trInvSpecialRemark[0];     $trInvSpecialRemark[0] = $tmpVal;
               $tmpVal = $trInvPerson[1];             $trInvPerson[1] = $trInvPerson[0];                   $trInvPerson[0] = $tmpVal;
               $tmpVal = $trInvPhone[1];              $trInvPhone[1] = $trInvPhone[0];                     $trInvPhone[0] = $tmpVal;
               $tmpVal = $trInvEmail[1];              $trInvEmail[1] = $trInvEmail[0];                     $trInvEmail[0] = $tmpVal;
               $tmpVal = $trInvAdSupplement_1[1];     $trInvAdSupplement_1[1] = $trInvAdSupplement_1[0];   $trInvAdSupplement_1[0] = $tmpVal;
               $tmpVal = $trInvAdSupplement_2[1];     $trInvAdSupplement_2[1] = $trInvAdSupplement_2[0];   $trInvAdSupplement_2[0] = $tmpVal;
               $tmpVal = $trInvAdSupplement_3[1];     $trInvAdSupplement_3[1] = $trInvAdSupplement_3[0];   $trInvAdSupplement_3[0] = $tmpVal;
               $tmpVal = $trInvAdSupplement_4[1];     $trInvAdSupplement_4[1] = $trInvAdSupplement_4[0];   $trInvAdSupplement_4[0] = $tmpVal;
               $tmpVal = $trInvAdSupplement_5[1];     $trInvAdSupplement_5[1] = $trInvAdSupplement_5[0];   $trInvAdSupplement_5[0] = $tmpVal;
               $tmpVal = $trInvPaymentMethod[1];      $trInvPaymentMethod[1] = $trInvPaymentMethod[0];     $trInvPaymentMethod[0] = $tmpVal;
               $tmpVal = $trInvVoucher[1];            $trInvVoucher[1] = $trInvVoucher[0];                 $trInvVoucher[0] = $tmpVal;
               $tmpVal = $trInvpartialPayment[1];     $trInvpartialPayment[1] = $trInvpartialPayment[0];   $trInvpartialPayment[0] = $tmpVal;
               $tmpVal = $trInvPriceMode[1];          $trInvPriceMode[1] = $trInvPriceMode[0];             $trInvPriceMode[0] = $tmpVal;
               $tmpVal = $trGdcArray[1];              $trGdcArray[1] = $trGdcArray[0];                     $trGdcArray[0] = $tmpVal;

               // Station services
               $tmpVal = $trServices[1];              $trServices[1] = $trServices[0];                     $trServices[0] = $tmpVal;
               $tmpVal = $trTimeslots[1];             $trTimeslots[1] = $trTimeslots[0];                   $trTimeslots[0] = $tmpVal;
               $tmpVal = $trTimesunits[1];            $trTimesunits[1] = $trTimesunits[0];                 $trTimesunits[0] = $tmpVal;
               $tmpVal = $trShipmentMode[1];          $trShipmentMode[1] = $trShipmentMode[0];             $trShipmentMode[0] = $tmpVal;
               $tmpVal = $trOrderType[1];             $trOrderType[1] = $trOrderType[0];                   $trOrderType[0] = $tmpVal;
               $tmpVal = $trDeliveryInfo[1];          $trDeliveryInfo[1] = $trDeliveryInfo[0];             $trDeliveryInfo[0] = $tmpVal;
               $tmpVal = $trFlagServiceDoc[1];        $trFlagServiceDoc[1] = $trFlagServiceDoc[0];         $trFlagServiceDoc[0] = $tmpVal;
               $tmpVal = $trDocumentsURL[1];          $trDocumentsURL[1] = $trDocumentsURL[0];             $trDocumentsURL[0] = $tmpVal;

               // Arrays for summarized article fields OR maximum values
               $tmpVal = $trSumWeight[1];             $trSumWeight[1] = $trSumWeight[0];                   $trSumWeight[0] = $tmpVal;
               $tmpVal = $trSumPositions[1];          $trSumPositions[1] = $trSumPositions[0];             $trSumPositions[0] = $tmpVal;
               $tmpVal = $trSumPieces[1];             $trSumPieces[1] = $trSumPieces[0];                   $trSumPieces[0] = $tmpVal;
               $tmpVal = $trSumVolume[1];             $trSumVolume[1] = $trSumVolume[0];                   $trSumVolume[0] = $tmpVal;
               $tmpVal = $trSumPrices[1];             $trSumPrices[1] = $trSumPrices[0];                   $trSumPrices[0] = $tmpVal;
               $tmpVal = $trMaxHeight[1];             $trMaxHeight[1] = $trMaxHeight[0];                   $trMaxHeight[0] = $tmpVal;
               $tmpVal = $trMaxLength[1];             $trMaxLength[1] = $trMaxLength[0];                   $trMaxLength[0] = $tmpVal;
               $tmpVal = $trMaxWidth[1];              $trMaxWidth[1] = $trMaxWidth[0];                     $trMaxWidth[0] = $tmpVal;
               $tmpVal = $trMaxDimension[1];          $trMaxDimension[1] = $trMaxDimension[0];             $trMaxDimension[0] = $tmpVal;
               
               $tmpVal = $trArticleArray[1];          $trArticleArray[1] = $trArticleArray[0];             $trArticleArray[0] = $tmpVal;
            endif;
            // WRAPPER END


            // Set service state for the job
            $jbService = $trShipmentMode[$tmpStation];
            if ($jbService == "" || !is_numeric($jbService)) :
               $jbService = 1;
            endif;
            if (((int)$jbService & 128) == 128 && ((int)$jbService & 1) == 0 && ((int)$jbService & 2) == 0) : $jbService = ($jbService | 1); endif;  // Add delivery to retour if neither delivery nor installation
            if (((int)$jbService & 4) == 4 && ((int)$jbService & 2) == 0) : $jbService = ($jbService | 2); endif;    // Add "standard installation bit" to special installation
            if (((int)$jbService & 16) == 16 && ((int)$jbService & 2) == 0) : $jbService = ($jbService | 2); endif;  // Add "standard installation bit" to special installation
            if ($orderIsExchange) :
               // Fallback for exchange
               if ($jbService == "" || $jbService == 0) : $jbService = 385; endif;  // Exchange (containing Delivery and Retoure)
            endif;

            // Set time units for the job
            $jbTimeUnits = $trTimesunits[$tmpStation];
            if ($jbTimeUnits == "" || !is_numeric($jbTimeUnits) || $jbTimeUnits < "2") :
               $jbTimeUnits = "2";
            endif;

$debugOut .= "trShipmentMode[0]: " . $trShipmentMode[0] . " (1 = Delivery, 0 = Retoure)<br><br>\n";
$debugOut .= "trShipmentMode[1]: " . $trShipmentMode[1] . " (1 = Delivery, 0 = Retoure)<br><br>\n";
$debugOut .= "(trShipmentMode[0] & 128): " . ((int)$trShipmentMode[0] & 128) . "<br><br>\n";
$debugOut .= "(trShipmentMode[1] & 128): " . ((int)$trShipmentMode[1] & 128) . "<br><br>\n";
$debugOut .= "tmpStation: " . $tmpStation . " (1 = Delivery, 0 = Retoure)<br><br>\n";
$debugOut .= "orderIsExchange: " . ($orderIsExchange ? "YES" : "NO") . "<br><br>\n";
$debugOut .= "jbService: " . $jbService . "<br><br>\n";

            // The authenticated customer will be the related customer and the end customer will be the payer (look below) !!!!
            $cscNameNew      = $trCompany[$tmpStation];
            $cscInvNameNew   = $trInvCompany[$tmpStation];
            if ($cscInvNameNew == "") : $cscInvNameNew = $cscNameNew; endif;
            $cscadHsnoNew    = $trHouseno[$tmpStation];
            $cscadInvHsnoNew = $trInvHouseno[$tmpStation];
            if ($cscadInvHsnoNew == "") : $cscadInvHsnoNew = $cscadHsnoNew; endif;
            $adIdNew         = $trAdId[$tmpStation];
            $adIdInvNew      = $trInvAdId[$tmpStation];
            if ($adIdInvNew == "") : $adIdInvNew = $adIdNew; endif;
            $cscadRemark     = "";  // $trSpecialRemark[$tmpStation];
            $cscadInvRemark  = "";  // $trInvSpecialRemark[$tmpStation];
            // if ($cscadInvRemark == "") : $cscadInvRemark = $cscadRemark; endif;
            $cscadPerson     = $trPerson[$tmpStation];
            $cscadInvPerson  = $trInvPerson[$tmpStation];
            // if ($cscadInvPerson == "") : $cscadInvPerson = $cscadPerson; endif;
            $cscadPhone      = $trPhone[$tmpStation];
            $cscadInvPhone   = $trInvPhone[$tmpStation];
            // if ($cscadInvPhone == "") : $cscadInvPhone = $cscadPhone; endif;
            $cscadEmail      = $trEmail[$tmpStation];
            $cscadInvEmail   = $trInvEmail[$tmpStation];
            // if ($cscadInvEmail == "") : $cscadInvEmail = $cscadEmail; endif;
            $cscadFloor      = $trFloor[$tmpStation];
            $cscadInvFloor   = $trInvFloor[$tmpStation];
            // if ($cscadInvFloor == "") : $cscadInvFloor = $cscadFloor; endif;

            $cscadZipcode    = $trZipcode[$tmpStation];

            // Handling of commission number(s)
            if ($commissionNo != "") :
               $trCommissionNo[$tmpStation] = $commissionNo;  // Overwrite if exist
            endif;

$debugOut .= "cscNameNew: " . $cscNameNew . "<br>\n";
$debugOut .= "cscadHsnoNew: " . $cscadHsnoNew . "<br>\n";
$debugOut .= "adIdNew: " . $adIdNew . "<br>\n";
$debugOut .= "adIdInvNew: " . $adIdInvNew . "<br>\n";
$debugOut .= "cscadRemark: " . $cscadRemark . "<br>\n";
$debugOut .= "cscadInvRemark: " . $cscadInvRemark . "<br>\n";
$debugOut .= "cscadPerson: " . $cscadPerson . "<br>\n";
$debugOut .= "cscadInvPerson: " . $cscadInvPerson . "<br>\n";
$debugOut .= "cscadPhone: " . $cscadPhone . "<br>\n";
$debugOut .= "cscadInvPhone: " . $cscadInvPhone . "<br>\n";
$debugOut .= "cscadEmail: " . $cscadEmail . "<br>\n";
$debugOut .= "cscadInvEmail: " . $cscadInvEmail . "<br>\n";
$debugOut .= "cscadFloor: " . $cscadFloor . "<br>\n";
$debugOut .= "cscadInvFloor: " . $cscadInvFloor . "<br>\n";
$debugOut .= "cscadZipcode: " . $cscadZipcode . "<br>\n";
$debugOut .= "<br>\n";

            if ($cscNameNew != "") :

               // Insert costcenter
               insertStmt("costcenter", array("csc_name", $cscNameNew, "csc_is_extern", 1, "csc_visible", 1));
               $cscIdNew = getLastInsertId();

               // Get tour.csc_id for the NEW end customer in csc.csc_id
               if ($trCscId[$tmpStation] == "") :
                  $trCscId[$tmpStation] = $cscIdNew;
                  $cscIdPayer = $cscIdNew;
               endif;

$debugOut .= "trCscId[$tmpStation]: " . $trCscId[$tmpStation] . "<br>\n";
$debugOut .= "cscIdPayer: " . $cscIdPayer . "<br>\n";
$debugOut .= "cscIdRelated: " . $cscIdRelated . "<br>\n";
$debugOut .= "<br>\n";

               // Insert company
               insertStmt("company", array("cmp_comp", $cscInvNameNew, "ad_id", $adIdInvNew,"cmp_hsno", $cscadInvHsnoNew, "cmp_authenticated", "1", "cmp_visible", "1", "cmp_modify_status", "0"));
               $cmpIdNew = getLastInsertId();
               $csEidNew = $parHqInstance . ($db->getOne("SELECT RIGHT(MAX(cs_eid),5) FROM customer WHERE LEFT(cs_eid, " . strlen($parHqInstance) . ") = '" . $parHqInstance . "'") + 1);

               // Insert customer
               insertStmt("customer", array("cmp_id", $cmpIdNew, "hq_id", $hqId, "csc_id", $cscIdNew, "cs_eid", $csEidNew, "cs_invmode", 2, "cs_id_related", $csIdRelated));
               $csIdNew = getLastInsertId();

               // Update new costcenter with new customer
               updateStmt("costcenter", "csc_id", $cscIdNew, array("cs_id", $csIdNew));

               // Update the costcenteraddresses
               insertStmt("costcenteraddress", array("csc_id", $cscIdNew, "cscad_comp", $cscNameNew, "ad_id", $adIdNew, "adt_id", 1, "cscad_hsno", $cscadHsnoNew, "cscad_remark", $cscadRemark, "cscad_person", $cscadPerson, "cscad_phone", $cscadPhone, "cscad_email", $cscadEmail, "cscad_floor", $cscadFloor));
               insertStmt("costcenteraddress", array("csc_id", $cscIdNew, "cscad_comp", $cscNameNew, "ad_id", $adIdInvNew, "adt_id", 2, "cscad_hsno", $cscadHsnoNew, "cscad_remark", $cscadInvRemark, "cscad_person", $cscadInvPerson, "cscad_phone", $cscadInvPhone, "cscad_email", $cscadInvEmail, "cscad_floor", $cscadInvFloor));
               insertStmt("costcenteraddress", array("csc_id", $cscIdNew, "cscad_comp", $cscNameNew, "ad_id", $adIdInvNew, "adt_id", 3, "cscad_hsno", $cscadHsnoNew, "cscad_remark", $cscadInvRemark, "cscad_person", $cscadInvPerson, "cscad_phone", $cscadInvPhone, "cscad_email", $cscadInvEmail, "cscad_floor", $cscadInvFloor));
               insertStmt("costcenteraddress", array("csc_id", $cscIdNew, "cscad_comp", $cscNameNew, "ad_id", $adIdNew, "adt_id", 4, "cscad_hsno", $cscadHsnoNew, "cscad_remark", $cscadRemark, "cscad_person", $cscadPerson, "cscad_phone", $cscadPhone, "cscad_email", $cscadEmail, "cscad_floor", $cscadFloor));

            else :
              $acceptOrder = false;
              $err[] = array("104", getLngt("Der Endkundendatensatz konnte nicht angelegt werden."));
            endif;
         endif;


         // Order
         if ($acceptOrder) :

            insertStmt("job", array("hq_id", $hqId, "csc_id", $cscIdPayer, "vht_id", $vhtId, "csc_id_payer", $cscIdPayer, "csc_id_related", $cscIdRelated, "jb_payment", "0",
                                    "jb_ordertime", $jbOrdertime, "jb_reserv", $jbReserv, "cr_id", "", "cr_sid", $crSid, "cr_id_order", $crIdOrder,
                                    "jb_cr_filter", $jbCrFilter, "jb_cr_filter_opt", "", "jb_waitstorno", "0", 
                                    "jb_taketime", "", "jb_status", $jbStatus, "jb_autoranking", "0", "jb_type", $jbType, 
                                    "jb_incomplete", "0", "jb_globaljob", "0", "jb_tourname", $jbTourname,
                                    "jb_finishtime", "", "jb_warningtime", $jbWarningtime, "emp_id", $usr_id, "jb_fixprice", $fixprice, "jb_totalprice", $fixprice,
                                    "jb_postage", $cmpPostage, "jb_invmode", $csInvmode, "jb_freetext_1", $jbRemark,
                                    "jb_weight", $jbCrvhWeight, "jb_crvh_length", $jbCrvhLength, "jb_crvh_width", $jbCrvhWidth, 
                                    "jb_crvh_height", $jbCrvhHeight, "jb_crvh_position", $jbCrvhPosition, 
                                    "jb_tourdata", $jbTourdata, "jb_lockuser", "0", "jb_id_parent", $jbIdParent, "jb_dispoinfo", "",
                                    "jb_sales_tax_rate", $txValue, "jb_sales_tax_rate_sign", $txSign, "jb_createtime", $currentTime,
                                    "jb_timeunits", $jbTimeUnits, "jb_service", $jbService, "jb_booktime", ""));
            $jbIdNew = getLastInsertId();

            // Look for REVERSE mode of parent relation
            // Standard mode: "jb_id_parent" of the current job will be set with value of identified ID in $jbIdParent
            // Reverse mode : "jb_id_parent" of the identified job in $jbIdParent will have the value $jbIdNew
            // (E.g. the installation job is older than the delivery job, but "jb_id_parent" of installation job has to be filled with the reference to the delivery job)
            $parNoRelatedReverse = "";
            if ($jbIdParent != "") :
               $parNoRelatedReverse = getObjectBasedParameterValue("ORDER_REQUEST_NO_RELATED_REVERSE_MODE", $csId, $hqId);
               if ($parNoRelatedReverse == "1") :
                  // Reverse mode activated
                  // [1.] Remove inserted standard relation
                  updateStmt("job","jb_id",$jbIdNew,array("jb_id_parent", ""));
                  // [2.] Update "jb_id_parent" eof xisting older job with current job in $jbIdNew
                  updateStmt("job","jb_id",$jbIdParent,array("jb_id_parent", $jbIdNew));
               endif;
            endif;

            // Change existing "jb_id_parent" of ALL jobs refering the deleted reference to the new one
            if (count($jbIdArrayWithParentOfCancellation) > 0 && ($updateMode == "1" && $opCancellationExecuted)) :
               updateStmt("job","","",array("jb_id_parent", $jbIdNew),"jb_id IN (" . implode(",",$jbIdArrayWithParentOfCancellation) . ")");
            endif;

            // Special informations inserted into GDC structure
            $numOfGdcEntries = count($jbGdcArray);
            if ($numOfGdcEntries > 0) :
               for ($k = 0; $k < $numOfGdcEntries; $k++) :
                   if ($jbGdcArray[$k] != "") :
                      insertStmt("genericdatacontainer", array("gdc_obj_type", "jb", "gdc_obj_id", $jbIdNew, "gdc_gen_fieldname", "info_" . $k, "gdc_content", $jbGdcArray[$k], "gdc_context", ""));
                   endif;
               endfor;
            endif;

            // Insert merged job in GDC
            if ($commNoMerged != "") :
               insertStmt("genericdatacontainer", array("gdc_obj_type", "jb", "gdc_obj_id", $jbIdNew, "gdc_gen_fieldname", "no_merged", "gdc_content", $commNoMerged, "gdc_context", ""));
            endif;
            if ($jbIdMerged != "") :
               insertStmt("genericdatacontainer", array("gdc_obj_type", "jb", "gdc_obj_id", $jbIdNew, "gdc_gen_fieldname", "jb_merged", "gdc_content", $jbIdMerged, "gdc_context", ""));
            endif;
            
            // Acquisition time, e.g. departure date from compound shipment. (It is NOT the create time of the job)
            if ($jbAcquisitiontime != "") :
               insertStmt("genericdatacontainer", array("gdc_obj_type", "jb", "gdc_obj_id", $jbIdNew, "gdc_gen_fieldname", "acquisitiontime", "gdc_content", $jbAcquisitiontime, "gdc_context", ""));
            endif;

            // Insert special service number of the job in GDC
            if ($commNoService != "") :
               insertStmt("genericdatacontainer", array("gdc_obj_type", "jb", "gdc_obj_id", $jbIdNew, "gdc_gen_fieldname", "jb_service_job", "gdc_content", "1", "gdc_context", $commNoService));
            endif;


            // Stations
            $trIdPickup = 0;  // Init for writing EVENT "PLANNED"
            for ($i = 0; $i < $numOfStations; $i++) :

                $trServicesArray[] = $trServices[$i];  // Services and prices for calling price function

                $trSort = $i + 1;

                $trCommissionNoNew = "";
                if ($globalParUseRelatedCustomer == 1) :
                   if ($i == $tmpStation) :
                      $trCommissionNoNew = $trCommissionNo[$i];
                   endif;
                else :
                   $trCommissionNoNew = $commissionNo;
                endif;

                // Insert tour data for station
                insertStmt("tour", array("jb_id", $jbIdNew, "ad_id", $trAdId[$i], "tr_sort", $trSort, "tr_comp", $trCompany[$i], "tr_comp2", $trCompany2[$i],
                                         "tr_hsno", $trHouseno[$i], "tr_floor", $trFloor[$i], "csc_id", $trCscId[$i], "tr_status", "0", 
                                         "tr_commission_no", $trCommissionNoNew, "tr_ware_from_to", $trWareFromTo[$i], 
                                         "tr_person", $trPerson[$i], "tr_phone", $trPhone[$i], "tr_remark", $trSpecialRemark[$i]));
                $trIdNew = getLastInsertId();

                // Remember unique tr_id of pick-up station for EVENT "PLANNED"
                if ($i == 0) :
                   $trIdPickup = $trIdNew;
                endif;

                // Insert tourservice data
                /* INSERTED BY FUNCTION mk_price()
                insertStmt("tourservice", array("jb_id", $jbIdNew, "csc_id", $trCscId[$i], "tr_sort", "0", 
                                                "srv_id", "0", "trs_srv_name", "Fixpreis", "srvt_id", "0", "trs_srvt_name", ""));
                */

                if ($globalParUseRelatedCustomer != 1) :
                   $commissionNo = "";   // Reset commission number because associated to the first station only
                endif;

                // Special informations inserted into GDC structure
                $numOfGdcEntries = count($trGdcArray[$i]);
                if ($numOfGdcEntries > 0) :
                   for ($k = 0; $k < $numOfGdcEntries; $k++) :
                       if ($trGdcArray[$i][$k] != "") :
                          insertStmt("genericdatacontainer", array("gdc_obj_type", "tr", "gdc_obj_id", $jbIdNew, "gdc_gen_fieldname", "info_" . $k, "gdc_content", $trGdcArray[$i][$k], "gdc_context", $i));
                       endif;
                   endfor;
                endif;

                // Mandatory scan (bar)code
                if ($trScanCodeMandatory[$i] != "") :
                   insertStmt("genericdatacontainer", array("gdc_obj_type", "tr", "gdc_obj_id", $trIdNew, "gdc_gen_fieldname", "scan_code_mandatory", "gdc_content", $trScanCodeMandatory[$i], "gdc_context", ""));
                endif;

                // Insert (or update existing) (invoice) address supplement entries in GDC
                $tmpAddressSupplement = $trAdSupplement_1[$i] . "|" . $trAdSupplement_2[$i] . "|" . $trAdSupplement_3[$i] . "|" . $trAdSupplement_4[$i] . "|" . $trAdSupplement_5[$i];
                if ($tmpAddressSupplement != "||||") :
                   if (existsEntry("genericdatacontainer",array("gdc_obj_type","jb","gdc_gen_fieldname","ad_supplement","gdc_obj_id",$jbIdNew,"gdc_context",$trSort))) :
                      updateStmt("genericdatacontainer","gdc_obj_type","jb",array("gdc_content", $tmpAddressSupplement),"gdc_obj_id = '" . $jbIdNew . "' AND gdc_gen_fieldname = 'ad_supplement' AND gdc_context = '" . $trSort . "'");
                   else :
                      insertStmt("genericdatacontainer", array("gdc_obj_type", "jb", "gdc_obj_id", $jbIdNew, "gdc_gen_fieldname", "ad_supplement", "gdc_content", $tmpAddressSupplement, "gdc_context", $trSort));
                   endif;
                endif;
                $tmpInvAddressSupplement = $trInvAdSupplement_1[$i] . "|" . $trInvAdSupplement_2[$i] . "|" . $trInvAdSupplement_3[$i] . "|" . $trInvAdSupplement_4[$i] . "|" . $trInvAdSupplement_5[$i];
                if ($tmpInvAddressSupplement != "||||") :
                   if (existsEntry("genericdatacontainer",array("gdc_obj_type","jb","gdc_gen_fieldname","ad_inv_supplement","gdc_obj_id",$jbIdNew,"gdc_context",$trSort))) :
                      updateStmt("genericdatacontainer","gdc_obj_type","jb",array("gdc_content", $tmpInvAddressSupplement),"gdc_obj_id = '" . $jbIdNew . "' AND gdc_gen_fieldname = 'ad_inv_supplement' AND gdc_context = '" . $trSort . "'");
                   else :
                      insertStmt("genericdatacontainer", array("gdc_obj_type", "jb", "gdc_obj_id", $jbIdNew, "gdc_gen_fieldname", "ad_inv_supplement", "gdc_content", $tmpInvAddressSupplement, "gdc_context", $trSort));
                   endif;
                endif;


                // Insert tourarticle data
                $numOfArticles = count($trArticleArray[$i]);
                if ($numOfArticles > 0) :
                   for ($j = 0; $j < $numOfArticles; $j++) :
                       insertStmt("tourarticle", array("jb_id", $jbIdNew, "tr_sort", $trSort, "trat_sort", $j, "at_id", "", "trat_quantity", $trArticleArray[$i][$j]["quantity"], 
                                                       "trat_weight", $trArticleArray[$i][$j]["weight"], "trat_price", $trArticleArray[$i][$j]["price"], 
                                                       "trat_packingpieces", $trArticleArray[$i][$j]["pieces"], "trat_serialno", $trArticleArray[$i][$j]["serialno"], 
                                                       "trat_remark", $trArticleArray[$i][$j]["description"], "trat_createtime", $currentTime));                                                 
                   endfor;

                   // If total sum of tourarticle weight had been sent and overruled the computed sum value then store it in the GDC
                   if ($trSumWeight != "" && is_numeric($trSumWeight) && $trSumWeight > 0 && $tmpTotalWeight != "" && is_numeric($tmpTotalWeight) && $tmpTotalWeight > 0) :
                      insertStmt("genericdatacontainer", array("gdc_obj_type", "tr", "gdc_obj_id", $trIdNew, "gdc_gen_fieldname", "trat_sum_weight", "gdc_content", $trSumWeight, "gdc_context", $trSort));
                   endif;

                   // If total sum of tourarticle weight had been sent and overruled the computed sum value then store it in the GDC
                   if ($trSumPieces != "" && is_numeric($trSumPieces) && $trSumPieces > 0 && $tmpTotalPieces != "" && is_numeric($tmpTotalPieces) && $tmpTotalPieces > 0) :
                      insertStmt("genericdatacontainer", array("gdc_obj_type", "tr", "gdc_obj_id", $trIdNew, "gdc_gen_fieldname", "trat_sum_pieces", "gdc_content", $trSumPieces, "gdc_context", $trSort));
                   endif;

                   // If total sum of tourarticle weight had been sent and overruled the computed sum value then store it in the GDC
                   if ($trSumVolume != "" && is_numeric($trSumVolume) && $trSumVolume > 0 && $tmpTotalVolume != "" && is_numeric($tmpTotalVolume) && $tmpTotalVolume > 0) :
                      insertStmt("genericdatacontainer", array("gdc_obj_type", "tr", "gdc_obj_id", $trIdNew, "gdc_gen_fieldname", "trat_sum_volume", "gdc_content", $trSumVolume, "gdc_context", $trSort));
                   endif;

                   // If total sum of tourarticle weight had been sent and overruled the computed sum value then store it in the GDC
                   if ($trSumMeters != "" && is_numeric($trSumMeters) && $trSumMeters > 0 && $tmpTotalMeters != "" && is_numeric($tmpTotalMeters) && $tmpTotalMeters > 0) :
                      insertStmt("genericdatacontainer", array("gdc_obj_type", "tr", "gdc_obj_id", $trIdNew, "gdc_gen_fieldname", "trat_sum_meters", "gdc_content", $trSumMeters, "gdc_context", $trSort));
                   endif;
                endif;
            endfor;

            // Write tour article services for the job
            if (count($tratModeArray) > 0) :
               insertStmt("genericdatacontainer", array("gdc_obj_type", "jb", "gdc_obj_id", $jbIdNew, "gdc_gen_fieldname", "jb_add_service_info", "gdc_content", implode(",",$tratModeArray), "gdc_context", ""));
            endif;

            // Write EVENT "PLANNED" (presently for installation only)
            if (((int)$jbService & 2) == 2) :
               if ($trIdPickup != "" && $trIdPickup > 0) :
                  insertStmt("phoenix_log.b2b_objects", array("bo_ver", "0", "bo_type", "300", "bo_state", "1", "bo_ext_id0", $jbIdNew, "bo_ext_id1", $trIdPickup, "bo_ext_id2", $usr_id, "bo_obj_data", $commissionNo . "|501", "bo_createtime", $currentTime));
               endif;
            endif;

            // Write relation to new job after cancellation
            if ($opCancellationExecuted && $jbIdCancellation != "") :
               // Reference to cancelled job by update
               insertStmt("genericdatacontainer", array("gdc_obj_type", "jb", "gdc_obj_id", $jbIdNew, "gdc_gen_fieldname", "jb_storno", "gdc_content", $jbIdCancellation, "gdc_context", ""));
               if ($updateMode == "1") :
                  // Reference to new job after update
                  insertStmt("genericdatacontainer", array("gdc_obj_type", "jb", "gdc_obj_id", $jbIdCancellation, "gdc_gen_fieldname", "jb_update", "gdc_content", $jbIdNew, "gdc_context", ""));
               endif;
            endif;

            // --------------------------------------------------------
            // Get available vehicle data
$debugOut .= "START DISPOSITION<br>\n";

            if (!isset($hourTimeUnits) || $hourTimeUnits == "") : $hourTimeUnits = 6; endif;
            $ecoDayTimeArray = array();     // Init for whole day
            $ecoWeekdayArray = array();     // Wochentage irrelevant !!!!!!!!!!!!!!!!!!!!!!!!!!

            // Check day time of the order regarding the day times of the (related) customer
            if ($csId != "") :
               $hourStart = substr($jbOrdertime,11);  // E.g. 07:00:00
               $hourEnd = substr($jbWarningtime,11);  // E.g. 21:00:00
           
               $clockTimeArray = metatypeGetMappedValues("day_time", "", $csId, "cs", "1");
               $clockTimeArrayLen = count($clockTimeArray);
               if ($clockTimeArrayLen > 0) :
                  for ($d = 0; $d < $clockTimeArrayLen; $d++) :
                    if ($clockTimeArray[$d][0] == $hourStart || $clockTimeArray[$d][1] == $hourEnd) :
                       array_push($ecoDayTimeArray, $d);
                    endif;
                  endfor;
               endif;
               // Reset to whole day if count("day_times_of_the_customer") == count($ecoDayTimeArray)
               if (count($clockTimeArray) == count($ecoDayTimeArray)) :
                  $ecoDayTimeArray = array();
               endif;
            endif;
            $dayTimesLen = count($dayTimes);
if ($debug) :
   echo "---- TAGESZEITBESCHRÄNKUNG ------------------------------------------------------------- <br>";
   echo "ecoDayTimeArray:<br>";
   print_r($ecoDayTimeArray);
   echo "---------------------------------------------------------------------------------------- <br>";
endif;

            $iterWhile = true;
            $iterCount = 0;
            while ($iterWhile) :

                  $sortSequence = "";             
                  $ecoWeight = "";                
                  $ecoPositions = "";             
                  $maxLimitOfRows = "";           // Vielleicht begrenzen ????? !!!!!!!!!!!!!!!!!!!!!
                  $deliveryTimeValue = "";        
                  $jbTimedFilter = "";            // MUSS noch "berechnet" werden
                  $dateSelectionByCalendar = "";  // LEER!
                  $deactivateMenu = "1";          // MUSS gesetzt sein
                  $hq_id = $hqId;                 // "$hq_id" needed in "in_disposition.inc.php"
                  $globalArrayIsDefined = false;  // In case of merged or related jobs the global array to get appointments has to set another way
                  $specialCrvhId = "";            // In case of merged or related jobs the CURRENT job has to bet set on the same vehicle like the MERGED/RELATED job
    
 
                  // Try to find an appointment for the current job in FDS near by the existing merged job
                  if ($jbIdParent != "") :
                     // [1.] Get day of the parent job
                     $sqlStmt = getStmtVehicledispositionData($jbIdParent,"","","vhd.vhd_timeslot LIMIT 0,1");
                     $vhdTimeslot = getOneStmt($sqlStmt, "vhd_timeslot");
                     $specialCrvhId = getOneStmt($sqlStmt, "crvh_id");
                     $jbIdParentOrdertime = getFieldValueFromId("job","jb_id",$jbIdParent,"jb_ordertime");  // LEFT($jbIdMergedOrdertime,10) =!= LEFT($vhdTimeslot,10)
                     $jbIdParentTimeunits = getFieldValueFromId("job","jb_id",$jbIdParent,"jb_timeunits");
      
                     if (substr($jbIdParentOrdertime,0,10) == substr($vhdTimeslot,0,10)) :
                        // The (merged) PARENT job is currently associated to a special vehicle on the present day. Try to associate the CURRENT job to this parent job
                        $globalParArray = array($jbIdNew, $csId, $ecoDayTimeArray, $ecoWeekdayArray, $cscadZipcode, ($jbTimeUnits + $jbIdParentTimeunits), $sortSequence, $jbService, $ecoWeight, $ecoPositions,
                                                $maxLimitOfRows, $deliveryTimeValue, $deactivateMenu, substr($jbIdParentOrdertime,8,2), substr($jbIdParentOrdertime,5,2), substr($jbIdParentOrdertime,0,4), 
                                                substr($jbIdParentOrdertime,8,2), substr($jbIdParentOrdertime,5,2), substr($jbIdParentOrdertime,0,4), $jbTimedFilter, $dateSelectionByCalendar, 0);
                        $globalArrayIsDefined = true;
                     endif;
                  endif;
      
                  // Try to find an appointment for the current job in FDS near by the existing merged job
                  if ($jbIdMerged != "") :
                     // [1.] Get day of the job to be merged
                     $sqlStmt = getStmtVehicledispositionData($jbIdMerged,"","","vhd.vhd_timeslot LIMIT 0,1");
                     $vhdTimeslot = getOneStmt($sqlStmt, "vhd_timeslot");
                     $specialCrvhId = getOneStmt($sqlStmt, "crvh_id");
                     $jbIdMergedOrdertime = getFieldValueFromId("job","jb_id",$jbIdMerged,"jb_ordertime");  // LEFT($jbIdMergedOrdertime,10) =!= LEFT($vhdTimeslot,10)
                     $jbIdMergedTimeunits = getFieldValueFromId("job","jb_id",$jbIdMerged,"jb_timeunits");
      
                     if (substr($jbIdMergedOrdertime,0,10) == substr($vhdTimeslot,0,10)) :
                        // The MERGED job is currently associated to a special vehicle on the present day. Try to associate the CURRENT job to this merged job
                        $globalParArray = array($jbIdNew, $csId, $ecoDayTimeArray, $ecoWeekdayArray, $cscadZipcode, $jbTimeUnits, $sortSequence, $jbService, $ecoWeight, $ecoPositions,
                                                $maxLimitOfRows, $deliveryTimeValue, $deactivateMenu, substr($jbIdMergedOrdertime,8,2), substr($jbIdMergedOrdertime,5,2), substr($jbIdMergedOrdertime,0,4), 
                                                substr($jbIdMergedOrdertime,8,2), substr($jbIdMergedOrdertime,5,2), substr($jbIdMergedOrdertime,0,4), $jbTimedFilter, $dateSelectionByCalendar, 0);
                        $globalArrayIsDefined = true;
                     endif;
                  endif;

                  if (!$globalArrayIsDefined) :
                     $globalParArray = array($jbIdNew, $csId, $ecoDayTimeArray, $ecoWeekdayArray, $cscadZipcode, $jbTimeUnits, $sortSequence, $jbService, $ecoWeight, $ecoPositions,
                                             $maxLimitOfRows, $deliveryTimeValue, $deactivateMenu, substr($jbOrdertime,8,2), substr($jbOrdertime,5,2), substr($jbOrdertime,0,4), 
                                             substr($jbOrdertime,8,2), substr($jbOrdertime,5,2), substr($jbOrdertime,0,4), $jbTimedFilter, $dateSelectionByCalendar, 0);
                  endif;
      
                  // Get vehicle list
                  $retArray = getDispositionAppointments("3", $globalParArray);
      
                  $globalParArray = $retArray[0];  // Global parameters
                  $tmpArray = $retArray[1];  // Available vehicle data as array OR error string
      
                  list($xJbId, $xCsId, $xEcoDayTimeArray, $xEcoWeekdayArray, $xEcoZipcode, $xEcoNeededTimeUnits, $xSortSequence, $xEcoServices, $xEcoWeight, $xEcoPositions,
                       $xMaxLimitOfRows, $xDeliveryTimeValue, $xDeactivateMenu, $x_day_from, $x_month_from, $x_year_from, $x_day_to, $x_month_to, $x_year_to, $xJbTimedFilter, 
                       $xDateSelectionByCalendar, $xCurrentTimestamp, $xCurrentDay, $xCurrentTime, $xCurrYear, $xCombinedJob, $xHourTimeUnits, $xEcoDayClockTimes, 
                       $xJbOrdertime, $xEcoCapacityMax, $xEcoSummatedNeededTimeUnits,$xEcoHasWholeDayRequest, $srvpId, $srvzId, $xWeekDayNames, $xCheckTotalweight, 
                       $xDispositionJbStatusMode, $xEcoChildrenServices, $xMaskDisplayWholeDayAvoidingSingleDaytimes, $xEcoIsInstallationJob, $xEcoIsSpecialServiceJob, 
                       $xDispositionAllocationMode, $xEcoChildrenTimeunitsArray, $xJbIdChildren, $xJbIdChildrenLen, $xDaytimeReadonlyArray) = $globalParArray;
      
                  // Check for ERRORS
                  if (!is_array($tmpArray)) :
                     $acceptOrder = false;
                     if (!(strpos($tmpArray, "ERR:ZIPCODE_NOT_IN_ANY_ZONE") === FALSE)) :
                        $err[] = array("108", getLngt("Die PLZ ist keiner Zone zugeordnet.") . " [" . $ecoZipcode . "]");
                     else :
                        $err[] = array("109", getLngt("Bereichsfehler."));
                     endif;
                  endif;
                  $errMsgArrayLen = count($errMsgArray);
      
                  if ($acceptOrder && is_array($tmpArray)) :
                     $tmpArrayLen = count($tmpArray);
      
                     if ($tmpArrayLen > 0) :
if ($debug) :
   echo "---- VERFÜGBARE FAHRZEUGE -------------------------------------------------------------- <br>";
   print_r($tmpArray);
   echo "---------------------------------------------------------------------------------------- <br>";
endif;
                        $iterWhile2 = true;
                        $iterCount2 = 0;
                        while ($iterWhile2) :

                              // Take vehicle, start with the first
                              for ($v = 0; $v < $tmpArrayLen; $v++) :
                              
                                  // array(vhaDay, crvhSid, daytimeValues, vhatTimeunits, starttime, service, vhatDaytime, crvhId, substr(vhat_starttimeunit,0,2), substr(vhat_starttimeunit,3,2), $daytimeMappedValues, crvhService)
                                  $vhtArray = $tmpArray[$v];
                              
                                  // Associate job to FDS
                                  if ($specialCrvhId == "" || $specialCrvhId == $vhtArray[7]) :

                                     // COMBINED JOB
                                     // In case of existence of a parent job try to get slots for both serial without space between them
                                     $jbId_1 = $jbIdNew;
                                     $jbTimeUnits_1 = $jbTimeUnits;
                                     $jbId_2 = "";
                                     $jbTimeUnits_2 = "";
                                     if ($jbIdParent != "") :
                                        // Check for dame day to make a combined job
                                        if ($jbIdParentOrdertime != "" && substr($jbIdParentOrdertime,0,10) == substr($jbOrdertime,0,10)) :
                                           $jbId_2 = $jbIdParent;
                                           $jbTimeUnits_2 = $jbIdParentTimeunits;
                                           if ($parNoRelatedReverse == "1") :
                                              $jbId_1 = $jbIdParent;
                                              $jbTimeUnits_1 = $jbIdParentTimeunits;
                                              $jbId_2 = $jbIdNew;
                                              $jbTimeUnits_2 = $jbTimeUnits;
                                           endif;
                                        endif;
                                     endif;

                                     if ($jbId_1 != "") :
                                        $retBool_1 = setAssocCrvhJb($jbId_1, $vhtArray[7], $csId, $vhtArray[0], $vhtArray[8], $vhtArray[9], $jbTimeUnits_1);
                                        $retBool_2 = true;  // Init with true because $jbId_2 can be empty (no parent does exist)
                                     endif;
                                     if ($jbId_2 != "") :
                                        // Get first timeslot and last timeslot (interval)
                                        $startTimeslotToBeChecked = $currDay . '_' . pad($hour, 2) . '_' . pad($hourUnit, 2);
                                        $tmpHour = $vhtArray[0];
                                        $tmpHourUnit = $vhtArray[8];
                                        $timeslots = $vhtArray[9];
                                        for ($t = 0; $t < $timeslots; $t++) :
                                            $tmpHourUnit++;
                                            if ($tmpHourUnit == $hourTimeUnits) :
                                               $tmpHour++;
                                               $tmpHourUnit = 0;
                                            endif;
                                        endfor;
                                        $endTimeslotToBeChecked = $currDay . '_' . pad($tmpHour, 2) . '_' . pad($tmpHourUnit, 2);

                                        $retBool_2 = setAssocCrvhJb($jbId_2, $vhtArray[7], $csId, $tmpHour, $tmpHourUnit, $timeslots, $jbTimeUnits_2);
                                     endif;
                              
                                     if ($retBool_1 && $retBool_2) :
                                        if ($dispositionJbStatusMode == "1") :
                                            $retIsBlocked = crvhIsBlocked($vhtArray[7], $vhtArray[0], 1);
                                            if ($retIsBlocked) :
                                               // Update jb_status for disposition by courier
                                               updateStmt("job","jb_id",$jbId_1,array("jb_status","0"));
                                               updateStmt("job","jb_id",$jbId_2,array("jb_status","0"));
                              
                                               // Get courier ID of the current vehicle ("jb.cr_id_order" has to be set regarding the current vehicle)
                                               $crvhSid = getFieldValueFromId("couriervehicle","crvh_id",$vhtArray[7],"crvh_sid");   // Get SID, needed for "fake" courier for the vehicle !!!!
                                               $crId = getFieldValueFromId("courier","cr_sid",$crvhSid,"cr_id");                     // Get "fake" courier ID
                                               $res = updateStmt("job", "jb_id", $jbIdNew, array("cr_sid", $crvhSid, "cr_id_order", $crId));
                                            endif;
                                        endif;
                                        $iterWhile = false;   // Terminate outer loop
                                        $iterWhile2 = false;  // Terminate inner loop
                                        break;
                                     else :
                                        // Remove job(s) from FDS (probably not needed)
                                        removeAssocCrvhJb($jbId_1, $csId);
                                        if ($jbId_2 != "") :
                                           removeAssocCrvhJb($jbId_2, $csId);
                                        endif;
                                     endif;
                                  endif;
                              endfor;
                              
                              if ($iterWhile2) :
                                 $specialCrvhId = "";  // Second iteration without special vehicle
                                 if ($iterCount2 > 1) :
                                    $iterWhile2 = false;
                                 endif;
                                 $iterCount2++;
                              endif;
                        endwhile;


                        // Write zone information and "dispo callback"
                        if ($globalParUseRelatedCustomer == "1") :
                           // Endcustomer time window
                           $tmpJbFreetext1 = substr($jbOrdertime,8,2) . "." .  substr($jbOrdertime,5,2) . "." .  substr($jbOrdertime,0,4) . "  ";
                           $tmpDaytime = "ganztägig";
                           if (false) : $tmpDaytime = "<Uhrzeitintervall>"; endif;  // e.g. "12:00 - 16:00"
                           $tmpJbFreetext1 .= $tmpDaytime;
      
                           // Get name of the zone
                           $srvzName = "";
                           if ($srvzId != "" && is_numeric($srvzId)) :
                              $srvzName = getFieldValueFromId("servicezone","srvz_id",$srvzId,"srvz_name");
                           else :
                              $srvzId = "";
//                            $acceptOrder = false;
//                            $err[] = array("108", getLngt("Die PLZ ist keiner Zone zugeordnet."));
                           endif;
      
                           if ($acceptOrder) :
                              updateStmt("job","jb_id",$jbIdNew,array("jb_freetext_1", $tmpJbFreetext1, "jb_mediationarea_id", $srvzId, "jb_mediationarea_name", $srvzName));
                           endif;
                        endif;
      
                     else :
                        $acceptOrder = false;
                        $err[] = array("115", getLngt("Kein Fahrzeug verfügbar."));
                     endif;
                  else :
                     $acceptOrder = false;
                     $err[] = array("115", getLngt("Kein Fahrzeug verfügbar."));
                  endif;

                  if ($iterWhile) :
                     if ($iterCount > 5) :
                        $iterWhile = false;
                     endif;
                     $iterCount++;
                  endif;
            endwhile;
$debugOut .= "tmpJbFreetext1: " . $tmpJbFreetext1 . "<br>\n";
$debugOut .= "<br>\n";
$debugOut .= "END DISPOSITION<br>\n";
            // --------------------------------------------------------


            if ($acceptOrder) :

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

               // Preparation...
               $hq_id = $hqId;
   
               // Generate prices
               $makePrice = true;
               $parOrderRequestJobNoPrice = getParameterValue("0", "ORDER_REQUEST_NO_PRICE_CS_" . $csId, "0");
               if ($parOrderRequestJobNoPrice == "1") :
                  $makePrice = false;
               endif;
               if ($makePrice) :
                  if ($globalParUseRelatedCustomer != "1") :
                     mk_jb_price($jbIdNew);
                  endif;
               endif;
   
               // Generate invoice text
               if ($globalParUseRelatedCustomer == "1") :
                 // .............
               else :
                  mk_jb_invtext($jbIdNew, false);
               endif;
   
               // ****
               // Special patch because of "bug" in function "mk_jb_invtext()"
               if ($jbIdNew != "" && is_numeric($jbIdNew)) :
                  updateStmt("job","jb_id",$jbIdNew,array("jb_tourdata",$jbTourdata));
               endif;
               // ****
   
               // Call price function
               // mk_jb_tourprices($jbIdNew, $trServicesArray);
   // print_r($trServicesArray); echo "<br><br>";
   
               writeToLogDB("102",$hq_id,$jbIdNew,$usr_id,"","",$csId,"B2B_IMPORT=1");  // Success!
            else :
               TA("R");
               TA("E");
            endif;
         else :
            TA("R");
            TA("E");
         endif;

      endif;  // Operation mode
   endif;
else :
  // Authentication data not ok
  $err[] = array("101", getLngt("Die Authentifizierungsdaten sind nicht in Ordnung."));
endif;
// print_r($err);

// Check existence of at least one error
$errLen = count($err);


// Output
$outResponse .= "<xml>";   
if ($errLen > 0) :
   orderRequestLogFile("ERRORS", 1);
   $outResponse .= "<state>NOT OK</state>";
   $outResponse .= "<errors>";
   for ($i = 0; $i < $errLen; $i++) :
       $outResponse .= "<error>";
       $outResponse .= "<err_no>" . $err[$i][0] . "</err_no>";
       $outResponse .= "<err_desc><![CDATA[" . mcEncode($err[$i][1]) . "]]></err_desc>";
       $outResponse .= "</error>";
       if ($debug) :
          $outResponse .= "<debug>" . $debugOut . "</debug>";
       endif;
       orderRequestLogFile($err[$i][0] . " : " . mcEncode($err[$i][1]), 1);
   endfor;
   $outResponse .= "</errors>";
else :
   $outResponse .= "<state>OK</state><carrier><orderno>" . $jbIdNew . "</orderno></carrier>";
   if ($debug) :
      $outResponse .= "<debug>" . $debugOut . "</debug>";
   endif;
endif;
$outResponse .= "</xml>";

// Log entries
orderRequestLogFile($outResponse);    // Write response into log
orderRequestLogFile("___________________________________________________________________________________");

// Return output
echo $outResponse;




/*
// ERROR CODES
100 : Commission number does still exit. Insert of new order not possible.
101 : Authentication Data not correct.
102 : Maximum limit of orders per day reached. Presently xxxx orders.
103 : Maximum limit of orders in progress reached. Presently xxxx orders.
104 : Customer data could not be inserted.
105 : Es wurde kein Rechnungstext übergeben.
105 : No order number for update!
106 : No order number for cancellation!
107 : Cancellation failed because order is canceled or is in progress!
108 : Zipcode did not match zone
109 : Zone error.
110 : Address data are not complete.
111 : Generation of stations failed.
112 : Datetime format not correct.
113 : Start time of the order is not correct.
114 : Latest finish time of the order is not correct.
115 : No vehicle available
116 : Start time has to be in the future


// FELDER UND IHRE BEDEUTUNG
<xml>
  <order>                                          // Fuhrauftrag
    <auth>                                         // Identifikation des Kunden
      <customer>...</customer>                     // Kundennummer (EID) {"STBxxxxxx", ...} => csc_id_payer
      <account>...</account>                       // Eingetragener Benutzer für den Kunden => cs.cs_admin => emp.emp_id => emp.usr_id => usr.usr_id => usr.usr_account
      <password>...</password>                     // Passwort für den Benutzer             => usr.usr_password
      <session_id>...</session_id>                 // Zusätzliche Session-ID, die mit dem Kunden ausgehandelt wurde   [mandatory]
      <costcenter_name>...</costcenter_name>       // Kostenstellenname {"abcd", "efgh", ...} => Mapping csc_id   [optional]
      <group_no>...</group_no>                     // Nummer der Kundengruppe (Bei einer automatischen Preisfindung muss entweder <group_no> oder <group_name> gesetzt sein)
      <group_name>...</group_name>                 // Name der Kundengruppe (Bei einer automatischen Preisfindung muss entweder <group_name> oder <group_no> gesetzt sein)
    </auth>                                        
    <operation>...</operation>                     // Operation (INS, UPD, DEL)
    <debug_on>...</debug_on>                       // Activates debug output ("ON" or "YES")
    <no>...</no>                                   // Order no of the customer  => tr_commission_no
    <type>...</type>                               // Type of the job  => jb_type
    <hq>...</hq>                                   // {HB, HH, ...} => hq_mnemonic => hq_id
    <vehicle>                                      // Angefordertes Fahrzeug
      <type_no>...</type_no>                       // {1,2,3...} => Mapping "metatype" => vht_id     (entweder <type_no> oder <type_name> ist mandatory)
      <type_name>...</type_name>                   // {"bus", ...} => Mapping "metatype" => vht_id   (entweder <type_no> oder <type_name> ist mandatory)
      <weight>...</weight>                         // Gewicht des Transportguts
      <length>...</length>                         // Angeforderte Mindestlänge des Fahrzeugs
      <width>...</width>                           // Angeforderte Mindestbreite des Fahrzeugs
      <height>...</height>                         // Angeforderte Mindesthöhe des Fahrzeugs
      <position>...</position>                     // Angeforderte Mindestanzahl an Stellplätzen im Fahrzeug
    </vehicle>                                     
    <ordertime>...</ordertime>                     // Startzeit des Auftrags (wenn leer, dann "adhoc"-Auftrag mit aktuellem Zeitstempel) => jb_ordertime und jb_reserv
    <ordertimeUTC>...</ordertimeUTC>               // Startzeit des Auftrags in UTC (erst wird nach der Inhalt in <ordertime> geschaut, dann ich <ordertimeUTC>)
    <warningtime>...</warningtime>                 // Späteste Erledigungszeit des Auftrags (Bsp: 2014-10-22 09:00:00)
    <warningtimeUTC></warningtimeUTC>              // Späteste Erledigungszeit des Auftrags in UTC (erst wird nach der Inhalt in <warningtime> geschaut, dann ich <warningtimeUTC>)
    <acquisition_time>...</acquisition_time>       // Erfassungszeit des Auftrags bei asynchroner Übertragung
    <courier>...</courier>                         // {HH1000, HH1420, ...} Wunschfahrer => jb.cr_sid => Abgleich mit cr.cr_sid => cr.cr_id => jb.cr_id_order   [optional]
    <filter>CK,DE,EN</filter>                      // Fahrzeug-Filter zur Einschränkung der Fahrzeugvermittlung (Aufstellung siehe Anhang)
    <remark>...</remark>                           // Bemerkung zum Auftrag
    <courier_remark>...</courier_remark>           // Bemerkung zum Auftrag für den Fahrer
    <gdc>                                          // Zusätzliche Informationen pro Auftrag, die gesondert behandelt und bei Rückgaben herangezogen werden können
      <val>[optional]</val>
      <val>[optional]</val>
      <val>[optional]</val>
      ...
    </gdc>
    <stations>                                     // Stationen
      <station>                                    // Station 1 (Abholung)
        <ware_from_to>...</ware_from_to>           // Abholung   [optional] {leer, 0 = weder Abholung noch Anlieferung, 1 = nur Abholung, 2 = nur Anlieferung, 3 = beides}
        <costcenter>...</costcenter>               // Kostenstellenname {"abcd", "efgh", ...} => Mapping csc_id   [optional, wenn gesetzt, dann weitere Felder leer]
        <company>...</company>                     // Firmenbezeichnung
        <company2>...</company2>                   // Firmenzusatz
        <street>...</street>                       // Straße
        <houseno>...</houseno>                     // Hausnummer
        <zipcode>...</zipcode>                     // PLZ
        <city>...</city>                           // Ort
        <special_remark>...</special_remark>       // Bemerkung zur Station
        <person>...</person>                       // Abgabe der Sendung bei ..., Ansprechpartner   [optional]
        <phone>...</phone>                         // Telefonnummer  [optional]
        <email>...</email>                         // Email  [optional]

        <invoice>                                  // Rechnungsangaben (des belieferten Endkunden)
          <costcenter>...</costcenter>             // Kostenstellenname {"abcd", "efgh", ...} => Mapping csc_id   [optional, wenn gesetzt, dann weitere Felder leer]
          <company>...</company>                   // Firmenbezeichnung
          <company2>...</company2>                 // Firmenzusatz
          <street>...</street>                     // Straße
          <houseno>...</houseno>                   // Hausnummer
          <floorno>...</floorno>                   // Etage, Flur
          <zipcode>...</zipcode>                   // PLZ
          <city>...</city>                         // Ort
          <special_remark>...</special_remark>     // Bemerkung zur Station
          <person>...</person>                     // Abgabe der Sendung bei ..., Ansprechpartner   [optional]
          <phone>...</phone>                       // Telefonnummer  [optional]
          <email>...</email>                       // Email  [optional]
          <voucher_no>...</voucher_no>             // Belegnummer des Endkunden (Rechnungsnummer, Kassenbon)
          <payment_method>...</payment_method>     // Zahlungsart (leer oder 0 = Bar, 1 = EC–Pin, 2 = EC–Lastschrift, etc.)
          <price_mode>...</price_mode>             // Art des rabattierten Preises ("" = Standardpreis, 0 = Aktionpreis_1 (z.B. "family card"), 1 = Aktionspreis_2)
          <partial_payment>...</partial_payment>   // Bereits geleisteter Betrag (leer = 0 = keine Anzahlung/Bezahlung)
        </invoice>                                 
                                                   
        <articles>                                 
          <article>                                
            <mode>...</mode>                       // Modus (leer oder 0 = Auslieferung, 1 = Retoure, 2 = Montage, 3 = Demontage, 4 = Entsorgung (bei 2 und 3 mindestens Felder "description" und "quantity" gesetzt))
            <no>...</no>                           // Artikelnummer
            <serialno>...</serialno>               // Seriennummer (<quantity>1</quantity>)
            <description>...</description>         // Beschreibung
            <quantity>...</quantity>               // Menge
            <price>...</price>                     // Stückpreis
            <weight>...</weight>                   // Einzelgewicht eines Artikels
            <length>...</length>                   // Länge eines Artikels
            <width>...</width>                     // Breite eines Artikels
            <height>...</height>                   // Höhe eines Artikels
            <pieces>...</pieces>                   // Anzahl Packstücke (leer oder 0 = z.B. keine Lieferung und nur Montage, ansonsten Anzahl)
            <positions>...</positions>             // Stellplätze, Kolli
            <articlegroup_no>...</articlegroup_no> // Warengruppe
          </article>                             
          ...                                    
        </articles>                              

        <services>                                 // Preisestruktur(en)  [optional]
          <timeslots>...</timeslots>               // Zeitintervalle für Belieferung bzw. Anfahrt (leer = keine Einschränkung, "0" = vormittags, "1" = nachmittags, "2" = abends, "1,2" = vormittags und abends, ..., "1,2,3 = ganztägig")
          <timeunits>...</timeunits>               // Anzahl Zeiteinheiten für Erfüllung des Auftrags (1 Zeiteinheit = 10 Minuten)
          <shipment_mode>...</shipment_mode>       // Versandart (bit-string)
                                                   // 0 => 2^0 =   1 Lieferung (Delivery)
                                                   // 1 => 2^1 =   2 Montage (Installation)
                                                   // 2 => 2^2 =   4 Neumöbelmontage (Installation furniture) ("Installation" [2^1] also has to be set)
                                                   // 3 => 2^3 =   8 Besichtigung (Viewing)
                                                   // 4 => 2^4 =  16 Kücheninstallation (Installation kitchen) ("Installation" [2^1] also has to be set)
                                                   // 5 => 2^5 =  32 Nachlieferung (Delivery supplementary)
                                                   // 6 => 2^6 =  64 Reklamation (Complaint)
                                                   // 7 => 2^7 = 128 Abholung (Return shipment, Retoure))
                                                   // 8 => 2^8 = 256 Austausch (Replacement)
                                                   // 9 => 2^9 = 512 Aufmaß (Measurement)
                                                   // (E.g.: Delivery = 1, Installation furniture = 6 (including "Installation"),
                                                   // Installation kitchen = 18 (including "Installation"),
                                                   // Retoure = 128, Delivery and Retoure = 129, Replacement = 256
                                                   // Delivery and Replacement = 257, ...)
          <order_type>...</order_type>             // Auftragsart(en) (Sameday = 0, Nextday = 1, Kurier = 2)

          <calculator>                             // Calculatorpreise  [optional]
            <calc_item>                            // Spezielle Zelle der Preis-/Leistungsmatrix
              <servicetype>...</servicetype>       // Leistungstyp
              <pricetype>...</pricetype>           // Preistyp
              <price>...</price>                   // Preis  [optional] => überschreibt den in der zelle eingetragenen Preis
              <quantity>...</quantity>             // Menge
            </calc_item>                           
            ...                                    
            <func_item>                            // Calculatorpreisfunktionen  [optional]
              <no>...</no>                         // Nummer der Funktion (Erläuterung siehe bitte unten)
              <par_1>...</par_1>                   // Wert für Parameter Nr. 1 der Funktion
              <par_2>...</par_2>                   // Wert für Parameter Nr. 2 der Funktion
              <par_3>...</par_3>                   // Wert für Parameter Nr. 3 der Funktion
              <par_4>...</par_4>                   // Wert für Parameter Nr. 4 der Funktion
              <par_5>...</par_5>                   // Wert für Parameter Nr. 5 der Funktion
              <quantity>...</quantity>             // Menge (leer = 1 = default, ansonsten angegebene Anzahl)
            </func_item>                           
            ...                                    
          </calculator>                            
        </services>                                

        <gdc>                                      // Zusätzliche Informationen pro Station, die gesondert behandelt und bei Rückgaben herangezogen werden können
          <1>[optional]</1>
          <2>[optional]</2>
          <3>[optional]</3>
          <4>[optional]</4>
          <5>[optional]</5>
        </gdc>
      </station>                                   
      <station>                                    // Station 2
        <ware_from_to>...<ware_from_to>            // Abholung, Anlieferung, beides   [optional]
        ...                                        
      </station>                                   
      ...                                          // Weitere Stationen
    </stations>
  </order>
</xml>


Calculatorpreisfunktionen:
<func_item>...</func_item>

Nr.   : Kontext
        Parameter (außer der Menge, die bei jeder Funktion optional übergeben werden kann)
        Menge (leer = 1 = default, ansonsten angegebene Anzahl)

10002 : Gestaffelter warenwertabhängiger Grundpreis für den Transport
        <func_item>
          <no>10002</no>
          <par_1>490</par_1>        // Warenwert (Bsp. 490,- €)
          <quantity></quantity>      
        </func_item>

10003 : Tagessatz für Lagerungskosten ab dem n. Tag
        <func_item>
          <no>10003</no>
          <par_1>14</par_1>         // Anzahl Tage  (bei 0 => keine Berechnung => keine Kosten für Endkunde)
          <quantity>1</quantity>     
        </func_item>
          
10004 : Montagebetrag auf Basis des Prozentsatzes p% vom Warenwert
        <func_item>
          <no>10004</no>
          <par_1>288</par_1>        // Warenwert
          <quantity></quantity>      
        </func_item>
          
10010 : Preis pro Meter Küchenmontage
        <func_item>
          <no>10010</no>
          <par_1>5</par_1>          // Angabe lfd. Meter
          <quantity></quantity>      
        </func_item>
          
20005 : Elektroanschluss bei Küchenmontage
        <func_item>
          <no>20005</no>
          <quantity>1</quantity>     
        </func_item>
      
20006 : Wasseranschluss bei Küchenmontage
        <func_item>
          <no>20006</no>
          <quantity>1</quantity>     
        </func_item>

10005 : Expresslieferung nach Zonen
        <func_item>
          <no>10005</no>
          <par_1>22525</par_1>      // PLZ
          <quantity></quantity>      
        </func_item>
        
20001 : Zusätzliche Montagestunde
        <func_item>
          <no>20001</no>
          <quantity>2.25</quantity>  
        </func_item>

20002 : Pauschale Nachmontage
        <func_item>
          <no>20002</no>
          <quantity>1.5</quantity>  
        </func_item>

20003 : Monteurstunde bei Nachmontage
        <func_item>
          <no>20003</no>
          <quantity>3</quantity>    
        </func_item>
        
10007 : Prozentsatzes p% des Lieferpreises beim Abholauftrag
        <func_item>
          <no>10007</no>
          <par_1>197</par_1>        // Preis des Abholauftrags
          <quantity>1</quantity>   
        </func_item>
        
10009 : Warengruppenabhängiger Preis für die Montage
        <func_item>
          <no>10009</no>
          <par_1>10</par_1>         // Warengruppe
          <quantity>1</quantity>   
        </func_item>
        
10006 : Warengruppenabhängiger Preis für die Altmöbelrücknahme
        <func_item>
          <no>10006</no>
          <par_1>15</par_1>         // Warengruppe
          <quantity>1</quantity>   
        </func_item>
        
10008 : Preis für Liefergewicht pro x kg höher als das Freigewicht
        <func_item>
          <no>10008</no>
          <par_1>350</par_1>        // Gewicht in kg
          <quantity>1</quantity>   
        </func_item>

20004 : Endkundenpreis für Einkaufsservice
        <func_item>
          <no>20004</no>
          <quantity>1</quantity>   
        </func_item>

10011 : Verrechnungssatz pro Artikel in Prozent p% vom Verkaufspreis bei Verlust und Schäden
        <func_item>
          <no>10011</no>
          <par_1>350</par_1>        // Warenwert
          <quantity>1</quantity>   
        </func_item>

20007 : Hantierungshilfsmittel: Verrechnungssatz Euro-Palette
        <func_item>
          <no>20007</no>
          <quantity>3</quantity>   
        </func_item>

20008 : Hantierungshilfsmittel: Verrechnungssatz IKEA-Palette
        <func_item>
          <no>20008</no>
          <quantity>3</quantity>   
        </func_item>

1xxxx : Kosten für Transportverpackung(en) z.B. bei Kleinteilen
        <func_item>
          <no>1xxxx</no>
          <quantity>1</quantity>   
        </func_item>



// PFLICHTFELDER UND OPTIONALE FELDER
<xml>
  <order>                                                 // Fuhrauftrag
    <auth>                                                // Identifikation des Kunden
      <customer>[mandatory]</customer>                    // Kundennummer (EID) {"STBxxxxxx", ...}
      <account>[mandatory]</account>                      // Eingetragener Benutzer für den Kunden
      <password>[mandatory]</password>                    // Passwort für den Benutzer
      <session_id>[mandatory]</session_id>                // Zusätzliche ausgehandelte Session-ID
      <costcenter_name>[optional]</costcenter_name>       // Bekannte Kostenstelle
      <group_no>[optional]</group_no>                     // Nummer der Kundengruppe (Bei einer automatischen Preisfindung muss entweder <group_no> oder <group_name> gesetzt sein)
      <group_name>[optional]</group_name>                 // Name der Kundengruppe (Bei einer automatischen Preisfindung muss entweder <group_name> oder <group_no> gesetzt sein)
    </auth>                                               
    <operation>[optional]</operation>                     // Operation (INS, UPD, DEL)
    <debug_on>[optional]</debug_on>                       // Activates debug output ("ON" or "YES")
    <no>[optional]</no>                                   // Eigene Auftragsnummer z.B. aus Lotus
    <type>[optional]</type>                               // Auftragstype (z.B. 1,2,3,...) (Mapping z.B. auf "G", "K", ...)
    <hq>[mandatory]</hq>                                  // HH (HB, B, DD), Städtekürzel
    <vehicle>                                             // Angefordertes Fahrzeug
      <type_no>[mandatory]</type_no>                      // {2=PKW, 3=Kombi, 4=Kastenwagen, 5=Bus, 6=Großer Bus, 7=LKW}
      <type_name>[optional]</type_name>                   // {PKW, ...}
      <weight>[optional]</weight>                         // Gewicht des Transportguts
      <length>[optional]</length>                         // Angeforderte Mindestlänge des Fahrzeugs
      <width>[optional]</width>                           // Angeforderte Mindestbreite des Fahrzeugs
      <height>[optional]</height>                         // Angeforderte Mindesthöhe des Fahrzeugs
      <position>[optional]</position>                     // Angeforderte Mindestanzahl an Stellplätzen im Fahrzeug
    </vehicle>                                            
    <ordertime>[optional]</ordertime>                     // Startzeit des Auftrags (wenn leer, dann "adhoc"-Auftrag mit aktuellem Zeitstempel) (Bsp: 2012-02-17 09:30:00)
    <ordertimeUTC>[optional]</ordertimeUTC>               // Startzeit des Auftrags in UTC (erst wird nach der Inhalt in <ordertime> geschaut, dann ich <ordertimeUTC>)
    <warningtime>[optional]</warningtime>                 // Späteste Erledigungszeit des Auftrags (Bsp: 2014-10-22 09:00:00)
    <warningtimeUTC>[optional]</warningtimeUTC>           // Späteste Erledigungszeit des Auftrags in UTC (erst wird nach der Inhalt in <warningtime> geschaut, dann ich <warningtimeUTC>)
    <acquisition_time>[optional]</acquisition_time>       // Erfassungszeit des Auftrags bei asynchroner Übertragung
    <courier>[optional]</courier>                         // {HH1000, HH1420, ...} Wunschfahrer
    <filter>[optional]</filter>                           // Fahrzeug-Filter zur Einschränkung der Fahrzeugvermittlung (Aufstellung siehe Anhang) (Bsp.: EN=Englisch, HW=Hubwagen, ...)
    <remark>[mandatory]</remark>                          // Rechnungstext und Bemerkung zum Auftrag
    <courier_remark>[optional]</courier_remark>           // Bemerkung zum Auftrag für den Fahrer
    <gdc>                                                 // Zusätzliche Informationen pro Auftrag, die gesondert behandelt und bei Rückgaben herangezogen werden können
      <val>[optional]</val>
      <val>[optional]</val>
      <val>[optional]</val>
      ...
    </gdc>
    <stations>                                            // Stationen
      <station>                                           // Station 1 (Abholung)
        <ware_from_to>[optional]</ware_from_to>           // Abholung, Anlieferung, beides {leer, 0, 1, 2, 3}
        <costcenter>[optional]</costcenter>               // Kostenstellenname {"abcd", "efgh", ...}
        <company>[mandatory]</company>                    // Firmenbezeichnung ODER Person
        <company2>[optional]</company2>                   // Firmenzusatz
        <street>[mandatory]</street>                      // Straße
        <houseno>[mandatory]</houseno>                    // Hausnummer
        <floorno>[optional]</floorno>                     // Etage, Flur
        <zipcode>[mandatory]</zipcode>                    // PLZ
        <city>[mandatory]</city>                          // Ort
        <special_remark>[optional]</special_remark>       // Bemerkung zur Station
        <person>[optional]</person>                       // Abgabe der Sendung bei ..., Ansprechpartner
        <phone>[optional]</phone>                         // Telefonnummer
        <email>[optional]</email>                         // Email

        <invoice>                                         // Rechnungsangaben (des belieferten Endkunden)
          <costcenter>[optional]</costcenter>             // Kostenstellenname {"abcd", "efgh", ...} => Mapping csc_id   [optional, wenn gesetzt, dann weitere Felder leer]
          <company>[optional]</company>                   // Firmenbezeichnung
          <company2>[optional]</company2>                 // Firmenzusatz
          <street>[optional]</street>                     // Straße
          <houseno>[optional]</houseno>                   // Hausnummer
          <zipcode>[optional]</zipcode>                   // PLZ
          <city>[optional]</city>                         // Ort
          <special_remark>[optional]</special_remark>     // Bemerkung zur Station
          <person>[optional]</person>                     // Abgabe der Sendung bei ..., Ansprechpartner   [optional]
          <phone>[optional]</phone>                       // Telefonnummer  [optional]
          <email>[optional]</email>                       // Email  [optional]
          <voucher_no>[optional]</voucher_no>             // Belegnummer des Endkunden (Rechnungsnummer, Kassenbon)
          <payment_method>[optional]</payment_method>     // Zahlungsart (leer oder 0 = Bar, 1 = EC–Pin, 2 = EC–Lastschrift, 20 = Familycard, 21 = Businesscard)
          <price_mode>[optional]</price_mode>             // Art des rabattierten Preises ("" = Standardpreis, 0 = Aktionpreis_1 (z.B. "family card"), 1 = Aktionspreis_2)
          <partial_payment>[optional]</partial_payment>   // Bereits geleisteter Betrag (leer = 0 = keine Anzahlung/Bezahlung)
        </invoice>    

        <articles>
          <article>
            <mode>[optional]</mode>                       // Modus (leer oder 0 = Auslieferung, 1 = Retoure, 2 = Montage, 3 = Demontage, 4 = Entsorgung (bei 2 und 3 mindestens Felder "description" und "quantity" gesetzt))
            <no>[optional]</no>                           // Artikelnummer
            <serialno>[optional]</serialno>               // Seriennummer (<quantity>1</quantity>)
            <description>[optional]</description>         // Beschreibung
            <quantity>[optional]</quantity>               // Menge
            <price>[optional]</price>                     // Stückpreis
            <weight>[optional]</weight>                   // Einzelgewicht eines Artikels
            <length>[optional]</length>                   // Länge eines Artikels
            <width>[optional]</width>                     // Breite eines Artikels
            <height>[optional]</height>                   // Höhe eines Artikels
            <pieces>[optional]</pieces>                   // Anzahl Packstücke (leer oder 0 = z.B. keine Lieferung und nur Montage, ansonsten Anzahl)
            <positions>[optional]</positions>             // Stellplätze, Kolli
            <articlegroup_no>[optional]</articlegroup_no> // Warengruppe
          </article>                             
          ...                                    
        </articles>                              

        <services>                                        // Preisestruktur(en)  [optional]
          <timeslots>[optional]</timeslots>               // Zeitintervalle für Belieferung bzw. Anfahrt (leer = keine Einschränkung, "0" = vormittags, "1" = nachmittags, "2" = abends, "1,2" = vormittags und abends, ..., "1,2,3" = ganztägig")
          <timeunits>[mandatory]</timeunits>              // Anzahl Zeiteinheiten für Erfüllung des Auftrags (1 Zeiteinheit = 10 Minuten)
          <shipment_mode>[optional]</shipment_mode>       // Versandart (bit-string)
                                                          // 0 => 2^0 =   1 Lieferung (Delivery)
                                                          // 1 => 2^1 =   2 Montage (Installation)
                                                          // 2 => 2^2 =   4 Neumöbelmontage (Installation furniture) ("Installation" [2^1] also has to be set)
                                                          // 3 => 2^3 =   8 Besichtigung (Viewing)
                                                          // 4 => 2^4 =  16 Kücheninstallation (Installation kitchen) ("Installation" [2^1] also has to be set)
                                                          // 5 => 2^5 =  32 Nachlieferung (Delivery supplementary)
                                                          // 6 => 2^6 =  64 Reklamation (Complaint)
                                                          // 7 => 2^7 = 128 Abholung (Return shipment, Retoure))
                                                          // 8 => 2^8 = 256 Austausch (Replacement)
                                                          // 9 => 2^9 = 512 Aufmaß (Measurement)
                                                          // (E.g.: Delivery = 1, Installation furniture = 6 (including "Installation"),
                                                          // Installation kitchen = 18 (including "Installation"),
                                                          // Retoure = 128, Delivery and Retoure = 129, Replacement = 256
                                                          // Delivery and Replacement = 257, ...)
          <order_type>[optional]</order_type>             // Auftragsart(en) (Sameday = 0, Nextday = 1, Kurier = 2)

          <calculator>                                    // Calculatorpreise  [optional]
            <calc_item>                                   // Spezielle Zelle der Preis-/Leistungsmatrix
              <servicetype>[mandatory]</servicetype>      // Leistungstyp
              <pricetype>[mandatory]</pricetype>          // Preistyp
              <price>[optional]</price>                   // Preis  [optional] => überschreibt den in der zelle eingetragenen Preis
              <quantity>[mandatory]</quantity>            // Menge
            </calc_item>                                  
            ...                                           
            <func_item>                                   // Calculatorpreisfunktionen  [optional]
              <no>[mandatory]</no>                        // Nummer der Funktion (Erläuterung siehe bitte unten)
              <par_1>[optional]</par_1>                   // Wert für Parameter Nr. 1 der Funktion
              <par_2>[optional]</par_2>                   // Wert für Parameter Nr. 2 der Funktion
              <par_3>[optional]</par_3>                   // Wert für Parameter Nr. 3 der Funktion
              <par_4>[optional]</par_4>                   // Wert für Parameter Nr. 4 der Funktion
              <par_5>[optional]</par_5>                   // Wert für Parameter Nr. 5 der Funktion
              <quantity>[optional]</quantity>             // Menge (leer = 1 = default, ansonsten angegebene Anzahl)
            </func_item>                                  
            ...                                           
          </calculator>                                   
        </services>                                       

        <gdc>                                             // Zusätzliche Informationen pro Station, die gesondert behandelt und bei Rückgaben herangezogen werden können
          <1>[optional]</1>
          <2>[optional]</2>
          <3>[optional]</3>
          <4>[optional]</4>
          <5>[optional]</5>
        </gdc>
      </station>                                          
      <station>                                           // Station 2
        <ware_from_to>[optional]<ware_from_to>            // Abholung, Anlieferung, beides   [optional]
        ...                                               
      </station>                                          
      ...                                                 // Weitere Stationen
    </stations>
  </order>
</xml>
*/
?>

