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


// $doNotIncludeGeocode = true;
include_once ("../import/import.php");
include_once ("../include/inc_vehicle.inc.php");
include_once ("../include/inc_job.inc.php");
include_once ("../include/services_func.inc.php");


// Execution-Time for script
set_time_limit(0);


// Check HTTP-Parameters
getSecHttpVars("1",array("f_act", "statusMessage", "importFile", "executeImportProcess", "deactivateMenu", "objType", "objId"));


getLanguage(__FILE__);

$deactivateMenuStatic = "1";
$pageTitel = getLngt("IMPORT AUFTRÄGE");
include_once ("../admin/menu.php");
include_once ("../include/html.inc.php");
getCurrentScript(__FILE__);

// Check for authentication access
$usrAccessArray["hq"] = "1";
authCheckForAccess($hq_id, $usr_id, $emp_id, "1", $customerId, $cscIdRoot, $cscIdActual);
if (!(authCheckEmployeeRights($emp_id, "22"))) : gotoReferer("1"); endif;

$empHasAdminRights = false;
$empIdRootAdmin = getEmpIdOfRootAdmin($userTypeName);
if ($empIdRootAdmin != "" && $emp_id == $empIdRootAdmin) : 
   $empHasAdminRights = true;
endif;
$debug = false;
if ($empIdRootAdmin == $emp_id) :
   $debug = false;
endif;

if ($f_act != "executeImport" || $executeImportProcess != "1") : $executeImportProcess = ""; endif;    // Execute import after check run
$showExecutionProcessButton = true;
$outText = "";
$closeWindow = "0";
$delimiter = ";";
$fire = true;  // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

$currentDate = getDateTime(3);
$objType = strtolower($objType);

// Import for special customer ONLY !!!!
$csId = "";
$csEid = "";
$cscIdPayer = "";
if ($objType == "cs" && $objId != "" && is_numeric($objId)) :
   $csId = $objId;
endif;
if ($objType == "csc" && $objId != "" && is_numeric($objId)) :
   $cscIdPayer = $objId;
   $csId = getFieldValueFromClause("costcenter", "cs_id", "csc_id = '" . $cscIdPayer . "'");   
endif;
$csAddress = array();
$adIdFrom = 0;
if ($csId != "") : 
   $hqId = getFieldValueFromClause("customer", "hq_id", "cs_id = '" . $csId . "'");
   $csEid = getFieldValueFromClause("customer", "cs_eid", "cs_id = '" . $csId . "'");
   // $csAddress = getAddress($csId, "customer");
   $csAddress = getAddress($csId, "costcenteraddress");
   $adIdFrom = $csAddress["id"];
   $trHsnoFrom = $csAddress["hsno"];
   if ($trHsnoFrom == "") : $trHsnoFrom = "."; endif;
   
   $trCompFrom = $csAddress["comp"];
   if ($trCompFrom == "") : $trCompFrom = "STANDARD_02"; endif;

   $trFloorFrom = "";
   // USE FOLLOWING FIX ADDRESS
   // $adIdFrom = "220594";  // Invoice address
   // $adIdFrom = "125964";  // Pick-up address
   // $trHsnoFrom = "4";
endif;
if ($hqId == "") : 
   $hqId = $hq_id;
endif;
$cscIdPayerExtern = getParameterValue("0", "CSC_ID_PAYER_EXTERN", $hqId);


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

$pickUpStationFinishedByDefault = true;


// Current file to be imported
$importFile = urldecode($importFile);
$posLastSlash = strrpos($importFile, "/");
$posLastSlash++;
$pathname = substr($importFile, 0, $posLastSlash);
$filename = substr($importFile, $posLastSlash);
$outText = "<span class=\"f10bp1_blue\">" . getLngt("IMPORTDATEI:") . "</span>&nbsp;" . $filename . "<br><br>";


// Mapping "tour id" to "vehicle SID"
/*
$tourVehicleArray = array();
$tourVehicleArray["294501"] = "E501";
$tourVehicleArray["294502"] = "E502";
$tourVehicleArray["294503"] = "E503";
$tourVehicleArray["294504"] = "E504";
$tourVehicleArray["294505"] = "E505";
$tourVehicleArray["294506"] = "E506";
$tourVehicleArray["294507"] = "E507";
$tourVehicleArray["294508"] = "E508";
$tourVehicleArray["294509"] = "E509";
$tourVehicleArray["294510"] = "E510";
$tourVehicleArray["294511"] = "E511";
$tourVehicleArray["294512"] = "E512";
$tourVehicleArray["294590"] = "E590";
*/

$tourCourierArray = array();
/*
$tourCourierArray["294501"] = "e8020201";
$tourCourierArray["294502"] = "e8020202";
$tourCourierArray["294503"] = "e8020203";
$tourCourierArray["294504"] = "e8020204";
$tourCourierArray["294505"] = "e8020205";
$tourCourierArray["294506"] = "e8020206";
$tourCourierArray["294507"] = "e8020207";
$tourCourierArray["294508"] = "e8020208";
$tourCourierArray["294509"] = "e8020209";
$tourCourierArray["294510"] = "e8020210";
$tourCourierArray["294511"] = "e8020211";
$tourCourierArray["294512"] = "e8020212";
$tourCourierArray["294590"] = "e8020213";
*/

function mcStrWrap($aStr)
{
	$aStr = str_replace("'", "", $aStr);
	$aStr = removeFieldSigns($aStr);
  // $aStr = str_replace("'", "\'", $aStr);
  $aStr = str_replace("\"", '', $aStr);
  return $aStr;
}

echo "importFile" . $importFile . "<br>";
echo "hqId" . $hqId . "<br>";
echo "csId" . $csId . "<br>";

if ($importFile != "" && $hqId != "" && is_numeric($hqId) && $csId != "" && is_numeric($csId)) :

   if (file_exists($importFile)) :

      $currentTime = getDateTime("0");


      // ***********************
      // * IMPORT FILE article *
      // ***********************
      if (!(strpos($filename, $csEid . "_import_ALLERGO_") === false)) :

         $executionCount = 0;
         $insertCount = 0;
         $updateCount = 0;
         $failedCount = 0;

         $remTourNo = "";
         $jbIdNew = 0;
         $trSort = 0;    // Init for 1st station
         $tratSort = 1;  // Init all serial numbers !!!!

         $rowToImport = array();
         
         $parImportFieldsGroup == "";
         if ($groupId != "") :
            $parImportFieldsGroup = getParameterValue("0", "IMPORT_ALLERGO_JOB_FIELDS", "0");
         endif;
         if ($parImportFieldsGroup != "") :
            $rowToImport = spliti(",", $parImportFieldsGroup);
         else :
            /*
            transcode	  0,"020"	                    N 3.0	  0: Transaction Code	X	
            transid	    1,"001"	                    A 30	  1: Transaction ID (primary - Schlüsselfeld - )	X	
            absender	  4	                          A 35	  4: Absender Firmenname	(oder Feld 32)	
            absid	      31,"SENDERID	              A 35	  31: Sender ID		
            abskontakt	32,"A. Mehlinger"	          A 35	  32: Absender Kontaktperson	(oder Feld 4)	
            absans1	    5,"Langer Kornweg 43k"	    A 35	  5: Absender Anschrift 1	X	
            absans2	    6,"Geb. 43"	                A 35	  6: Absender Anschrift 2		
            absort	    7,"Kelsterbach"	            A 35	  7: Absender Ort	X	
            absplz	    9,"65451"	                  A 10	  9: Absender Postleitzahl	X	
            kdnrabs	    10,"111111111"	            N 9.0	  10: Stadtbote Kundennummer Absender	X	
            absland     ACHTUNG! Steht NICHT in der Schnittstellenbeschreibung, ist aber eine Spalte der mitgelieferten Beispieldatei!
            abstel	    183,"061079370"	            A 15	  183: Absender Telefonnummer	X	
            absunters	  1150,"A. Mehlinger"	        A 35	  1150: Absender Unterschrift	X	
            empname	    11	                        A 35	  11: Empfänger Firmenname	(oder Feld 12)	
            empkontakt	12,"Mr. Contact"	          A 35	  12: Empfänger Kontaktperson	(oder Feld 11)	
            empans1	    13,"Prestwick Drive"	      A 35	  13: Empfänger Anschrift 1	X	
            empans2	    14,"Bldg. 118"	            A 35	  14: Empfänger Anschrift 2		
            emport	    15,"Memphis"	              A 35	  15: Empfänger Ort	X	
            empbsp	    16,"TN"	                    A 2	    16: Empfänger Bundesstaat/Provinz		
            empplz	    17,"38191"	                A 10	  17: Empfänger Postleitzahl	X	
            emptel	    18,"9012331789"	            A 15	  18: Empfänger Telefonnummer	X	
            kdnrfz      ACHTUNG! Steht NICHT in der Schnittstellenbeschreibung, ist aber eine Spalte der mitgelieferten Beispieldatei!
            comuw	      4129,"5000000"	            N 16.   111111	4129: commodity unit weight	X	
            fzahler	    23,"1"	                    N 1.0	  23: Frachtzahler	X	
            vdatum	    24,"20100322"	              N 8	    24: Versanddatum YYYYMMDD		
            referenz	  25,"CC: DEU12345"	          A 35	  25: Referenz	X	
            pakh	      57-1,"10"	                  N 3.0	  57: Pakethöhe in cm		kann entfallen
            pakb	      58-1,"20"	                  N 3.0	  58: Paketbreite in cm		kann entfallen
            pakl	      59-1,"30"	                  N 3.0	  59: Paketlänge in cm		kann entfallen
            waehrg	    68,"EUR"	                  A 3	    68: Währung	X	
            geweinh	    75,"KGS"	                  A 3	    75: Gewichtseinheit	X	
            commw	      77,"50"                     N 8	    77: Commodity weight		kann entfallen
            produkt	    79-1,"Computer Spareparts"	A 148	  79: Inhalt / Produktbeschreibung	X	
            comminfl	  113,"Y"	                    A 1	    113: commercial invoice flag	(bedingt Feld 1681)	
            packanz	    116,"1"	                    N 7.0	  116: Anzahl Packstücke	X	
            doksend	    190,"N"	                    B 1	    190:Dokumentensendung		kann entfallen
            verpack	    1273,"1"	                  N 2.0	  1273: Verpackung	X	
            servart	    1274,"1"	                  N 2.0	  1274: Serviceart	X	
            rsamail	    1202,"reci@reci.com"	      A 60	  1202: Recipient ship alert Email	X	
            endtr	      99,""	                      A 2	    99: Ende einer Transaktion	X	
            paketnr		                              A 15    - vom Versandunternehmen vergebene Nr. des Paketes
            empfdatum		                            N 8	    gewünschtes Zustelldatum YYYYMMDD		
            zustelldatum		                        N 8	    Datum der Zustellung YYYYMMDD		
            zustellzeit		                          A 5	    Zeitpunkt der Zustellung (Bsp.: 15:30)		
            kuriernr			                                  Debitorennr. Kurier- Info ans Lager		
            aend			                                      Timestamp Datum und Zeit der letzten Änderung
            */

            $rowToImport[0]  = "transcode";     // A
            $rowToImport[1]  = "transid";       // B
            $rowToImport[2]  = "absender";      // C
            $rowToImport[3]  = "absid";         // D
            $rowToImport[4]  = "abskontakt";    // E
            $rowToImport[5]  = "absans1";       // F
            $rowToImport[6]  = "absans2";       // G
            $rowToImport[7]  = "absort";        // H
            $rowToImport[8]  = "absplz";        // I
            $rowToImport[9]  = "kdnrabs";       // J
            $rowToImport[10] = "absland";       // K
            $rowToImport[11] = "abstel";        // L
            $rowToImport[12] = "absunters";     // M
            $rowToImport[13] = "empname";       // N
            $rowToImport[14] = "empkontakt";    // O
            $rowToImport[15] = "empans1";       // P
            $rowToImport[16] = "empans2";       // Q
            $rowToImport[17] = "emport";        // R
            $rowToImport[18] = "empbsp";        // S
            $rowToImport[19] = "empplz";        // T
            $rowToImport[20] = "emptel";        // U
            $rowToImport[21] = "kdnrfz";        // V
            $rowToImport[22] = "comuw";         // W 
            $rowToImport[23] = "fzahler";       // X 
            $rowToImport[24] = "vdatum";        // Y 
            $rowToImport[25] = "referenz";      // Z 
            $rowToImport[26] = "pakh";          // AA
            $rowToImport[27] = "pakb";          // AB
            $rowToImport[28] = "pakl";          // AC
            $rowToImport[29] = "waehrg";        // AD
            $rowToImport[30] = "geweinh";       // AE
            $rowToImport[31] = "commw";         // AF
            $rowToImport[32] = "produkt";       // AG
            $rowToImport[33] = "comminfl";      // AH
            $rowToImport[34] = "packanz";       // AI
            $rowToImport[35] = "doksend";       // AJ
            $rowToImport[36] = "verpack";       // AK
            $rowToImport[37] = "servart";       // AL
            $rowToImport[38] = "rsamail";       // AM
            $rowToImport[39] = "endtr";         // AN
            $rowToImport[40] = "paketnr";       // AO
            $rowToImport[41] = "empfdatum";     // AP
            $rowToImport[42] = "zustelldatum";  // AQ
            $rowToImport[43] = "zustellzeit";   // AR
            $rowToImport[44] = "kuriernr";      // AS
            $rowToImport[45] = "aend";          // AT
         endif;                 


         $rowToImportLen = count($rowToImport);
                                
         // Read file to import 
         $data = importCSV($importFile, $delimiter, "1");
         $dataLen = count($data);

         // Loop all rows (EXCEPT header row [$j = 1])
         for ($j = 0; $j < $dataLen; $j++) {

            // Loop for all fields of $fields of the row
            for ($i = 0; $i < $rowToImportLen; $i++) {
                ${$rowToImport[$i]} = $data[$j][$i];
            }                   

            $f_jb_tourname = "ALLERGO";    // In the beginning constant because import into single job!

            $f_transcode          =  mcStrWrap($transcode);
            $f_transid            =  mcStrWrap($transid);
            $f_tr_comp_sender     =  mcStrWrap($absender);
            $f_tr_comp2_sender    = "";
            $f_absid              =  mcStrWrap($absid);
            $f_tr_person_sender   =  mcStrWrap($abskontakt);
            $f_absans1            =  mcStrWrap($absans1);
            $f_absans2            =  mcStrWrap($absans2);
            $f_ad_city_sender     =  mcStrWrap($absort);
            $f_ad_zipcode_sender  =  mcStrWrap($absplz);
            $f_kdnrabs            =  mcStrWrap($kdnrabs);
            $f_ad_country_sender  =  mcStrWrap($absland);
            $f_tr_phone_sender    =  mcStrWrap($abstel);
            $f_tr_signname_sender =  mcStrWrap($absunters);
            $f_tr_comp            =  mcStrWrap($empname);
            $f_tr_person          =  mcStrWrap($empkontakt);
            $f_empans1            =  mcStrWrap($empans1);
            $f_empans2            =  mcStrWrap($empans2);
            $f_ad_city            =  mcStrWrap($emport);
            $f_ad_country         =  mcStrWrap($empbsp);
            $f_ad_zipcode         =  mcStrWrap($empplz);
            $f_tr_phone           =  mcStrWrap($emptel);
            $f_kdnrfz             =  mcStrWrap($kdnrfz);
            $f_comuw              =  mcStrWrap($comuw);
            $f_fzahler            =  mcStrWrap($fzahler);
            $f_vdatum             =  mcStrWrap($vdatum);
            $f_referenz           =  mcStrWrap($referenz);
            $f_pakh               =  mcStrWrap($pakh);
            $f_pakb               =  mcStrWrap($pakb);
            $f_pakl               =  mcStrWrap($pakl);
            $f_currency           =  mcStrWrap($waehrg);
            $f_geweinh            =  mcStrWrap($geweinh);
            $f_commw              =  mcStrWrap($commw);
            $f_produkt            =  mcStrWrap($produkt);
            $f_comminfl           =  mcStrWrap($comminfl);
            $f_trat_packingpieces =  mcStrWrap($packanz);
            $f_doksend            =  mcStrWrap($doksend);
            $f_verpack            =  mcStrWrap($verpack);
            $f_servart            =  mcStrWrap($servart);
            $f_rsamail            =  mcStrWrap($rsamail);
            $f_endtr              =  mcStrWrap($endtr);
            $f_paketnr            =  mcStrWrap($paketnr);
            // $f_jb_orderdate       =  mcStrWrap($empfdatum);
            $f_jb_orderdate       = "";  // Init empty => "today"
            // $f_jb_warningdate     =  mcStrWrap($zustelldatum);
            $f_jb_warningdate     = "";  // Init empty => "today"
            // $f_clocktimewarning   =  mcStrWrap($zustellzeit);
            $f_clocktimewarning   =  "";  // Init empty => Default warning time
            $f_kuriernr           =  mcStrWrap($kuriernr);
            $f_aend               =  mcStrWrap($aend);

                                                  
            // Check for existing headline
            if ($j > 0) :

               $f_tr_remark = "";  // Init
               $f_tr_remark .= "Sender&nbsp;ID: " . $f_absid   . "<br>";
               $f_tr_remark .= "Kd-Nr.&nbsp;Abs.: " . $f_kdnrabs . "<br>";
               $f_tr_remark .= "Kd-Nr.&nbsp;Fz.: "  . $f_kdnrfz  . "<br>";
               $f_tr_remark .= "Gewichtseinheit: "  . $f_comuw  . "<br>";
               $f_tr_remark .= "Frachtzahler: "  . $f_fzahler  . "<br>";
               $f_tr_remark .= "Versanddatum: "  . $f_vdatum  . "<br>";
               $f_tr_remark .= "Referenz: "  . $f_referenz  . "<br>";
               $f_tr_remark .= "Paketmaße&nbsp;(LxBxH): "  . $f_pakl  . "&nbsp;x&nbsp;" . $f_pakb  . "&nbsp;x&nbsp;" . $f_pakh  . "<br>";
               // $f_tr_remark .= "Währung: "  . $f_currency  . "<br>";
               $f_tr_remark .= "Gewichtseinheit: "  . $f_geweinh  . "<br>";
               $f_tr_remark .= "Warengewicht: "  . $f_commw  . "<br>";
               $f_tr_remark .= "Produktbeschreibung: "  . $f_produkt  . "<br>";
               $f_tr_remark .= "Rechnungs-Flag: "  . $f_comminfl  . "<br>";
               $f_tr_remark .= "Anz.&nbsp;Packstücke: "  . $f_trat_packingpieces  . "<br>";
               $f_tr_remark .= "Dokumentensendung: "  . $f_doksend  . "<br>";
               $f_tr_remark .= "Verpackung: "  . $f_verpack  . "<br>";
               $f_tr_remark .= "Serviceart: "  . $f_servart  . "<br>";
               // $f_tr_remark .= "Alarm-Mail: "  . $f_rsamail  . "<br>";
               // $f_tr_remark .= "Transaktionsende: "  . $f_endtr  . "<br>";
               $f_tr_remark .= "Paketnr.&nbsp;Versand-UN: "  . $f_paketnr  . "<br>";
               // $f_tr_remark .= "Kuriernr.: "  . $f_kuriernr  . "<br>";
               $f_tr_remark .= "Letzte&nbsp;Änderung: "  . $f_aend  . "<br>";


               $f_ad_street_sender = trim($f_absans1 . " " . $f_absans2);
               $f_tr_hsno_sender = "";
               if ($f_tr_hsno_sender == "") :
                  $f_tr_hsno_sender = ".";
               endif;

               $f_ad_street = trim($f_empans1 . " " . $f_empans2);
               $f_tr_hsno = "";
               if ($f_tr_hsno == "") :
                  $f_tr_hsno = ".";
               endif;

               $clockTime = " 16:00:00";
               if ($f_jb_orderdate == "") :
                  $f_jb_orderdate = $currentDate;
               else :
                  $f_jb_orderdate = substr($f_jb_orderdate,0,4) . "-" . substr($f_jb_orderdate,4,2) . "-" . substr($f_jb_orderdate,6,2);
               endif;
               $f_jb_ordertime = $f_jb_orderdate . " " . $clockTime;

               $clockTimeWarning = " 20:00:00";
               if ($f_jb_warningdate == "") :
                  $f_jb_warningdate = $currentDate;
               else :
                  $f_jb_warningdate = substr($f_jb_warningdate,0,4) . "-" . substr($f_jb_warningdate,4,2) . "-" . substr($f_jb_warningdate,6,2);
               endif;
               if ($f_clocktimewarning != "") :
                  $clockTimeWarning = $f_clocktimewarning .= ":00";
               endif;
               $f_jb_warningtime = $f_jb_warningdate . " " . $clockTimeWarning;
               

               // The first row of the tour contains the tour name. The following rows of the same tour are empty for $f_jb_tourname !!!!
               if ($f_jb_tourname == "") :
                  $f_jb_tourname = $remTourNo;
               endif;
               
               
               // Set vehicle and courier
               $crId = "";
               /*
               $crSid = $tourVehicleArray[$f_jb_tourname];
               if ($crSid != "") :
                  $crId = getFieldValueFromId("courier","cr_sid",$crSid,"cr_id");
               endif;
               */
               $crEid = $tourCourierArray[$f_jb_tourname];
               if ($crEid != "") :
                  $crId = getFieldValueFromId("courier","cr_eid",$crEid,"cr_id");
               endif;
               
               $jbStatus = "9";
               $jbTaketime = "";
               if ($crId != "" && is_numeric($crId)) :
                  $jbStatus = "1";
                  $jbTaketime = $currentTime;
               endif;
               $jbType = "";
               $jbFinishtime = "";
               $jbRemark = "";
               $vhtId = "";
               $jbCrFilter = "";
               $sum_totalprice = 0;
               $f_jb_cr_price = 0;
               $jbCrvhWeight = 0;
               $jbCrvhLength = 0;
               $jbCrvhWidth = 0;
               $jbCrvhHeight = 0;
               $jbCrvhPosition = 0;

               echo $f_jb_tourname . ";" . $f_transcode . ";" . $f_transid . ";";
               echo "<br>";

               // Check for existence of the imported "transid" (unique for station)
               $gdcEntryExists = false;
               if (existsEntry("genericdatacontainer",array("gdc_obj_type","tr","gdc_gen_fieldname","info_0","gdc_content",$f_transid,"gdc_context","ALLERGO"))) :
                  $gdcEntryExists = true;
               endif;

               // Do NOT import if ALLERGO number does exist !!!!
               if (!$gdcEntryExists) :

                  // Insert new article
                  if ($executeImportProcess == "1") :

                     TA("B");

                     if ($cscIdPayer == "") :
                        // Get root costcenter
                        $cscIdPayer = getFieldValueFromClause("costcenter", "csc_id", "cs_id = '" . $csId . "' AND (isnull(csc_pre_id) OR csc_pre_id = '')");
                     endif;
/*             
                     $crId = "";
                     $crSid = "";
                     if ($crvhId != "") :
                        $crId = getFieldValueFromId("couriervehicle","crvh_id",$crvhId,"cr_id");
                        if ($crId != "") :
                           $crSid = $vhtPrefix . $f_crvh_sid;
                        endif;
                     endif;
*/             
                     $txValue = "4";
                     $txSign = "V";
                     $noValidationOfAddress = true;

                     if ($remTourNo == "" || $remTourNo == $f_jb_tourname) :
                        if ($jbTourdataZipcode != "") : $jbTourdataZipcode .= ";"; endif;
                        $jbTourdataZipcode .= $f_ad_zipcode;
                        if ($jbTourdataCity != "") : $jbTourdataCity .= ";"; endif;
                        $jbTourdataCity .= $f_ad_city;
                        if ($jbTourdataCountry != "") : $jbTourdataCountry .= ";"; endif;
                        $jbTourdataCountry .= "DE";
                     endif;

                     // Insert address
                     $tmpArray = insertAddress($f_ad_street, $f_ad_zipcode, $f_ad_city, "", $f_ad_country, $noValidationOfAddress);
                     $ad_id_new = $tmpArray[0];
               
                     $outText .= "AD_ID : " . $ad_id_new . " | ";
               
               
                     if ($fire) :
               
                        // Insert new job because new cartage note does begin
                        if ($remTourNo == "" || $remTourNo != $f_jb_tourname) :

                           // Finalize currently imported job
                           // Write "jb_tourdata" of the job currently imported
                           if ($remTourNo != "" && $jbIdNew != "" && is_numeric($jbIdNew)) :
                              $jbTourdata = $jbTourdataZipcode . "|" . $jbTourdataCity . "|" . $jbTourdataCountry;
                              updateStmt("job","jb_id",$jbIdNew,array("jb_tourdata",$jbTourdata));
                           endif;

                           // Remove existing tourname
                           updateStmt("job","jb_tourname",$f_jb_tourname,array("jb_tourname",""), "jb_tourname = '" . $f_jb_tourname . "'");

                           // Tour data                           
                           /*
                           if ($jbIdNew != "" && is_numeric($jbIdNew)) :
                           //    updateStmt("job","jb_id",$jbIdNew,array("jb_tourdata",$jbTourdata));
                           endif;
                           */               

                           if ($cscIdPayer == "") :
                              // Get root costcenter
                              $cscIdPayer = getFieldValueFromClause("costcenter", "csc_id", "cs_id = '" . $csId . "' AND (isnull(csc_pre_id) OR csc_pre_id = '')");
                           endif;

                           $jbIdNew = "";  // Init

                           // Insert job
                           insertStmt("job", array("hq_id", $hqId, "csc_id", "", "vht_id", $vhtId, "csc_id_payer", $cscIdPayer, "csc_id_related", "0", "jb_payment", "0",
                                                   "jb_ordertime", $f_jb_ordertime, "jb_reserv", "1", "cr_id", $crId, "cr_sid", $crSid, "cr_id_order", $crId,
                                                   "jb_cr_filter", $jbCrFilter, "jb_cr_filter_opt", "", "jb_waitstorno", "0", 
                                                   "jb_taketime", $jbTaketime, "jb_status", $jbStatus, "jb_autoranking", "0", "jb_type", $jbType, 
                                                   "jb_incomplete", "0", "jb_globaljob", "0", "jb_tourname", $f_jb_tourname,
                                                   "jb_finishtime", $jbFinishtime, "emp_id", $usr_id, 
                                                   "jb_serviceprice", "0", "jb_fixprice", $sum_totalprice, "jb_totalprice", $sum_totalprice, "jb_subtotalprice", $sum_totalprice, 
                                                   "jb_cr_price", $f_jb_cr_price, "jb_cr_subprice", $f_jb_cr_price,
                                                   "jb_postage", "0", "jb_freetext_1", $jbRemark,
                                                   "jb_weight", $jbCrvhWeight, "jb_crvh_length", $jbCrvhLength, "jb_crvh_width", $jbCrvhWidth, 
                                                   "jb_crvh_height", $jbCrvhHeight, "jb_crvh_position", $jbCrvhPosition, 
                                                   "jb_tourdata", $jbTourdata, "jb_lockuser", "0", "jb_id_parent", "0", "jb_dispoinfo", "",
                                                   "jb_sales_tax_rate", $txValue, "jb_sales_tax_rate_sign", $txSign, "jb_timeunits", "0", 
                                                   "jb_service", "", "jb_booktime", ""));
                           $jbIdNew = getLastInsertId();                        


                           if ($jbIdNew != "") :

                              // Insert sender address
                              $tmpArray = insertAddress($f_ad_street_sender, $f_ad_zipcode_sender, $f_ad_city_sender, "", $f_ad_country_sender, $noValidationOfAddress);
                              $ad_id_sender_new = $tmpArray[0];
                              if ($ad_id_sender_new == "") :
                                 $ad_id_sender_new = $adIdFrom;
                                 $f_tr_hsno_sender = $trHsnoFrom;
                              endif;                              

                              insertStmt("tour", array("jb_id", $jbIdNew, "ad_id", $ad_id_sender_new, "tr_sort", "1", "tr_comp", my_str_check($f_tr_comp_sender), "tr_comp2", my_str_check($f_tr_comp2_sender),
                                                       "tr_hsno", $f_tr_hsno_sender, "csc_id", $cscIdPayer, "tr_status", "1", "tr_signname", $f_tr_signname_sender,
                                                       "tr_finishtime", $jbFinishtime, "tr_commission_no", $trCommissionNo, "tr_person", $f_tr_person_sender, "tr_phone", $f_tr_phone_sender));
                              
                              if ($trsPrice != 0) :
                                 insertStmt("tourservice", array("jb_id", $jbIdNew, "csc_id", $cscIdPayer, "tr_sort", "0", 
                                                                 "srv_id", "0", "trs_srv_name", "Fixpreis", "srvt_id", "0", "trs_srvt_name", "", 
                                                                 "trs_price", $trsPrice, "trs_discount", $csDiscount));
                              endif;
                              if ($servicePrice != 0) :
                                 insertStmt("tourservice", array("jb_id", $jbIdNew, "csc_id", $cscIdPayer, "tr_sort", "0", 
                                                                 "srv_id", "0", "trs_srv_name", "Servicepreis", "srvt_id", "0", "trs_srvt_name", "", 
                                                                 "trs_price", $servicePrice, "trs_discount", "0"));
                              endif;
                           endif;
      

                           $trSort = 1;    // Init for 1st station
                           $tratSort = 1;  // Init all serial numbers !!!!
                           $remTourNo = $f_jb_tourname;
                           
                           // Init for the next job to be imported
                           $jbTourdata = "";
                           // Init with current values
                           $jbTourdataZipcode = $f_ad_zipcode;
                           $jbTourdataCity = $f_ad_city;
                           $jbTourdataCountry = "DE";                           
                        endif;


                        // Check for inserted job
                        if ($jbIdNew != "") :
               
                           $trSort++;
               
                           insertStmt("tour", array("jb_id", $jbIdNew, "ad_id", $ad_id_new, "tr_sort", $trSort, "tr_comp", my_str_check($f_tr_comp), "tr_comp2", "",
                                                    "tr_hsno", $f_tr_hsno, "csc_id", $cscIdPayerExtern, "tr_status", "0", 
                                                    "tr_commission_no", $f_tr_commission_no, "tr_ware_from_to", "", 
                                                    "tr_person", $f_tr_person, "tr_phone", $f_tr_phone, "tr_remark", $f_tr_remark, "tr_cs_freetext", $f_tr_cs_freetext));
                           $trIdNew = getLastInsertID();
               
                
                           // Insert tourservice data
/*
                           insertStmt("tourservice", array("tr_id", $trIdNew, "jb_id", $jbIdNew, "csc_id", $cscIdPayer, "tr_sort", $trSort, 
                                                           "srv_id", "0", "trs_srv_name", "Fixpreis", "srvt_id", "0", "trs_srvt_name", "",
                                                           "trs_price", $sum_totalprice));
*/                                                           
insertStmt("tourservice", array("jb_id", $jbIdNew, "csc_id", $cscIdPayer, "tr_sort", $trSort, "srv_id", "0", "trs_srv_name", "Fixpreis", "srvt_id", "0", "trs_srvt_name", "", "trs_price", $sum_totalprice));
               
                           // Generate invoice text
                           // mk_jb_invtext($jbIdNew, false);

               
                           // Tourname
                           insertStmt("genericdatacontainer", array("gdc_obj_type", "tr", "gdc_obj_id", $trIdNew, "gdc_gen_fieldname", "info_0", "gdc_content", $f_transid, "gdc_context", "ALLERGO"));
               
                           // Insert tourarticle data (delivery stations)
                           /*
                           insertStmt("tourarticle", array("tr_id", $trIdNew, "jb_id", $jbIdNew, "tr_sort", $trSort, "trat_sort", "1", "at_id", "", "trat_quantity", "0", 
                                                           "trat_weight", $f_trat_weight, "trat_price", "0", "trat_packingpieces", $f_trat_packingpieces, "trat_serialno", $f_tr_commission_no, 
                                                           "trat_remark", $f_trat_remark, "trat_createtime", $currentTime));
                           */
               
                           // Insert tourarticle data (pick up station only)
                           // ATTENTION: Execution only if pick-up station is NOT finished by default
                           /*
                           if (!$pickUpStationFinishedByDefault) :
                              insertStmt("tourarticle", array("tr_id", $trIdPickUpNew, "jb_id", $jbIdNew, "tr_sort", "1", "trat_sort", $tratSort, "at_id", "", "trat_quantity", "0", 
                                                              "trat_weight", $f_trat_weight, "trat_price", "0", "trat_packingpieces", $f_trat_packingpieces, "trat_serialno", $f_tr_commission_no, 
                                                              "trat_remark", $f_trat_remark, "trat_createtime", $currentTime));
                              $tratSort++;
                           endif;
                           */

                           $executionCount++;
                        endif;
               
                        TA("C");
                        TA("E");
                     endif;
                  endif;
               else :
                  $outText .= getLngt("Der Datensatz existiert schon! Es erfolgte kein Import!") . " [" . $$f_jb_tourname . " " . $f_tr_sort .  "]<br>";
               endif;    
            endif;  // Check for headline
         }
         
         // If at least onne imported job does exist ($jbIdNew > 0) then finalize last imported job
         // Write "jb_tourdata" of the job currently imported
         if ($jbIdNew != "" && is_numeric($jbIdNew)) :
            $jbTourdata = $jbTourdataZipcode . "|" . $jbTourdataCity . "|" . $jbTourdataCountry;
            updateStmt("job","jb_id",$jbIdNew,array("jb_tourdata",$jbTourdata));
         endif;

         $outText .= getLngt("Einträge in der Importdatei: " . $dataLen . "<br>");
         $outText .= getLngt("Verarbeitete Einträge: " . $executionCount . "<br>");
      else :
         $statusMessage .= getLngt("Die angegebene Datei scheint nicht kompatibel zur angeforderten Importfunktionalität!");
      endif;
   else :
      $statusMessage .= getLngt("Die angegebene Datei existiert nicht!");
   endif;
else :
   $statusMessage .= getLngt("Es wurde keine Datei spezifiziert!");
endif;
?>

<html>
<head>
<title><?php echo $pageTitel ?></title>
<link rel="stylesheet" type="text/css" href="../css/phoenix.css">
<style type="text/css">
  <?php include_once ("../css/navigation.css.php"); ?>
</style>

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

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

function finishPageExecuteImportProcess(f_act) {  
  document.forms[0].f_act.value=f_act;
  document.forms[0].executeImportProcess.value = '1';
  document.forms[0].submit();
};

function onBodyLoad() {
	displayStatusMessage();
	var closeWindow = '<?php echo $closeWindow ?>';
	if (closeWindow == '1') {
     opener.document.forms[0].submit();
     window.close();
  };
};
-->
</script>

</head>

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

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

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

  <div>
    <form name="import_form" action="../import/import_ALLERGO.php" method="post">
      <input type="hidden" name="f_act" value="">
      <?php echo $phpCurrentNavigationInputHidden ?>
      <input type="hidden" name="deactivateMenu" value="<?php echo ec($deactivateMenu) ?>">
      <input type="hidden" name="importFile" value="<?php echo $importFile; ?>">
      <input type="hidden" name="executeImportProcess" value="<?php echo $executeImportProcess; ?>">
      <input type="hidden" name="objType" value="<?php echo $objType; ?>">
      <input type="hidden" name="objId" value="<?php echo $objId; ?>">

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

      <?php
        if ($showExecutionProcessButton && $executeImportProcess != "1") :
           echo defineButtonType10(getLngt("Import starten"), "action_import", "finishPageExecuteImportProcess('executeImport');", "200");
           echo htmlDivLineSpacer("5px");
           echo defineButtonType10(getLngt("Schließen"), "action_close", "window.close();", "200");
           echo htmlDivLineSpacer("5px");
        endif;
      ?>

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

      <div>
        <table border="1" margin="10" padding="10">
        	<tr>
        		<td style="vertical-align:top;">
              <?php echo $outText; ?>
            </td>
          </tr>
        </table>    
      </div>
    </form>
  </div>

</div>

</body>

</html>