<?php
/*=======================================================================
 *
 * inc_metafield.inc.php
 *
 * Autor: Marc Vollmann
 *
 =======================================================================*/
 

include_once ("../include/image.inc.php");
if ($phpVersion >= "8.0") :
   include ("../include/barcode_BCGcode39_saveImage_php8.php");
elseif ($phpVersion >= "7.0") :
   include ("../include/barcode_BCGcode39_saveImage_php7.php");
else :
   include ("../include/barcode_BCGcode39_saveImage.php");
endif;
include_once ("../include/inc_file.inc.php");
include_once ("../include/inc_job.inc.php");         // Needed for getting all data for a special table (e.g. tour data of ALL stations)
include_once ("../include/services_func.inc.php");   // Needed for getting prices based on price structures
include_once ("../include/inc_mtf_func.inc.php");    // Functions (e.g. for services)


// Gets col values of a specified db field of a certain table
// $table         : table of the db
// $pWhereClause  : WHERE clause of the statement
// $pValName      : name of the field to get the data
// $pSortName     : "order by"-field
/* ATTENTION: DEFINED IN "db_global" !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
function getColVectorFromDB2ArrayByClause($table, $pValName, $pWhereClause, $pKeyName = "", $pSortName = "") {
     global $db, $PHP_SELF;
     $retArray = array();
     $sqlStmt = "SELECT " . ($pKeyName != "" ? $pKeyName . ", " : "") . "$pValName FROM $table " . ($pWhereClause != "" ? "WHERE " . $pWhereClause : "");
     if ($pSortName != "") : $sqlStmt .= " ORDER BY $pSortName"; endif;
     $result = $db->dbQ($sqlStmt);     
     while ($row = $result->fetch_assoc()):
           if ($pKeyName != "") :
              $retArray[$row[$pKeyName]]= $row[$pValName];
           else :
              array_push($retArray, $row[$pValName]);
           endif;
     endwhile;
     $result->free();
     return $retArray;
}
*/

// Converts formular DB data into an associative array.
// If requested it will be sorted ($mtfvArraySortColArray)
// The DB result (in $result) has to contain the fields:
// mtfv.mtfck_id, mtfv.mtfv_id, mtfv.mtfv_value, mtfk.mtfk_type
function convertFormdataToArray() {
  global $db, $PHP_SELF;
	global $result, $mtfvArraySortColArray, $mtfvTypeArray;
	global $mtfvArray, $mtfvKeysArray, $mtfvKeysArrayLen;
  $remObjId = "";
  while ($row = $result->fetch_assoc()) :
        if ($remObjId == "" || $remObjId != $row["mtfv_id"]) :
           $remObjId = $row["mtfv_id"];
        endif;
        $mtfvArray[$remObjId][] = $row["mtfv_value"];
        $mtfvTypeArray[$remObjId][] = $row["mtfk_type"];
  endwhile;
  $mtfvKeysArray = array_keys($mtfvArray);
  $mtfvKeysArrayLen = count($mtfvKeysArray);
  
  // Sort if requested
  $mtfvArraySortColArrayLen = count($mtfvArraySortColArray);
  if ($mtfvArraySortColArrayLen > 0) :
     $colArray = array();
     for ($i = 0; $i < $mtfvKeysArrayLen; $i++) :
         $tmpKey = "";
         for ($j = 0; $j < $mtfvArraySortColArrayLen; $j++) :
             $tmpKey .= $mtfvArray[$mtfvKeysArray[$i]][$mtfvArraySortColArray[$j]] . ":";
         endfor;
         $tmpKey .= $mtfvKeysArray[$i];    // E.g. "Name:Firstname:ObjId"
         $colArray[$tmpKey] = $mtfvKeysArray[$i];
     endfor;
     // Sort keys of $colArray (key = column to be sorted)
     ksort($colArray);
     $colValueArray = array_values($colArray);
     $colValueArrayLen = count($colValueArray);
     // Generate new sorted array of the formular data
     $tmpMtfvArray = array();
     for ($i = 0; $i < $colValueArrayLen; $i++) :
         $tmpMtfvArray[$colValueArray[$i]] = $mtfvArray[$colValueArray[$i]];
     endfor;
     $mtfvArray = $tmpMtfvArray;
     $mtfvKeysArray = array_keys($mtfvArray);
     $mtfvKeysArrayLen = count($mtfvKeysArray);
  endif;
}

// Returns a special system information according to calling type (e.g. current date)
function getFieldValueBySystemCall ($typeString) {
	global $metaTypeSystemArray, $hq_id, $usr_id;
	$retArray = array();

	if ($typeString != "") :
     $tmpArray = spliti(":",$typeString);
     $sysField = $tmpArray[1];
	   $sysField = $metaTypeSystemArray[$sysField];

	   if ($sysField == "current_date") :
	      $retArray[0] = "varchar";
	      $retArray[1] = getDateTime(5); 
	   endif;
	   if ($hq_id != "") :
	      if ($sysField == "empty_field") :
	         $retArray[0] = "varchar";
	         $retArray[1] = "&nbsp;";
	      endif;
	      if ($sysField == "current_hq_id") :
	         $retArray[0] = "varchar";
	         $retArray[1] = $hq_id; 
	      endif;
	      if ($sysField == "current_hq_mnemonic") :
	         $retArray[0] = "varchar";
	         $retArray[1] = getFieldValueFromId("headquarters", "hq_id", $hq_id, "hq_mnemonic");
	      endif;
	      if ($sysField == "current_hq_name") :
	         $retArray[0] = "varchar";
	         $retArray[1] = getFieldValueFromId("headquarters", "hq_id", $hq_id, "hq_name");
	      endif;
	      if ($sysField == "current_hq_cmp_name") :
	         $retArray[0] = "varchar";
	         $tmpCmpId = getFieldValueFromId("headquarters", "hq_id", $hq_id, "cmp_id");
	         $retArray[1] = getFieldValueFromId("company", "cmp_id", $tmpCmpId, "cmp_comp");
	      endif;
	      if ($sysField == "current_hq_cmp_name2") :
	         $retArray[0] = "varchar";
	         $tmpCmpId = getFieldValueFromId("headquarters", "hq_id", $hq_id, "cmp_id");
	         $retArray[1] = getFieldValueFromId("company", "cmp_id", $tmpCmpId, "cmp_comp2");
	      endif;
	      if ($sysField == "current_hq_cmp_logo") :
	         $retArray[0] = "image";
	         $tmpCmpId = getFieldValueFromId("headquarters", "hq_id", $hq_id, "cmp_id");
	         $retArray[1] = getFieldValueFromId("company", "cmp_id", $tmpCmpId, "cmp_logo");
	         $retArray[2] = getFieldValueFromId("company", "cmp_id", $tmpCmpId, "cmp_logo_height");
	         $retArray[3] = getFieldValueFromId("company", "cmp_id", $tmpCmpId, "cmp_logo_width");
	         $retArray[4] = "0";  // border, currently static ...
	      endif;
	      if ($sysField == "current_hq_ad_street") :
	         $retArray[0] = "varchar";
	         $tmpCmpId = getFieldValueFromId("headquarters", "hq_id", $hq_id, "cmp_id");
	         $tmpAdId = getFieldValueFromId("company", "cmp_id", $tmpCmpId, "ad_id");
	         $retArray[1] = getFieldValueFromId("address", "ad_id", $tmpAdId, "ad_street");
	      endif;
	      if ($sysField == "current_hq_cmp_hsno") :
	         $retArray[0] = "varchar";
	         $tmpCmpId = getFieldValueFromId("headquarters", "hq_id", $hq_id, "cmp_id");
	         $retArray[1] = getFieldValueFromId("company", "cmp_id", $tmpCmpId, "cmp_hsno");
	      endif;
	      if ($sysField == "current_hq_ad_zipcode") :
	         $retArray[0] = "varchar";
	         $tmpCmpId = getFieldValueFromId("headquarters", "hq_id", $hq_id, "cmp_id");
	         $tmpAdId = getFieldValueFromId("company", "cmp_id", $tmpCmpId, "ad_id");
	         $retArray[1] = getFieldValueFromId("address", "ad_id", $tmpAdId, "ad_zipcode");
	      endif;
	      if ($sysField == "current_hq_ad_city") :
	         $retArray[0] = "varchar";
	         $tmpCmpId = getFieldValueFromId("headquarters", "hq_id", $hq_id, "cmp_id");
	         $tmpAdId = getFieldValueFromId("company", "cmp_id", $tmpCmpId, "ad_id");
	         $retArray[1] = getFieldValueFromId("address", "ad_id", $tmpAdId, "ad_city");
	      endif;
	      if ($sysField == "current_user") :
	         $retArray[0] = "readonly";
	         $retArray[1] = getFieldValueFromId("user", "usr_id", $usr_id, "usr_firstname") . " " . getFieldValueFromId("user", "usr_id", $usr_id, "usr_name");
	      endif;
	   endif;

	endif;
  return $retArray;
}

// Returns a special DB field according to calling type
// $typeString : Contains the special type of the field (e.g. "db:cs:eid") which will be mapped to the internal database field name
// $tagDbIndexValue  : Contains a numeric value or asterisk (eq. ALL elements) for the index (key) to identify a special row out of a list (e.g. tr_sort = 2 from the associative job array)
// $tagDbIndexValue2 : Dito for the next cascade! (E.g.: jb <=> m x tour AND tour <=> n x tourarticle)
function getFieldValueBySpecialCall ($typeString, $tagDbIndexValue = "", $tagDbIndexValue2 = "", $systemPath = "..") {
  global $db, $objId, $cascadingObjType, $metaTypeMappingArray, $jobData;
  $retVal = "";

  if ($objId != "" && $typeString != "") :
     $tmpArray = spliti(":",$typeString);
     $objType = $tmpArray[1];
     $objField = $tmpArray[2];
     $mappedObjField = $metaTypeMappingArray[$objType . ":" . $objField];

     $usedObjId = $objId;  // !!!!

     if ($objType != "" && $mappedObjField != "") :
        if ($objType == "cs") :
            if ($cascadingObjType == "rp") :
               $usedObjId = getFieldValueFromId("phoenix_group.report_process", "rp_id", $objId, "rp_objid");
            endif;
            if ($cascadingObjType == "jb") :
               $tmpCscId = getFieldValueFromId("job", "jb_id", $objId, "csc_id_payer");
               $usedObjId = getFieldValueFromId("costcenter", "csc_id", $tmpCscId, "cs_id");
            endif;
            if ($cascadingObjType == "jb_related") :    // Related customer
               $tmpCscId = getFieldValueFromId("job", "jb_id", $objId, "csc_id_related");
               $usedObjId = getFieldValueFromId("costcenter", "csc_id", $tmpCscId, "cs_id");
            endif;

            $tmpCmpId = getFieldValueFromId("customer", "cs_id", $usedObjId, "cmp_id");
            $tmpAdId = getFieldValueFromId("company", "cmp_id", $tmpCmpId, "ad_id");
            $tmpEmpId = getFieldValueFromId("customer", "cs_id", $usedObjId, "cs_admin");
            $tmpUsrId = getFieldValueFromId("employee", "emp_id", $tmpEmpId, "usr_id");
            if (substr($mappedObjField, 0, 3) == "cmp") :
               $retVal = getFieldValueFromId("company", "cmp_id", $tmpCmpId, $mappedObjField);
            elseif (substr($mappedObjField, 0, 2) == "ad") :
               $retVal = getFieldValueFromId("address", "ad_id", $tmpAdId, $mappedObjField);
            elseif (substr($mappedObjField, 0, 5) == "cscad") :
               if ($tmpCscId != "") :
                  $tmpAdtId = $tagDbIndexValue;
                  if ($tmpAdtId == "") : $tmpAdtId = 4; endif;   // "adt_id" <=> addresstype
                  $mappedObjField = substr($mappedObjField, 6);  // E.g.: "cscad_ad_street" => "ad_street" OR "cscad_cscad_hsno" => "cscad_hsno"
                  if (substr($mappedObjField, 0, 2) == "ad") :
                     $tmpAdId = getFieldValueFromClause("costcenteraddress", "ad_id", "csc_id = '" . $tmpCscId . "' AND adt_id = '" . $tmpAdtId . "'");
                     if ($tmpAdId != "") :
                        $retVal = getFieldValueFromId("address", "ad_id", $tmpAdId, $mappedObjField);
                     endif;
                  else :
                     $retVal = getFieldValueFromClause("costcenteraddress", $mappedObjField, "csc_id = '" . $tmpCscId . "' AND adt_id = '" . $tmpAdtId . "'");
                  endif;
                  // If $retVal is empty, try to get costcenteraddress data from root costcenter
                  if ($retVal == "") :
                     $tmpCscIdRoot = getFieldValueFromId("customer", "cs_id", $usedObjId, "csc_id");
                     if (substr($mappedObjField, 0, 2) == "ad") :
                        $tmpAdId = getFieldValueFromClause("costcenteraddress", "ad_id", "csc_id = '" . $tmpCscIdRoot . "' AND adt_id = '" . $tmpAdtId . "'");
                        if ($tmpAdId != "") :
                           $retVal = getFieldValueFromId("address", "ad_id", $tmpAdId, $mappedObjField);
                        endif;
                     else :
                        $retVal = getFieldValueFromClause("costcenteraddress", $mappedObjField, "csc_id = '" . $tmpCscIdRoot . "' AND adt_id = '" . $tmpAdtId . "'");
                     endif;
                  endif;
               endif;
            elseif (substr($mappedObjField, 0, 3) == "usr") :
               $retVal = getFieldValueFromId("user", "usr_id", $tmpUsrId, $mappedObjField);
            elseif (substr($mappedObjField, 0, 4) == "stat") :
               $usedHqId = getFieldValueFromId("customer", "cs_id", $usedObjId, "hq_id");
               $tmpCurrYear = getDateTime("year");
               $tmpCurrDate = getDateTime("3");
               if ($mappedObjField == "stat_bv_02") :
                  $tmpCurrYear = getDateTime("lastyear");
                  $tmpCurrDate = getDateTime("date_lastyear");
               endif;
// echo $usedObjId . "<br>";
               // Statistic business volume from 01.01. of the current year to the current day
               $tmpSqlVal = $db->getOne("SELECT SUM(jb.jb_totalprice) AS business_volume FROM job AS jb,costcenter AS csc,customer AS cs,company AS cmp 
                                           WHERE jb.jb_status = '2' AND jb.hq_id = '" . $usedHqId . "' AND (isnull(jb.jb_storno) OR jb.jb_storno = '0' OR jb.jb_storno = '1' OR jb.jb_storno = '3') AND 
                                                 jb.jb_finishtime >= '" . $tmpCurrYear . "-01-01 00:00:00' AND jb.jb_finishtime <= '" . $tmpCurrDate . " 23:59:59' AND 
                                                 jb.csc_id_payer = csc.csc_id AND csc.cs_id = cs.cs_id AND cs.cmp_id = cmp.cmp_id AND cs.cs_id = '".  $usedObjId . "' GROUP BY cs.cs_id");                                                 
               if ($tmpSqlVal == "") : $tmpSqlVal = 0; endif;
// echo $tmpSqlVal . "<br>";
               $retVal = number_format(round($tmpSqlVal,2), 2, ",", ".");

            elseif (substr($mappedObjField, 0, 7) == "special") :
               if ($mappedObjField == "special_hash") :
                  $usedHqId = getFieldValueFromId("customer", "cs_id", $usedObjId, "hq_id");
                  $tmpCmpNewDate = getFieldValueFromId("company", "cmp_id", $tmpCmpId, "cmp_new_date");
                  $retVal = makeMD5Hash($usedHqId, $usedObjId, $tmpCmpNewDate);
               endif;
            else :
               $retVal = getFieldValueFromId("customer", "cs_id", $usedObjId, $mappedObjField);
            endif;

        elseif ($objType == "pt") :
            if ($cascadingObjType == "rp") :
               $usedObjId = getFieldValueFromId("phoenix_group.report_process", "rp_id", $objId, "rp_objid");
            endif;
            
            $tmpAdId = getFieldValueFromId("prospect", "pt_id", $usedObjId, "ad_id");

            if (substr($mappedObjField, 0, 2) == "ad") :
               $retVal = getFieldValueFromId("address", "ad_id", $tmpAdId, $mappedObjField);
            else :
               $retVal = getFieldValueFromId("prospect", "pt_id", $usedObjId, $mappedObjField);
            endif;

        elseif ($objType == "cr") :
            if ($cascadingObjType == "rp") :
               $usedObjId = getFieldValueFromId("phoenix_group.report_process", "rp_id", $objId, "rp_objid");
            endif;
            if ($cascadingObjType == "jb") :
               $usedObjId = getFieldValueFromId("job", "jb_id", $objId, "cr_id");
            endif;
            if ($cascadingObjType == "jb_related") :
               $tmpUsedObjId = getFieldValueFromId("job", "jb_id", $objId, "cr_id");
               $usedObjId = getFieldValueFromId("courier", "cr_id", $tmpUsedObjId, "cr_id_parent");
            endif;

            $tmpCmpId = getFieldValueFromId("courier", "cr_id", $usedObjId, "cmp_id");
            $tmpAdId = getFieldValueFromId("company", "cmp_id", $tmpCmpId, "ad_id");
            $tmpUsrId = getFieldValueFromId("courier", "cr_id", $usedObjId, "usr_id");

            if (substr($mappedObjField, 0, 3) == "cmp") :
               $retVal = getFieldValueFromId("company", "cmp_id", $tmpCmpId, $mappedObjField);
            elseif (substr($mappedObjField, 0, 2) == "ad") :
               $retVal = getFieldValueFromId("address", "ad_id", $tmpAdId, $mappedObjField);
            elseif (substr($mappedObjField, 0, 3) == "usr") :
               $retVal = getFieldValueFromId("user", "usr_id", $tmpUsrId, $mappedObjField);
            else :
              $retVal = getFieldValueFromId("courier", "cr_id", $usedObjId, $mappedObjField);
            endif;

        elseif ($objType == "crvh") :
            if ($cascadingObjType == "rp") :
               $usedObjId = getFieldValueFromId("phoenix_group.report_process", "rp_id", $objId, "rp_objid");
            endif;
            if ($cascadingObjType == "jb") :
               $tmpSid = getFieldValueFromId("job", "jb_id", $objId, "cr_sid");
               $usedObjId = getFieldValueFromId("couriervehicle", "crvh_sid", $tmpSid, "crvh_id");
            endif;
            $retVal = getFieldValueFromId("couriervehicle", "crvh_id", $usedObjId, $mappedObjField);

        elseif ($objType == "at") :
            $retVal = getFieldValueFromId("article", "at_id", $usedObjId, $mappedObjField);
            if ($mappedObjField == "at_barcode") :
               $retVal = barcode_BCGcode39_saveImage($barcodeFilename , $systemPath, $mappedObjField, "2", "30", "", "");
            endif;

        elseif ($objType == "jb") :
            if ($jobData == "" || !is_array($jobData)) :
               getDBData("job", $usedObjId);
            endif;
            if (count($jobData["job"]) == 0) :
               $retVal = getFieldValueFromId("job", "jb_id", $usedObjId, $mappedObjField);
            else :
               $retVal = $jobData["job"][$mappedObjField];
            endif;

            if ($mappedObjField == "jb_ordertime" || $mappedObjField == "jb_taketime" || $mappedObjField == "jb_finishtime" || $mappedObjField == "jb_warningtime" || $mappedObjField == "jb_export_time" || $mappedObjField == "jb_createtime") :
               $retVal = formatOutput($retVal,"datetime","5");

            elseif (substr($mappedObjField,0,11) == "jb_freetext") :
               $retVal = getFieldValueFromId("job", "jb_id", $usedObjId, $mappedObjField);

            elseif ($mappedObjField == "parent_id_fallback_jb_id") :
               $retVal = $jobData["job"]["jb_id_parent"];
               if ($retVal == "" || $retVal == 0) :
                  $retVal = $usedObjId;
               endif;

            elseif ($mappedObjField == "service_sign") :
               $retVal = getFieldValueFromId("phoenix_log.b2b_objects", "bo_ext_id2", $usedObjId . "12", "bo_obj_data");
               if ($retVal == "") :
                  $dbHistoryConnection = getDbHistoryConnection($dbHistoryConnection);
                  if (is_object($dbHistoryConnection)) :
                     $retVal = getFieldValueFromId("phoenix_log.b2b_objects_2015", "bo_ext_id2", $usedObjId . "12", "bo_obj_data", $dbHistoryConnection);
                  endif;
               endif;
               
               if ($retVal != "") :
                  $retVal = str_replace("|", "-,-", $retVal);
                  if (!(strpos($retVal, "-,-") === FALSE)) :
                     $tmpArray = spliti("-,-",$retVal);
                     $retVal = $tmpArray[2];  // 3. element = service sign
                  else :
                     $retVal = "";
                  endif;
               endif;
               $retVal = saveImageToFile($retVal, $usedObjId . "_" . ".png", $systemPath, "150", "75");

            elseif ($mappedObjField == "jb_is_installation") :
               $tmpJbService = $jobData["job"]["jb_service"];
               $retVal = "0";
               if (($tmpJbService & 2) == 2) :
                  $retVal = "1";
               endif;

            elseif ($mappedObjField == "service_acceptance_protocol_text") :
               $retVal = "";
               // Get acceptance protocol text depending on the RELATED customer
               $tmpCscIdRelated = $jobData["job"]["csc_id_related"];                                     // Get related costcenter (customer)
               if ($tmpCscIdRelated == "") : $tmpCscIdRelated = $jobData["job"]["csc_id_payer"]; endif;  // Get paying costcenter (customer) if related costcenter does not exist
               $tmpJbService = $jobData["job"]["jb_service"];                                            // Get service(s) of the job
               if ($tmpJbService == "") : $tmpJbService = "1"; endif;                                    // Init to basic service if not defined in job ("Lieferung") !!!!
               $tmpServiceAcceptanceProtocolContent = "";
               if ($tmpCscIdRelated != "") :
                  $tmpCsId = getFieldValueFromId("costcenter", "csc_id", $tmpCscIdRelated, "cs_id");
                  $tmpServiceAcceptanceProtocolContent = getFieldValueFromClause("genericdatacontainer", "gdc_content", "gdc_obj_type = 'cs' AND gdc_obj_id = '" . $tmpCsId . "' AND gdc_gen_fieldname = 'service_acceptance_protocol_text'");
               endif;

               // Try to get the correct protocol from rules
               $tmpJbService = mcGetServiceAcceptanceProtocolByRule($tmpJbService, "cs", $tmpCsId);

               // Get texts based on the protocol computed on rules
               $outputText = "";
               if ($tmpServiceAcceptanceProtocolContent != "") :
                  $tmpTextArray = getKeyValueArrayFromString($tmpServiceAcceptanceProtocolContent);

                  // Take the texts (array) of the current service only
                  $tmpText = $tmpTextArray[$tmpJbService];
                  if ($tmpText != "") :
                        $outputText .= "<table>";
                        $outputText .= "  <tr>";
                        $outputText .= "    <td style=\"font-size:8pt; align:left;\">" . $tmpText . "</td>";
                        $outputText .= "  </tr>";
                        $outputText .= "</table>";
                  endif;
               endif;
               $retVal = $outputText;

            elseif ($mappedObjField == "service_acceptance_protocol_packing_pieces") :
               // Get number of packing pieces the end customer has signed for
               $retVal = getFieldValueFromClause("genericdatacontainer", "gdc_content", "gdc_obj_type = 'jb' AND gdc_obj_id = '" . $jobData["job"]["jb_id"] . "' AND gdc_gen_fieldname = 'pack_pieces'");

            elseif ($mappedObjField == "service_acceptance_protocol_points") :
               $retVal = "";
               $boObjData = getFieldValueFromId("phoenix_log.b2b_objects", "bo_ext_id2", $usedObjId . "12", "bo_obj_data");
               if ($boObjData == "") :
                  $dbHistoryConnection = getDbHistoryConnection($dbHistoryConnection);
                  if (is_object($dbHistoryConnection)) :
                     $boObjData = getFieldValueFromId("phoenix_log.b2b_objects_2015", "bo_ext_id2", $usedObjId . "12", "bo_obj_data", $dbHistoryConnection);
                  endif;
               endif;

               if ($boObjData != "") :
                  $boObjData = str_replace("|", "-,-", $boObjData);
                  if (!(strpos($boObjData, "-,-") === FALSE)) :

                     // Prepare answers of the service acceptance protocol
                     $tmpArray = spliti("-,-",$boObjData);
                     $tmpArrayLen = count($tmpArray);
                     // Static offset because of data structure in database [:-/]
                     $tmpAnswersArray = array();
                     $tmpArticlesArray = array();
                     $tmpRemarksArray = array();

                     for ($j = 2; $j <= $tmpArrayLen; $j++) :
                         if (substr($tmpArray[$j],-2) == "pp") :
                            $tmpAnswer = substr($tmpArray[$j + 2],0,1);
                            if ($tmpAnswer == "J") : $tmpAnswer = getLngt("Ja"); endif;
                            if ($tmpAnswer == "N") : $tmpAnswer = getLngt("Nein"); endif;
                            if ($tmpAnswer == "Z") : $tmpAnswer = getLngt("Nicht&nbsp;zutreffend"); endif;
                            $tmpAnswersArray[$tmpArray[$j + 1]] = $tmpAnswer;
                         elseif (substr($tmpArray[$j],-2) == "pa") :
                            $tmpArticlesArray[$tmpArray[$j + 1]] = $tmpArray[$j + 2];
                            $tmpRemarksArray[$tmpArray[$j + 1]] = $tmpArray[$j + 3];
                         endif;
                     endfor;

                     // Get acceptance protocol questions of the job
                     $tmpCscIdRelated = $jobData["job"]["csc_id_related"];                                     // Get related costcenter (customer)
                     if ($tmpCscIdRelated == "") : $tmpCscIdRelated = $jobData["job"]["csc_id_payer"]; endif;  // Get paying costcenter (customer) if related costcenter does not exist
                     $tmpJbService = $jobData["job"]["jb_service"];                                            // Get service(s) of the job
                     if ($tmpJbService == "") : $tmpJbService = "1"; endif;                                    // Init to basic service if not defined in job ("Lieferung") !!!!
                     $tmpServiceAcceptanceProtocolContent = "";
                     if ($tmpCscIdRelated != "") :
                        $tmpCsId = getFieldValueFromId("costcenter", "csc_id", $tmpCscIdRelated, "cs_id");
                        $tmpServiceAcceptanceProtocolContent = getFieldValueFromClause("genericdatacontainer", "gdc_content", "gdc_obj_type = 'cs' AND gdc_obj_id = '" . $tmpCsId . "' AND gdc_gen_fieldname = 'service_acceptance_protocol_questions'");
                     endif;

                     // Try to get the correct protocol from rules
                     $tmpJbService = mcGetServiceAcceptanceProtocolByRule($tmpJbService, "cs", $tmpCsId);

                     // Get questions based on the protocol computed on rules
                     $outputQuestions = "";
                     if ($tmpServiceAcceptanceProtocolContent != "") :
                        // Split content to get the questions of the current selected service
                        // E.g.: "0=Q1,Q2,Q3|1=Q1,Q2,Q3,Q4,Q5|2=Q1..."  => x(0) = Q1,Q2,Q3, x(1) = Q1,Q2,Q3,Q4,Q5, ...
                        // [=> 0=Q1,Q2,Q3 => Service "0" (= Lieferung) is mapped to the questions]
                        $tmpQuestionArray = getKeyValueArrayFromString($tmpServiceAcceptanceProtocolContent);

                        // Take the questions (array) of the current service only
                        $tmpQuestionString = $tmpQuestionArray[$tmpJbService];
                        if ($tmpQuestionString != "") :
                           $tmpQuestionArray = spliti(",", $tmpQuestionString);
                           $tmpQuestionArrayLen = count($tmpQuestionArray);
                           if ($tmpQuestionArrayLen > 0) :
                              $outputQuestions .= "<table>";
                              for ($i = 0; $i < $tmpQuestionArrayLen; $i++) :
                                  $outputQuestions .= "<tr>";
                                  $outputQuestions .= "<td style=\"font-size:8pt; align:right;\">" . ($i + 1) . ".&nbsp;</td>";
                                  $outputQuestions .= "<td style=\"font-size:8pt; align:left;\">" . $tmpQuestionArray[$i] . "&nbsp;&nbsp;</td>";
                                  $outputQuestions .= "<td style=\"font-size:8pt; align:left;\">" . $tmpAnswersArray[($i + 1)] . "&nbsp;&nbsp;&nbsp;</td>";
                                  $outputQuestions .= "<td style=\"font-size:8pt; align:left;\">" . $tmpArticlesArray[($i + 1)] . "&nbsp;&nbsp;&nbsp;</td>";
                                  // $outputQuestions .= "<td style=\"font-size:8pt; align:left;\">" . $tmpRemarksArray[($i + 1)] . "&nbsp;&nbsp;&nbsp;</td>";
                                  $srvAccProtRemark = $tmpRemarksArray[($i + 1)];
                                  if (substr($srvAccProtRemark,-2) == "pp") : $srvAccProtRemark = substr($srvAccProtRemark,0,-2); endif;
                                  $outputQuestions .= "<td style=\"font-size:8pt; align:left;\">" . $srvAccProtRemark . "&nbsp;&nbsp;&nbsp;</td>";
                                  $outputQuestions .= "</tr>";
                              endfor;
                              $outputQuestions .= "</table>";
                           endif;
                        endif;
                     endif;
                     $retVal = $outputQuestions;
                  endif;
               endif;

            elseif ($mappedObjField == "service_photos") :
               $retVal = "";
               $tmpPhotoFilenames = getFieldValueFromClause("genericdatacontainer", "gdc_content", "gdc_obj_type = 'jb' AND gdc_obj_id = '" . $usedObjId . "' AND gdc_gen_fieldname = 'mobile_photos'");

               $outputPhotos = "";
               if ($tmpPhotoFilenames != "") :
                  $tmpPhotoFilenames = str_replace("|", "-,-", $tmpPhotoFilenames);
                  if (!(strpos($tmpPhotoFilenames, "-,-") === FALSE)) :
                     $tmpArray = spliti("-,-",$tmpPhotoFilenames);
                  else :
                     $tmpArray = array($tmpPhotoFilenames);
                  endif;
                  $tmpArrayLen = count($tmpArray);
                  if ($tmpArrayLen > 0) :
                     $tmpImgHeight = 100;
                     $tmpImgWidth = 133;
                     $outputPhotos .= "<table>";
                     $outputPhotos .= "<tr>";
                     for ($i = 0; $i < $tmpArrayLen; $i++) {
                         $outputPhotos .= "<td height=\"130\" width=\"160\" align=\"center\"><img src=\"" . $systemPath . "/documents/photos/" . $tmpArray[$i] . "\" border=\"" . "0" . "\" height=\"" . $tmpImgHeight . "\" width=\"" . $tmpImgWidth . "\"></td>";
                         if ((($i + 1) % 4) == 0 && $i < ($tmpArrayLen - 1)) :
                            $outputPhotos .= "</tr><tr>";
                         endif;
                     }
                     $outputPhotos .= "</tr>";
                     $outputPhotos .= "<table>";
                  endif;
               endif;
               $retVal = $outputPhotos;

            elseif ($mappedObjField == "jb_daytime") :
               $retVal = "";
               // Check for being a job for the whole day
               if (substr($jobData["job"]["jb_ordertime"], -8) != "00:00:01") :
                  $tmpCscIdRelated = $jobData["job"]["csc_id_related"];                                     // Get related costcenter (customer)
                  if ($tmpCscIdRelated == "") : $tmpCscIdRelated = $jobData["job"]["csc_id_payer"]; endif;  // Get paying costcenter (customer) if related costcenter does not exist
                  if ($tmpCscIdRelated != "") :
                     $tmpCsId = getFieldValueFromId("costcenter", "csc_id", $tmpCscIdRelated, "cs_id");
                     // Get mapped value of the day time (clock time)
                     $retVal = getDaytimeTimeInterval($jobData["job"]["jb_ordertime"], $tmpCsId);
                  endif;
               endif;

            elseif ($mappedObjField == "gdc_jb") :
               if ($jobData["gdc_jb"] == "" || !is_array($jobData["gdc_jb"])) :
                  getDBData("genericdatacontainer", $usedObjId);  // $usedObjId equals "jb_id"
               endif;
               $retVal = "";
               if ($tagDbIndexValue != "") :
                  if ($tagDbIndexValue2 == "") :
                     $tagDbIndexValue2 = "gdc_content";
                  endif;
                  $retVal = $jobData["gdc_jb"][$tagDbIndexValue][$tagDbIndexValue2];  // $tagDbIndexValue equals "gdc_gen_fieldname"
               endif;
            endif;

        elseif ($objType == "tr") :
            if ($jobData["tour"] == "" || !is_array($jobData["tour"])) :
               getDBData("tour", $usedObjId);  // $usedObjId equals "jb_id"
            endif;
            $retVal = $jobData["tour"][$tagDbIndexValue][$mappedObjField];  // $tagDbIndexValue equals "tr_sort"
            if ($mappedObjField == "tr_sign") :
               $retVal = saveImageToFile($retVal, $usedObjId . "_" . $tagDbIndexValue . ".png", $systemPath, "150", "75");
            elseif ($mappedObjField == "trat_value_of_goods") :
               // Get value of goods associated to station (sum of all tour articles, depending on the RELATED customer)
               $currentTime = getDateTime("0");
               $tmpCscIdRelated = $jobData["job"]["csc_id_related"];  // Get costcenter of the related  customer from job
               $tmpCsId = getFieldValueFromId("costcenter", "csc_id", $tmpCscIdRelated, "cs_id");  // Get "cs_id" of the related costcenter
               $tmpGrpId = getCustomerGroupIdFromJob("", $tmpCscIdRelated);
               // Get single tour article of the station
               $tmpAtId = $jobData["tourarticle"][$tagDbIndexValue][$tagDbIndexValue2]["at_id"];
               $tmpTratQuantity = $jobData["tourarticle"][$tagDbIndexValue][$tagDbIndexValue2]["trat_quantity"];
               $retVal = getValueOfGoodsOfTratArticles(array(array($tmpAtId, $tmpTratQuantity)), $currentTime, $tmpGrpId, $tmpCsId);
            elseif ($mappedObjField == "trat_summated_value_of_goods" || $mappedObjField == "trat_summated_price") :
               // Get value of goods associated to station (sum of all tour articles, depending on the RELATED customer)
               $currentTime = getDateTime("0");
               $tmpCscIdRelated = $jobData["job"]["csc_id_related"];  // Get costcenter of the related  customer from job
               $tmpCsId = getFieldValueFromId("costcenter", "csc_id", $tmpCscIdRelated, "cs_id");  // Get "cs_id" of the related costcenter
               $tmpGrpId = getCustomerGroupIdFromJob("", $tmpCscIdRelated);
               // Get tour articles of the station
               $tmpAtArray = getTratArticles($usedObjId, $tagDbIndexValue);
               if ($mappedObjField == "trat_summated_value_of_goods") :
                  $retVal = getValueOfGoodsOfTratArticles($tmpAtArray, $currentTime, $tmpGrpId, $tmpCsId);
               else :
                  $retVal = 0;
                  $tmpAtArrayLen = count($tmpAtArray);
                  for ($j = 0; $j < $tmpAtArrayLen; $j++) :
                      $retVal += $tmpAtArray[$j][7];  // trat_price
                  endfor;
               endif;
            elseif ($mappedObjField == "trat_number_of_all_pieces") :
               // Get the number of all pieces (associated to a single station)
               // Check for stored value got by interface
               // $retVal = getFieldValueFromClause("genericdatacontainer", "gdc_content", "gdc_obj_type = 'tr' AND gdc_obj_id = '" . $usedObjId . "' AND gdc_gen_fieldname = 'trat_sum_pieces'");
               $retVal = getFieldValueFromClause("genericdatacontainer", "gdc_content", "gdc_obj_type = 'jb' AND gdc_obj_id = '" . $usedObjId . "' AND gdc_gen_fieldname = 'pack_pieces'");
               if ($retVal == "" || !is_numeric($retVal) || $retVal == 0) :
                  $retVal = getTratPackingPieces($usedObjId, $tagDbIndexValue);
               endif;
            elseif ($mappedObjField == "trat_sum_of_weight") :
               // Get the sum of the tourarticle weight (associated to a single station)
               // Check for stored value got by interface
               $retVal = getFieldValueFromClause("genericdatacontainer", "gdc_content", "gdc_obj_type = 'tr' AND gdc_obj_id = '" . $usedObjId . "' AND gdc_gen_fieldname = 'trat_sum_weight'");
               if ($retVal == "" || !is_numeric($retVal) || $retVal == 0) :
                  $retVal = getTratTotalweight($usedObjId, $tagDbIndexValue);
               endif;
            elseif ($mappedObjField == "trat_sum_of_volume") :
               // Get the sum of the tourarticle weight (associated to a single station)
               // Check for stored value got by interface
               $retVal = getFieldValueFromClause("genericdatacontainer", "gdc_content", "gdc_obj_type = 'tr' AND gdc_obj_id = '" . $usedObjId . "' AND gdc_gen_fieldname = 'trat_sum_volume'");
               if ($retVal == "" || !is_numeric($retVal) || $retVal == 0) :
                  // $retVal = getTratTotalVolume($usedObjId, $tagDbIndexValue);
               endif;
            elseif (substr($mappedObjField, 0, 5) == "trat_" || substr($mappedObjField, 0, 3) == "at_") :
                if ($jobData["tourarticle"] == "" || !is_array($jobData["tourarticle"])) :
                   getDBData("tourarticle", $usedObjId);
                endif;
                $retVal = $jobData["tourarticle"][$tagDbIndexValue][$tagDbIndexValue2][$mappedObjField];  // $tagDbIndexValue2 equals "trat_sort"
            elseif (substr($mappedObjField, 0, 8) == "tr_calc_") :
               // Get special value (single row) out of all calculator entries associated to station
               $mappedObjField = substr($mappedObjField, 8);
               $tmpCalcArray = getCalculatorData($usedObjId, $tagDbIndexValue, $tagDbIndexValue2, "1");
               $retVal = $tmpCalcArray[$mappedObjField];

            elseif ($mappedObjField == "tr_summated_calc_value") :
               // Get summated value of all calculator entries associated to station
               $tmpCalcArray = getCalculatorData($usedObjId, $tagDbIndexValue);
               $retVal = getCalculatorPrice($tmpCalcArray);

            elseif ($mappedObjField == "jbp_mode") :
               // Get payment method from jb_id and tr_sort
               $whereClause = "";
               if ($tagDbIndexValue != "") : $whereClause = " AND tr_sort = '" . $tagDbIndexValue . "'"; endif;
               $jbpMode = getFieldValueFromClause("jobpayment","jbp_mode","jb_id = '" . $usedObjId . "'" . $whereClause);
               // Take customer
               $tmpCscIdRelated = $jobData["job"]["csc_id_related"];  // Get costcenter of the related  customer from job
               $tmpCsId = getFieldValueFromId("costcenter", "csc_id", $tmpCscIdRelated, "cs_id");  // Get "cs_id" of the related costcenter
               $tmpGrpId = getCustomerGroupIdFromJob("", $tmpCscIdRelated);
               // Get payment types using cascading structure
               $mtPaymentTypeNames = array();
               if ($tmpCsId != "") :
                  $mtPaymentTypeNames = getColVectorFromDB2ArrayByClause("metatype", "mt_value", "mt_type = 'payment_type' AND mt_objtype = 'cs' AND mt_objid = '" . $tmpCsId . "'", "mt_sort", "mt_sort", "");
                  if (count($mtPaymentTypeNames) == 0) :
                     $mtPaymentTypeNames = getColVectorFromDB2ArrayByClause("metatype", "mt_value", "mt_type = 'payment_type' AND mt_objtype = 'grp' AND mt_objid = '" . $tmpGrpId . "'", "mt_sort", "mt_sort", "");
                  endif;
               endif;
               if (count($mtPaymentTypeNames) == 0) :
                  $mtPaymentTypeNames = getColVectorFromDB2ArrayByClause("metatype", "mt_value", "mt_type = 'payment_type' AND mt_objtype = '' AND mt_objid = '0'", "mt_sort", "mt_sort", "");
               endif;
               $retVal = $mtPaymentTypeNames[$jbpMode];

            elseif ($mappedObjField == "exist_payment_difference") :
               // Compute the difference between jb_totalprice and summation payments. Returns "" if difference is 0
               $retVal = "";
               // Get summation of "jbp_price" of relevant rows to update the new collection row
               $sumOfJbpPrice = getSumOfTable("jobpayment AS jbp", "jbp.jbp_price", "jbp.jb_id = '" . $usedObjId . "'");
               // Get jb_titalprice
               $jbTotalprice = $jobData["job"]["jb_totalprice"];
               $tmpDiff = $jbTotalprice - $sumOfJbpPrice;
               if (round($tmpDiff, 2) != 0) :
                  $retVal = "&nbsp;";  // E.g. not visible if could not be removed by tag <REMOVE_EMPTY_nn>
               endif;

            endif;

        else :
            $retVal = "";
        endif;
     endif;
  endif;
  return $retVal;
}

// Returns a result by a called formular function
function getFieldValueByFunctionCall ($typeString) {
	global $hq_id, $objId, $category;
	$retArray = array();
	if ($objId != "" && $typeString != "") :
	   // Structures:
	   // Activated value:  func:<no_of_function>:activated => (0|1)
	   //                   e.g.: func:0029:activated => "1" (yes), func:0037:activated => "0" (no), func:0024:activated => "1" (yes), ...
	   // Date valid:       func:<no_of_function>:date_valid => ('10-07-2013|31-12-2999')
	   // Parameter values: func:<no_of_function>:<no_of_parameter>:<type_of_parameter> 
	   //                   e.g.: func:0029:06:int, func:0037:04:varchar, func:0024:02:float, ...
	   // Return value:     func:<no_of_function>:return => <type_of_return_value>,<format_of_the_type_of_return_value>
	   //                   e.g.: func:0029:return => "int,2"      <=> "Formatierung nach Schema 2 für int" [<=> Function "formatOutput(...)"]
	   //                         func:0037:return => "varchar,1"  <=> "Standardformatierung für varchar"
	   //                         func:0024:return => "float,3"    <=> "Formatierung nach Schema 3 für float"
	   // For an object (e.g. a special customer) a function have to be activated! 
	   // The "activation-value" has to exist and has to be set to "1" (func:xxxx:activated => "1" (activated yes)).
	   // Only if it is set, all other values of the function "xxxx" will be computed by the implemented function!
     $tmpArray = spliti(":",$typeString);
     $funcNo = $tmpArray[1];
     $funcParNo = $tmpArray[2];
     $funcParType = $tmpArray[3];
     if ($funcParType == "") : $funcParType = "varchar"; endif;
	   if ($funcNo != "" && $funcParNo != "") :
	      if ($funcParNo == "activated") :	      
   	       $retArray[0] = "checkbox";
   	       $retArray[1] = "";
	      elseif ($funcParNo == "date_valid") :
   	       $retArray[0] = "date_valid";
   	       $retArray[1] = "";
	      elseif ($funcParNo == "global_repayment") :
   	       $retArray[0] = "float_2";
   	       $retArray[1] = "";
	      elseif ($funcParNo == "return") :
   	       $retArray[0] = "computed";
   	       $retArray[1] = "missing function";  // Init
   	       if (function_exists("getMtfFunctionSingleResult")) :
   	          $retArray[1] = getMtfFunctionSingleResult($hq_id, $objId, $category, $funcNo);
   	       endif;
	      else:
   	       $retArray[0] = $funcParType;
   	       $retArray[1] = "";
        endif;
     endif;
	endif;
  return $retArray;
}

// Get all field names defined for all meta fields
function mtfk_getAllIDs ($sort = "") {
  return getColVectorFromDB2ArrayByClause("metafieldkey", "mtfk_id", "", "", $sort);
}

// Get all field names defined for all meta fields
function mtfk_getAllFieldNames () {
  return getColVectorFromDB2ArrayByClause("metafieldkey", "mtfk_name", "", "mtfk_id", "");
}

// Get all field types defined for all meta fields
function mtfk_getAllFieldTypes () {
  return getColVectorFromDB2ArrayByClause("metafieldkey", "mtfk_type", "", "mtfk_id", "");
}

// Get values of a special object (customer, courier, etc.)
function mtfv_getObjValues () {
  global $db, $PHP_SELF, $hq_id, $category, $objId;
  global $mtfk_allFieldNames, $mtfck_mtfkIds, $mtfck_mtfckIds, $mtfck_mtfckIdsLen;
  $mtfvValueArray = array();
  if ($category != "" && $objId != "" && $mtfck_mtfckIdsLen > 0) :
     $mtfvValueArray = getColVectorFromDB2ArrayByClause("metafieldvalue", "mtfv_value", "mtfv_id = '" . $objId . "' AND mtfck_id IN (" . implode(",", $mtfck_mtfckIds) . ")", "mtfck_id", "");
  endif;
  return $mtfvValueArray;
}

// Get fields according to a special headquarters and a specified category
function mtfck_getIds ($category, $hqId, $idField = "mtfck_id", $keyField = "") {
  global $db, $PHP_SELF, $hq_id, $gHqId;
  if ($hqId == "") : $hqId = $hq_id; endif;
  if ($hqId == "") : $hqId = "0"; endif;
  // Check for setting according to global usage
  if ($gHqId) : $hqId = "0"; endif;
  if ($category != "") : 
     $mtfckArray = getColVectorFromDB2ArrayByClause("metafieldcategorykey", $idField, "hq_id = '" . $hqId . "' AND mtfc_id = '" . $category . "' ", $keyField, "mtfck_sort");
  endif;
  return $mtfckArray;
}

function initMetaFieldStructure () {
  global $db, $PHP_SELF, $hq_id, $category, $objId;
  global $mtfk_allIDs, $mtfk_allFieldNames, $mtfk_allFieldTypes;
  global $mtfck_mtfkIds, $mtfck_mtfkSortedIds, $mtfck_mtfckIds, $mtfck_mtfckIdsLen, $mtfck_mtfckHistoryIds;

  $hqId = "";  // Init

  // Get all key fields independent from category, "key-value" representation
  $mtfk_allIDs = mtfk_getAllIDs();
  $mtfk_allFieldNames = mtfk_getAllFieldNames();
  $mtfk_allFieldTypes = mtfk_getAllFieldTypes();

  If ($category != "") :
     $mtfck_mtfkIds = mtfck_getIds($category, $hqId, "mtfk_id");                            // Key field IDs from table "mtfck"
     $mtfck_mtfkSortedIds = mtfck_getIds($category, $hqId, "mtfck_sort", "mtfk_id");        // Sort field from table "mtfck"
     $mtfck_mtfckIds = mtfck_getIds($category, $hqId);                                      // Category key field IDs from table "mtfck"
     $mtfck_mtfckIdsLen = count($mtfck_mtfckIds);                                           // # $mtfck_mtfkIds == # $mtfck_mtfckIds (!!!)
     $mtfck_mtfckHistoryIds = mtfck_getIds($category, $hqId, "mtfck_history", "mtfck_id");  // History field from table "mtfck"
  endif;
}

// Save object data
function saveObjectData () {
	global $db, $PHP_SELF, $hq_id, $usr_id, $category, $objId;
	global $mtfck_mtfkIds, $mtfck_mtfckIds, $mtfck_mtfckIdsLen, $mtfk_allFieldNames, $mtfk_allFieldTypes, $mtfck_mtfckHistoryIds;

  TA("B");      

  // Remove current entries of the specified object
  if ($objId != "" && $category != "") :
     deleteStmt("metafieldvalue","mtfv_id = '" . $objId . "' AND mtfck_id IN (" . implode(",",$mtfck_mtfckIds) . ")");
  endif;

  // Get new objId (especially used by "contacts" WITHOUT reference to an existing object like cs, etc.)
  if ($objId == "") : 
     $objId = getMaxOfField("metafieldvalue", "mtfv_id");
     if ($objId == "" || $objId == "0") :
        $objId = "1";
     else :
        $objId++;
     endif;
  endif;

  $logString = "";
  $logArray = array();
  for ($j = 0; $j < $mtfck_mtfckIdsLen; $j++) :
  
      // Get input-type-text-field
      $newValueToBeStored = "";
      $typeDef = false;
      $ft = $mtfk_allFieldTypes[$mtfck_mtfkIds[$j]];   // !!!

      if ($ft == "date" || $ft == "date_begin" || $ft == "date_end" || $ft == "birthdate" || $ft == "datetime" || $ft == "triggerdate" || $ft == "triggerdatetime" || $ft == "triggerdate_single") :
         list ($tmpDay, $tmpMonth, $tmpYear) = getHttpVars(array("f_mtfv_" . $category . "_". $mtfck_mtfkIds[$j] . "_day", "f_mtfv_" . $category . "_". $mtfck_mtfkIds[$j] . "_month", "f_mtfv_" . $category . "_". $mtfck_mtfkIds[$j] . "_year"));
         if ($tmpDay != "" && $tmpMonth != "" && $tmpYear != "") :
            $newValueToBeStored .= pad($tmpDay, 2) . "." . pad($tmpMonth, 2) . "." . pad($tmpYear, 4);
            $typeDef = true;
         endif;
      endif;
      
      if ($ft == "time" || $ft == "datetime" || $ft == "triggerdatetime") :
         list ($tmpSecond, $tmpMinute, $tmpHour) = getHttpVars(array("f_mtfv_" . $category . "_". $mtfck_mtfkIds[$j] . "_second", "f_mtfv_" . $category . "_". $mtfck_mtfkIds[$j] . "_minute", "f_mtfv_" . $category . "_". $mtfck_mtfkIds[$j] . "_hour"));
         if ($tmpSecond != "" && $tmpMinute != "" && $tmpHour != "") :
            if ($ft == "datetime") : $newValueToBeStored .= " "; endif;
            // $newValueToBeStored .= pad($tmpHour, 2) . ":" . pad($tmpMinute, 2) . ":" . pad($tmpSecond, 2);
            $newValueToBeStored .= pad($tmpHour, 2) . ":" . pad($tmpMinute, 2);
            $typeDef = true;
         endif;
      endif;
      
      if ($ft == "author") :
         list ($newValueToBeStored) = getHttpVars(array("f_mtfv_" . $category . "_". $mtfck_mtfkIds[$j]));
         // "$newValueToBeStored" contains the usr_id or it is empty. 
         // Only if it is empty, the current usr_id will be added during the first storing process (creation time)
         $newValueToBeStored = trim($newValueToBeStored);
         if ($newValueToBeStored == "") :
            $newValueToBeStored = $usr_id;
         endif;
         $typeDef = true;
      endif;
      
      if ($ft == "co2cs") :
         list ($newValueToBeStored) = getHttpVars(array("f_mtfv_" . $category . "_". $mtfck_mtfkIds[$j]));
         // "$newValueToBeStored" contains the EID. Conversion to the internal representation cs_id
         $newValueToBeStored = trim($newValueToBeStored);
         if ($newValueToBeStored != "") :
            $newValueToBeStored = getFieldValueFromId("customer", "cs_eid", $newValueToBeStored, "cs_id");
         endif;
         $typeDef = true;
      endif;            
      
      if ($ft == "checkbox") :
         $tmpCheckbox = getHttpVars(array("f_mtfv_" . $category . "_". $mtfck_mtfkIds[$j]));
         if (!(array_search("1",$tmpCheckbox) === FALSE)) : $newValueToBeStored .= "1"; endif;
         $typeDef = true;
      endif;

      if ($ft == "checkboxes_hq") :
         $tmpCheckboxes = getHttpVars(array("f_mtfv_" . $category . "_". $mtfck_mtfkIds[$j]));
         $tmpCheckboxes = $tmpCheckboxes[0];
         if (is_array($tmpCheckboxes)) :
            $newValueToBeStored = implode(",",$tmpCheckboxes);
         elseif ($tmpCheckboxes != "") :
            $newValueToBeStored = $tmpCheckboxes;
         endif;
         $typeDef = true;
      endif;

      if ($ft == "number" || $ft == "float" || $ft == "float_2" || $ft == "integer") :  // Number types
         list ($newValueToBeStored) = getHttpVars(array("f_mtfv_" . $category . "_". $mtfck_mtfkIds[$j]));
         $newValueToBeStored = trim($newValueToBeStored);
         $newValueToBeStored = str_replace (",", ".", $newValueToBeStored);
         if (is_numeric($newValueToBeStored)) :
            if ($ft == "float_2") : $newValueToBeStored = round($newValueToBeStored, 2); endif;
            if ($ft == "integer") : $newValueToBeStored = round($newValueToBeStored, 0); endif;
         else :
            $newValueToBeStored = "";
         endif;
         $typeDef = true;
      endif;

      if (substr($ft,0,5) == "func:") :
         if (substr($ft, -15) == "graduated_price" || substr($ft, -18) == "articlegroup_price") :  // Graduated price, article group price
            $newValueToBeStored = "";
            $repeat = true;
            $i = 0;
            while ($repeat) :
                  list ($newValueToBeStored_01) = getHttpVars(array("f_mtfv_" . $category . "_". $mtfck_mtfkIds[$j] . "_" . $i . "_01"));
                  $newValueToBeStored_01 = str_replace (",", ".", $newValueToBeStored_01);
                  list ($newValueToBeStored_02) = getHttpVars(array("f_mtfv_" . $category . "_". $mtfck_mtfkIds[$j] . "_" . $i . "_02"));
                  $newValueToBeStored_02 = str_replace (",", ".", $newValueToBeStored_02);
                  if ($newValueToBeStored_01 != "" && is_numeric($newValueToBeStored_01) && $newValueToBeStored_02 != "" && is_numeric($newValueToBeStored_02)) :
                     if ($newValueToBeStored != "") : $newValueToBeStored .= "|"; endif;
                     $newValueToBeStored .= $newValueToBeStored_01 . "," . $newValueToBeStored_02;
                  else :
                     $repeat = false;
                  endif;
                  $i++;
            endwhile;
            // Check for new values for the graduated prices to be inserted
            list ($newValueToBeStored_01) = getHttpVars(array("f_mtfv_" . $category . "_". $mtfck_mtfkIds[$j] . "_new_01"));
            $newValueToBeStored_01 = str_replace (",", ".", $newValueToBeStored_01);
            list ($newValueToBeStored_02) = getHttpVars(array("f_mtfv_" . $category . "_". $mtfck_mtfkIds[$j] . "_new_02"));
            $newValueToBeStored_02 = str_replace (",", ".", $newValueToBeStored_02);
            if ($newValueToBeStored_01 != "" && is_numeric($newValueToBeStored_01) && $newValueToBeStored_02 != "" && is_numeric($newValueToBeStored_02)) :
               if ($newValueToBeStored != "") : $newValueToBeStored .= "|"; endif;
               $newValueToBeStored .= $newValueToBeStored_01 . "," . $newValueToBeStored_02;
            endif;
            $typeDef = true;
         elseif (substr($ft, -10) == "date_valid") :
             $newValueToBeStored = "01012010|31122999";   // Init (static values NOT being a problem because here restricted to type "func:....")
             list ($tmpFromDateDay) = getHttpVars(array("f_mtfv_" . $category . "_". $mtfck_mtfkIds[$j] . "_01_day"));
             list ($tmpFromDateMonth) = getHttpVars(array("f_mtfv_" . $category . "_". $mtfck_mtfkIds[$j] . "_01_month"));
             list ($tmpFromDateYear) = getHttpVars(array("f_mtfv_" . $category . "_". $mtfck_mtfkIds[$j] . "_01_year"));
             list ($tmpToDateDay) = getHttpVars(array("f_mtfv_" . $category . "_". $mtfck_mtfkIds[$j] . "_02_day"));
             list ($tmpToDateMonth) = getHttpVars(array("f_mtfv_" . $category . "_". $mtfck_mtfkIds[$j] . "_02_month"));
             list ($tmpToDateYear) = getHttpVars(array("f_mtfv_" . $category . "_". $mtfck_mtfkIds[$j] . "_02_year"));
             if ($tmpFromDateDay != "" && $tmpFromDateMonth != "" && $tmpFromDateYear != "" && $tmpToDateDay != "" && $tmpToDateMonth != "" && $tmpToDateYear != "") :
                $newValueToBeStored = $tmpFromDateDay . $tmpFromDateMonth . $tmpFromDateYear . "|" . $tmpToDateDay . $tmpToDateMonth . $tmpToDateYear;
             endif;
             $typeDef = true;
         elseif (substr($ft, -16) == "global_repayment") :
             list ($newValueToBeStored) = getHttpVars(array("f_mtfv_" . $category . "_". $mtfck_mtfkIds[$j]));
             $newValueToBeStored = trim($newValueToBeStored);
             $newValueToBeStored = str_replace (",", ".", $newValueToBeStored);
             if (is_numeric($newValueToBeStored)) :
                if ($ft == "float_2") : $newValueToBeStored = round($newValueToBeStored, 2); endif;
                if ($ft == "integer") : $newValueToBeStored = round($newValueToBeStored, 0); endif;
             else :
                $newValueToBeStored = "";
             endif;
             $typeDef = true;
         endif;
      endif;

      if (substr($ft,0,4) == "ref:") :  // REFERENCE FIELD
         $tmpArray = spliti(":",$ft);
         $tmpArrayLen = count($tmpArray);
         $refOut = "";
         for ($i = 1; $i < $tmpArrayLen; $i++) :
             $tmpMtfckId = getFieldValueFromClause("metafieldcategorykey","mtfck_id","mtfk_id = '" . $tmpArray[$i] . "' AND mtfc_id = '" . $category . "'");
             $newValueToBeStored .= getFieldValueFromClause("metafieldvalue","mtfv_value","mtfck_id = '" . $tmpMtfckId . "' AND mtfv_id = '" . $objId . "'");
             if ($i < ($tmpArrayLen - 1)) : $newValueToBeStored .= " "; endif;
         endfor;
         $typeDef = true;
      endif;

      
      if (!$typeDef) :
         list ($newValueToBeStored) = getHttpVars(array("f_mtfv_" . $category . "_". $mtfck_mtfkIds[$j]));
         $typeDef = true;
      endif;
      $logArray[] = $newValueToBeStored;

      // Insert the new value
      insertStmt("metafieldvalue", array("mtfck_id", $mtfck_mtfckIds[$j], "mtfv_id", $objId, "mtfv_value", $newValueToBeStored));
      
      // Write into history ("mtfvh") if activated for category and key in "mtfck"
      if ($mtfck_mtfckHistoryIds[$mtfck_mtfckIds[$j]] == "1") :
         // Check last value stored in history [ATTENTION: The returned value can be empty (<=> "")!]
         $tmpLastVal = getOneStmt("SELECT mtfv_value FROM metafieldvaluehistory WHERE mtfck_id = '" . $mtfck_mtfckIds[$j] . "' AND mtfv_id = '" . $objId . "' ORDER BY mtfvh_createtime DESC LIMIT 0,1", "mtfv_value");
         if ($tmpLastVal != $newValueToBeStored) :
            $currentTime = getDateTime("0");
            insertStmt("metafieldvaluehistory", array("mtfck_id", $mtfck_mtfckIds[$j], "mtfv_id", $objId, "mtfv_value", $newValueToBeStored, "mtfvh_createtime", $currentTime));
         endif;
      endif;
  
      // Generate log string
      $logString .= makeLogString($logArray, ";", "0");
      
      if ($typeDef) :
         $statusMessage = "Der Datensatz wurde gespeichert!";
      else :
         $statusMessage = "Der Datensatz wurde nicht gespeichert!";
      endif;
  endfor;

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

  initMetaFieldStructure();    // Reload the meta field structure in memory
}

// Preparses a template, e.g. to substitute iteration tags, etc.
function templatePreparser ($contentOfCurrTemplate, $systemPath) {
  global $db, $PHP_SELF, $hq_id, $usr_id;
  global $category, $objId, $cascadingObjType, $globalB2bValues;

  if ($contentOfCurrTemplate != "") :

     // Possibility of 10 levels of nested substitutions
     for ($iter = 0; $iter <= 9; $iter++) :

         // Content of db-fields
         $tagBegin = "<PREPARSE_" . $iter . ":";
         $tagEnd = "</PREPARSE_" . $iter . ">";
         $repeat = TRUE;
         while ($repeat && !(strpos($contentOfCurrTemplate, $tagBegin) === FALSE) && !(strpos($contentOfCurrTemplate, $tagEnd) === FALSE)) :

            $pos0 = strpos($contentOfCurrTemplate, $tagBegin);                         // Begin of tagBegin (first occurrence)
            $pos1 = strpos($contentOfCurrTemplate, $tagBegin) + strlen($tagBegin);     // End of tagBegin   (first occurrence)
            $pos2 = strpos($contentOfCurrTemplate, $tagEnd);                           // Begin of tagEnd   (first occurrence)
            $pos3 = strpos($contentOfCurrTemplate, $tagEnd) + strlen($tagEnd);         // End of tagEnd     (first occurrence)

            $repeat = FALSE;
            if ($pos2 - $pos1 > 0) :

               // First get the content of the tag (<=> field-number, size (optional), maxlength (optional)) for substitution
               $tagContent = substr($contentOfCurrTemplate, $pos1, $pos2 - $pos1);

               // Get position of closing bracket (">") of $tagBegin
               $posClosingBracketOfBeginTag = strpos($tagContent, ">");
               if (!($posClosingBracketOfBeginTag === FALSE)) :
                  $operationOfBeginTag = substr($tagContent, 0, $posClosingBracketOfBeginTag);

                  // Remove defined operation (eq. the beginning) of $tagBegin and get real content
                  $tagContent = substr($tagContent, ($posClosingBracketOfBeginTag + 1));

                  // Get components of the operation
                  $opArray = spliti(":",$operationOfBeginTag);   // E.g. "ITER,3,4" => array("ITER", "3", "4")

                  if ($opArray[0] == "ITER") :
                      $dbIndexValueFrom = $opArray[1];   // Index from
                      if (!is_numeric($dbIndexValueFrom)) : $dbIndexValueFrom = 1; endif;
                      $dbIndexValueTo = $opArray[2];     // Index to
                      if (!is_numeric($dbIndexValueTo) && $dbIndexValueTo != "*") : $dbIndexValueTo = 1; endif;
                  
                      $newTagContent = "";
                      for ($i = $dbIndexValueFrom; $i <= $dbIndexValueTo; $i++) :
                          $newTagContent .= str_replace("<ITER_" . $iter . ">", $i, $tagContent);
                      endfor;
                      
                      $contentOfCurrTemplate = substr_replace($contentOfCurrTemplate, $newTagContent, $pos0, $pos3 - $pos0);
                      $repeat = TRUE;

                  elseif ($opArray[0] == "DB_COUNT") :
                      $dbTable = $opArray[1];        // Database table
                      $dbWhereClause = $opArray[2];  // WHERE clause for the table
                      $dbIncrement = $opArray[3];    // Increment value

                      // Get result of statement
                      $newTagContent = getCountOfTable($dbTable, $dbWhereClause);
                      if (is_numeric($newTagContent) && $newTagContent > 0) : $newTagContent--; endif;
                      if ($dbIncrement != "" && is_numeric($dbIncrement) && is_numeric($newTagContent)) : $newTagContent = $newTagContent + $dbIncrement; endif;

                      $contentOfCurrTemplate = substr_replace($contentOfCurrTemplate, $newTagContent, $pos0, $pos3 - $pos0);
                      $repeat = TRUE;

                  elseif ($opArray[0] == "DB_SUM") :
                      $dbTable = $opArray[1];        // Database table
                      $dbField = $opArray[2];        // Table field
                      $dbWhereClause = $opArray[3];  // WHERE clause for the table

                      // Get result of statement
                      $newTagContent = getSumOfTable($dbTable, $dbField, $dbWhereClause);

                      $contentOfCurrTemplate = substr_replace($contentOfCurrTemplate, $newTagContent, $pos0, $pos3 - $pos0);
                      $repeat = TRUE;

                  elseif ($opArray[0] == "THIS_OBJECT_ID") :
                      $contentOfCurrTemplate = substr_replace($contentOfCurrTemplate, $objId, $pos0, $pos3 - $pos0);
                      $repeat = TRUE;

                  elseif ($opArray[0] == "SHOW_IF_DB_ROW_EXIST") :
                      $dbTable = $opArray[1];                            // Database table

                      $checkFieldArray = $opArray;
                      array_shift($checkFieldArray);  // Remove first element (operation name)
                      array_shift($checkFieldArray);  // Remove second element (table name)

                      $newTagContent = "";
                      if (existsEntry($dbTable,$checkFieldArray)) :
                         $newTagContent = $tagContent;
                      endif;
                      $contentOfCurrTemplate = substr_replace($contentOfCurrTemplate, $newTagContent, $pos0, $pos3 - $pos0);
                      $repeat = TRUE;

                  elseif ($opArray[0] == "B2B_OBJECT") :
                      // E.g. B2B_OBJECT:bo_obj_data::bo_ext_id2::500:<jb_id>
                      $b2bFieldSearch   = $opArray[1];  // Field to searched for
                      $b2bFieldKey      = $opArray[2];  // Field to be key
                      $b2bFieldSort     = $opArray[3];  // Field to be sorted by
                      $b2bFieldDistinct = $opArray[4];  // Search result to be DISTINCT
                      // ----
                      $b2bType          = $opArray[5];  // b2b_objects.bo_type
                      $b2bExtId0        = $opArray[6];  // b2b_objects.bo_ext_id0
                      $b2bExtId1        = $opArray[7];  // b2b_objects.bo_ext_id1
                      $b2bExtId2        = $opArray[8];  // b2b_objects.bo_ext_id2

                      // "b2b_type" AND "bo_ext_id0" have to exist !!!!
                      if ($b2bType != "" && is_numeric($b2bType) && $b2bType > 0 && $b2bExtId0 != "" && is_numeric($b2bExtId0) && $b2bExtId0 > 0) :

                         $whereClauseB2B = "bo_type = '" . $b2bType . "' AND bo_ext_id0 = '" . $b2bExtId0 . "'";
                         if ($b2bExtId1 != "" && is_numeric($b2bExtId1) && $b2bExtId1 > 0) :
                            $whereClauseB2B .= " AND bo_ext_id1 = '" . $b2bExtId1 . "'";
                         endif;
                         if ($b2bExtId2 != "" && is_numeric($b2bExtId2) && $b2bExtId2 > 0) :
                            $whereClauseB2B .= " AND bo_ext_id2 = '" . $b2bExtId2 . "'";
                         endif;
                         if ($b2bFieldDistinct != "") : $b2bFieldDistinct = "DISTINCT"; endif;

                         $boResultArray = getColVectorFromDB2ArrayByClause("phoenix_log.b2b_objects", $b2bFieldSearch, $whereClauseB2B, $b2bFieldKey, $b2bFieldSort, $b2bFieldDistinct);
                         if (count($boResultArray) == 0) :
                            $dbHistoryConnection = getDbHistoryConnection($dbHistoryConnection);
                            if (is_object($dbHistoryConnection)) :
                               $boResultArray = getColVectorFromDB2ArrayByClause("phoenix_log.b2b_objects_2015", $b2bFieldSearch, $whereClauseB2B, $b2bFieldKey, $b2bFieldSort, $b2bFieldDistinct, $dbHistoryConnection);
                            endif;
                         endif;

                         $boResultKeysArray = array_keys($boResultArray);
                         $boResultKeysArrayLen = count($boResultKeysArray);

                         // SPECIAL HANDLING REGARDING B2B TYPES (bo_type)
                         // ****
                         /*
                         if ($b2bType == "501") :
                            $tmpSpecialKeyArray = array();
                            for ($i = 0; $i < $boResultKeysArrayLen; $i++) :
                                $tmpValue = str_replace("|", "-,-", $boResultArray[$boResultKeysArray[$i]]);
                                $tmpArray = spliti("-,-",$tmpValue);
                                $tmpSpecialKeyArray[] = $tmpArray[0];  // First element is the index number (eq. question number) for bo_type == "501"
                            endfor;
                            $boResultKeysArray = $tmpSpecialKeyArray;
                            $boResultKeysArrayLen = count($boResultKeysArray);
                         endif;
                         */
                         // ****

                         if ($boResultKeysArrayLen > 0) :
                            for ($i = 0; $i < $boResultKeysArrayLen; $i++) :

                                // Check for existing key field
                                $b2bIndexValue = $boResultKeysArray[$i];

                                // Generate associative array with called "bo_type" values
                                $boResult = str_replace("|", "-,-", $boResultArray[$b2bIndexValue]);
                                $tmpResultArray = spliti("-,-",$boResult);


                                // SPECIAL HANDLING REGARDING B2B TYPES (bo_type)
                                // ****
                                if ($b2bType == "500") :
                                   $globalB2bValues[$b2bType][$b2bIndexValue] = $tmpResultArray;

                                   if ($globalB2bValues[$b2bType][$b2bIndexValue][2] != "") :
                                      $globalB2bValues[$b2bType][$b2bIndexValue][2] = saveImageToFile($globalB2bValues[$b2bType][$b2bIndexValue][2], $b2bExtId0 . "_A" . ".png", $systemPath, "150", "75");
                                   endif;
                                   if ($globalB2bValues[$b2bType][$b2bIndexValue][3] != "") :
                                      $globalB2bValues[$b2bType][$b2bIndexValue][3] = saveImageToFile($globalB2bValues[$b2bType][$b2bIndexValue][3], $b2bExtId0 . "_B" . ".png", $systemPath, "150", "75");
                                   endif;

                                elseif ($b2bType == "501") :
                                   // Get parameter to handle elemt types
                                   $b2bModeChoice = getParameterValue("0", "B2B_MODE_CHOICE_AND_RADIO", $hq_id);
                                   if ($b2bModeChoice == "") : $b2bModeChoice = getParameterValue("0", "B2B_MODE_CHOICE_AND_RADIO", "0"); endif;

                                   $b2bIndexValue = $tmpResultArray[0];  // First element is the index number (eq. question number) for bo_type == "501"
                                   $globalB2bValues[$b2bType][$b2bIndexValue] = $tmpResultArray;

                                   if ($globalB2bValues[$b2bType][$b2bIndexValue][1] == "datetime") :

                                   elseif ($globalB2bValues[$b2bType][$b2bIndexValue][1] == "choice" || $globalB2bValues[$b2bType][$b2bIndexValue][1] == "radio") :

                                       if ($globalB2bValues[$b2bType][$b2bIndexValue][2] != "") :

                                          if ($b2bModeChoice == "" || $b2bModeChoice == "0") :
                                             // Default
                                             $b2bTmpArray = spliti(",",$globalB2bValues[$b2bType][$b2bIndexValue][2]);
                                             $b2bTmpArrayLen = count($b2bTmpArray);
                                             $globalB2bValues[$b2bType][$b2bIndexValue][2] = array();
                                             for ($j = 0; $j < $b2bTmpArrayLen; $j++) :
                                                 if ($b2bTmpArray[$j] != "") :
                                                    $globalB2bValues[$b2bType][$b2bIndexValue][2][$b2bTmpArray[$j]] = "checked";
                                                 endif;
                                             endfor;
                                          else :
                                             $b2bTmpValue = $globalB2bValues[$b2bType][$b2bIndexValue][2];
                                             $globalB2bValues[$b2bType][$b2bIndexValue][2] = array();
                                             if ($b2bTmpValue == "1") :
                                                 $globalB2bValues[$b2bType][$b2bIndexValue][2][1] = "checked";
                                             else :
                                                 $globalB2bValues[$b2bType][$b2bIndexValue][2][2] = "checked";
                                             endif;
                                          endif;
                                       endif;

                                   elseif ($globalB2bValues[$b2bType][$b2bIndexValue][1] == "time") :

                                   elseif ($globalB2bValues[$b2bType][$b2bIndexValue][1] == "txt") :

                                          // Check text having lines
                                          /*
                                          if (!(strpos($b2bIndexValue, ".") === FALSE) :
                                             $tmpArtIndexVal = str_replace(".", "-,-", $b2bIndexValue);
                                             $tmpArtIndexArr = spliti('-,-',$tmpArtIndexVal);  // E.g. "200.x" => array("200", "x")
                                             $tmpArtIndexVal = $tmpArtIndexArr[0];             // Use "200" only
                                             $tmpArtSubIndexVal = $tmpArtIndexArr[1];          // Use "x" only

                                             $b2bTmpValue = $globalB2bValues[$b2bType][$b2bIndexValue][2];
                                             // $globalB2bValues[$b2bType][$tmpArtIndexVal][2] = array();
                                             $globalB2bValues[$b2bType][$tmpArtIndexVal][2][$tmpArtSubIndexVal] = $b2bTmpValue;
                                          endif;
                                          */

                                   elseif ($globalB2bValues[$b2bType][$b2bIndexValue][1] == "num") :

                                   elseif ($globalB2bValues[$b2bType][$b2bIndexValue][1] == "art") :

                                          // Article "substr($b2bIndexValue,0,2)" <=> ("12.x" => "12")
                                          $tmpArtIndexVal = str_replace(".", "-,-", $b2bIndexValue);
                                          $tmpArtIndexArr = spliti('-,-',$tmpArtIndexVal);  // E.g. "12.x" => array("12", "x")
                                          $tmpArtIndexVal = $tmpArtIndexArr[0];          // Use "12" only

                                          // 501 (default)
                                          $tmpTratId = $globalB2bValues[$b2bType][$b2bIndexValue][3];
                                          if ($tmpTratId != "" && is_numeric($tmpTratId) && $tmpTratId > 0) :
                                             $tmpJbId = getFieldValueFromId("tourarticle", "trat_id", $tmpTratId, "jb_id");
                                             $tratArray = getTratArticles($tmpJbId, "", "trat.trat_id = '" . $tmpTratId . "' ");
                                             $tratArrayLen = count($tratArray);
                                          
                                             for ($j = 0; $j < $tratArrayLen; $j++) :
                                                 // if ($b2bTmpArray[$j] != "") :
                                                    // Get article error text from error number
                                                    $tmpMtValue = getFieldValueFromClause("metatype", "mt_value", "mt_type = 'sap_at_err_code' AND mt_sort = '" . $globalB2bValues[$b2bType][$b2bIndexValue][2] . "'");
                                                    $globalB2bValues[$b2bType][$tmpArtIndexVal] .= "
                                                       <tr>
                                                           <td style=\"padding: 5px;\">" . $tratArray[$j][9] . "</td>
                                                           <td style=\"padding: 5px;\" align=\"right\">" . $tratArray[$j][7] . "</td>
                                                           <td style=\"padding: 5px;\" align=\"right\">" . ($tratArray[$j][7] * (getSalesTaxFactor($tmpJbId) - 1)) . "</td>
                                                           <td style=\"padding: 5px;\" align=\"right\">" . ($tratArray[$j][7] * getSalesTaxFactor($tmpJbId)) . "</td>
                                                           <td style=\"padding: 5px;\" align=\"right\"></td>
                                                           <td style=\"padding: 5px;\" align=\"right\">" . $tratArray[$j][1] . "</td>
                                                           <td align=\"center\" class=\"borderunten\">" . $tmpMtValue . "</td>
                                                       </tr>
                                                    ";
                                                    // $retArray[] = array($row["at_id"], $row["trat_quantity"], $row["trat_sort"], $row["trat_packingpieces"], $row["trat_serialno"], $row["trat_state"], $row["trat_remark"], $row["trat_price"], $row["trat_name"], $row["trat_description"], $row["trat_weight"], $row["trat_id"]);
                                                 // endif;
                                             endfor;
                                          endif;

                                          // 501A
                                          $mappedB2bType = $b2bType . "A";
                                          $globalB2bValues[$mappedB2bType][$tmpArtIndexVal] .= "
                                             <tr>
                                               	<td width=\"10%\" class=\"klein borderrechts\" style=\"padding: 5px;\">" . $globalB2bValues[$b2bType][$b2bIndexValue][2] . "</td>
                                               	<td width=\"90%\" class=\"klein\" style=\"padding: 5px;\">" . $globalB2bValues[$b2bType][$b2bIndexValue][3] . "</td>
                                             </tr>
                                          ";
                                   endif;
                                else :
                                   $globalB2bValues[$b2bType][$b2bIndexValue] = $tmpResultArray;
                                endif;
                                // ****
                            endfor;
                         endif;
                      endif;
                  endif;
               endif;
            endif;
         endwhile;
     endfor;
  endif;
  return $contentOfCurrTemplate;
}

// Generates HTML output
function outputMetaFieldSpecial ($currTemplateId, $editMode = "1", $systemPath = "..") {
  global $db, $PHP_SELF, $hq_id, $usr_id;
  global $mtfk_allFieldNames, $mtfk_allFieldTypes, $mtfck_mtfkIds, $mtfck_mtfckIds, $mtfck_mtfckIdsLen, $category, $cascadingObjType;
  global $atLeastOneImageDoesExistInForm, $globalB2bValues;
  global $objId;

  $globalB2bValues = array();
  $out = "";
  $jsOut = "";
  $jsOutSelect = "";
  $tagSize = "";
  $tagMaxlength = "";
  
  $jsOut .= "function checkDate(checkObj,mode) {\n";
  $jsOut .= "  var resetValue = checkDateFields(checkObj,mode);\n";
  $jsOut .= "  if (resetValue) {\n";
  $jsOut .= "     checkObj.value = '';\n";
  $jsOut .= "     checkObj.focus();\n";
  $jsOut .= "  }\n";
  $jsOut .= "}\n";
  $jsOut .= "\n";
  $jsOut .= "function finishPage(f_act) {\n";
  $jsOut .= "  var ok = true;\n";

  $atLeastOneImageDoesExistInForm = false;
  if ($systemPath == "") : $systemPath = ".."; endif;  // Relative path as default

  if ($mtfck_mtfckIdsLen > 0) :
     $mtfv_values = mtfv_getObjValues();
     
     if ($currTemplateId == "0") :
        // Default output without template
        $out .= "<table>\n";
        for ($j = 0; $j < $mtfck_mtfckIdsLen; $j++) :
            
            $ft = $mtfk_allFieldTypes[$mtfck_mtfkIds[$j]];
            
            mcArrIsSet($mtfv_values, $mtfck_mtfckIds[$j]);
            
            if ($tagSize == "") : $tagSize = "30"; endif;
            if ($tagMaxlength == "") : $tagMaxlength = "100"; endif;
        
            // Pay attention for reference fields, because they do not generate output
            if (substr($ft,0,4) != "ref:") :
               $out .= "<tr>\n";
               $out .= "<td>" . $mtfk_allFieldNames[$mtfck_mtfkIds[$j]] . "</td>\n";    // Name of the field
               $out .= "<td>&nbsp;:&nbsp;</td>\n";
               $out .= "<td>\n";
            endif;

            if ($ft == "date" || $ft == "date_begin" || $ft == "date_end" || $ft == "birthdate" || $ft == "datetime" || $ft == "triggerdate" || $ft == "triggerdatetime" || $ft == "triggerdate_single") :
               if ($editMode == "1") :
                  $tmpVal = $mtfv_values[$mtfck_mtfckIds[$j]];
                  $out .= "<input type=\"text\" name=\"f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "_day\" value=\"" . substr($tmpVal ,0 ,2) . "\" size=\"2\" maxlength=\"2\" onBlur=\"checkDate(this,'day')\">&nbsp;\n";
                  $out .= "<input type=\"text\" name=\"f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "_month\" value=\"" . substr($tmpVal ,3 ,2) . "\" size=\"2\" maxlength=\"2\" onBlur=\"checkDate(this,'month')\">&nbsp;\n";
                  $out .= "<input type=\"text\" name=\"f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "_year\" value=\"" . substr($tmpVal ,6 ,4) . "\" size=\"4\" maxlength=\"4\" onBlur=\"checkDate(this,'')\">&nbsp;&nbsp;\n";
                  $out .= getLngt("(TT.MM.JJJJ)");
               else :
                  $tmpOut = substr($mtfv_values[$mtfck_mtfckIds[$j]] ,0 ,2) . "." . substr($mtfv_values[$mtfck_mtfckIds[$j]] ,3 ,2) . "." . substr($mtfv_values[$mtfck_mtfckIds[$j]] ,6 ,4);
                  if ($tmpOut == "..") :
                     $tmpOut = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
                  endif;
                  $out .= $tmpOut;
               endif;               
        
            elseif ($ft == "time" || $ft == "datetime" || $ft == "triggerdatetime") :
               if ($editMode == "1") :
                  $out .= "<input type=\"text\" name=\"f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "_hour\" value=\"" . substr($mtfv_values[$mtfck_mtfckIds[$j]] ,0 ,2) . "\" size=\"2\" maxlength=\"2\" onBlur=\"checkDate(this,'hour')\">&nbsp;\n";
                  $out .= "<input type=\"text\" name=\"f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "_minute\" value=\"" . substr($mtfv_values[$mtfck_mtfckIds[$j]] ,3 ,2) . "\" size=\"2\" maxlength=\"2\" onBlur=\"checkDate(this,'minute')\">&nbsp;\n";
                  // $out .= "<input type=\"text\" name=\"f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "_second\" value=\"" . substr($mtfv_values[$mtfck_mtfckIds[$j]] ,6 ,4) . "\" size=\"4\" maxlength=\"4\" onBlur=\"checkDate(this,'second')\">&nbsp;&nbsp;\n";
                  $out .= "(Std:Min.)";
               else :
                  $tmpOut = substr($mtfv_values[$mtfck_mtfckIds[$j]] ,0 ,2) . ":" . substr($mtfv_values[$mtfck_mtfckIds[$j]] ,3 ,2);
                  if ($tmpOut == ":") :
                     $tmpOut = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
                  endif;
                  $out .= $tmpOut;
               endif;

            elseif ($ft == "author") :  // User created the current dataset
               $tmpUsrId = $mtfv_values[$mtfck_mtfckIds[$j]];
               if ($tmpUsrId != "") :               
                  $tmpUsrFirstname = getFieldValueFromId("user", "usr_id", $tmpUsrId, "usr_firstname");
                  $tmpUsrName = getFieldValueFromId("user", "usr_id", $tmpUsrId, "usr_name");
                  $tmpHqId = getFieldValueFromId("user", "usr_id", $tmpUsrId, "hq_id");
                  $tmpHqMnemonic = getFieldValueFromId("headquarters", "hq_id", $tmpHqId, "hq_mnemonic");
                  $out .= "<input type=\"hidden\" name=\"f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "\" value=\"" . $tmpUsrId . "\" readonly>";
                  $out .= $tmpUsrFirstname . " " . $tmpUsrName . " [" . $tmpHqMnemonic . "]";
               else :
                  $out .= "<input type=\"hidden\" name=\"f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "\" value=\"\" readonly>";
               endif;

            elseif ($ft == "co2cs") :  // Contact person in relation to the customer
               $tmpCsId = $mtfv_values[$mtfck_mtfckIds[$j]];
               $tmpCmpId = getFieldValueFromId("customer", "cs_id", $tmpCsId, "cmp_id");
               $tmpCmpComp1 = trim(getFieldValueFromId("company", "cmp_id", $tmpCmpId, "cmp_comp"));
               $valueToBeDisplayed = getFieldValueFromId("customer", "cs_id", $tmpCsId, "cs_eid");
               if ($editMode == "1") :
                  $out .= "<input type=\"text\" name=\"f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "\" value=\"" . $valueToBeDisplayed . "\" size=\"10\">&nbsp;&nbsp;\n";
                  $constMaskPreset = urlencode(getParameterValue("0", "MASK_CS2CO_PRESET", "0"));
                  $out .= "<input type=\"hidden\" name=\"f_presetFields_" . $category . "_" . $mtfck_mtfkIds[$j] . "\" value=\"" . $constMaskPreset . "\">&nbsp;&nbsp;\n";
                  $out .= "<input type=\"hidden\" name=\"f_presetFt_" . $category . "_" . $mtfck_mtfkIds[$j] . "\" value=\"" . $ft . "\">&nbsp;&nbsp;\n";
                  $out .= "<input type=\"hidden\" name=\"f_presetCategory_" . $category . "_" . $mtfck_mtfkIds[$j] . "\" value=\"" . $category . "\">&nbsp;&nbsp;\n";
                  $out .= defineButtonType08("...", "action_form", "document.forms[0].doPresetFieldsPerAction.value='" . $category . "_" . $mtfck_mtfkIds[$j] . "'; searchCsCscGeneric('00000000000010','presetFieldsByAction()','f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "');", "20", "left", "2");
               else :
                  $out .= $valueToBeDisplayed;
               endif;
               $out .= "(ExtID)";
               if ($tmpCmpComp1 != "") :
                  // $out .= "&nbsp;&nbsp;&nbsp;[" . trim($tmpCmpComp1) . "]";
                  // $out .= "&nbsp;&nbsp;&nbsp;[<a href=\"" . $systemPath . "/admin/customer_special.php?companyId=" . ec($tmpCmpId) . "\" target=\"_blank\">" . trim($tmpCmpComp1) . "</a>]";
                  $out .= "&nbsp;&nbsp;&nbsp;[<a href=\"" . $systemPath . "/admin/customer_special.php?companyId=" . ec($tmpCmpId) . "\" target=\"_blank\">" . trim($tmpCmpComp1) . "</a>&nbsp;&nbsp;&nbsp;" . 
                                             "(<a href=\"" . $systemPath . "/groupware/report.php?rpObjType=cs&g_cs_eid=" . $valueToBeDisplayed . "\" target=\"_blank\">" . getLngt("Berichte") . "</a>" .
                                             ")]";
               endif;

            elseif ($ft == "text") :  // Text field
               if ($editMode == "1") :
                  $out .= "<textarea name=\"f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "\" cols=\"70\" rows=\"5\">" . $mtfv_values[$mtfck_mtfckIds[$j]] . "</textarea>";
               else :
                  $out .= "<textarea name=\"f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "\" cols=\"70\" rows=\"5\" readonly>" . $mtfv_values[$mtfck_mtfckIds[$j]] . "</textarea>";
               endif;

            elseif (substr($ft,0,7) == "button:") :  // SELECTION BY BUTTON
               if ($editMode == "1") :
                  $subTypeArray = spliti(":",$ft);
                  $table = $subTypeArray[1];
                  $idField = $subTypeArray[2];
                  $textField = $subTypeArray[3];
                  $orderByField = $subTypeArray[4];
                  $distinct = $subTypeArray[5];
                  $hqFilter = $subTypeArray[6];
                  if ($table == "cr") :
                     if ($idField == "") : $idField = "cr_id"; endif;
                     if ($textField == "") : $textField = "cr_eid"; endif;
                     if ($orderByField == "") : $orderByField = "cr_eid"; endif;
                     $whereClauseHq = " AND cr.hq_id = '" . $hq_id . "' ";
                     if ($hqFilter == "hq_all") : $whereClauseHq = ""; endif;
                     $out .= "<input type=\"text\" name=\"f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "\" value=\"" . $mtfv_values[$mtfck_mtfckIds[$j]] . "\" size=\"10\">&nbsp;&nbsp;\n";
                     $out .= defineButtonType08("...", "action_form", "searchCourierGeneric('f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "');", "20", "left", "2");
                  endif;
                  if ($table == "cs") :
                     if ($idField == "") : $idField = "cs_id"; endif;
                     if ($textField == "") : $textField = "cs_eid"; endif;
                     if ($orderByField == "") : $orderByField = "cs_eid"; endif;
                     $whereClauseHq = " AND cs.hq_id = '" . $hq_id . "' ";
                     if ($hqFilter == "hq_all") : $whereClauseHq = ""; endif;
                     $out .= "<input type=\"text\" name=\"f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "\" value=\"" . $mtfv_values[$mtfck_mtfckIds[$j]] . "\" size=\"10\">&nbsp;&nbsp;\n";
                     $out .= defineButtonType08("...", "action_form", "searchCsCscGeneric('00000000000010','','f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "');", "20", "left", "2");
                  endif;
               else :
                  $out .= $mtfv_values[$mtfck_mtfckIds[$j]];
               endif;

            elseif (substr($ft,0,7) == "select:") :  // SELECT FIELD
               if ($editMode == "1") :
                  $subTypeArray = spliti(":",$ft);
                  $table = $subTypeArray[1];
                  $idField = $subTypeArray[2];
                  $textField = $subTypeArray[3];
                  $orderByField = $subTypeArray[4];
                  $distinct = $subTypeArray[5];
                  $hqFilter = $subTypeArray[6];
                  if ($table == "crvh") :
                     if ($idField == "") : $idField = "crvh_id"; endif;
                     if ($textField == "") : $textField = "crvh_sid"; endif;
                     if ($orderByField == "") : $orderByField = "crvh_sid"; endif;
                     $whereClauseHq = " AND cr.hq_id = '" . $hq_id . "' ";
                     if ($hqFilter == "hq_all") : $whereClauseHq = ""; endif;
                     $tmpSelectOut = addOptionsFromTable("couriervehicle AS crvh, courier AS cr", $idField, $textField, $orderByField, "crvh.cr_id = cr.cr_id" . $whereClauseHq, $mtfv_values[$mtfck_mtfckIds[$j]], $distinct);
                  endif;
                  if ($table == "cr") :
                     if ($idField == "") : $idField = "cr_id"; endif;
                     if ($textField == "") : $textField = "cr_eid"; endif;
                     if ($orderByField == "") : $orderByField = "cr_eid"; endif;
                     $whereClauseHq = " AND cr.hq_id = '" . $hq_id . "' ";
                     if ($hqFilter == "hq_all") : $whereClauseHq = ""; endif;
                     $tmpSelectOut = addOptionsFromTable("courier AS cr, company AS cmp", $idField, $textField, $orderByField, "cr.cmp_id = cmp.cmp_id AND cmp.cmp_authenticated = '1' AND cmp.cmp_visible = '1'" . $whereClauseHq, $mtfv_values[$mtfck_mtfckIds[$j]], $distinct);
                  endif;
                  if ($table == "cs") :
                     if ($idField == "") : $idField = "cs_id"; endif;
                     if ($textField == "") : $textField = "cs_eid"; endif;
                     if ($orderByField == "") : $orderByField = "cs_eid"; endif;
                     $whereClauseHq = " AND cs.hq_id = '" . $hq_id . "' ";
                     if ($hqFilter == "hq_all") : $whereClauseHq = ""; endif;
                     $tmpSelectOut = addOptionsFromTable("customer AS cs, company AS cmp", $idField, $textField, $orderByField, "cs.cmp_id = cmp.cmp_id AND cmp.cmp_authenticated = '1' AND cmp.cmp_visible = '1'" . $whereClauseHq, $mtfv_values[$mtfck_mtfckIds[$j]], $distinct);
                  endif;
                  if ($table == "hq") :
                     if ($idField == "") : $idField = "hq_id"; endif;
                     if ($textField == "") : $textField = "hq_mnemonic"; endif;
                     if ($orderByField == "") : $orderByField = "hq_mnemonic"; endif;
                     $mdId = getFieldValueFromId("mandatorheadquarters","hq_id",$hq_id,"md_id");
                     if ($mdId != "") :
                        $tmpSelectOut = addOptionsFromTable("headquarters AS hq, mandatorheadquarters AS mdhq", "hq." . $idField, "hq." . $textField, "hq." . $orderByField, "hq.hq_id = mdhq.hq_id AND mdhq.md_id = '" .$mdId  . "'", $mtfv_values[$mtfck_mtfckIds[$j]], $distinct);
                     endif;
                  endif;
                  if ($table == "vht") :
                     if ($idField == "") : $idField = "mt_sort"; endif;
                     if ($textField == "") : $textField = "mt_value"; endif;
                     if ($orderByField == "") : $orderByField = "mt_sort"; endif;
                     $tmpSelectOut = addOptionsFromTable("metatype",$idField, $textField, $orderByField,"mt_type = 'vehicletype'",$mtfv_values[$mtfck_mtfckIds[$j]], $distinct);
                  endif;
                  if ($table == "grp") :
                     if ($idField == "") : $idField = "grp_id"; endif;
                     if ($textField == "") : $textField = "grp_name"; endif;
                     if ($orderByField == "") : $orderByField = "grp_name"; endif;
                     $mdId = getFieldValueFromId("mandatorheadquarters","hq_id",$hq_id,"md_id");
                     if ($mdId != "") :
                        $tmpSelectOut = addOptionsFromTable("groups AS grp, headquarters AS hq", "grp." . $idField, "grp." . $textField, "grp." . $orderByField, "grp.md_id = '" . $mdId . "' AND grp.hq_id = hq.hq_id", $mtfv_values[$mtfck_mtfckIds[$j]], $distinct);
                     endif;
                  endif;
                  if ($table == "br") :
                     if ($idField == "") : $idField = "br_id"; endif;
                     if ($textField == "") : $textField = "br_name"; endif;
                     if ($orderByField == "") : $orderByField = "br_name"; endif;
                     $tmpSelectOut = addOptionsFromTable("branch",$idField, $textField, $orderByField,"",$mtfv_values[$mtfck_mtfckIds[$j]], $distinct);
                  endif;
                  $out .= "<select class=\"f8np1\" name=\"f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "\">" . "<option value=\"\"></option>" . $tmpSelectOut . "</select>";
               else :
                  $out .= $mtfv_values[$mtfck_mtfckIds[$j]];
               endif;

            elseif ($ft == "number" || $ft == "float" || $ft == "float_2" || $ft == "integer") :  // Number types
               $valueToBeDisplayed = $mtfv_values[$mtfck_mtfckIds[$j]];
               if ($editMode == "1") :
                  $out .= "<input type=\"text\" name=\"f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "\" value=\"" . $mtfv_values[$mtfck_mtfckIds[$j]] . "\" size=\"10\">&nbsp;&nbsp;\n";
               else :
                  $decimals = "";
                  if ($ft == "float_2") : $decimals = "2"; endif;
                  if ($ft == "integer") : $decimals = "0"; endif;
                  $valueToBeDisplayed = formatOutput($valueToBeDisplayed,"number","1",$decimals);
                  $out .= $valueToBeDisplayed;
               endif;
        
            elseif ($ft == "checkbox") :  // Checkbox               
               if ($editMode == "1") :
                  $out .= "<input type=\"checkbox\" name=\"f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "\" value=\"1\" " . ($mtfv_values[$mtfck_mtfckIds[$j]] == "1" ? "checked" : "") . ">";
               else :
                  $out .= "<input type=\"checkbox\" name=\"f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "\" value=\"1\" " . ($mtfv_values[$mtfck_mtfckIds[$j]] == "1" ? "checked" : "") . " readonly>";
               endif;

            elseif ($ft == "checkboxes_hq") :  // Headquarter checkboxes
               $tmpHqArray = spliti(",", $mtfv_values[$mtfck_mtfckIds[$j]]);
               if ($editMode == "1") :
                  $out .= getHeadquartersCheckboxes($tmpHqArray, "", "", "&nbsp;", $docFormParName = "f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j], "Mtfk");
                  $jsOutSelect .= "function hqCheckAllMtfk(numOfHq) {\n";
                  $jsOutSelect .= "  for (i = 0; i < numOfHq; i++) {\n";
                  $jsOutSelect .= "      document.getElementsByName('" . "f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "[]')[i].checked = true;\n";
                  $jsOutSelect .= "  }\n";
                  $jsOutSelect .= "}\n";
                  $jsOutSelect .= "\n";
                  $jsOutSelect .= "function hqUncheckAllMtfk(numOfHq) {\n";
                  $jsOutSelect .= "  for (i = 0; i < numOfHq; i++) {\n";
                  $jsOutSelect .= "      document.getElementsByName('" . "f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "[]')[i].checked = false;\n";
                  $jsOutSelect .= "  }\n";
                  $jsOutSelect .= "}\n";
                  $jsOutSelect .= "\n";
               else :
                  $tmpHqArrayLen = count($tmpHqArray);
                  for ($i = 0; $i < $tmpHqArrayLen; $i++) :
                      $tmpHqArray[$i] = getFieldValueFromId("headquarters","hq_id",$tmpHqArray[$i],"hq_mnemonic");
                  endfor;
                  $out .= implode(",",$tmpHqArray);
               endif;

            elseif ($ft == "link") :  // Link
               $linkData = spliti(",", $mtfv_values[$mtfck_mtfckIds[$j]]);
               $linkHref = trim($linkData[0]); $linkText = trim($linkData[1]); $linkTarget = trim($linkData[2]);
               if ($linkText == "") : $linkText = $linkHref; endif;
               if (substr($linkHref, 0, 5) != "http:" && substr($linkHref, 0, 6) != "https:") : $linkHref = "http:" . $linkHref; endif;
               // if ($linkTarget == "") : $linkTarget = "_blank"; endif;
               if ($editMode == "1") :
                  $out .= "<input type=\"text\" name=\"f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "\" value=\"" . $mtfv_values[$mtfck_mtfckIds[$j]] . "\" size=\"30\" maxlength=\"100\"> " . getLngt("URL[,Text[,Ziel]]");
               else :
                  $out .= "<a href=\"" . $linkHref . "\" tabindex=\"\" " . ($linkTarget !== "" ? "target=\"" . $linkTarget . "\"" : "") . ">" . $linkText . "</a>";
               endif;

            elseif (substr($ft,0,12) == "link_static_") :  // Static link
               $parNo = substr($ft,12);
               $linkStaticContent = getParameterValue("0", "MTF_LINK_STATIC_" . $parNo, $hq_id);
               if ($linkStaticContent == "") : $linkStaticContent = getParameterValue("0", "MTF_LINK_STATIC_" . $parNo, "0"); endif;
               if ($linkStaticContent != "") :
                  $linkData = spliti(",", $linkStaticContent);
                  $linkHref = trim($linkData[0]); $linkText = trim($linkData[1]); $linkTarget = trim($linkData[2]);
                  // Optional substitutions in static link
                  if (!(strpos($linkHref, "<SUBST_") === false)) :
                     $linkHref = str_replace("<SUBST_OBJ_TYPE>", $cascadingObjType, $linkHref);
                     $linkHref = str_replace("<SUBST_OBJ_ID>", $objId, $linkHref);
                     // ....
                  endif;
                  if ($linkText == "") : $linkText = $linkHref; endif;
                  $out .= "<a href=\"" . $linkHref . "\" tabindex=\"\" " . ($linkTarget !== "" ? "target=\"" . $linkTarget . "\"" : "") . ">" . $linkText . "</a>";
               endif;

            elseif ($ft == "image") :
               $imgData = spliti(",", $mtfv_values[$mtfck_mtfckIds[$j]]);
               $imgFilename = trim($imgData[0]); $imgWidth = trim($imgData[1]); $imgHeight = trim($imgData[2]); $imgName = trim($imgData[3]);
               if ($editMode == "1") :
                  $out .= "<input type=\"text\" name=\"f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "\" value=\"" . $mtfv_values[$mtfck_mtfckIds[$j]] . "\" size=\"30\" maxlength=\"100\"> " . getLngt("Bildname,Breite,Höhe,Titel");
                  $atLeastOneImageDoesExistInForm = true;
               else :
                  if ($imgFilename != "") :
                     $out .= "<img src=\"" . $systemPath . "/documents/images/" . $imgFilename . "\" border=\"" . "0" . "\" height=\"" . $imgHeight . "\" width=\"" . $imgWidth . "\">";
                     if ($imgName != "") :
                        $out .= "<br>" . $imgName;
                     endif;
                  endif;
               endif;

            elseif (substr($ft,0,4) == "sys:") :  // SYSTEM FIELD
               $sysOut = $mtfv_values[$mtfck_mtfckIds[$j]];
               if (trim($sysOut) == "") :
                  $sysOut = getFieldValueBySystemCall($ft);
               endif;
               if ($editMode == "1") :
                  $out .= "<input type=\"text\" name=\"f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "\" value=\"" . $sysOut . "\" size=\"" . $tagSize . "\" maxlength=\"" . $tagMaxlength . "\">";
               else :
                  $out .= $sysOut;
               endif;

            elseif (substr($ft,0,3) == "db:") :  // DATABASE FIELD
               $dbOut = $mtfv_values[$mtfck_mtfckIds[$j]];
               if (trim($dbOut) == "") :
                  $dbOut = getFieldValueBySpecialCall($ft, "", "", $systemPath);
               endif;
               if ($editMode == "1" && strpos($ft, ":stat_") === false) :
                  $out .= "<input type=\"text\" name=\"f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "\" value=\"" . $dbOut . "\" size=\"" . $tagSize . "\" maxlength=\"" . $tagMaxlength . "\">";
               else :
                  $out .= $dbOut;
               endif;

            elseif (substr($ft,0,4) == "ref:") :  // REFERENCE FIELD
               $tmpArray = spliti(":",$ft);
               $tmpArrayLen = count($tmpArray);
               $refOut = "";
               for ($i = 1; $i < $tmpArrayLen; $i++) :
                   $tmpMtfckId = getFieldValueFromClause("metafieldcategorykey","mtfck_id","mtfk_id = '" . $tmpArray[$i] . "' AND mtfc_id = '" . $category . "'");
                   $refOut .= $mtfv_values[$tmpMtfckId];
                   if ($i < ($tmpArrayLen - 1)) : $refOut .= " "; endif;
               endfor;
               $out .= "<input type=\"hidden\" name=\"f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "\" value=\"" . $refOut . "\" size=\"30\" maxlength=\"100\" readonly>";

            elseif (substr($ft,0,5) == "func:") :  // FUNCTION FIELD

               $funcOut = $mtfv_values[$mtfck_mtfckIds[$j]];
               $funcOutArray = getFieldValueByFunctionCall($ft);
               
               if ($funcOutArray[0] == "computed") :
                  $funcOut = $funcOutArray[1];
               endif;

               if ($funcOutArray[0] == "checkbox") :
                  if ($editMode == "1") :
                     $out .= "<input type=\"checkbox\" name=\"f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "\" value=\"1\" " . ($funcOut == "1" ? "checked" : "") . ">";
                  else :
                     $out .= "<input type=\"checkbox\" name=\"f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "\" value=\"1\" " . ($funcOut == "1" ? "checked" : "") . " readonly>";
                  endif;
               else :
                  if ($editMode == "1") :
                     $out .= "<input type=\"text\" name=\"f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "\" value=\"" . $funcOut . "\" size=\"" . $tagSize . "\" maxlength=\"" . $tagMaxlength . "\">";
                  else :
                     $out .= $funcOut;
                  endif;
               endif;

            else :
               if ($editMode == "1") :
                  $out .= "<input type=\"text\" name=\"f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "\" value=\"" . $mtfv_values[$mtfck_mtfckIds[$j]] . "\" size=\"30\" maxlength=\"100\">";   // Value of the field according to the object
               else :
                  $out .= $mtfv_values[$mtfck_mtfckIds[$j]];
               endif;
            endif;

            // Pay attention for reference fields, because they do not generate output
            if (substr($ft,0,4) != "ref:") :
               $out .= "</td>\n";
               $out .= "</tr>\n";
            endif;
        
            if ($editMode == "1") :
               if ($ft == "phone" || $ft == "phone_business" || $ft == "phone_private" || $ft == "mobile" || $ft == "mobile_business" || $ft == "mobile_private" || $ft == "fax" || $ft == "fax_business" || $ft == "fax_private") :
                  $jsOut .= "if (!checkIsNaNIgnoreSpace(document.forms[0].f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . ".value, '" . getLngt("Bitte tragen Sie eine Nummer bei " . $mtfk_allFieldNames[$mtfck_mtfkIds[$j]] . " ein!") . "')) {ok = false;};\n";
               endif;
               if ($ft == "mail" || $ft == "mail_business" || $ft == "mail_private") :
                  $jsOut .= "if (document.forms[0].f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . ".value.length != 0) {\n";
                  $jsOut .= "   if (!checkMailAddress(document.forms[0].f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . ", '" . getLngt("Bitte tragen Sie eine gültige Email-Adresse bei " . $mtfk_allFieldNames[$mtfck_mtfkIds[$j]] . " ein!") . "')) {ok = false;};";
                  $jsOut .= "}\n";
               endif;
            endif;
        endfor;
        $out .= "<table>\n";

     else :
     
// ****************************************************
// * FUCKING HACK "Abnahmeprotokoll" ******************
if ($currTemplateId == "300") :
   // Look for 
   // global $objId;
   if (existsEntry("genericdatacontainer",array("gdc_obj_type","jb","gdc_gen_fieldname","acquisitiontime","gdc_obj_id",$objId))) :
      $currTemplateId = "3000";
      // Check for another version
      $tmpValue = getFieldValueFromClause("genericdatacontainer", "gdc_content", "gdc_obj_type = 'jb' AND gdc_gen_fieldname = 'jb_accept_prot_ver' AND gdc_obj_id = '" . $objId . "'");
      if ($tmpValue == "3") : $currTemplateId = "3001"; endif;
      if ($tmpValue == "4") : $currTemplateId = "3002"; endif;
      if ($tmpValue == "5") : $currTemplateId = "3003"; endif;
      if ($tmpValue == "6") : $currTemplateId = "3004"; endif;
      if ($tmpValue == "7") : $currTemplateId = "3005"; endif;
   else :
      $tmpJbOrdertime = getFieldValueFromId("job","jb_id",$objId,"jb_ordertime");
      if ($tmpJbOrdertime >= "2015-11-10 00:00:00") :
         // $currTemplateId = "3001";
      endif;
   endif;
endif;
// ****************************************************
     
        // Get template
        $contentOfCurrTemplate = getFieldValueFromId("metafieldtemplate","mtft_id",$currTemplateId,"mtft_content");

        // Preparse template
        $contentOfCurrTemplate = templatePreparser($contentOfCurrTemplate, $systemPath);

        // Content of db-fields
        $tagBegin = "[-";
        $tagEnd = "-]";
        $repeat = TRUE;
        while ($repeat && !(strpos($contentOfCurrTemplate, $tagBegin) === FALSE) && !(strpos($contentOfCurrTemplate, $tagEnd) === FALSE)) :

           $pos0 = strpos($contentOfCurrTemplate, $tagBegin);                         // Begin of tagBegin (first occurrence)
           $pos1 = strpos($contentOfCurrTemplate, $tagBegin) + strlen($tagBegin);     // End of tagBegin   (first occurrence)
           $pos2 = strpos($contentOfCurrTemplate, $tagEnd);                           // Begin of tagEnd   (first occurrence)
           $pos3 = strpos($contentOfCurrTemplate, $tagEnd) + strlen($tagEnd);         // End of tagEnd     (first occurrence)

           $repeat = FALSE;
           if ($pos2 - $pos1 > 0) :

              // First get the content of the tag (<=> field-number, size (optional), maxlength (optional)) for substitution
              $tagContent = substr($contentOfCurrTemplate, $pos1, $pos2 - $pos1);

              // Check for template based system calls like dynamic change of parameters during parsing process
              if (substr($tagContent,0,7) == "SYSTEM:") :
                 if (substr($tagContent,7,26) == "SET_CASCADING_OBJECT_TYPE:") :
                    $tmpCascadingObjType = strtolower(substr($tagContent,33));
                    if ($tmpCascadingObjType != "") :
                       $cascadingObjType = $tmpCascadingObjType;
                    endif;
                 endif;

                 // Remove system tag after it has been processed
                 $contentOfCurrTemplate = substr_replace($contentOfCurrTemplate, "", $pos0, $pos3 - $pos0);
                 $repeat = TRUE;

              elseif (substr($tagContent,0,4) == "B2B:") :

                 $b2bObjContent = substr($tagContent,4);  // Get indices for global B2B array
                 $b2bObjContentArray = spliti(":",$b2bObjContent);
                 $globalB2bVal = $globalB2bValues[$b2bObjContentArray[0]][$b2bObjContentArray[1]];  // "bo_type" AND "bo_ext_id0" HAS TO BE EXIST !!!!
                 if ($b2bObjContentArray[2] != "") : 
                    $globalB2bVal = $globalB2bValues[$b2bObjContentArray[0]][$b2bObjContentArray[1]][$b2bObjContentArray[2]];  // "bo_type", "bo_ext_id0" and "idx_special_01"
                 endif;
                 if ($b2bObjContentArray[3] != "") : 
                    $globalB2bVal = $globalB2bValues[$b2bObjContentArray[0]][$b2bObjContentArray[1]][$b2bObjContentArray[2]][$b2bObjContentArray[3]];  // "bo_type", "bo_ext_id0", "idx_special_01" and "idx_special_02"
                 endif;
                 if ($b2bObjContentArray[4] != "") : 
                    $globalB2bVal = $globalB2bValues[$b2bObjContentArray[0]][$b2bObjContentArray[1]][$b2bObjContentArray[2]][$b2bObjContentArray[3]][$b2bObjContentArray[4]];  // "bo_type", "bo_ext_id0", "idx_special_01", "idx_special_02" and "idx_special_03"
                 endif;

                 // Remove system tag after it has been processed
                 $contentOfCurrTemplate = substr_replace($contentOfCurrTemplate, $globalB2bVal, $pos0, $pos3 - $pos0);
                 $repeat = TRUE;

              else :
                 $tagDbFieldId = $tagContent;
                 $tagSize = "";
                 $tagMaxlength = "";
                 if (!(strpos($tagContent, ",") === FALSE)) :
                    $tagContentArray = spliti(",",$tagContent);
                    $tagDbFieldId = $tagContentArray[0];
                    $tagSize = $tagContentArray[1];       // Also means: number of rows in textfield OR height in image OR number of decimals for a number
                    $tagMaxlength = $tagContentArray[2];  // Also means: number of cols in textfield OR width in image
                 endif;
                 
                 // In case of database fields we have to identify the correct index (e.g. tr.tr_sort) to get the information out of the tour list
                 $tagDbIndexValue = "";
                 $tagDbIndexValue2 = "";  // List in list (next cascade)
                 if (!(strpos($tagDbFieldId, ":") === FALSE)) :
                    $tmpArray = spliti(":",$tagDbFieldId);
                    $tagDbFieldId = $tmpArray[0];
                    // $tagDbIndexValue = $tmpArray[1];   // Contains an index value (key) or asterisk (eq. ALL elements). The semantic will be raise for the special object type !!!!
                    $tagDbIndexValue = mcArrIsSet($tmpArray, 1);   // Contains an index value (key) or asterisk (eq. ALL elements). The semantic will be raise for the special object type !!!!
                    // $tagDbIndexValue2 = $tmpArray[2];  // Dito for the next cascade! (E.g.: jb <=> m x tour AND tour <=> n x tourarticle)
                    $tagDbIndexValue2 = mcArrIsSet($tmpArray, 2);  // Dito for the next cascade! (E.g.: jb <=> m x tour AND tour <=> n x tourarticle)
                 endif;

                 $out = "";  // Init
                 if (is_numeric($tagDbFieldId)) :
                 
                    // Iterate all identified key fields associated to the object
                    for ($j = 0; $j < $mtfck_mtfckIdsLen; $j++) :

                        mcArrIsSet($mtfv_values, $mtfck_mtfckIds[$j]);

                        // Check field number in tag matching with element in key field list
                        if ($mtfck_mtfkIds[$j] == $tagDbFieldId) :
                 
                           $ft = $mtfk_allFieldTypes[$mtfck_mtfkIds[$j]];
                 
                           // Substitute tag with HTML tag
                           if ($ft == "date" || $ft == "birthdate" || $ft == "datetime" || $ft == "triggerdate" || $ft == "triggerdatetime" || $ft == "triggerdate_single") :
                              if ($tagSize == "") : $tagSize = "2"; endif;
                              if ($editMode == "1") :
                                 $out .= "<input type=\"text\" name=\"f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "_day\" value=\"" . substr($mtfv_values[$mtfck_mtfckIds[$j]] ,0 ,2) . "\" size=\"" . $tagSize . "\" maxlength=\"2\" onBlur=\"checkDate(this,'day')\">&nbsp;";
                                 $out .= "<input type=\"text\" name=\"f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "_month\" value=\"" . substr($mtfv_values[$mtfck_mtfckIds[$j]] ,3 ,2) . "\" size=\"" . $tagSize . "\" maxlength=\"2\" onBlur=\"checkDate(this,'month')\">&nbsp;";
                                 $out .= "<input type=\"text\" name=\"f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "_year\" value=\"" . substr($mtfv_values[$mtfck_mtfckIds[$j]] ,6 ,4) . "\" size=\"" . (2 * $tagSize) . "\" maxlength=\"4\" onBlur=\"checkDate(this,'')\">&nbsp;&nbsp;";
                                 $out .= getLngt("(TT.MM.JJJJ)");
                              else :
                                 $tmpOut = substr($mtfv_values[$mtfck_mtfckIds[$j]] ,0 ,2) . "." . substr($mtfv_values[$mtfck_mtfckIds[$j]] ,3 ,2) . "." . substr($mtfv_values[$mtfck_mtfckIds[$j]] ,6 ,4);
                                 if ($tmpOut == "..") :
                                    $tmpOut = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
                                 endif;
                                 $out .= $tmpOut;
                              endif;
                           
                           elseif ($ft == "time" || $ft == "datetime" || $ft == "triggerdatetime") :
                              if ($editMode == "1") :
                                 $out .= "<input type=\"text\" name=\"f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "_hour\" value=\"" . substr($mtfv_values[$mtfck_mtfckIds[$j]] ,0 ,2) . "\" size=\"2\" maxlength=\"2\" onBlur=\"checkDate(this,'hour')\">&nbsp;";
                                 $out .= "<input type=\"text\" name=\"f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "_minute\" value=\"" . substr($mtfv_values[$mtfck_mtfckIds[$j]] ,3 ,2) . "\" size=\"2\" maxlength=\"2\" onBlur=\"checkDate(this,'minute')\">&nbsp;";
                                 // $out .= "<input type=\"text\" name=\"f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "_second\" value=\"" . substr($mtfv_values[$mtfck_mtfckIds[$j]] ,6 ,4) . "\" size=\"4\" maxlength=\"4\" onBlur=\"checkDate(this,'second')\">&nbsp;&nbsp;";
                                 $out .= "(Std:Min.)";
                              else :
                                 $tmpOut = substr($mtfv_values[$mtfck_mtfckIds[$j]] ,0 ,2) . ":" . substr($mtfv_values[$mtfck_mtfckIds[$j]] ,3 ,2);
                                 if ($tmpOut == ":") :
                                    $tmpOut = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
                                 endif;
                                 $out .= $tmpOut;
                              endif;
                 
                           elseif ($ft == "author") :  // User created the current dataset
                              $tmpUsrId = $mtfv_values[$mtfck_mtfckIds[$j]];
                              if ($tmpUsrId != "") :               
                                 $tmpUsrFirstname = getFieldValueFromId("user", "usr_id", $tmpUsrId, "usr_firstname");
                                 $tmpUsrName = getFieldValueFromId("user", "usr_id", $tmpUsrId, "usr_name");
                                 $tmpHqId = getFieldValueFromId("user", "usr_id", $tmpUsrId, "hq_id");
                                 $tmpHqMnemonic = getFieldValueFromId("headquarters", "hq_id", $tmpHqId, "hq_mnemonic");
                                 $out .= "<input type=\"hidden\" name=\"f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "\" value=\"" . $tmpUsrId . "\" readonly>";
                                 $out .= $tmpUsrFirstname . " " . $tmpUsrName . " [" . $tmpHqMnemonic . "]";
                              else :
                                 $out .= "<input type=\"hidden\" name=\"f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "\" value=\"\" readonly>";
                              endif;
                 
                           elseif ($ft == "co2cs") :  // Contact person in relation to the customer
                              $tmpCsId = $mtfv_values[$mtfck_mtfckIds[$j]];
                              $tmpCmpId = getFieldValueFromId("customer", "cs_id", $tmpCsId, "cmp_id");
                              $tmpCmpComp1 = trim(getFieldValueFromId("company", "cmp_id", $tmpCmpId, "cmp_comp"));
                              $valueToBeDisplayed = getFieldValueFromId("customer", "cs_id", $tmpCsId, "cs_eid");
                              if ($editMode == "1") :
                                 $out .= "<input type=\"text\" name=\"f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "\" value=\"" . $valueToBeDisplayed . "\" size=\"10\">&nbsp;&nbsp;\n";
                                 // $constMaskPreset = urlencode(getParameterValue("0", "MASK_CS2CO_PRESET", "0"));
                                 // $out .= "<input type=\"hidden\" name=\"f_presetFields_" . $category . "_" . $mtfck_mtfkIds[$j] . "\" value=\"" . $constMaskPreset . "\">&nbsp;&nbsp;\n";
                                 // $out .= "<input type=\"hidden\" name=\"f_presetFt_" . $category . "_" . $mtfck_mtfkIds[$j] . "\" value=\"" . $ft . "\">&nbsp;&nbsp;\n";
                                 // $out .= "<input type=\"hidden\" name=\"f_presetCategory_" . $category . "_" . $mtfck_mtfkIds[$j] . "\" value=\"" . $category . "\">&nbsp;&nbsp;\n";
                                 // $out .= defineButtonType08("...", "action_form", "document.forms[0].doPresetFieldsPerAction.value='" . $category . "_" . $mtfck_mtfkIds[$j] . "'; searchCsCscGeneric('00000000000010','presetFieldsByAction()','f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "');", "20", "left", "2");
                              else :
                                 $out .= $valueToBeDisplayed;
                              endif;
                              $out .= "(ExtID)";
                              if ($tmpCmpComp1 != "") :
                                 // $out .= "&nbsp;&nbsp;&nbsp;[" . trim($tmpCmpComp1) . "]";
                                 // $out .= "&nbsp;&nbsp;&nbsp;[<a href=\"" . $systemPath . "/admin/customer_special.php?companyId=" . ec($tmpCmpId) . "\" target=\"_blank\">" . trim($tmpCmpComp1) . "</a>]";
                                 $out .= "&nbsp;&nbsp;&nbsp;[<a href=\"" . $systemPath . "/admin/customer_special.php?companyId=" . ec($tmpCmpId) . "\" target=\"_blank\">" . trim($tmpCmpComp1) . "</a>&nbsp;&nbsp;&nbsp;" . 
                                                            "(<a href=\"" . $systemPath . "/groupware/report.php?rpObjType=cs&g_cs_eid=" . $valueToBeDisplayed . "\" target=\"_blank\">" . getLngt("Berichte") . "</a>" .
                                                            ")]";
                              endif;
                           
                           elseif ($ft == "text") :  // Text field
                              if ($tagSize == "") : $tagSize = "5"; endif;
                              if ($tagMaxlength == "") : $tagMaxlength = "75"; endif;
                              if ($editMode == "1") :
                                 $out .= "<textarea name=\"f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "\" cols=\"" . $tagMaxlength . "\" rows=\"" . $tagSize . "\">" . $mtfv_values[$mtfck_mtfckIds[$j]] . "</textarea>";
                              else :
                                 // $out .= "<textarea name=\"f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "\" cols=\"" . $tagMaxlength . "\" rows=\"" . $tagSize . "\" readonly>" . $mtfv_values[$mtfck_mtfckIds[$j]] . "</textarea>";
                                 // $out .= splitText($mtfv_values[$mtfck_mtfckIds[$j]], "1", $tagMaxlength);
                                 $out = str_replace("\r\n", "<br>", $mtfv_values[$mtfck_mtfckIds[$j]]);
                              endif;

                           elseif (substr($ft,0,7) == "button:") :  // SELECTION BY BUTTON
                              if ($editMode == "1") :
                                 $subTypeArray = spliti(":",$ft);
                                 $table = $subTypeArray[1];
                                 $idField = $subTypeArray[2];
                                 $textField = $subTypeArray[3];
                                 $orderByField = $subTypeArray[4];
                                 $distinct = $subTypeArray[5];
                                 $hqFilter = $subTypeArray[6];
                                 if ($table == "cr") :
                                    if ($idField == "") : $idField = "cr_id"; endif;
                                    if ($textField == "") : $textField = "cr_eid"; endif;
                                    if ($orderByField == "") : $orderByField = "cr_eid"; endif;
                                    $whereClauseHq = " AND cr.hq_id = '" . $hq_id . "' ";
                                    if ($hqFilter == "hq_all") : $whereClauseHq = ""; endif;
                                    $out .= "<input type=\"text\" name=\"f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "\" value=\"" . $mtfv_values[$mtfck_mtfckIds[$j]] . "\" size=\"10\">&nbsp;&nbsp;\n";
                                    $out .= defineButtonType08("...", "action_form", "searchCourierGeneric('f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "');", "20", "left", "2");
                                 endif;
                                 if ($table == "cs") :
                                    if ($idField == "") : $idField = "cs_id"; endif;
                                    if ($textField == "") : $textField = "cs_eid"; endif;
                                    if ($orderByField == "") : $orderByField = "cs_eid"; endif;
                                    $whereClauseHq = " AND cs.hq_id = '" . $hq_id . "' ";
                                    if ($hqFilter == "hq_all") : $whereClauseHq = ""; endif;
                                    $out .= "<input type=\"text\" name=\"f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "\" value=\"" . $mtfv_values[$mtfck_mtfckIds[$j]] . "\" size=\"10\">&nbsp;&nbsp;\n";
                                    $out .= defineButtonType08("...", "action_form", "searchCsCscGeneric('00000000000010','','f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "');", "20", "left", "2");
                                 endif;
                              else :
                                 $out .= $mtfv_values[$mtfck_mtfckIds[$j]];
                              endif;

                           elseif (substr($ft,0,7) == "select:") :  // SELECT FIELD
                              if ($editMode == "1") :
                                 $subTypeArray = spliti(":",$ft);
                                 $table = $subTypeArray[1];
                                 $idField = $subTypeArray[2];
                                 $textField = $subTypeArray[3];
                                 $orderByField = $subTypeArray[4];
                                 $distinct = $subTypeArray[5];
                                 $hqFilter = $subTypeArray[6];
                                 if ($table == "crvh") :
                                    if ($idField == "") : $idField = "crvh_id"; endif;
                                    if ($textField == "") : $textField = "crvh_sid"; endif;
                                    if ($orderByField == "") : $orderByField = "crvh_sid"; endif;
                                    $whereClauseHq = " AND cr.hq_id = '" . $hq_id . "' ";
                                    if ($hqFilter == "hq_all") : $whereClauseHq = ""; endif;
                                    $tmpSelectOut = addOptionsFromTable("couriervehicle AS crvh, courier AS cr", $idField, $textField, $orderByField, "crvh.cr_id = cr.cr_id" . $whereClauseHq, $mtfv_values[$mtfck_mtfckIds[$j]], $distinct);
                                 endif;
                                 if ($table == "cr") :
                                    if ($idField == "") : $idField = "cr_id"; endif;
                                    if ($textField == "") : $textField = "cr_eid"; endif;
                                    if ($orderByField == "") : $orderByField = "cr_eid"; endif;
                                    $whereClauseHq = " AND cr.hq_id = '" . $hq_id . "' ";
                                    if ($hqFilter == "hq_all") : $whereClauseHq = ""; endif;
                                    $tmpSelectOut = addOptionsFromTable("courier AS cr, company AS cmp", $idField, $textField, $orderByField, "cr.cmp_id = cmp.cmp_id AND cmp.cmp_authenticated = '1' AND cmp.cmp_visible = '1'" . $whereClauseHq, $mtfv_values[$mtfck_mtfckIds[$j]], $distinct);
                                 endif;
                                 if ($table == "cs") :
                                    if ($idField == "") : $idField = "cs_id"; endif;
                                    if ($textField == "") : $textField = "cs_eid"; endif;
                                    if ($orderByField == "") : $orderByField = "cs_eid"; endif;
                                    $whereClauseHq = " AND cs.hq_id = '" . $hq_id . "' ";
                                    if ($hqFilter == "hq_all") : $whereClauseHq = ""; endif;
                                    $tmpSelectOut = addOptionsFromTable("customer AS cs, company AS cmp", $idField, $textField, $orderByField, "cs.cmp_id = cmp.cmp_id AND cmp.cmp_authenticated = '1' AND cmp.cmp_visible = '1'" . $whereClauseHq, $mtfv_values[$mtfck_mtfckIds[$j]], $distinct);
                                 endif;
                                 if ($table == "hq") :
                                    if ($idField == "") : $idField = "hq_id"; endif;
                                    if ($textField == "") : $textField = "hq_mnemonic"; endif;
                                    if ($orderByField == "") : $orderByField = "hq_mnemonic"; endif;
                                    $mdId = getFieldValueFromId("mandatorheadquarters","hq_id",$hq_id,"md_id");
                                    if ($mdId != "") :
                                       $tmpSelectOut = addOptionsFromTable("headquarters AS hq, mandatorheadquarters AS mdhq", "hq." . $idField, "hq." . $textField, "hq." . $orderByField, "hq.hq_id = mdhq.hq_id AND mdhq.md_id = '" .$mdId  . "'", $mtfv_values[$mtfck_mtfckIds[$j]], $distinct);
                                    endif;
                                 endif;
                                 if ($table == "vht") :
                                    if ($idField == "") : $idField = "mt_sort"; endif;
                                    if ($textField == "") : $textField = "mt_value"; endif;
                                    if ($orderByField == "") : $orderByField = "mt_sort"; endif;
                                    $tmpSelectOut = addOptionsFromTable("metatype",$idField, $textField, $orderByField,"mt_type = 'vehicletype'",$mtfv_values[$mtfck_mtfckIds[$j]], $distinct);
                                 endif;
                                 if ($table == "grp") :
                                    if ($idField == "") : $idField = "grp_id"; endif;
                                    if ($textField == "") : $textField = "grp_name"; endif;
                                    if ($orderByField == "") : $orderByField = "grp_name"; endif;
                                    $mdId = getFieldValueFromId("mandatorheadquarters","hq_id",$hq_id,"md_id");
                                    if ($mdId != "") :
                                       $tmpSelectOut = addOptionsFromTable("groups AS grp, headquarters AS hq", "grp." . $idField, "grp." . $textField, "grp." . $orderByField, "grp.md_id = '" . $mdId . "' AND grp.hq_id = hq.hq_id", $mtfv_values[$mtfck_mtfckIds[$j]], $distinct);
                                    endif;
                                 endif;
                                 if ($table == "br") :
                                    if ($idField == "") : $idField = "br_id"; endif;
                                    if ($textField == "") : $textField = "br_name"; endif;
                                    if ($orderByField == "") : $orderByField = "br_name"; endif;
                                    $tmpSelectOut = addOptionsFromTable("branch",$idField, $textField, $orderByField,"",$mtfv_values[$mtfck_mtfckIds[$j]], $distinct);
                                 endif;
                                 $out .= "<select class=\"f8np1\" name=\"f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "\">" . "<option value=\"\"></option>" . $tmpSelectOut . "</select>";
                              else :
                                 $out .= $mtfv_values[$mtfck_mtfckIds[$j]];
                              endif;
                 
                           elseif ($ft == "number" || $ft == "float" || $ft == "float_2" || $ft == "integer") :  // Number types
                              $valueToBeDisplayed = $mtfv_values[$mtfck_mtfckIds[$j]];
                              if ($editMode == "1") :
                                 $out .= "<input type=\"text\" name=\"f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "\" value=\"" . $mtfv_values[$mtfck_mtfckIds[$j]] . "\" size=\"10\">&nbsp;&nbsp;\n";
                              else :
                                 $decimals = "";
                                 if ($ft == "float_2") : $decimals = "2"; endif;
                                 if ($ft == "integer") : $decimals = "0"; endif;
                                 $valueToBeDisplayed = formatOutput($valueToBeDisplayed,"number","1",$decimals);
                                 $out .= $valueToBeDisplayed;
                              endif;
                 
                           elseif ($ft == "checkbox") :  // Checkbox
                              if ($editMode == "1") :
                                 $out .= "<input type=\"checkbox\" name=\"f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "\" value=\"1\" " . ($mtfv_values[$mtfck_mtfckIds[$j]] == "1" ? "checked" : "") . ">";
                              else :
                                 $out .= "<input type=\"checkbox\" name=\"f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "\" value=\"1\" " . ($mtfv_values[$mtfck_mtfckIds[$j]] == "1" ? "checked" : "") . " readonly>";
                              endif;

                           elseif ($ft == "checkboxes_hq") :  // Headquarter checkboxes
                              $tmpHqArray = spliti(",", $mtfv_values[$mtfck_mtfckIds[$j]]);
                              if ($editMode == "1") :
                                 $out .= getHeadquartersCheckboxes($tmpHqArray, "", "", "&nbsp;", $docFormParName = "f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j], "Mtfk");
                                 $jsOutSelect .= "function hqCheckAllMtfk(numOfHq) {\n";
                                 $jsOutSelect .= "  for (i = 0; i < numOfHq; i++) {\n";
                                 $jsOutSelect .= "      document.getElementsByName('" . "f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "[]')[i].checked = true;\n";
                                 $jsOutSelect .= "  }\n";
                                 $jsOutSelect .= "}\n";
                                 $jsOutSelect .= "\n";
                                 $jsOutSelect .= "function hqUncheckAllMtfk(numOfHq) {\n";
                                 $jsOutSelect .= "  for (i = 0; i < numOfHq; i++) {\n";
                                 $jsOutSelect .= "      document.getElementsByName('" . "f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "[]')[i].checked = false;\n";
                                 $jsOutSelect .= "  }\n";
                                 $jsOutSelect .= "}\n";
                                 $jsOutSelect .= "\n";
                              else :
                                 $tmpHqArrayLen = count($tmpHqArray);
                                 for ($i = 0; $i < $tmpHqArrayLen; $i++) :
                                     $tmpHqArray[$i] = getFieldValueFromId("headquarters","hq_id",$tmpHqArray[$i],"hq_mnemonic");
                                 endfor;
                                 $out .= implode(",",$tmpHqArray);
                              endif;

                           elseif ($ft == "link") :  // Link
                              $linkData = spliti(",", $mtfv_values[$mtfck_mtfckIds[$j]]);
                              $linkHref = trim($linkData[0]); $linkText = trim($linkData[1]); $linkTarget = trim($linkData[2]);                           
                              if ($linkText == "") : $linkText = $linkHref; endif;
                              if (substr($linkHref, 0, 5) != "http:" && substr($linkHref, 0, 6) != "https:") : $linkHref = "http:" . $linkHref; endif;
                              // if ($linkTarget == "") : $linkTarget = "_blank"; endif;
                              if ($editMode == "1") :
                                 $out .= "<input type=\"text\" name=\"f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "\" value=\"" . $mtfv_values[$mtfck_mtfckIds[$j]] . "\" size=\"30\" maxlength=\"100\"> " . getLngt("URL[,Text[,Ziel]]");
                              else :
                                 $out .= "<a href=\"" . $linkHref . "\" tabindex=\"\" " . ($linkTarget !== "" ? "target=\"" . $linkTarget . "\"" : "") . ">" . $linkText . "</a>";
                              endif;

                           elseif (substr($ft,0,12) == "link_static_") :  // Static link
                              $parNo = substr($ft,12);
                              $linkStaticContent = getParameterValue("0", "MTF_LINK_STATIC_" . $parNo, $hq_id);
                              if ($linkStaticContent == "") : $linkStaticContent = getParameterValue("0", "MTF_LINK_STATIC_" . $parNo, "0"); endif;
                              if ($linkStaticContent != "") :
                                 $linkData = spliti(",", $linkStaticContent);
                                 $linkHref = trim($linkData[0]); $linkText = trim($linkData[1]); $linkTarget = trim($linkData[2]);
                                 // Optional substitutions in static link
                                 if (!(strpos($linkHref, "<SUBST_") === false)) :
                                    $linkHref = str_replace("<SUBST_OBJ_TYPE>", $cascadingObjType, $linkHref);
                                    $linkHref = str_replace("<SUBST_OBJ_ID>", $objId, $linkHref);
                                    // ....
                                 endif;
                                 if ($linkText == "") : $linkText = $linkHref; endif;
                                 $out .= "<a href=\"" . $linkHref . "\" tabindex=\"\" " . ($linkTarget !== "" ? "target=\"" . $linkTarget . "\"" : "") . ">" . $linkText . "</a>";
                              endif;
                 
                           elseif ($ft == "image") :
                              $imgData = spliti(",", $mtfv_values[$mtfck_mtfckIds[$j]]);
                              $imgFilename = trim($imgData[0]); $imgWidth = trim($imgData[1]); $imgHeight = trim($imgData[2]); $imgName = trim($imgData[3]);
                              if ($editMode == "1") :
                                 $out .= "<input type=\"text\" name=\"f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "\" value=\"" . $mtfv_values[$mtfck_mtfckIds[$j]] . "\" size=\"30\" maxlength=\"100\"> " . getLngt("Bildname,Breite,Höhe,Titel");
                                 $atLeastOneImageDoesExistInForm = true;
                              else :
                                 if ($imgFilename != "") :
                                    $out .= "<img src=\"" . $systemPath . "/documents/images/" . $imgFilename . "\" border=\"" . "0" . "\" height=\"" . $imgHeight . "\" width=\"" . $imgWidth . "\">";
                                    if ($imgName != "") :
                                       $out .= "<br>" . $imgName;
                                    endif;
                                 endif;
                              endif;
                 
                           elseif (substr($ft,0,4) == "sys:") :  // SYSTEM FIELD
                              $sysOutArray = array("varchar", $mtfv_values[$mtfck_mtfckIds[$j]]);
                              if (trim($mtfv_values[$mtfck_mtfckIds[$j]]) == "") :
                                 $sysOutArray = getFieldValueBySystemCall($ft);
                              endif;
                 
                              if ($sysOutArray[0] == "image") :   // $sysOutArray = (type, path and filename, height, width, border)
                                 if ($tagSize == "") : $tagSize = $sysOutArray[2]; endif;
                                 if ($tagMaxlength == "") : $tagMaxlength = $sysOutArray[3]; endif;                           
                                 $out .= "<img src=\"" . $systemPath . "/images/external/" . $sysOutArray[1] . "\" border=\"" . $sysOutArray[4] . "\" height=\"" . $tagSize . "\" width=\"" . $tagMaxlength . "\">";
                 
                              elseif ($sysOutArray[0] == "readonly") :
                                 $out .= $sysOutArray[1];
                 
                              elseif ($sysOutArray[0] == "xxx") :   // $sysOutArray = (type, ???)
                                 // $out .= 
                 
                              else :   // $sysOutArray = (type, content)
                                 if ($editMode == "1") :
                                    $out .= "<input type=\"text\" name=\"f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "\" value=\"" . $sysOutArray[1] . "\" size=\"" . $tagSize . "\" maxlength=\"" . $tagMaxlength . "\">";
                                 else :
                                    $out .= $sysOutArray[1];
                                 endif;
                              endif;
                 
                           elseif (substr($ft,0,3) == "db:") :  // DATABASE FIELD
                              $dbOut = $mtfv_values[$mtfck_mtfckIds[$j]];
                              if (trim($dbOut) == "") :
                                 $dbOut = getFieldValueBySpecialCall($ft, $tagDbIndexValue, $tagDbIndexValue2, $systemPath);
                              endif;
                              if ($tagSize == "") : $tagSize = "30"; endif;
                              if ($tagMaxlength == "") : $tagMaxlength = "100"; endif;
                              if ($editMode == "1" && strpos($ft, ":stat_") === false) :
                                 $out .= "<input type=\"text\" name=\"f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "\" value=\"" . $dbOut . "\" size=\"" . $tagSize . "\" maxlength=\"" . $tagMaxlength . "\">";
                              else :
                                 $out .= $dbOut;
                              endif;
                 
                           elseif (substr($ft,0,4) == "ref:") :  // REFERENCE FIELD
                              $tmpArray = spliti(":",$ft);
                              $tmpArrayLen = count($tmpArray);
                              $refOut = "";
                              for ($i = 1; $i < $tmpArrayLen; $i++) :
                                  $tmpMtfckId = getFieldValueFromClause("metafieldcategorykey","mtfck_id","mtfk_id = '" . $tmpArray[$i] . "' AND mtfc_id = '" . $category . "'");
                                  $refOut .= $mtfv_values[$tmpMtfckId];
                                  if ($i < ($tmpArrayLen - 1)) : $refOut .= " "; endif;
                              endfor;
                              $out .= "<input type=\"hidden\" name=\"f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "\" value=\"" . $refOut . "\" size=\"30\" maxlength=\"100\" readonly>";
                 
                           elseif (substr($ft,0,5) == "func:") :  // FUNCTION FIELD
                              $funcOut = $mtfv_values[$mtfck_mtfckIds[$j]];
                              $funcOutArray = getFieldValueByFunctionCall($ft);
                 
                              if ($funcOutArray[0] == "computed") :
                                 $funcOut = $funcOutArray[1];
                              endif;
                 
                              if ($funcOutArray[0] == "checkbox") :
                                 if ($editMode == "1") :
                                    $out .= "<input type=\"checkbox\" name=\"f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "\" value=\"1\" " . ($funcOut == "1" ? "checked" : "") . ">";
                                 else :
                                    $out .= "<input type=\"checkbox\" name=\"f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "\" value=\"1\" " . ($funcOut == "1" ? "checked" : "") . " readonly>";
                                 endif;
                              elseif ($funcOutArray[0] == "number" || $funcOutArray[0] == "float" || $funcOutArray[0] == "float_2" || $funcOutArray[0] == "integer") :  // Number types
                                 if ($funcOut != "" && is_numeric($funcOut)) :
                                    $decimals = "";
                                    if ($funcOutArray[0] == "float_2") : $decimals = "2"; endif;
                                    if ($funcOutArray[0] == "integer") : $decimals = "0"; endif;
                                    $funcOut = formatOutput($funcOut,"number","1",$decimals);
                                 endif;
                                 if ($editMode == "1") :
                                    $out .= "<input type=\"text\" name=\"f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "\" value=\"" . $funcOut . "\" size=\"10\">&nbsp;&nbsp;\n";
                                 else :
                                    $out .= $funcOut;
                                 endif;                                                                  
                              elseif ($funcOutArray[0] == "date_valid") :
                                 if ($editMode == "1") :
                                    $out .= "";
                                    $tmpFuncOut = str_replace("|", "-,-", $funcOut);
                                    $tmp = spliti("-,-",$tmpFuncOut);
                                    $tmpFromDate = $tmp[0];
                                    $tmpToDate = $tmp[1];
                                    $out .= getLngt("von") . "&nbsp;";
                                    $out .= "<input type=\"text\" style=\"font-size: 8pt;\" name=\"f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "_01_day\" value=\"" . substr($tmpFromDate ,0 ,2) . "\" size=\"2\" maxlength=\"2\" onBlur=\"checkDate(this,'day')\">-\n";
                                    $out .= "<input type=\"text\" style=\"font-size: 8pt;\" name=\"f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "_01_month\" value=\"" . substr($tmpFromDate ,2 ,2) . "\" size=\"2\" maxlength=\"2\" onBlur=\"checkDate(this,'month')\">-\n";
                                    $out .= "<input type=\"text\" style=\"font-size: 8pt;\" name=\"f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "_01_year\" value=\"" . substr($tmpFromDate ,4 ,4) . "\" size=\"4\" maxlength=\"4\" onBlur=\"checkDate(this,'')\">&nbsp;\n";
                                    $out .= getLngt("bis") . "&nbsp;";
                                    $out .= "<input type=\"text\" style=\"font-size: 8pt;\" name=\"f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "_02_day\" value=\"" . substr($tmpToDate ,0 ,2) . "\" size=\"2\" maxlength=\"2\" onBlur=\"checkDate(this,'day')\">-\n";
                                    $out .= "<input type=\"text\" style=\"font-size: 8pt;\" name=\"f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "_02_month\" value=\"" . substr($tmpToDate ,2 ,2) . "\" size=\"2\" maxlength=\"2\" onBlur=\"checkDate(this,'month')\">-\n";
                                    $out .= "<input type=\"text\" style=\"font-size: 8pt;\" name=\"f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "_02_year\" value=\"" . substr($tmpToDate ,4 ,4) . "\" size=\"4\" maxlength=\"4\" onBlur=\"checkDate(this,'')\">&nbsp;&nbsp;\n";
                                    $out .= getLngt("(TT-MM-JJJJ)");
                                 else :
                                    $out .= substr($tmpFromDate ,0 ,2) . "-" . substr($tmpFromDate ,2 ,2) . "-" . substr($tmpFromDate ,4 ,4) . "&nbsp;&nbsp;";
                                    $out .= substr($tmpToDate ,0 ,2) . "-" . substr($tmpToDate ,2 ,2) . "-" . substr($tmpToDate ,4 ,4);
                                 endif;
                              elseif ($funcOutArray[0] == "graduated_price") :
                                 if ($editMode == "1") :
                                    $tagSize = 10;
                                    $tagMaxlength = 10;
                                    $out .= "";
                                    $tmpFuncOut = str_replace("|", "-,-", $funcOut);
                                    $tmp = spliti("-,-",$tmpFuncOut);
                                    $lenTmp = count($tmp);
                                    for ($i = 0; $i < $lenTmp; $i++) {
                                    	  if (!(strpos($tmp[$i], ",") === FALSE)) :
                                           $tmp2 = spliti(",",$tmp[$i]);
                                           if ($tmp2[1] != "") :
                                              $out .= "<input type=\"text\" name=\"f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "_" . $i . "_01" . "\" value=\"" . $tmp2[0] . "\" size=\"" . $tagSize . "\" maxlength=\"" . $tagMaxlength . "\">&nbsp;&nbsp;";
                                              $out .= "<input type=\"text\" name=\"f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "_" . $i . "_02" . "\" value=\"" . $tmp2[1] . "\" size=\"" . $tagSize . "\" maxlength=\"" . $tagMaxlength . "\"><br>";
                                           endif;
                                       endif;
                                    }
                                    // Add for a new entry
                                    $out .= "<input type=\"text\" name=\"f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "_new_01" . "\" value=\"\" size=\"" . $tagSize . "\" maxlength=\"" . $tagMaxlength . "\">&nbsp;&nbsp;";
                                    $out .= "<input type=\"text\" name=\"f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "_new_02" . "\" value=\"\" size=\"" . $tagSize . "\" maxlength=\"" . $tagMaxlength . "\"><br>";
                                 else :
                                    $out .= $funcOut;
                                 endif;
                              elseif ($funcOutArray[0] == "articlegroup_price") :
                                 if ($editMode == "1") :
                                    $tagSize = 10;
                                    $tagMaxlength = 10;
                                    $out .= "";
                                    $tmpFuncOut = str_replace("|", "-,-", $funcOut);
                                    $tmp = spliti("-,-",$tmpFuncOut);
                                    $lenTmp = count($tmp);
                                    for ($i = 0; $i < $lenTmp; $i++) {
                                    	  if (!(strpos($tmp[$i], ",") === FALSE)) :
                                           $tmp2 = spliti(",",$tmp[$i]);
                                           if ($tmp2[1] != "") :
                                              $out .= "<select class=\"f8np1\" name=\"f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "_" . $i . "_01\">" . addOptionsFromTable("articlegroup","atg_key","atg_name","atg_key","",$tmp2[0]) . "</select>&nbsp;&nbsp;";
                                              $out .= "<input type=\"text\" name=\"f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "_" . $i . "_02" . "\" value=\"" . $tmp2[1] . "\" size=\"" . $tagSize . "\" maxlength=\"" . $tagMaxlength . "\"><br>";
                                           endif;
                                       endif;
                                    }
                                    // Add for a new entry
                                    $out .= "<select class=\"f8np1\" name=\"f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "_new_01\"><option value=\"\">----</option>" . addOptionsFromTable("articlegroup","atg_key","atg_name","atg_key","","") . "</select>&nbsp;&nbsp;";
                                    $out .= "<input type=\"text\" name=\"f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "_new_02" . "\" value=\"\" size=\"" . $tagSize . "\" maxlength=\"" . $tagMaxlength . "\"><br>";
                                 else :
                                    $out .= $funcOut;
                                 endif;
                              else :
                                 if ($editMode == "1") :
                                    $out .= "<input type=\"text\" name=\"f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "\" value=\"" . $funcOut . "\" size=\"" . $tagSize . "\" maxlength=\"" . $tagMaxlength . "\">";
                                 else :
                                    $out .= $funcOut;
                                 endif;
                              endif;
                 
                           else :
                              if ($tagSize == "") : $tagSize = "30"; endif;
                              if ($tagMaxlength == "") : $tagMaxlength = "100"; endif;
                              if ($editMode == "1") :
                                 $out .= "<input type=\"text\" name=\"f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . "\" value=\"" . $mtfv_values[$mtfck_mtfckIds[$j]] . "\" size=\"" . $tagSize . "\" maxlength=\"" . $tagMaxlength . "\">";   // Value of the field according to the object
                              else :
                                 $out .= $mtfv_values[$mtfck_mtfckIds[$j]];
                              endif;
                           endif;
                 
                           if ($editMode == "1") :
                              if ($ft == "phone" || $ft == "phone_business" || $ft == "phone_private" || $ft == "mobile" || $ft == "mobile_business" || $ft == "mobile_private" || $ft == "fax" || $ft == "fax_business" || $ft == "fax_private") :
                                 $jsOut .= "if (!checkIsNaNIgnoreSpace(document.forms[0].f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . ".value, '" . getLngt("Bitte tragen Sie eine Nummer bei " . $mtfk_allFieldNames[$mtfck_mtfkIds[$j]] . " ein!") . "')) {ok = false;};\n";
                              endif;
                              if ($ft == "mail" || $ft == "mail_business" || $ft == "mail_private") :
                                 $jsOut .= "if (document.forms[0].f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . ".value.length != 0) {\n";
                                 $jsOut .= "   if (!checkMailAddress(document.forms[0].f_mtfv_" . $category . "_" . $mtfck_mtfkIds[$j] . ", '" . getLngt("Bitte tragen Sie eine gültige Email-Adresse bei " . $mtfk_allFieldNames[$mtfck_mtfkIds[$j]] . " ein!") . "')) {ok = false;};";
                                 $jsOut .= "}\n";
                              endif;
                           endif;
                        endif;
                    endfor;
                    
                    // Replace original content with string-content
                    $contentOfCurrTemplate = substr_replace($contentOfCurrTemplate, $out, $pos0, $pos3 - $pos0);
                    $repeat = TRUE;
                 endif;
              endif;
           endif;
        endwhile;

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

        // Postparsing for font size substitution
        for ($i = 1; $i <= 20; $i++) :

           $tagBegin = "<F" . $i . ">";
           $tagEnd = "</F" . $i . ">";

           $pos0 = strpos($contentOfCurrTemplate, $tagBegin);                         // begin of tagBegin (first occurrence)
           $pos1 = strpos($contentOfCurrTemplate, $tagBegin) + strlen($tagBegin);     // end of tagBegin   (first occurrence)
           $pos2 = strpos($contentOfCurrTemplate, $tagEnd);                           // begin of tagEnd   (first occurrence)
           $pos3 = strpos($contentOfCurrTemplate, $tagEnd) + strlen($tagEnd);         // end of tagEnd     (first occurrence)              

           if (is_numeric($pos0) && is_numeric($pos1) && is_numeric($pos2) && is_numeric($pos3)) :

              // Get the content of the tag for substitution
              $tagContent = substr($contentOfCurrTemplate, $pos1, $pos2 - $pos1);                 

              // Check for inner container being empty
              if ($tagContent == "") :
                 // Remove tag with empty content
                 $contentOfCurrTemplate = substr_replace($contentOfCurrTemplate, "", $pos0, $pos3 - $pos0);
              else:
                 // Substitute tags
                 $tmpSubstTextBegin = "<span style=\"font-size:" . $i . "pt;\">";
                 $tmpSubstTextBeginLen = strlen($tmpSubstTextBegin);
                 $tmpSubstTextEnd = "</span>";
                 $tmpSubstTextEndLen = strlen($tmpSubstTextEnd);

                 $contentOfCurrTemplate = substr_replace($contentOfCurrTemplate, $tmpSubstTextBegin, $pos0, $pos1 - $pos0);
                 $tmpPos = $pos2 + ($tmpSubstTextBeginLen - ($pos1 - $pos0)) ;
                 $contentOfCurrTemplate = substr_replace($contentOfCurrTemplate, $tmpSubstTextEnd, $tmpPos, $pos3 - $pos2);
              endif;
              $i--;
           endif;
        endfor;


        // Postparsing for hiding elements depending on the calling category (regarding a template is called by more categories)
        $tagBegin = "<MTFC_HIDE_" . $category . ">";
        $tagEnd = "</MTFC_HIDE_" . $category . ">";
        $repeat = TRUE;
        while ($repeat && !(strpos($contentOfCurrTemplate, $tagBegin) === FALSE) && !(strpos($contentOfCurrTemplate, $tagEnd) === FALSE)) :
              $pos0 = strpos($contentOfCurrTemplate, $tagBegin);                         // begin of tagBegin (first occurrence)
              $pos1 = strpos($contentOfCurrTemplate, $tagBegin) + strlen($tagBegin);     // end of tagBegin   (first occurrence)
              $pos2 = strpos($contentOfCurrTemplate, $tagEnd);                           // begin of tagEnd   (first occurrence)
              $pos3 = strpos($contentOfCurrTemplate, $tagEnd) + strlen($tagEnd);         // end of tagEnd     (first occurrence)              

              $repeat = FALSE;
              if (is_numeric($pos0) && is_numeric($pos1) && is_numeric($pos2) && is_numeric($pos3)) :

                 $contentOfCurrTemplate = substr_replace($contentOfCurrTemplate, "", $pos0, $pos3 - $pos0);
                 $repeat = TRUE;
              endif;
        endwhile;


        // Postparsing for execution of mathematical operations
        for ($iter = 0; $iter <= 9; $iter++) :
            $tagBegin = "<MATH_" . $iter . ":";
            $tagEnd = "</MATH_" . $iter . ">";
            $repeat = TRUE;
            while ($repeat && !(strpos($contentOfCurrTemplate, $tagBegin) === FALSE) && !(strpos($contentOfCurrTemplate, $tagEnd) === FALSE)) :
                  $pos0 = strpos($contentOfCurrTemplate, $tagBegin);                         // begin of tagBegin (first occurrence)
                  $pos1 = strpos($contentOfCurrTemplate, $tagBegin) + strlen($tagBegin);     // end of tagBegin   (first occurrence)
                  $pos2 = strpos($contentOfCurrTemplate, $tagEnd);                           // begin of tagEnd   (first occurrence)
                  $pos3 = strpos($contentOfCurrTemplate, $tagEnd) + strlen($tagEnd);         // end of tagEnd     (first occurrence)              
            
                  $repeat = FALSE;
                  if (is_numeric($pos0) && is_numeric($pos1) && is_numeric($pos2) && is_numeric($pos3)) :
            
                     // Get the content (relative path)
                     $tagContent = substr($contentOfCurrTemplate, $pos1, $pos2 - $pos1);
                     $tagContent = trim($tagContent);
            
                     if ($tagContent != "") :
            
                        $mathOperationResult = "";  // Init result with ""
            
                        // Get position of closing bracket (">") of $tagBegin
                        $posClosingBracketOfBeginTag = strpos($tagContent, ">");
                        if (!($posClosingBracketOfBeginTag === FALSE)) :
                           $mathOptions = substr($tagContent, 0, $posClosingBracketOfBeginTag);
            
                           // Remove defined operation (eq. the beginning) of $tagBegin and get real content
                           $tagContent = substr($tagContent, ($posClosingBracketOfBeginTag + 1));
            
                           // Get components of the operation
                           $mathOptionsArray = spliti(":",$mathOptions);   // E.g. "MULT,0.19" => array("MULT", "0.19")
                           $mathOptionsArrayLen = count($mathOptionsArray);
            
                           if ($tagContent != "" && is_numeric($tagContent)) :
                              $mathOp = $mathOptionsArray[0];
                              if ($mathOperationResult == "") :
                                 $mathOperationResult = $tagContent;
                              endif;
            
                              if ($mathOp == "MULT" || $mathOp == "ADD" || $mathOp == "SUB" || $mathOp == "DIV" || $mathOp == "MOD") :
                                 for ($i = 1; $i < $mathOptionsArrayLen; $i++) :
                                     if ($mathOptionsArray[$i] != "" && is_numeric($mathOptionsArray[$i])) :
                                        if ($mathOp == "MULT") :
                                           $mathOperationResult *= $mathOptionsArray[$i];
                                        endif;
                                        if ($mathOp == "ADD") :
                                           $mathOperationResult += $mathOptionsArray[$i];
                                        endif;
                                        if ($mathOp == "SUB") :
                                           $mathOperationResult -= $mathOptionsArray[$i];
                                        endif;
                                        if ($mathOp == "DIV") :
                                           $mathOperationResult = ($mathOperationResult / $mathOptionsArray[$i]);
                                        endif;
                                        if ($mathOp == "MOD") :
                                           $mathOperationResult = ($mathOperationResult % $mathOptionsArray[$i]);
                                        endif;
                                     endif;
                                 endfor;
                              endif;
            
                              if ($mathOp == "INCLUDED_TAX_AMOUNT") :
                                 if ($mathOptionsArray[1] != "" && is_numeric($mathOptionsArray[1])) :
                                    $mathOperationResult = $mathOperationResult - ($mathOperationResult / (1 +  ($mathOptionsArray[1] / 100)));  // MwSt-Betrag = Bruttobetrag - Nettobetrag
                                 endif;
                              endif;
                           endif;
                        endif;
            
                        $tagContent = $mathOperationResult;
                     endif;
            
                     $contentOfCurrTemplate = substr_replace($contentOfCurrTemplate, $tagContent, $pos0, $pos3 - $pos0);
                     $repeat = TRUE;
                  endif;
            endwhile;
        endfor;


        // Postparsing for formatting numeric elements
        $tagBegin = "<FORMAT_NUMBER_DECIMAL_2>";
        $tagEnd = "</FORMAT_NUMBER_DECIMAL_2>";
        $repeat = TRUE;
        while ($repeat && !(strpos($contentOfCurrTemplate, $tagBegin) === FALSE) && !(strpos($contentOfCurrTemplate, $tagEnd) === FALSE)) :
              $pos0 = strpos($contentOfCurrTemplate, $tagBegin);                         // begin of tagBegin (first occurrence)
              $pos1 = strpos($contentOfCurrTemplate, $tagBegin) + strlen($tagBegin);     // end of tagBegin   (first occurrence)
              $pos2 = strpos($contentOfCurrTemplate, $tagEnd);                           // begin of tagEnd   (first occurrence)
              $pos3 = strpos($contentOfCurrTemplate, $tagEnd) + strlen($tagEnd);         // end of tagEnd     (first occurrence)              

              $repeat = FALSE;
              if (is_numeric($pos0) && is_numeric($pos1) && is_numeric($pos2) && is_numeric($pos3)) :

                 // Get the content (relative path)
                 $tagContent = substr($contentOfCurrTemplate, $pos1, $pos2 - $pos1);
                 $tagContent = trim($tagContent);

                 if ($tagContent != "" && is_numeric($tagContent)) :

                    $tagContent = formatOutput($tagContent, "float_rounded_2");
                 endif;

                 $contentOfCurrTemplate = substr_replace($contentOfCurrTemplate, $tagContent, $pos0, $pos3 - $pos0);
                 $repeat = TRUE;
              endif;
        endwhile;


        // Postparsing for formatting numeric elements
        $tagBegin = "<FORMAT_TIMESTAMP_TO_DATE>";
        $tagEnd = "</FORMAT_TIMESTAMP_TO_DATE>";
        $repeat = TRUE;
        while ($repeat && !(strpos($contentOfCurrTemplate, $tagBegin) === FALSE) && !(strpos($contentOfCurrTemplate, $tagEnd) === FALSE)) :
              $pos0 = strpos($contentOfCurrTemplate, $tagBegin);                         // begin of tagBegin (first occurrence)
              $pos1 = strpos($contentOfCurrTemplate, $tagBegin) + strlen($tagBegin);     // end of tagBegin   (first occurrence)
              $pos2 = strpos($contentOfCurrTemplate, $tagEnd);                           // begin of tagEnd   (first occurrence)
              $pos3 = strpos($contentOfCurrTemplate, $tagEnd) + strlen($tagEnd);         // end of tagEnd     (first occurrence)              

              $repeat = FALSE;
              if (is_numeric($pos0) && is_numeric($pos1) && is_numeric($pos2) && is_numeric($pos3)) :

                 // Get the content (relative path)
                 $tagContent = substr($contentOfCurrTemplate, $pos1, $pos2 - $pos1);
                 $tagContent = trim($tagContent);

                 if ($tagContent != "" && is_numeric($tagContent)) :

                    $tagContent = substr($tagContent,6,2) . "." . substr($tagContent,4,2) . "." . substr($tagContent,0,4);
                 endif;

                 $contentOfCurrTemplate = substr_replace($contentOfCurrTemplate, $tagContent, $pos0, $pos3 - $pos0);
                 $repeat = TRUE;
              endif;
        endwhile;


        // Postparsing for formatting numeric elements
        $tagBegin = "<FORMAT_TIMESTAMP_TO_DATETIME>";
        $tagEnd = "</FORMAT_TIMESTAMP_TO_DATETIME>";
        $repeat = TRUE;
        while ($repeat && !(strpos($contentOfCurrTemplate, $tagBegin) === FALSE) && !(strpos($contentOfCurrTemplate, $tagEnd) === FALSE)) :
              $pos0 = strpos($contentOfCurrTemplate, $tagBegin);                         // begin of tagBegin (first occurrence)
              $pos1 = strpos($contentOfCurrTemplate, $tagBegin) + strlen($tagBegin);     // end of tagBegin   (first occurrence)
              $pos2 = strpos($contentOfCurrTemplate, $tagEnd);                           // begin of tagEnd   (first occurrence)
              $pos3 = strpos($contentOfCurrTemplate, $tagEnd) + strlen($tagEnd);         // end of tagEnd     (first occurrence)              

              $repeat = FALSE;
              if (is_numeric($pos0) && is_numeric($pos1) && is_numeric($pos2) && is_numeric($pos3)) :

                 // Get the content (relative path)
                 $tagContent = substr($contentOfCurrTemplate, $pos1, $pos2 - $pos1);
                 $tagContent = trim($tagContent);

                 if ($tagContent != "" && is_numeric($tagContent)) :
                    $tagContent = substr($tagContent,6,2) . "." . substr($tagContent,4,2) . "." . substr($tagContent,2,2) . " " . substr($tagContent,8,2) . ":" . substr($tagContent,10,2);
                 endif;

                 $contentOfCurrTemplate = substr_replace($contentOfCurrTemplate, $tagContent, $pos0, $pos3 - $pos0);
                 $repeat = TRUE;
              endif;
        endwhile;


        // Postparsing for generating a barcode image
        $tagBegin = "<BARCODE:";
        $tagEnd = "</BARCODE>";
        $imgCount = 0;
        $repeat = TRUE;
        while ($repeat && !(strpos($contentOfCurrTemplate, $tagBegin) === FALSE) && !(strpos($contentOfCurrTemplate, $tagEnd) === FALSE)) :
              $pos0 = strpos($contentOfCurrTemplate, $tagBegin);                         // begin of tagBegin (first occurrence)
              $pos1 = strpos($contentOfCurrTemplate, $tagBegin) + strlen($tagBegin);     // end of tagBegin   (first occurrence)
              $pos2 = strpos($contentOfCurrTemplate, $tagEnd);                           // begin of tagEnd   (first occurrence)
              $pos3 = strpos($contentOfCurrTemplate, $tagEnd) + strlen($tagEnd);         // end of tagEnd     (first occurrence)              

              $repeat = FALSE;
              if (is_numeric($pos0) && is_numeric($pos1) && is_numeric($pos2) && is_numeric($pos3)) :

                 // Get the content (relative path)
                 $tagContent = substr($contentOfCurrTemplate, $pos1, $pos2 - $pos1);
                 $tagContent = trim($tagContent);

                 if ($tagContent != "") :

                    // Get position of closing bracket (">") of $tagBegin
                    $posClosingBracketOfBeginTag = strpos($tagContent, ">");
                    if (!($posClosingBracketOfBeginTag === FALSE)) :
                       $barcodeOptions = substr($tagContent, 0, $posClosingBracketOfBeginTag);
     
                       // Remove defined operation (eq. the beginning) of $tagBegin and get real content
                       $tagContent = substr($tagContent, ($posClosingBracketOfBeginTag + 1));
     
                       // Get components of the operation
                       $barcodeOptionsArray = spliti(":",$barcodeOptions);   // E.g. "ITER,3,4" => array("ITER", "3", "4")
     
                       if ($barcodeOptionsArray[0] != "") :
                           $tmpScaleFactor = $barcodeOptionsArray[0];   // Scale factor
                           if ($tmpScaleFactor == "" || !is_numeric($tmpScaleFactor)) : $tmpScaleFactor = 1; endif;
                       endif;
                       if ($barcodeOptionsArray[1] != "") :
                           $tmpThickness = $barcodeOptionsArray[1];   // Thickness
                           if ($tmpThickness == "" || !is_numeric($tmpThickness)) : $tmpThickness = 30; endif;
                       endif;
                       if ($barcodeOptionsArray[2] != "") :
                           $tmpImgWidth = $barcodeOptionsArray[2];   // Scale up barcode image to fixed width
                           if (!is_numeric($tmpImgWidth)) : $tmpImgWidth = ""; endif;
                       endif;
                       if ($barcodeOptionsArray[3] != "") :
                           $tmpImgHeight = $barcodeOptionsArray[3];   // Scale up barcode image to fixed height
                           if (!is_numeric($tmpImgHeight)) : $tmpImgHeight = ""; endif;
                       endif;
                    endif;

                    // Get barcode image
                    // $tagContent = "<img src=\"<PATH_ABS>../include/</PATH_ABS>barcode_BCGcode39.php?text=" . $tagContent . "\">";
                    $barcodeFilename = "../temp/download/barcode_" . $tagContent . "_" . $imgCount . "_" . getDateTime("6") . ".png";
                    $tagContent = barcode_BCGcode39_saveImage($barcodeFilename , $systemPath, $tagContent, $tmpScaleFactor, $tmpThickness, $tmpImgWidth, $tmpImgHeight);
                 endif;

                 $contentOfCurrTemplate = substr_replace($contentOfCurrTemplate, $tagContent, $pos0, $pos3 - $pos0);
                 $imgCount++;
                 $repeat = TRUE;
              endif;
        endwhile;


        // Postparsing for getting a substring of the content
        $tagBegin = "<SUBSTR:";
        $tagEnd = "</SUBSTR>";
        $imgCount = 0;
        $repeat = TRUE;
        while ($repeat && !(strpos($contentOfCurrTemplate, $tagBegin) === FALSE) && !(strpos($contentOfCurrTemplate, $tagEnd) === FALSE)) :
              $pos0 = strpos($contentOfCurrTemplate, $tagBegin);                         // begin of tagBegin (first occurrence)
              $pos1 = strpos($contentOfCurrTemplate, $tagBegin) + strlen($tagBegin);     // end of tagBegin   (first occurrence)
              $pos2 = strpos($contentOfCurrTemplate, $tagEnd);                           // begin of tagEnd   (first occurrence)
              $pos3 = strpos($contentOfCurrTemplate, $tagEnd) + strlen($tagEnd);         // end of tagEnd     (first occurrence)              

              $repeat = FALSE;
              if (is_numeric($pos0) && is_numeric($pos1) && is_numeric($pos2) && is_numeric($pos3)) :

                 // Get the content (relative path)
                 $tagContent = substr($contentOfCurrTemplate, $pos1, $pos2 - $pos1);
                 $tagContent = trim($tagContent);

                 if ($tagContent != "") :

                    // Get position of closing bracket (">") of $tagBegin
                    $posClosingBracketOfBeginTag = strpos($tagContent, ">");
                    if (!($posClosingBracketOfBeginTag === FALSE)) :
                       $substrOptions = substr($tagContent, 0, $posClosingBracketOfBeginTag);
     
                       // Remove defined operation (eq. the beginning) of $tagBegin and get real content
                       $tagContent = substr($tagContent, ($posClosingBracketOfBeginTag + 1));
     
                       // Get components of the operation
                       $substrOptionsArray = spliti(":",$substrOptions);   // E.g. "ITER,3,4" => array("ITER", "3", "4")
     
                       if ($substrOptionsArray[0] != "") :
                           $tmpStartPos = $substrOptionsArray[0];   // Start position of the substring
                           if ($tmpStartPos == "" || !is_numeric($tmpStartPos)) : $$tmpStartPos = 0; endif;
                       endif;
                       if ($substrOptionsArray[1] != "") :
                           $tmpLength = $substrOptionsArray[1];     // Length of the substring from starting position
                           if ($tmpLength == "" || !is_numeric($tmpLength)) : $tmpLength = strlen($tagContent); endif;
                       endif;
                    endif;

                    // Get substring of "$tagContent"
                    $tagContent = substr($tagContent, $tmpStartPos, $tmpLength);
                 endif;

                 $contentOfCurrTemplate = substr_replace($contentOfCurrTemplate, $tagContent, $pos0, $pos3 - $pos0);
                 $imgCount++;
                 $repeat = TRUE;
              endif;
        endwhile;


        // Postparsing for setting or converting the absolute system path
        $tagBegin = "<PATH_ABS>";
        $tagEnd = "</PATH_ABS>";
        $repeat = TRUE;
        while ($repeat && !(strpos($contentOfCurrTemplate, $tagBegin) === FALSE) && !(strpos($contentOfCurrTemplate, $tagEnd) === FALSE)) :
              $pos0 = strpos($contentOfCurrTemplate, $tagBegin);                         // begin of tagBegin (first occurrence)
              $pos1 = strpos($contentOfCurrTemplate, $tagBegin) + strlen($tagBegin);     // end of tagBegin   (first occurrence)
              $pos2 = strpos($contentOfCurrTemplate, $tagEnd);                           // begin of tagEnd   (first occurrence)
              $pos3 = strpos($contentOfCurrTemplate, $tagEnd) + strlen($tagEnd);         // end of tagEnd     (first occurrence)              

              $repeat = FALSE;
              if (is_numeric($pos0) && is_numeric($pos1) && is_numeric($pos2) && is_numeric($pos3)) :

                 // Get the content (relative path)
                 $tagContent = substr($contentOfCurrTemplate, $pos1, $pos2 - $pos1);
                 $tagContent = trim($tagContent);

                 if ($tagContent != "") :

                    // Get absolute system path
                    $pathAbsolute = getAbsoluteSystemPath();

                    // Modify existing relative path if neccessary
                    if (substr($tagContent,0,1) == ".") : $tagContent = substr($tagContent,1); endif;  // Remove dot sign if it does exist
                    if (substr($tagContent,0,1) == ".") : $tagContent = substr($tagContent,1); endif;  // Second call needed for "../"
                    $tagContent = $pathAbsolute . $tagContent;
                 endif;

                 $contentOfCurrTemplate = substr_replace($contentOfCurrTemplate, $tagContent, $pos0, $pos3 - $pos0);
                 $repeat = TRUE;
              endif;
        endwhile;


        // Get current system path in $systemPath
        $tagPath = "</SYSTEM_PATH>";
        $repeat = TRUE;
        while ($repeat && !(strpos($contentOfCurrTemplate, $tagPath) === FALSE)) :
              $pos0 = strpos($contentOfCurrTemplate, $tagPath);                         // begin of tagPath (first occurrence)
              $pos1 = strpos($contentOfCurrTemplate, $tagPath) + strlen($tagPath);      // end of tagPath   (first occurrence)

              $repeat = FALSE;
              if (is_numeric($pos0) && is_numeric($pos1)) :

                 $contentOfCurrTemplate = substr_replace($contentOfCurrTemplate, $systemPath, $pos0, $pos1 - $pos0);
                 $repeat = TRUE;
              endif;
        endwhile;


        // Postparsing for substitution with database parameter
        $tagBegin = "<DB_PAR>";
        $tagEnd = "</DB_PAR>";
        $repeat = TRUE;
        while ($repeat && !(strpos($contentOfCurrTemplate, $tagBegin) === FALSE) && !(strpos($contentOfCurrTemplate, $tagEnd) === FALSE)) :
              $pos0 = strpos($contentOfCurrTemplate, $tagBegin);                         // begin of tagBegin (first occurrence)
              $pos1 = strpos($contentOfCurrTemplate, $tagBegin) + strlen($tagBegin);     // end of tagBegin   (first occurrence)
              $pos2 = strpos($contentOfCurrTemplate, $tagEnd);                           // begin of tagEnd   (first occurrence)
              $pos3 = strpos($contentOfCurrTemplate, $tagEnd) + strlen($tagEnd);         // end of tagEnd     (first occurrence)              

              $repeat = FALSE;
              if (is_numeric($pos0) && is_numeric($pos1) && is_numeric($pos2) && is_numeric($pos3)) :

                 // Get the content (name of the parameter key) of the tag for substitution
                 $tagContent = substr($contentOfCurrTemplate, $pos1, $pos2 - $pos1);
                 $tagContent = trim($tagContent);

                 // Get content of the parameter out of the database
                 $parContent = "";
                 if ($tagContent != "") :
                    // Check defined output mode defined as prefix of the parameter like "EMAIL::", "PRINT::", "SCREEN::"
                    // Check corresponding required output mode in "$editMode" and compare to parameter output mode
                    $parOutMode = "1";  // Default for screen
                    $parRrefixLen = 0;
                    if (substr($tagContent,0,7) == "PRINT::") : $parOutMode = "0"; $parRrefixLen = 7; endif;
                    if (substr($tagContent,0,7) == "EMAIL::") : $parOutMode = "3"; $parRrefixLen = 7; endif;

                    // Switch behaviour regarding the accordance of $editMode and $parOutMode
                    // Do substitute ONLY if both modes matches
                    if ($editMode == $parOutMode) :
                       $tagContent = substr($tagContent,$parRrefixLen);  // Remove prefix to get real name of the parameter

                       $parContent = getParameterValue("0", $tagContent, $hq_id);  // get value of the parameter key
                       if ($parContent == "") : $parContent = getParameterValue("0", $tagContent, "0"); endif;
                    endif;
                 endif;

                 $contentOfCurrTemplate = substr_replace($contentOfCurrTemplate, $parContent, $pos0, $pos3 - $pos0);

                 $repeat = TRUE;
              endif;
        endwhile;


        // Postparsing for substitution with "metatype" ("MT") mapping "mt_sort" => "mt_value"
        $tagBegin = "<DB_MT:";
        $tagEnd = "</DB_MT>";
        $repeat = TRUE;
        $repeat = TRUE;
        while ($repeat && !(strpos($contentOfCurrTemplate, $tagBegin) === FALSE) && !(strpos($contentOfCurrTemplate, $tagEnd) === FALSE)) :
              $pos0 = strpos($contentOfCurrTemplate, $tagBegin);                         // begin of tagBegin (first occurrence)
              $pos1 = strpos($contentOfCurrTemplate, $tagBegin) + strlen($tagBegin);     // end of tagBegin   (first occurrence)
              $pos2 = strpos($contentOfCurrTemplate, $tagEnd);                           // begin of tagEnd   (first occurrence)
              $pos3 = strpos($contentOfCurrTemplate, $tagEnd) + strlen($tagEnd);         // end of tagEnd     (first occurrence)              

              $repeat = FALSE;
              if (is_numeric($pos0) && is_numeric($pos1) && is_numeric($pos2) && is_numeric($pos3)) :

                 // Get the content (relative path)
                 $tagContent = substr($contentOfCurrTemplate, $pos1, $pos2 - $pos1);
                 $tagContent = trim($tagContent);

                 if ($tagContent != "") :

                    // Get position of closing bracket (">") of $tagBegin
                    $posClosingBracketOfBeginTag = strpos($tagContent, ">");
                    if (!($posClosingBracketOfBeginTag === FALSE)) :
                       $mtOptions = substr($tagContent, 0, $posClosingBracketOfBeginTag);

                       // Remove defined operation (eq. the beginning) of $tagBegin and get real content
                       $tagContent = substr($tagContent, ($posClosingBracketOfBeginTag + 1));

                       // Get components of the operation
                       $mtOptionsArray = spliti(":",$mtOptions);

                       $mtType             = $mtOptionsArray[0];  // "mt_type"
                       $mtMappingFieldFrom = $mtOptionsArray[1];  // Default "mt_sort"
                       $mtMappingFieldTo   = $mtOptionsArray[2];  // Default "mt_value"

                       if ($mtType != "") :
                          if ($mtMappingFieldFrom == "") : $mtMappingFieldFrom = "mt_sort"; endif;
                          if ($mtMappingFieldTo == "") : $mtMappingFieldTo = "mt_value"; endif;
                          
                          $tagContent = getFieldValueFromClause("metatype", $mtMappingFieldTo, "mt_type = '" . $mtType . "' AND " . $mtMappingFieldFrom . " = '" . $tagContent . "'");

                          $contentOfCurrTemplate = substr_replace($contentOfCurrTemplate, $tagContent, $pos0, $pos3 - $pos0);
                          $repeat = TRUE;
                       endif;
                    endif;
                 endif;
              endif;
        endwhile;


        // Postparsing for getting a substring of the content
        // <IF:operation:returnValueByTrue:returnValueByFalse:valueToBeChecked:valueToBeCheckedWith>
        // => <IF:EMPTY: : :[-nnnn-]:0>
        $tagBegin = "<IF:";
        $tagEnd = "</IF>";
        $imgCount = 0;
        $repeat = TRUE;
        while ($repeat && !(strpos($contentOfCurrTemplate, $tagBegin) === FALSE) && !(strpos($contentOfCurrTemplate, $tagEnd) === FALSE)) :
              $pos0 = strpos($contentOfCurrTemplate, $tagBegin);                         // begin of tagBegin (first occurrence)
              $pos1 = strpos($contentOfCurrTemplate, $tagBegin) + strlen($tagBegin);     // end of tagBegin   (first occurrence)
              $pos2 = strpos($contentOfCurrTemplate, $tagEnd);                           // begin of tagEnd   (first occurrence)
              $pos3 = strpos($contentOfCurrTemplate, $tagEnd) + strlen($tagEnd);         // end of tagEnd     (first occurrence)              

              $repeat = FALSE;
              if (is_numeric($pos0) && is_numeric($pos1) && is_numeric($pos2) && is_numeric($pos3)) :

                 // Get the content (relative path)
                 $tagContent = substr($contentOfCurrTemplate, $pos1, $pos2 - $pos1);
                 $tagContent = trim($tagContent);

                 if ($tagContent != "") :

                    // Get position of closing bracket (">") of $tagBegin
                    $posClosingBracketOfBeginTag = strpos($tagContent, ">");
                    if (!($posClosingBracketOfBeginTag === FALSE)) :
                       $ifOptions = substr($tagContent, 0, $posClosingBracketOfBeginTag);

                       // Remove defined operation (eq. the beginning) of $tagBegin and get real content
                       $tagContent = substr($tagContent, ($posClosingBracketOfBeginTag + 1));

                       // Get components of the operation
                       $ifOptionsArray = spliti(":",$ifOptions);

                       $ifOperation = $ifOptionsArray[0];  // EMPTY, EQUAL, UNEQUAL, etc.
                       $ifRetTrue   = $ifOptionsArray[1];  // Return value in case if is true
                       $ifRetFalse  = $ifOptionsArray[2];  // Return value in case if is false
                       $ifVal1      = $ifOptionsArray[3];  // Value 1 to be checked (e.g. DB field [-nnnn-] or normal value)
                       $ifVal2      = $ifOptionsArray[4];  // Value 2 to be checked (e.g. DB field [-nnnn-] or normal value)

                       if ($ifOperation == "EMPTY" || $ifOperation == "EQUAL" || $ifOperation == "UNEQUAL") :

                          if ($ifOperation == "EMPTY") :
                             if ($ifVal1 == "") : $tagContent = $ifRetTrue; else : $tagContent = $ifRetFalse; endif;
                          endif;

                          if ($ifOperation == "EQUAL") :
                             if ($ifVal1 == $ifVal2) : $tagContent = $ifRetTrue; else : $tagContent = $ifRetFalse; endif;
                          endif;

                          if ($ifOperation == "UNEQUAL") :
                             if ($ifVal1 != $ifVal2) : $tagContent = $ifRetTrue; else : $tagContent = $ifRetFalse; endif;
                          endif;

                          $contentOfCurrTemplate = substr_replace($contentOfCurrTemplate, $tagContent, $pos0, $pos3 - $pos0);
                          $repeat = TRUE;
                       endif;
                    endif;
                 endif;
              endif;
        endwhile;


        // Postparsing for getting a substring of the content
        // <SELECT:name:table:idField:textField_orderByField:whereClause:distinct>
        // => <SELECT:f_name:couriervehicle AS crvh, courier AS cr:crvh_id:crvh_sid:crvh_sid:crvh.cr_id = cr.cr_id:DISTINCT>
        $tagBegin = "<SELECT:";
        $tagEnd = "</SELECT>";
        $imgCount = 0;
        $repeat = TRUE;
        while ($repeat && !(strpos($contentOfCurrTemplate, $tagBegin) === FALSE) && !(strpos($contentOfCurrTemplate, $tagEnd) === FALSE)) :
              $pos0 = strpos($contentOfCurrTemplate, $tagBegin);                         // begin of tagBegin (first occurrence)
              $pos1 = strpos($contentOfCurrTemplate, $tagBegin) + strlen($tagBegin);     // end of tagBegin   (first occurrence)
              $pos2 = strpos($contentOfCurrTemplate, $tagEnd);                           // begin of tagEnd   (first occurrence)
              $pos3 = strpos($contentOfCurrTemplate, $tagEnd) + strlen($tagEnd);         // end of tagEnd     (first occurrence)              

              $repeat = FALSE;
              if (is_numeric($pos0) && is_numeric($pos1) && is_numeric($pos2) && is_numeric($pos3)) :

                 // Get the content (relative path)
                 $tagContent = substr($contentOfCurrTemplate, $pos1, $pos2 - $pos1);
                 $tagContent = trim($tagContent);

                 if ($tagContent != "") :

                    // Get position of closing bracket (">") of $tagBegin
                    $posClosingBracketOfBeginTag = strpos($tagContent, ">");
                    if (!($posClosingBracketOfBeginTag === FALSE)) :
                       $ifOptions = substr($tagContent, 0, $posClosingBracketOfBeginTag);

                       // Remove defined operation (eq. the beginning) of $tagBegin and get real content
                       $tagContent = substr($tagContent, ($posClosingBracketOfBeginTag + 1));

                       // Get components of the operation
                       $selOptionsArray = spliti(":",$ifOptions);

                       $selName         = $selOptionsArray[0];
                       $selTable        = $selOptionsArray[1];
                       $selIdField      = $selOptionsArray[2];
                       $selTextField    = $selOptionsArray[3];
                       $selOrderByField = $selOptionsArray[4];
                       $selWhereClause  = $selOptionsArray[5];
                       $selDistinct     = $selOptionsArray[6];

                       $tmpSubstText = addOptionsFromTable($selTable, $selIdField, $selTextField, $selOrderByField, $selWhereClause, $tagContent, $selDistinct);
                       $tagContent = "<select name=\"" . $selName . "\">" . "<option value=\"0\">&nbsp;</option>" . $tmpSubstText . "</select>";

                       $contentOfCurrTemplate = substr_replace($contentOfCurrTemplate, $tagContent, $pos0, $pos3 - $pos0);
                       $repeat = TRUE;
                    endif;
                 endif;
              endif;
        endwhile;
        
        
        // Postparsing for getting a substring of the content
        // <CASE:valueToBeCompared:defaultReturnValueIfNoValueMatched:value01:returnValue01ByTrue:value02:returnValue02ByTrue:value03:returnValue03ByTrue:....>
        // => <CASE:[-nnnn-]:Lieferung:128:Abholung:256:Austausch:....>
        $tagBegin = "<CASE:";
        $tagEnd = "</CASE>";
        $imgCount = 0;
        $repeat = TRUE;
        while ($repeat && !(strpos($contentOfCurrTemplate, $tagBegin) === FALSE) && !(strpos($contentOfCurrTemplate, $tagEnd) === FALSE)) :
              $pos0 = strpos($contentOfCurrTemplate, $tagBegin);                         // begin of tagBegin (first occurrence)
              $pos1 = strpos($contentOfCurrTemplate, $tagBegin) + strlen($tagBegin);     // end of tagBegin   (first occurrence)
              $pos2 = strpos($contentOfCurrTemplate, $tagEnd);                           // begin of tagEnd   (first occurrence)
              $pos3 = strpos($contentOfCurrTemplate, $tagEnd) + strlen($tagEnd);         // end of tagEnd     (first occurrence)              

              $repeat = FALSE;
              if (is_numeric($pos0) && is_numeric($pos1) && is_numeric($pos2) && is_numeric($pos3)) :

                 // Get the content (relative path)
                 $tagContent = substr($contentOfCurrTemplate, $pos1, $pos2 - $pos1);
                 $tagContent = trim($tagContent);

                 if ($tagContent != "") :

                    // Get position of closing bracket (">") of $tagBegin
                    $posClosingBracketOfBeginTag = strpos($tagContent, ">");
                    if (!($posClosingBracketOfBeginTag === FALSE)) :
                       $caseOptions = substr($tagContent, 0, $posClosingBracketOfBeginTag);

                       // Remove defined operation (eq. the beginning) of $tagBegin and get real content
                       $tagContent = substr($tagContent, ($posClosingBracketOfBeginTag + 1));

                       // Get components of the operation
                       $caseOptionsArray = spliti(":",$caseOptions);
                       $caseOptionsArrayLen = count($caseOptionsArray);

                       $caseValueToBeCompared  = $caseOptionsArray[0];  // Value to be checked (e.g. DB field [-nnnn-] or normal value)
                       $caseRetVal             = $caseOptionsArray[1];  // Init with default return value in case of all values to be compared do not match
                       for ($l = 2; $l < $caseOptionsArrayLen; $l += 2) :
                           if ($caseValueToBeCompared == $caseOptionsArray[$l]) :
                              $caseRetVal = $caseOptionsArray[($l+ 1)];
                              break;
                           endif;
                       endfor;

                       $contentOfCurrTemplate = substr_replace($contentOfCurrTemplate, $caseRetVal, $pos0, $pos3 - $pos0);
                       $repeat = TRUE;
                    endif;
                 endif;
              endif;
        endwhile;


        // Postparsing for removing containers with empty elements
        if ($editMode != "1") :
           $containerNoToBeCheckedForEmptyContent = 0;
           $tagBegin = "<CHK_EMPTY_" . $containerNoToBeCheckedForEmptyContent . ">";
           $tagEnd = "</CHK_EMPTY_" . $containerNoToBeCheckedForEmptyContent . ">";
           $tag2Begin = "<REMOVE_EMPTY_" . $containerNoToBeCheckedForEmptyContent . ">";
           $tag2End = "</REMOVE_EMPTY_" . $containerNoToBeCheckedForEmptyContent . ">";
           $repeat = TRUE;
           while ($repeat && !(strpos($contentOfCurrTemplate, $tagBegin) === FALSE) && !(strpos($contentOfCurrTemplate, $tagEnd) === FALSE)) :

              $pos0 = strpos($contentOfCurrTemplate, $tagBegin);                         // begin of tagBegin (first occurrence)
              $pos1 = strpos($contentOfCurrTemplate, $tagBegin) + strlen($tagBegin);     // end of tagBegin   (first occurrence)
              $pos2 = strpos($contentOfCurrTemplate, $tagEnd);                           // begin of tagEnd   (first occurrence)
              $pos3 = strpos($contentOfCurrTemplate, $tagEnd) + strlen($tagEnd);         // end of tagEnd     (first occurrence)
              
              $posA0 = strpos($contentOfCurrTemplate, $tag2Begin);                       // begin of tag2Begin (first occurrence)
              $posA1 = strpos($contentOfCurrTemplate, $tag2Begin) + strlen($tag2Begin);  // end of tag2Begin   (first occurrence)
              $posA2 = strpos($contentOfCurrTemplate, $tag2End);                         // begin of tag2End   (first occurrence)
              $posA3 = strpos($contentOfCurrTemplate, $tag2End) + strlen($tag2End);      // end of tag2End     (first occurrence)
              
              $repeat = FALSE;
              if (is_numeric($pos0) && is_numeric($pos1) && is_numeric($pos2) && is_numeric($pos3)) :

                 // First get the content of the tag (<=> field-number, size (optional), maxlength (optional)) for substitution
                 $tagContent = substr($contentOfCurrTemplate, $pos1, $pos2 - $pos1);
                 $tagContent = trim(str_replace("<br>", "" , $tagContent));
                 $tagContent = trim(str_replace("<img src=\"" . $systemPath . "/documents/images/\" border=\"0\" height=\"\" width=\"\">", "" , $tagContent));
// echo "------------------------------------------<br>\n";
// echo $pos0 . " " . $pos1 . " " . $pos2 . " " . $pos3 . "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" . $posA0 . " " . $posA1 . " " . $posA2 . " " . $posA3 . "<br>\n";
// echo $tagBegin . " " . $tagEnd . " " . $tagContent . "<br>\n";
                 // Check for inner container being empty
                 if ($tagContent == "") :
                    // Remove specified parent container
                    if (is_numeric($posA0) && is_numeric($posA1) && is_numeric($posA2) && is_numeric($posA3)) :
                       $contentOfCurrTemplate = substr_replace($contentOfCurrTemplate, "", $posA0, $posA3 - $posA0);
                    endif;
                 else:
                    // Only remove tags
                    $posBegin = strpos($contentOfCurrTemplate, $tagBegin);
                    $posEnd = $posBegin + strlen($tagBegin);
                    $contentOfCurrTemplate = substr_replace($contentOfCurrTemplate, "", $posBegin, $posEnd - $posBegin);

                    $posBegin = strpos($contentOfCurrTemplate, $tagEnd);
                    $posEnd = $posBegin + strlen($tagEnd);
                    $contentOfCurrTemplate = substr_replace($contentOfCurrTemplate, "", $posBegin, $posEnd - $posBegin);

                    $posBegin = strpos($contentOfCurrTemplate, $tag2Begin);
                    $posEnd = $posBegin + strlen($tag2Begin);
                    $contentOfCurrTemplate = substr_replace($contentOfCurrTemplate, "", $posBegin, $posEnd - $posBegin);

                    $posBegin = strpos($contentOfCurrTemplate, $tag2End);
                    $posEnd = $posBegin + strlen($tag2End);
                    $contentOfCurrTemplate = substr_replace($contentOfCurrTemplate, "", $posBegin, $posEnd - $posBegin);
                 endif;
                 $repeat = TRUE;
              endif;

              $containerNoToBeCheckedForEmptyContent++;
              $tagBegin = "<CHK_EMPTY_" . $containerNoToBeCheckedForEmptyContent . ">";
              $tagEnd = "</CHK_EMPTY_" . $containerNoToBeCheckedForEmptyContent . ">";
              $tag2Begin = "<REMOVE_EMPTY_" . $containerNoToBeCheckedForEmptyContent . ">";
              $tag2End = "</REMOVE_EMPTY_" . $containerNoToBeCheckedForEmptyContent . ">";
           endwhile;
        endif;

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

        $out = $contentOfCurrTemplate;        
     endif;
  endif;
  
  $jsOut .= "  if (ok) {\n";
  $jsOut .= "     document.forms[0].f_act.value = 'saveObjectData';\n";
  $jsOut .= "     document.forms[0].submit();\n";
  $jsOut .= "  }\n";
  $jsOut .= "};\n";
  $jsOut .= "\n";

  // Merge special JS functions
  $jsOut .= $jsOutSelect;

  return array($out, $jsOut);   // Returns PHP output and Javascript output
}


// Check setting according to the headquarters dependency
/*
$gHqId = false;
$constFormSingleHQ = getParameterValue("0", "SYSTEM_FORM_SINGLE_HQ", "0");
if ($constFormSingleHQ == "" || $constFormSingleHQ == "0") : 
   $gHqId = true;
endif;
*/
$gHqId = true;
$constFormSingleHQ = getParameterValue("0", "SYSTEM_FORM_SINGLE_HQ_" . $category, "0");
if ($constFormSingleHQ != "" && $constFormSingleHQ != "0") :
   $gHqId = false;
else :
   $constFormSingleHQ = getParameterValue("0", "SYSTEM_FORM_SINGLE_HQ", "0");
   if ($constFormSingleHQ != "" && $constFormSingleHQ != "0") :
      $gHqId = false;
   endif;
endif;

// Get object data based on category for output (e.g. for page headline)
$mtfcDescription = getFieldValueFromId("metafieldcategory","mtfc_id",$category,"mtfc_description");
$mtfcMnemonic = getFieldValueFromId("metafieldcategory","mtfc_id",$category,"mtfc_mnemonic");
$mtfObjDataArr = array();
if ($mtfcMnemonic == "cs" || $mtfcMnemonic == "cr") :
   if ($objId != "") :
      $mtfObjDataArr = getAddress($objId, $mtfcMnemonic);
   endif;
   if (count($mtfObjDataArr) == 0) :
      if ($callObjId != "") :
         $mtfObjDataArr = getAddress($callObjId, ($callMode == "1" ? "cs" : $mtfcMnemonic));  // Call mode "1" <=> Contacts
      endif; 
   endif;
elseif ($mtfcMnemonic == "crvh") :
   if ($objId != "") :
      $mtfObjDataArr["crvh_sid"] = getFieldValueFromId("couriervehicle", "crvh_id", $objId, "crvh_sid");
      $mtfObjDataArr["crvh_vh_sign"] = getFieldValueFromId("couriervehicle", "crvh_id", $objId, "crvh_vh_sign");
   endif;
endif;
// echo "objId = " . $objId . "<br>";
// echo "callObjId = " . $callObjId . "<br>";
// echo "mtfcMnemonic = " . $mtfcMnemonic . "<br>";
// echo "mtfcDescription = " . $mtfcDescription . "<br>";

// Mapping of displayed fields to system fields
$metaTypeSystemArray = array('empty_field' => 'empty_field', 'current_date' => 'current_date', 'current_headquarters_name' => 'current_hq_name',
        'current_headquarters_id' => 'current_hq_id', 'current_headquarters_mnemonic' => 'current_hq_mnemonic',
        'current_headquarters_company_name' => 'current_hq_cmp_name', 'current_headquarters_company_name2' => 'current_hq_cmp_name2',
        'current_headquarters_company_logo' => 'current_hq_cmp_logo', 'current_user' => 'current_user',
        'current_headquarters_street' => 'current_hq_ad_street', 'current_headquarters_housenumber' => 'current_hq_cmp_hsno', 
        'current_headquarters_zipcode' => 'current_hq_ad_zipcode', 'current_headquarters_city' => 'current_hq_ad_city');

// Mapping of displayed fields to db fields
$metaTypeMappingArray = array('cs:eid' => 'cs_eid', 'cs:discount' => 'cs_discount', 'cs:provision' => 'cs_prov', 
        'cs:markup_provision' => 'cs_markup_prov', 'cs:company_name' => 'cmp_comp', 'cs:company_name2' => 'cmp_comp2', 
        'cs:street' => 'ad_street', 'cs:housenumber' => 'cmp_hsno', 'cs:zipcode' => 'ad_zipcode', 'cs:city' => 'ad_city',
        'cs:taxno' => 'cmp_tax_idno', 'cs:staxno' => 'cmp_stax_idno', 'cs:bank' => 'cmp_bank', 'cs:banknumber' => 'cmp_bankno', 
        'cs:stat_businessvolume_01' => 'stat_bv_01', 'cs:stat_businessvolume_02' => 'stat_bv_02',
        'cs:bankaccount' => 'cmp_bankacc', 'cs:iban' => 'cmp_iban', 'cs:swift' => 'cmp_swift', 'cs:postage' => 'cmp_postage',
        'cs:logo' => 'cmp_logo', 'cs:logo_width' => 'cmp_logo_width', 'cs:logo_height' => 'cmp_logo_height',
        'cs:phone' => 'usr_phone', 'cs:phone2' => 'usr_phone2', 'cs:fax' => 'usr_fax', 'cs:email' => 'usr_email',
        'cs:hash' => 'special_hash', 'cs:costcenteraddress_comp' => 'cscad_cscad_comp',
        'cs:costcenteraddress_street' => 'cscad_ad_street', 'cs:costcenteraddress_hsno' => 'cscad_cscad_hsno',
        'cs:costcenteraddress_zipcode' => 'cscad_ad_zipcode', 'cs:costcenteraddress_city' => 'cscad_ad_city',
        'cs:costcenteraddress_phone' => 'cscad_cscad_phone', 'cs:costcenteraddress_email' => 'cscad_cscad_email',
        'cr:courier_eid' => 'cr_eid', 'cr:imei' => 'cr_imei', 'cr:phone_pda' => 'cr_mobile_pda', 'cr:outlay' => 'cr_outlay',
        'cr:company_name' => 'cmp_comp', 'cr:company_name2' => 'cmp_comp2', 
        'cr:street' => 'ad_street', 'cr:housenumber' => 'cmp_hsno', 'cr:zipcode' => 'ad_zipcode', 'cr:city' => 'ad_city',
        'cr:taxno' => 'cmp_tax_idno', 'cr:staxno' => 'cmp_stax_idno', 'cr:bank' => 'cmp_bank', 'cr:banknumber' => 'cmp_bankno', 
        'cr:bankaccount' => 'cmp_bankacc', 'cr:iban' => 'cmp_iban', 'cr:swift' => 'cmp_swift', 'cr:postage' => 'cmp_postage',
        'cr:name' => 'usr_name', 'cr:firstname' => 'usr_firstname', 'cr:birthdate' => 'usr_birthdate', 'cr:email' => 'usr_email',
        'cr:phone' => 'usr_phone', 'cr:phone2' => 'usr_phone2', 'cr:fax' => 'usr_fax',
        'pt:company_name' => 'pt_cmp_comp', 'pt:company_name2' => 'pt_cmp_comp2', 'pt:street' => 'ad_street',
        'pt:housenumber' => 'pt_cmp_hsno', 'pt:zipcode' => 'ad_zipcode', 'pt:city' => 'ad_city', 'pt:eid' => 'pt_cs_eid',
        'pt:discount' => 'pt_cs_discount',
        'jb:id' => 'jb_id', 'jb:id_parent' => 'jb_id_parent', 'jb:parent_id_fallback_jb_id' => 'parent_id_fallback_jb_id', 
        'jb:vehicle_planned' => 'vht_id', 'jb:vehicle_real' => 'vht_id_real', 
        'jb:weight' => 'jb_weight', 'jb:vehicle_length' => 'jb_crvh_length', 'jb:vehicle_width' => 'jb_crvh_width',
        'jb:vehicle_height' => 'jb_crvh_height', 'jb:vehicle_position' => 'jb_crvh_position',
        'jb:ordertime' => 'jb_ordertime', 'jb:daytime' => 'jb_daytime', 'jb:cr_sid' => 'cr_sid', 
        'jb:filter_mandatory' => 'jb_cr_filter', 'jb:filter_optional' => 'jb_cr_filter_opt',
        'jb:taketime' => 'jb_taketime', 'jb:status' => 'jb_status', 'jb:type' => 'jb_type', 'jb:finishtime' => 'jb_finishtime',
        'jb:warningtime' => 'jb_warningtime', 'jb:fixprice' => 'jb_fixprice', 'jb:serviceprice' => 'jb_serviceprice',
        'jb:totalprice' => 'jb_totalprice', 'jb:cr_price' => 'jb_cr_price', 'jb:postage' => 'jb_postage',
        'jb:subtotalprice' => 'jb_subtotalprice', 'jb:cr_subprice' => 'jb_cr_subprice', 'jb:markup' => 'jb_markup',
        'jb:invoice_text' => 'jb_invtext', 'jb:sales_tax_rate' => 'jb_sales_tax_rate', 'jb:freetext_1' => 'jb_freetext_1',
        'jb:freetext_2' => 'jb_freetext_2', 'jb:freetext_3' => 'jb_freetext_3', 'jb:tourdata' => 'jb_tourdata',
        'jb:timeunits' => 'jb_timeunits', 'jb:service' => 'jb_service', 'jb:is_installation' => 'jb_is_installation', 'jb:export_time' => 'jb_export_time', 
        'jb:createtime' => 'jb_createtime', 'jb:service_sign' => 'service_sign', 'jb:service_acceptance_protocol_points' => 'service_acceptance_protocol_points', 
        'jb:service_acceptance_protocol_text' => 'service_acceptance_protocol_text', 
        'jb:service_acceptance_protocol_packing_pieces' => 'service_acceptance_protocol_packing_pieces', 
        'jb:service_photos' => 'service_photos', 'jb:gdc_jb' => 'gdc_jb', 
        'tr:street' => 'ad_street', 'tr:hsno' => 'tr_hsno', 'tr:zipcode' => 'ad_zipcode', 'tr:city' => 'ad_city', 'tr:country' => 'ad_country',
        'tr:comp' => 'tr_comp', 'tr:comp2' => 'tr_comp2', 'tr:phone' => 'tr_phone', 'tr:person' => 'tr_person', 'tr:remark' => 'tr_remark', 
        'tr:commission_number' => 'tr_commission_no', 'tr:station_no' => 'tr_sort', 'tr:sign' => 'tr_sign', 'tr:ware_from_to' => 'tr_ware_from_to',
        'tr:tourarticle_id' => 'trat_id', 'tr:tourarticle_sort' => 'trat_sort', 'tr:tourarticle_article_id' => 'at_id', 
        'tr:tourarticle_quantity' => 'trat_quantity', 'tr:tourarticle_price' => 'trat_price', 'tr:tourarticle_summated_price' => 'trat_summated_price',
        'tr:tourarticle_serialno' => 'trat_serialno', 'tr:tourarticle_state' => 'trat_state', 'tr:tourarticle_remark' => 'trat_remark',
        'tr:tourarticle_packingpieces' => 'trat_packingpieces', 'tr:tourarticle_number_of_all_packingpieces' => 'trat_number_of_all_pieces',
        'tr:tourarticle_sum_of_weight' => 'trat_sum_of_weight', 'tr:tourarticle_sum_of_volume' => 'trat_sum_of_volume',
        'tr:tourarticle_value_of_goods' => 'trat_value_of_goods', 'tr:tourarticle_summated_value_of_goods' => 'trat_summated_value_of_goods',
        'tr:tourarticle_calculator_servicename' => 'tr_calc_srv_name', 'tr:tourarticle_calculator_quantity' => 'tr_calc_jbc_amount',
        'tr:tourarticle_calculator_single_price' => 'tr_calc_jbc_price', 'tr:tourarticle_calculator_total_price' => 'tr_calc_jbc_totalprice',
        'tr:tourarticle_summated_calculator_value' => 'tr_summated_calc_value',
        'tr:tourarticle_article_eid' => 'at_eid', 'tr:tourarticle_article_name' => 'at_name', 'tr:tourarticle_article_match' => 'at_match', 
        'tr:tourarticle_article_description' => 'at_description', 'tr:tourarticle_article_barcode' => 'at_barcode', 
        'tr:tourarticle_article_bundlequantity' => 'at_bundlequantity', 'tr:tourarticle_article_bundlecode' => 'at_bundlecode',
        'tr:tourarticle_article_stock_itemquantity' => 'at_stk_itemquantity', 'tr:tourarticle_article_stock_areaquantity' => 'at_stk_areaquantity', 
        'tr:tourarticle_article_serialnumber' => 'at_serialno', 
        'tr:tourarticle_article_packingpieces' => 'at_packingpieces', 'tr:tourarticle_article_timeunits' => 'at_timeunits',
        'tr:jobpayment_payment_method' => 'jbp_mode', 'tr:jobpayment_exist_payment_difference' => 'exist_payment_difference',
        'at:article_eid' => 'at_eid', 'at:article_name' => 'at_name', 'at:article_match' => 'at_match', 'at:article_description' => 'at_description',
        'at:article_barcode' => 'at_barcode', 'at:article_bundlequantity' => 'at_bundlequantity', 'at:article_bundlecode' => 'at_bundlecode',
        'at:article_stock_itemquantity' => 'at_stk_itemquantity', 'at:article_stock_areaquantity' => 'at_stk_areaquantity', 
        'at:article_serialnumber' => 'at_serialno', 'at:article_packingpieces' => 'at_packingpieces', 'at:article_timeunits' => 'at_timeunits');


// Load the meta field structure in memory
initMetaFieldStructure();
?>
