<?php
/*=======================================================================
 *
 * inc_courier.inc.php
 *
 * Autor: Marc Vollmann
 *
 * Functions for couriers
 *
 =======================================================================*/   


include_once ("../include/inc_asset.inc.php");
include_once ("../include/inc_vehicle.inc.php");


// Gets a courier list according to a special search string
function getCourierList ($search) {
	global $db, $PHP_SELF;
	global $f_hq_id;
	$retArray = array();

	$search = trim($search);
	if ($search == "") :
	   $retArray = array("301","<err_no>301</err_no>\n","<err_desc>" . getLngt("Ein Suchbegriff wurde nicht eingegeben!") . "</err_desc>\n");
	else :
	   $whereClauseExtendedSearch = "";
	   if (false) :
	      $whereClauseExtendedSearch = " OR usr.usr_name LIKE '%" . $search . "%' OR usr.usr_firstname LIKE '%" . $search . "%' OR usr.usr_phone LIKE '%" . $search . "%' OR "
	                                 . " usr.usr_phone2 LIKE '%" . $search . "%' OR ad.ad_street LIKE '%" . $search . "%' ";
	   endif;
     $sqlquery = "SELECT cr.cr_id, cmp.cmp_type, cr.cr_eid, cmp.cmp_comp, cmp.cmp_comp2, cmp.cmp_comp3, cmp.cmp_comp4,"
                  . "    usr.usr_name, usr.usr_firstname, usr.usr_phone, usr.usr_phone2,"
                  . "    ad.ad_street, cmp.cmp_hsno, ad.ad_zipcode, ad.ad_city"
                  . " FROM company AS cmp, courier AS cr, user AS usr, address AS ad"
                  . " WHERE cmp.cmp_id = cr.cmp_id      AND"
                  . "       cr.hq_id IN " . getSQLMandatorArray($f_hq_id) . " AND"
                  . "       cmp.cmp_authenticated = '1' AND "
                  . "       cmp.cmp_visible = '1'       AND "
                  . "       cmp.ad_id = ad.ad_id        AND"
                  . "       cr.usr_id = usr.usr_id      AND"
                  . "       usr.hq_id IN " . getSQLMandatorArray($f_hq_id) . " AND"
                  . "       (cr.cr_eid LIKE '%" . $search . "%' OR cmp.cmp_comp LIKE '%" . $search . "%' OR cmp.cmp_comp2 LIKE '%" . $search . "%' OR cmp.cmp_comp3 LIKE '%" . $search . "%' OR cmp.cmp_comp4 LIKE '%" . $search . "%' OR cmp.cmp_match LIKE '%" . $search . "%'"
                  .         $whereClauseExtendedSearch . ")"
                  . " ORDER BY cmp.cmp_comp"
                  . " LIMIT 0,30";
     $result = $db->query($sqlquery);
     if (DB::isError($result)):
        $retArray = array("202","<err_no>202</err_no>\n","<err_desc>" . getLngt("Datenbankfehler") . "</err_desc>\n");
     else:
        while ($row = $result->fetch_assoc()):
              $retArray[] = array($row["cr_id"], $row["cmp_type"], $row["cr_eid"], $row["cmp_comp"], $row["cmp_comp2"], $row["usr_name"], $row["usr_firstname"], $row["usr_phone"], $row["usr_phone2"], $row["ad_street"], $row["cmp_hsno"], $row["ad_zipcode"], $row["ad_city"], $row["cmp_comp3"], $row["cmp_comp4"]);
        endwhile;
        $result->free();
     endif;
	endif;
	return $retArray;
}

// Gets special data from a single courier
function getCourierSpecial ($crId) {
	global $db, $PHP_SELF;
	global $f_hq_id, $emp_id, $hq_id;
	$retArray = array();
	if ($crId == "" || !is_numeric($crId)) :
	   $retArray = array("301","<err_no>301</err_no>\n","<err_desc>" . getLngt("Die Transporteurs-ID ist leer!") . "</err_desc>\n");
	else :
     $sqlquery = "SELECT cmp.cmp_id, cmp.cmp_type, cmp.cmp_comp, cmp.cmp_comp2, cmp.cmp_comp3, cmp.cmp_comp4,"
                  . "    cmp.cmp_hsno, cmp.cmp_iln, cmp.cmp_tax_idno, cmp.cmp_stax_idno,"
                  . "    cmp.cmp_bank, cmp.cmp_bankno, cmp.cmp_bankacc, cmp.cmp_iban, cmp.cmp_swift,"
                  . "    cmp.cmp_authenticated, cmp.cmp_remark, cmp.cmp_visible, cmp.cmp_remark2, cmp.cmp_freetext1, cmp.cmp_contract_date,"
                  . "    cr.cr_id, cr.cr_sid, cr.cr_eid, cr.vht_id, cr.vht_id_inv, cr.cr_maxweight, cr.cr_outlay, cr.cr_homezipcode,"
                  . "    cr.cr_available, cr.cr_id_parent, cr.cr_vh_sign, cr.cr_imei, cr.cr_mobile_pda, cr.cr_serialno,"
                  . "    cr.cr_disposition, cr.cr_price_show,"
                  . "    usr.usr_id, usr.usr_name, usr.usr_firstname, usr.usr_email, usr.usr_inv_email,"
                  . "    usr.usr_phone, usr.usr_phone2, usr.usr_fax, usr.usr_account,usr.usr_birthdate,"
                  . "    ad.ad_street, ad.ad_zipcode, ad.ad_city, ad.ad_country"
                  . " FROM company AS cmp, courier AS cr, user AS usr, address AS ad"
                  . " WHERE cr.cr_id = '" . $crId . "' AND"
                  . "       cmp.cmp_id = cr.cmp_id     AND"
                  . "       cr.usr_id = usr.usr_id     AND"
                  . "       cmp.ad_id = ad.ad_id";
     $result = $db->query($sqlquery);
     if (DB::isError($result)):
        $retArray = array("202","<err_no>202</err_no>\n","<err_desc>" . getLngt("Datenbankfehler") . "</err_desc>\n");
     else:
        while ($row = $result->fetch_assoc()):
              $retArray[] = array($row["cr_id"], $row["cmp_type"], $row["cr_eid"], $row["cmp_comp"], $row["cmp_comp2"], $row["usr_name"], $row["usr_firstname"], $row["usr_phone"], $row["usr_phone2"], $row["ad_street"], $row["cmp_hsno"], $row["ad_zipcode"], $row["ad_city"], $row["cmp_comp3"], $row["cmp_comp4"]);
        endwhile;
        $result->free();
     endif;
	endif;
	return $retArray;
}

// Gets ALL data from a special courier
function getCourier ($cmpId, $retMode = "") {
	global $db, $PHP_SELF;
	global $emp_id, $usr_id, $hq_id, $f_hq_id;

	$retArray = array();	

	// Global parameters will be defined by default
	if ($retMode == "") :
     global $f_cmp_authenticated, $f_cmp_type, $f_cmp_comp, $f_cmp_comp2, $f_cmp_comp3, $f_cmp_comp4, $f_usr_id, $f_usr_name, $f_usr_firstname;
     global $f_usr_phone, $f_usr_phone2, $f_usr_fax, $f_usr_email, $f_usr_inv_email, $f_usr_birthdate, $f_cr_sid, $f_cr_eid, $f_vht_id, $f_vht_id_inv, $f_cr_maxweight;
     global $f_cr_outlay, $f_cr_locationzipcode, $f_cr_homezipcode, $f_cr_available, $f_cmp_iln, $f_cmp_tax_idno, $f_cmp_stax_idno, $f_cmp_bank, $f_cmp_bankno, $f_cmp_bankacc;
     global $f_cmp_bankmode, $f_cmp_iban, $f_cmp_swift, $f_usr_account;
     global $f_ad_street, $f_cmp_hsno, $f_ad_zipcode, $f_ad_city, $f_ad_country;
     global $f_cr_id_parent, $f_cr_sid_parent, $f_cr_eid_parent, $f_cr_vh_sign;
     global $f_cr_imei, $f_cr_mobile_pda, $f_cr_serialno, $f_cr_weekdays, $f_cmp_remark, $f_cmp_remark2, $f_cmp_freetext1, $f_cmp_visible, $noValidationOfAddress, $objecttypemode;
     global $f_cmp_postage, $f_cmp_hqlino, $f_cmp_inv2hq, $f_cmp_visible_internal, $f_cmp_archived, $f_cmp_match, $f_cmp_match2, $f_cmp_new_date, $f_cmp_contract_date;
	endif;

  if ($cmpId != "" && is_numeric($cmpId)) :
     // Mandator filter
     if ($f_hq_id == "") : $f_hq_id = array(); endif;
     if (count($f_hq_id) == 0) : array_push($f_hq_id, $hq_id); endif;

     // Get asset data if enabled
     $parAssetsEnabled = getParameterValue("0", "ASSET_MANAGEMENT_ENABLED", "0");

     $sqlquery = "SELECT cmp.cmp_id, cmp.cmp_type, cmp.cmp_comp, cmp.cmp_comp2, cmp.cmp_comp3, cmp.cmp_comp4, cmp.cmp_iln,"
                  . "    cmp.cmp_tax_idno, cmp.cmp_stax_idno, cmp.tx_id, cmp.br_id, cmp.emp_id_sales, cmp.cmp_sales_ranking_man,"
                  . "    cmp.cmp_hsno, cmp.cmp_bank, cmp.cmp_bankno, cmp.cmp_bankacc, cmp.cmp_iban, cmp.cmp_swift, cmp.cmp_hqlino, cmp.cmp_match, cmp.cmp_match2,"
                  . "    cmp.cmp_remark, cmp.cmp_remark2, cmp.cmp_freetext1, cmp.cmp_newsletter, cmp.cmp_proof_delivery, cmp.cmp_pda_usage, cmp.cmp_bankmode, cmp.cmp_postage, cmp.cmp_inv2hq,"
                  . "    cmp.cmp_authenticated, cmp.cmp_visible, cmp.cmp_cashmode, cmp.cmp_new_date, cmp.cmp_contract_date, cmp.cmp_modify,"
                  . "    cr.cr_id, cr.cmp_id, cr.hq_id, cr.usr_id, cr.cr_eid, cr.cr_sid, cr.cr_id_parent, cr.vht_id, cr.vht_id_inv,"
                  . "    cr.cr_vh_sign, cr.cr_imei, cr.cr_mobile_pda, cr.cr_serialno, cr.cr_maxweight, cr.cr_outlay, cr.cr_locationzipcode, cr.cr_homezipcode,"
                  . "    cr.cr_ar_jb_id, cr.cr_available, cr.cr_availabletime, cr.cr_occupied, cr.cr_logintime, cr.cr_gps_long, cr.cr_gps_lat,"
                  . "    cr.cr_gps_time, cr.cr_gps_type, cr.cr_gps_acc, cr.cr_mobile_cell, cr.cr_group, cr.cr_msggrp, cr.cr_disposition, cr.cr_price_show, cr.cr_modify,"
                  . "    usr.usr_id, usr.usr_name, usr.usr_firstname, usr.usr_email, usr.usr_inv_email,"
                  . "    usr.usr_phone, usr.usr_phone2, usr.usr_fax, usr.usr_account,usr.usr_birthdate,"
                  . "    ad.ad_id, ad.ad_street, ad.ad_zipcode, ad.ad_city, ad.ad_country"
                  . " FROM company AS cmp, courier AS cr, user AS usr, address AS ad"
                  . " WHERE cmp.cmp_id = '" . $cmpId . "' AND"
                  . "       cmp.cmp_id = cr.cmp_id        AND"
                  . "       cr.usr_id = usr.usr_id        AND"
                  . "       cmp.ad_id = ad.ad_id";

     $result = $db->query($sqlquery);
     if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
     while ($row = $result->fetch_assoc()):
           if ($retMode == "1") :
              $retArray["cmp_id"]             = $row["cmp_id"];
              $retArray["cmp_type"]           = $row["cmp_type"];
              $retArray["cmp_comp"]           = $row["cmp_comp"];
              $retArray["cmp_comp2"]          = $row["cmp_comp2"];
              $retArray["cmp_comp3"]          = $row["cmp_comp3"];
              $retArray["cmp_comp4"]          = $row["cmp_comp4"];
              $retArray["cmp_hsno"]           = $row["cmp_hsno"];
              $retArray["cmp_iln"]            = $row["cmp_iln"];
              $retArray["cmp_tax_idno"]       = $row["cmp_tax_idno"];
              $retArray["cmp_stax_idno"]      = $row["cmp_stax_idno"];
              $retArray["cmp_bank"]           = $row["cmp_bank"];
              $retArray["cmp_bankno"]         = $row["cmp_bankno"];
              $retArray["cmp_bankacc"]        = $row["cmp_bankacc"];
              $retArray["cmp_bankmode"]       = $row["cmp_bankmode"];
              $retArray["cmp_iban"]           = $row["cmp_iban"];
              $retArray["cmp_swift"]          = $row["cmp_swift"];
              $retArray["cmp_hqlino"]         = $row["cmp_hqlino"];
              $retArray["cmp_postage"]        = $row["cmp_postage"];
              $retArray["cmp_inv2hq"]         = $row["cmp_inv2hq"];
              $retArray["cmp_match"]          = $row["cmp_match"];
              $retArray["cmp_match2"]         = $row["cmp_match2"];
              $retArray["cmp_remark"]         = $row["cmp_remark"];
              $retArray["cmp_remark2"]        = $row["cmp_remark2"];
              $retArray["cmp_freetext1"]      = $row["cmp_freetext1"];
              $retArray["cmp_newsletter"]     = $row["cmp_newsletter"];
              $retArray["cmp_proof_delivery"] = $row["cmp_proof_delivery"];
              $retArray["cmp_pda_usage"]      = $row["cmp_pda_usage"];
              $retArray["cmp_authenticated"]  = $row["cmp_authenticated"];
              $retArray["cmp_authenticated2"] = 0;
              if ($retArray["cmp_authenticated"] != "1") :
                 $retArray["cmp_authenticated"] = 0; 
                 $retArray["cmp_authenticated2"] = 1;
              endif;
              $retArray["cmp_visible"] = $row["cmp_visible"];
              $retArray["cmp_visible2"] = 0;
              if ($retArray["cmp_visible"] != "1") :
                 $retArray["cmp_visible"] = 0; 
                 $retArray["cmp_visible2"] = 1;
              endif;
              $retArray["cmp_cashmode"] = $row["cmp_cashmode"];
              $retArray["cmp_cashmode2"] = 0;
              if ($retArray["cmp_cashmode"] != "1") :
                 $retArray["cmp_cashmode"] = 0; 
                 $retArray["cmp_cashmode2"] = 1;
              endif;
              $retArray["cmp_sales_ranking_man"] = $row["cmp_sales_ranking_man"];
              $retArray["cmp_new_date"]          = $row["cmp_new_date"];
              $retArray["cmp_contract_date"]     = $row["cmp_contract_date"];
              $retArray["cmp_modify"]            = $row["cmp_modify"];

              $retArray["ad_id"]                 = $row["ad_id"];
              $retArray["ad_street"]             = $row["ad_street"];
              $retArray["ad_zipcode"]            = $row["ad_zipcode"];
              $retArray["ad_city"]               = $row["ad_city"];
              $retArray["ad_country"]            = $row["ad_country"];

              $retArray["cr_id"]                 = $row["cr_id"];
              $retArray["cr_eid"]                = $row["cr_eid"];
              $retArray["cr_hq_id"]              = $row["hq_id"];
              $retArray["cr_sid"]                = $row["cr_sid"];
              $retArray["cr_id_parent"]          = $row["cr_id_parent"];
              $retArray["vht_id"]                = $row["vht_id"];
              $retArray["vht_id_inv"]            = $row["vht_id_inv"];
              $retArray["cr_vh_sign"]            = $row["cr_vh_sign"];
              $retArray["cr_imei"]               = $row["cr_imei"];
              $retArray["cr_mobile_pda"]         = $row["cr_mobile_pda"];
              $retArray["cr_serialno"]           = $row["cr_serialno"];
              $retArray["cr_maxweight"]          = $row["cr_maxweight"];
              $retArray["cr_outlay"]             = $row["cr_outlay"];
              $retArray["cr_locationzipcode"]    = $row["cr_locationzipcode"];
              $retArray["cr_homezipcode"]        = $row["cr_homezipcode"];
              $retArray["cr_ar_jb_id"]           = $row["cr_ar_jb_id"];
              $retArray["cr_available"]          = $row["cr_available"];
              $retArray["cr_availabletime"]      = $row["cr_availabletime"];
              $retArray["cr_occupied"]           = $row["cr_occupied"];
              $retArray["cr_logintime"]          = $row["cr_logintime"];            
              $retArray["cr_gps_long"]           = $row["cr_gps_long"];
              $retArray["cr_gps_lat"]            = $row["cr_gps_lat"];
              $retArray["cr_gps_time"]           = $row["cr_gps_time"];
              $retArray["cr_gps_type"]           = $row["cr_gps_type"];
              $retArray["cr_gps_acc"]            = $row["cr_gps_acc"];
              $retArray["cr_mobile_cell"]        = $row["cr_mobile_cell"];
              $retArray["cr_group"]              = $row["cr_group"];
              $retArray["cr_msggrp"]             = $row["cr_msggrp"];
              $retArray["cr_disposition"]        = $row["cr_disposition"];
              $retArray["cr_price_show"]         = $row["cr_price_show"];
              $retArray["cr_modify"]             = $row["cr_modify"];

              $retArray["usr_id"]                = $row["usr_id"];
              $retArray["usr_name"]              = $row["usr_name"];
              $retArray["usr_firstname"]         = $row["usr_firstname"];
              $retArray["usr_birthdate"]         = $row["usr_birthdate"];
              $retArray["usr_email"]             = $row["usr_email"];
              $retArray["usr_inv_email"]         = $row["usr_inv_email"];
              $retArray["usr_phone"]             = $row["usr_phone"];
              $retArray["usr_phone2"]            = $row["usr_phone2"];
              $retArray["usr_fax"]               = $row["usr_fax"];
              $retArray["usr_account"]           = $row["usr_account"];

           elseif ($retMode == "2") :
              $retArray["cr_id"]                 = $row["cr_id"];
              $retArray["cr_eid"]                = $row["cr_eid"];
              $retArray["cr_hq_id"]              = $row["hq_id"];
              $retArray["cr_sid"]                = $row["cr_sid"];
              $retArray["cr_id_parent"]          = $row["cr_id_parent"];
              $retArray["vht_id"]                = $row["vht_id"];
              $retArray["vht_id_inv"]            = $row["vht_id_inv"];
              $retArray["cr_vh_sign"]            = $row["cr_vh_sign"];
              $retArray["cr_imei"]               = $row["cr_imei"];
              $retArray["cr_mobile_pda"]         = $row["cr_mobile_pda"];
              $retArray["cr_serialno"]           = $row["cr_serialno"];
              $retArray["cr_maxweight"]          = $row["cr_maxweight"];
              $retArray["cr_outlay"]             = $row["cr_outlay"];
              $retArray["cr_locationzipcode"]    = $row["cr_locationzipcode"];
              $retArray["cr_homezipcode"]        = $row["cr_homezipcode"];
              $retArray["cr_ar_jb_id"]           = $row["cr_ar_jb_id"];
              $retArray["cr_available"]          = $row["cr_available"];
              $retArray["cr_availabletime"]      = $row["cr_availabletime"];
              $retArray["cr_occupied"]           = $row["cr_occupied"];
              $retArray["cr_logintime"]          = $row["cr_logintime"];            
              $retArray["cr_gps_long"]           = $row["cr_gps_long"];
              $retArray["cr_gps_lat"]            = $row["cr_gps_lat"];
              $retArray["cr_gps_time"]           = $row["cr_gps_time"];
              $retArray["cr_gps_type"]           = $row["cr_gps_type"];
              $retArray["cr_gps_acc"]            = $row["cr_gps_acc"];
              $retArray["cr_mobile_cell"]        = $row["cr_mobile_cell"];
              $retArray["cr_group"]              = $row["cr_group"];
              $retArray["cr_msggrp"]             = $row["cr_msggrp"];
              $retArray["cr_disposition"]        = $row["cr_disposition"];
              $retArray["cr_price_show"]         = $row["cr_price_show"];
              $retArray["cr_modify"]             = $row["cr_modify"];

              $retArray["company"]["cmp_id"]             = $row["cmp_id"];
              $retArray["company"]["cmp_type"]           = $row["cmp_type"];
              $retArray["company"]["cmp_comp"]           = $row["cmp_comp"];
              $retArray["company"]["cmp_comp2"]          = $row["cmp_comp2"];
              $retArray["company"]["cmp_comp3"]          = $row["cmp_comp3"];
              $retArray["company"]["cmp_comp4"]          = $row["cmp_comp4"];
              $retArray["company"]["ad_id"]              = $row["ad_id"];
              $retArray["company"]["ad_street"]          = $row["ad_street"];
              $retArray["company"]["ad_zipcode"]         = $row["ad_zipcode"];
              $retArray["company"]["ad_city"]            = $row["ad_city"];
              $retArray["company"]["ad_country"]         = $row["ad_country"];
              $retArray["company"]["cmp_hsno"]           = $row["cmp_hsno"];
              $retArray["company"]["cmp_iln"]            = $row["cmp_iln"];
              $retArray["company"]["cmp_tax_idno"]       = $row["cmp_tax_idno"];
              $retArray["company"]["cmp_stax_idno"]      = $row["cmp_stax_idno"];
              $retArray["company"]["cmp_bank"]           = $row["cmp_bank"];
              $retArray["company"]["cmp_bankno"]         = $row["cmp_bankno"];
              $retArray["company"]["cmp_bankacc"]        = $row["cmp_bankacc"];
              $retArray["company"]["cmp_bankmode"]       = $row["cmp_bankmode"];
              $retArray["company"]["cmp_iban"]           = $row["cmp_iban"];
              $retArray["company"]["cmp_swift"]          = $row["cmp_swift"];
              $retArray["company"]["cmp_hqlino"]         = $row["cmp_hqlino"];
              $retArray["company"]["cmp_postage"]        = $row["cmp_postage"];
              $retArray["company"]["cmp_inv2hq"]         = $row["cmp_inv2hq"];
              $retArray["company"]["cmp_match"]          = $row["cmp_match"];
              $retArray["company"]["cmp_match2"]         = $row["cmp_match2"];
              $retArray["company"]["cmp_remark"]         = $row["cmp_remark"];
              $retArray["company"]["cmp_remark2"]        = $row["cmp_remark2"];
              $retArray["company"]["cmp_freetext1"]      = $row["cmp_freetext1"];
              $retArray["company"]["cmp_newsletter"]     = $row["cmp_newsletter"];
              $retArray["company"]["cmp_proof_delivery"] = $row["cmp_proof_delivery"];
              $retArray["company"]["cmp_pda_usage"]      = $row["cmp_pda_usage"];
              $retArray["company"]["cmp_authenticated"]  = $row["cmp_authenticated"];
              $retArray["company"]["cmp_authenticated2"] = 0;
              if ($retArray["company"]["cmp_authenticated"] != "1") :
                 $retArray["company"]["cmp_authenticated"] = 0; 
                 $retArray["company"]["cmp_authenticated2"] = 1;
              endif;
              $retArray["company"]["cmp_visible"] = $row["cmp_visible"];
              $retArray["company"]["cmp_visible2"] = 0;
              if ($retArray["company"]["cmp_visible"] != "1") :
                 $retArray["company"]["cmp_visible"] = 0; 
                 $retArray["company"]["cmp_visible2"] = 1;
              endif;
              $retArray["company"]["cmp_cashmode"] = $row["cmp_cashmode"];
              $retArray["company"]["cmp_cashmode2"] = 0;
              if ($retArray["company"]["cmp_cashmode"] != "1") :
                 $retArray["company"]["cmp_cashmode"] = 0; 
                 $retArray["company"]["cmp_cashmode2"] = 1;
              endif;
              $retArray["company"]["cmp_sales_ranking_man"] = $row["cmp_sales_ranking_man"];
              $retArray["company"]["cmp_new_date"]          = $row["cmp_new_date"];
              $retArray["company"]["cmp_contract_date"]     = $row["cmp_contract_date"];
              $retArray["company"]["cmp_modify"]            = $row["cmp_modify"];

              $retArray["user"]["usr_id"]           = $row["usr_id"];
              $retArray["user"]["usr_name"]         = $row["usr_name"];
              $retArray["user"]["usr_firstname"]    = $row["usr_firstname"];
              $retArray["user"]["usr_birthdate"]    = $row["usr_birthdate"];
              $retArray["user"]["usr_email"]        = $row["usr_email"];
              $retArray["user"]["usr_inv_email"]    = $row["usr_inv_email"];
              $retArray["user"]["usr_phone"]        = $row["usr_phone"];
              $retArray["user"]["usr_phone2"]       = $row["usr_phone2"];
              $retArray["user"]["usr_fax"]          = $row["usr_fax"];
              $retArray["user"]["usr_account"]      = $row["usr_account"];

              if ($parAssetsEnabled == "1") :
                 // Get weekdays if the courier is an operational asset, too....
                 // $retArray["asset"] = getColVectorFromDB2ArrayByClause("asset", "as_weekdays", "as_obj_type = 'cr' AND as_obj_id = '" . $row["cr_id"] . "'", "as_obj_id", "", "");
                 // !!!! WORK IS NOT FINISHED HERE! PERHAPS A SEPARATE SERVICE?!  !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
              endif;

           else :
              // $retMode == "" <=> default <=> set global parameters
              $f_cmp_type           = $row["cmp_type"];
              $f_cmp_comp           = $row["cmp_comp"];
              $f_cmp_comp2          = $row["cmp_comp2"];
              $f_cmp_comp3          = $row["cmp_comp3"];
              $f_cmp_comp4          = $row["cmp_comp4"];
              $f_cmp_hsno           = $row["cmp_hsno"];
              $f_cmp_iln            = $row["cmp_iln"];
              $f_cmp_tax_idno       = $row["cmp_tax_idno"];
              $f_cmp_stax_idno      = $row["cmp_stax_idno"];
              $f_cmp_bank           = $row["cmp_bank"];
              $f_cmp_bankno         = $row["cmp_bankno"];
              $f_cmp_bankacc        = $row["cmp_bankacc"];
              $f_cmp_bankmode       = $row["cmp_bankmode"];
              $f_cmp_iban           = $row["cmp_iban"];
              $f_cmp_swift          = $row["cmp_swift"];
              $f_cmp_hqlino         = $row["cmp_hqlino"];
              $f_cmp_postage        = $row["cmp_postage"];
              $f_cmp_inv2hq         = $row["cmp_inv2hq"];
              $f_cmp_match          = $row["cmp_match"];
              $f_cmp_match2         = $row["cmp_match2"];
              $f_cmp_remark         = $row["cmp_remark"];
              $f_cmp_remark2        = $row["cmp_remark2"];
              $f_cmp_freetext1      = $row["cmp_freetext1"];
              $f_cmp_newsletter     = $row["cmp_newsletter"];
              $f_cmp_proof_delivery = $row["cmp_proof_delivery"];
              $f_cmp_pda_usage      = $row["cmp_pda_usage"];
              $f_cmp_authenticated  = $row["cmp_authenticated"];
              $f_cmp_authenticated2 = 0;
              if ($f_cmp_authenticated != "1") :
                 $f_cmp_authenticated = 0; 
                 $f_cmp_authenticated2 = 1;
              endif;
              $f_cmp_visible = $row["cmp_visible"];
              $f_cmp_visible2 = 0;
              if ($f_cmp_visible != "1") :
                 $f_cmp_visible = 0; 
                 $f_cmp_visible2 = 1;
              endif;
              $f_cmp_cashmode = $row["cmp_cashmode"];
              $f_cmp_cashmode2 = 0;
              if ($f_cmp_cashmode != "1") :
                 $f_cmp_cashmode = 0; 
                 $f_cmp_cashmode2 = 1;
              endif;
              $f_cmp_sales_ranking_man = $row["cmp_sales_ranking_man"];
              $f_cmp_new_date          = $row["cmp_new_date"];
              $f_cmp_contract_date     = $row["cmp_contract_date"];
              $f_cmp_modify            = $row["cmp_modify"];
              $f_cr_id                 = $row["cr_id"];
              $f_cr_eid                = $row["cr_eid"];
              $f_cr_hq_id              = $row["hq_id"];
              $f_cr_sid                = $row["cr_sid"];
              $f_vht_id                = $row["vht_id"];
              $f_vht_id_inv            = $row["vht_id_inv"];
              $f_cr_vh_sign            = $row["cr_vh_sign"];
              $f_cr_maxweight          = $row["cr_maxweight"];
              $f_cr_outlay             = $row["cr_outlay"];
              $f_cr_homezipcode        = $row["cr_homezipcode"];
              $f_cr_available          = $row["cr_available"];
              $f_cr_imei               = $row["cr_imei"];
              $f_cr_mobile_pda         = $row["cr_mobile_pda"];
              $f_cr_serialno           = $row["cr_serialno"];
              $f_cr_id_parent          = $row["cr_id_parent"];

              $f_usr_id                = $row["usr_id"];
              $f_usr_name              = $row["usr_name"];
              $f_usr_firstname         = $row["usr_firstname"];
              $f_usr_birthdate         = $row["usr_birthdate"];
              $f_usr_phone             = $row["f_usr_phone"];
              $f_usr_phone2            = $row["f_usr_phone2"];
              $f_usr_fax               = $row["f_usr_fax"];
              $f_usr_email             = $row["f_usr_email"];
              $f_usr_inv_email         = $row["f_usr_inv_email"];
           endif;
     endwhile;
     $result->free();
  endif;

	return $retArray;
}

// Inserts a new courier
function insertCourier ($crArray = array(), $retMode = "") {
  global $db, $PHP_SELF;
  global $usr_id, $hq_id;
  global $cs_id_new, $cmp_id_new, $currentTime, $statusMessage, $debug;

  $retBool = false;
  $retArray = array();
  if ($debug) : echo "insertCourier :: DEBUG enabled! <br>"; endif;
  $hqId = $hq_id;   // Init
  $crArrayLen = 0;
  if (is_array($crArray)) : $crArrayLen = count($crArray); endif;

  if ($crArrayLen == 0) :
     global $f_cmp_authenticated, $f_cmp_type, $f_cmp_comp, $f_cmp_comp2, $f_cmp_comp4, $f_cmp_comp4, $f_usr_id, $f_usr_name, $f_usr_firstname, $f_usr_birthdate;
     global $f_usr_phone, $f_usr_phone2, $f_usr_fax, $f_usr_email, $f_usr_inv_email, $f_cr_sid, $f_cr_eid, $f_vht_id, $f_vht_id_inv, $f_cr_maxweight;
     global $f_cr_outlay, $f_cr_locationzipcode, $f_cr_homezipcode, $f_cr_available, $f_cr_availabletime, $f_cmp_iln, $f_cmp_tax_idno, $f_cmp_stax_idno, $f_cmp_bank, $f_cmp_bankno, $f_cmp_bankacc;
     global $f_cmp_bankmode, $f_cmp_iban, $f_cmp_swift, $f_usr_account, $f_usr_password, $f_usr_password2;
     global $f_ad_street, $f_cmp_hsno, $f_ad_zipcode, $f_ad_city, $f_ad_country;
     global $f_cr_id_parent, $f_cr_sid_parent, $f_cr_eid_parent, $f_cr_vh_sign;
     global $f_usr_birthdate_day, $f_usr_birthdate_month, $f_usr_birthdate_year, $f_cr_disposition, $f_cr_price_show;
     global $f_cr_imei, $f_cr_mobile_pda, $f_cr_serialno, $f_cmp_remark, $f_cmp_remark2, $f_cmp_freetext1, $f_cmp_visible, $noValidationOfAddress, $pageTitel, $f_inc_geocode_disabled;
     global $f_cmp_postage, $f_cmp_hqlino, $f_cmp_inv2hq, $f_cmp_visible_internal, $f_cmp_archived, $f_cmp_match, $f_cmp_match2, $f_cmp_new_date;
     global $f_cmp_contract_date, $f_cmp_contract_date_day, $f_cmp_contract_date_month, $f_cmp_contract_date_year;

  else :
     // Regard courier insert by external request
     $hqId = $crArray["hq_id"];                                       // It should be possible to insert a new courier für another headquarters
     if ($hqId == "" || !is_numeric($hqId)) :
        if ($hqId != "" && !is_numeric($hqId)) : 
           $hqId = getFieldValueFromId("headquarters","hq_mnemonic",$hqId,"hq_id");
        endif;
        if ($hqId == "") :
           if ($hq_id != "" && is_numeric($hq_id)) :
              $hqId = $hq_id;
           else :
              $hqId = "1"; // Default
           endif;
        endif;
     endif;

     $pageTitel = $crArray["pageTitel"];                              // Represents the string ("Kunde", Interessent", ...) according to the value in "cmp_type"
     $noValidationOfAddress   = $crArray["noValidationOfAddress"];    // For function "insertAddress" only

     $f_cmp_authenticated     = $crArray["cmp_authenticated"]; 
     $f_cmp_comp              = $crArray["cmp_comp"]; 
     $f_cmp_comp2             = $crArray["cmp_comp2"]; 
     $f_cmp_comp3             = $crArray["cmp_comp3"]; 
     $f_cmp_comp4             = $crArray["cmp_comp4"]; 
     $f_cmp_iln               = $crArray["cmp_iln"];  
     $f_cmp_tax_idno          = $crArray["cmp_tax_idno"]; 
     $f_cmp_stax_idno         = $crArray["cmp_stax_idno"];
     $f_cmp_bank              = $crArray["cmp_bank"]; 
     $f_cmp_bankno            = $crArray["cmp_bankno"]; 
     $f_cmp_bankacc           = $crArray["cmp_bankacc"]; 
     $f_cmp_bankmode          = $crArray["cmp_bankmode"]; 
     $f_cmp_postage           = $crArray["cmp_postage"]; 
     $f_cmp_inv2hq            = $crArray["cmp_inv2hq"]; 
     $f_cmp_cashmode          = $crArray["cmp_cashmode"];
     $f_cmp_visible           = $crArray["cmp_visible"]; 
     $f_ad_street             = $crArray["ad_street"];
     $f_cmp_hsno              = $crArray["cmp_hsno"];
     $f_ad_zipcode            = $crArray["ad_zipcode"];
     $f_ad_city               = $crArray["ad_city"];
     $f_ad_country            = $crArray["ad_country"];
     $f_cmp_remark            = $crArray["cmp_remark"];
     $f_cmp_remark2           = $crArray["cmp_remark2"];
     $f_cmp_freetext1         = $crArray["cmp_freetext1"];
     $f_cmp_match             = $crArray["cmp_match"];
     $f_cmp_match2            = $crArray["cmp_match2"];
     $f_cmp_iban              = $crArray["cmp_iban"];
     $f_cmp_swift             = $crArray["cmp_swift"];
     $f_cmp_hqlino            = $crArray["cmp_hqlino"];
     $f_cmp_type              = $crArray["cmp_type"];
     $f_cmp_newsletter        = $crArray["cmp_newsletter"];
     $f_cmp_proof_delivery    = $crArray["cmp_proof_delivery"];
     $f_cmp_pda_usage         = $crArray["cmp_pda_usage"];
     $f_cmp_sales_ranking_man = $crArray["cmp_sales_ranking_man"];
     $f_cmp_logo              = $crArray["cmp_logo"];
     $f_cmp_logo_width        = $crArray["cmp_logo_width"];
     $f_cmp_logo_height       = $crArray["cmp_logo_height"];
     $f_cmp_contract_date     = $crArray["cmp_contract_date"];
     if ($f_cmp_contract_date == "" && ($f_cmp_contract_date_year != "" && $f_cmp_contract_date_month != "" && $f_cmp_contract_date_day != "")) :
       $f_cmp_contract_date = $f_cmp_contract_date_year . "-" . pad($f_cmp_contract_date_month, 2, "0") . "-" . pad($f_cmp_contract_date_day, 2, "0");
     endif;

     // $f_cr_id = $row["cr_id"];
     $f_cr_eid                = $crArray["cr_eid"];
     $f_cr_sid                = $crArray["cr_sid"];
     $f_cr_hq_id              = $crArray["hq_id"];
     $f_vht_id                = $crArray["vht_id"];
     $f_vht_id_inv            = $crArray["vht_id_inv"];
     $f_cr_vh_sign            = $crArray["cr_vh_sign"];
     $f_cr_maxweight          = $crArray["cr_maxweight"];
     $f_cr_outlay             = $crArray["cr_outlay"];
     $f_cr_locationzipcode    = $crArray["cr_locationzipcode"];
     $f_cr_homezipcode        = $crArray["cr_homezipcode"];
     $f_cr_available          = $crArray["cr_available"];
     $f_cr_availabletime      = $crArray["cr_availabletime"];
     $f_cr_imei               = $crArray["cr_imei"];
     $f_cr_mobile_pda         = $crArray["cr_mobile_pda"];
     $f_cr_serialno           = $crArray["cr_serialno"];
     $f_cr_id_parent          = $crArray["cr_id_parent"];
     $f_cr_disposition        = $crArray["cr_disposition"];
     $f_cr_price_show         = $crArray["cr_price_show"];
     $f_cr_weekdays           = $crArray["cr_weekdays"];

     $f_usr_name              = $crArray["usr_name"]; 
     $f_usr_firstname         = $crArray["usr_firstname"];
     $f_usr_birthdate         = $crArray["usr_birthdate"];
     if ($f_usr_birthdate == "" && ($f_usr_birthdate_year != "" && $f_usr_birthdate_month != "" && $f_usr_birthdate_day != "")) :
       $f_usr_birthdate = $f_usr_birthdate_year . "-" . pad($f_usr_birthdate_month, 2, "0") . "-" . pad($f_usr_birthdate_day, 2, "0");
     endif;
     $f_usr_phone             = $crArray["usr_phone"]; 
     $f_usr_phone2            = $crArray["usr_phone2"]; 
     $f_usr_fax               = $crArray["usr_fax"]; 
     $f_usr_email             = $crArray["usr_email"];
     $f_usr_inv_email         = $crArray["usr_inv_email"];
     $f_usr_account           = $crArray["usr_account"]; 
     $f_usr_password          = $crArray["usr_password"];
     $f_usr_password2         = $crArray["usr_password2"];
     
     $f_inc_geocode_disabled  = $crArray["sys_inc_geocode_disabled"];
  endif;

  // Check fields  
  if ($f_cmp_comp == "") : $f_cmp_comp = $f_usr_name . ", " . $f_usr_firstname; endif;
  // if ($f_usr_phone == "" && $f_usr_phone2 != "") : $f_usr_phone = $f_usr_phone2; $f_usr_phone2 = "";  endif;

  // Check displaying mode for field "cr_mobile_pda"
  $parMaskCrMobilePdaEdit = getParameterValue("0", "MASK_CR_MOBILE_PDA_EDIT", $hq_id);
  if ($parMaskCrMobilePdaEdit == "") :
     $parMaskCrMobilePdaEdit = getParameterValue("0", "MASK_CR_MOBILE_PDA_EDIT", "0");
  endif;
  if ($debug) : echo "MASK_CR_MOBILE_PDA_EDIT = " . $parMaskCrMobilePdaEdit . "<br>"; endif;

  $maskHideCrVhtInv = getParameterValue("0", "MASK_HIDE_CR_VHT_INV", $hq_id);
  if ($maskHideCrVhtInv == "") : 
     $maskHideCrVhtInv = getParameterValue("0", "MASK_HIDE_CR_VHT_INV", "0");
  endif;
  if ($debug) : echo "MASK_HIDE_CR_VHT_INV = " . $maskHideCrVhtInv . "<br>"; endif;

  $cdSidStaus = getParameterValue("0", "CR_SID_STATUS", $hq_id);
  if ($cdSidStaus == "") : 
     $cdSidStaus = getParameterValue("0", "CR_SID_STATUS", "0");
  endif;
  if ($debug) : echo "CR_SID_STATUS = " . $cdSidStaus . "<br>"; endif;


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

  if ($debug) :
      echo "currentTime = " . $currentTime . "<br>"; 
      echo "f_cmp_comp = " . $f_cmp_comp . "<br>"; 
      echo "f_usr_name = " . $f_usr_name . "<br>"; 
      echo "f_usr_firstname = " . $f_usr_firstname . "<br>"; 
      echo "f_usr_phone = " . $f_usr_phone . "<br>"; 
      echo "f_ad_street = " . $f_ad_street . "<br>"; 
      echo "f_ad_zipcode = " . $f_ad_zipcode . "<br>"; 
      echo "f_ad_city = " . $f_ad_city . "<br>"; 
      echo "f_cmp_hsno = " . $f_cmp_hsno . "<br>"; 
      echo "cdSidStaus = " . $cdSidStaus . "<br>"; 
      echo "f_cr_sid = " . $f_cr_sid . "<br>"; 
      echo "f_cr_eid = " . $f_cr_eid . "<br>";
  endif;

  if ($f_cmp_comp != "" && $f_usr_name != "" && $f_usr_firstname != "" && 
      $f_usr_phone != "" && $f_usr_account != "" && ($parMaskCrMobilePdaEdit != "1" || $f_cr_mobile_pda != "") &&
      $f_ad_street != "" && $f_ad_zipcode != "" && $f_ad_city != "" &&
      $f_cmp_hsno != "" && ($maskHideCrVhtInv == "1" || $f_vht_id_inv != "") && $f_cmp_tax_idno != "" && 
      ($cdSidStaus == "0" || $f_cr_sid != "") && $f_cr_eid != "") :

     // Parameter for checking company name
     $parChkCmpDisabled = getParameterValue("0", "MASK_CR_CHK_CMP_EXIST_DISABLED", "0");
     if ($debug) : echo "MASK_CR_CHK_CMP_EXIST_DISABLED = " . $parChkCmpDisabled . "<br>"; endif;

     // Check unique account for all couriers (all data) except the current one to be updated
     if ($db->getOne("SELECT usr.usr_id FROM user AS usr WHERE usr.usr_account = '" . $f_usr_account . "' ")) :
        $statusMessage = "Der Benutzername existiert schon! Bitte wählen Sie einen anderen!";

     elseif ($parChkCmpDisabled != "1" && $db->getOne("SELECT cmp.cmp_comp FROM company AS cmp, courier AS cr WHERE cmp.cmp_comp = '" . $f_cmp_comp . "' AND cmp.cmp_id = cr.cmp_id AND cr.hq_id = '" . $hq_id . "'")) :
        $statusMessage = getLngt("Der Firmenname ist bereits vorhanden! Bitte wählen Sie einen anderen!");

     // elseif ($db->getOne("SELECT cr_sid FROM courier WHERE cr_sid = '" . $f_cr_sid . "'")) :
     //    $statusMessage = "Die systemweit eindeutige Kuriernummer ist bereits vergeben! Bitte wählen Sie eine andere";

     elseif ($cdSidStaus == "1" && $db->getOne("SELECT cr_sid FROM courier WHERE cr_sid = '" . $f_cr_sid . "' AND hq_id = '" . $hq_id . "'")) :
        $statusMessage = getLngt("Die eindeutige Kuriernummer (SID) ist bereits vergeben! Bitte wählen Sie eine andere");

     elseif ($db->getOne("SELECT cr_eid FROM courier WHERE cr_eid = '" . $f_cr_eid . "' AND hq_id = '" . $hq_id . "'")) :
        $statusMessage = getLngt("Die eindeutige Kuriernummer (ExtID) ist bereits vergeben! Bitte wählen Sie eine andere");

     elseif (checkPasswordValidation($f_usr_password,$f_usr_password2)) : 

        if ($debug) : echo "checkPasswordValidation() OK!<br>"; endif;

        if ($f_inc_geocode_disabled == "1") :
           $addressValid = "OK";
        else :
           $addressValid = getGeoCoordinates($f_ad_street, $f_ad_zipcode, $f_ad_city, $f_cmp_hsno, $f_ad_country, "");
        endif;
        if ($debug) : echo "addressValid = " . $addressValid . "<br>"; endif;
        if ($addressValid != "") :

           // Check zipcode and city
           $addressValidityArray = checkCityZipcode($f_ad_zipcode, $f_ad_city, $f_ad_street);
           if ($noValidationOfAddress || $addressValidityArray[0] >= 1) :                        

              if ($debug) : echo "noValidationOfAddress = " . $noValidationOfAddress . "<br>"; endif;
              if ($debug) : echo "addressValidation OK!<br>"; endif;

              TA("B");

              $currentTime = getDateTime("0");

              // Insert user
              $sqlStmtPwd = "INSERT INTO user (hq_id,usr_type,usr_name,usr_firstname,usr_email,usr_inv_email,usr_phone,usr_phone2,usr_fax,usr_account,usr_password,usr_password_modify,usr_birthdate)" .
                                " VALUES ($hqId,'3','$f_usr_name','$f_usr_firstname','$f_usr_email','$f_usr_inv_email','$f_usr_phone','$f_usr_phone2','$f_usr_fax','$f_usr_account',PASSWORD('$f_usr_password'),'$currentTime','$f_usr_birthdate')";
              // writeDbLog($sqlStmtPwd);
              $res = $db->query($sqlStmtPwd);
              if (DB::isError($res)) : die ("$PHP_SELF: " . $res->getMessage()); endif;                                     
              $usr_id_new = getLastInsertID(); 
              if ($debug) : echo "usr_id_new : " . $usr_id_new . "<br>"; endif;
              // Insert company
              insertStmt("company", array("cmp_type", $f_cmp_type, "cmp_comp", $f_cmp_comp, "cmp_comp2", $f_cmp_comp2, 
                         "cmp_hsno", $f_cmp_hsno, "cmp_iln", $f_cmp_iln, "cmp_tax_idno", $f_cmp_tax_idno, "cmp_stax_idno", $f_cmp_stax_idno, 
                         "cmp_bank", $f_cmp_bank, "cmp_bankno", $f_cmp_bankno, "cmp_bankacc", $f_cmp_bankacc, "cmp_iban", $f_cmp_iban, "cmp_swift", $f_cmp_swift,
                         "cmp_authenticated", "1", "cmp_visible", "1", "cmp_remark", $f_cmp_remark, "cmp_remark2", $f_cmp_remark2, "cmp_freetext1", $f_cmp_freetext1,
                         "cmp_new_date", $currentTime, "cmp_contract_date", $f_cmp_contract_date, "cmp_modify_status", "1"));
              $cmp_id_new = getLastInsertId();
              if ($debug) : echo "cmp_id_new : " . $cmp_id_new . "<br>"; endif;
              // Check for mobile number
              if ($parMaskCrMobilePdaEdit != "1" && $dbhostArrayLen > 0 && $dbConnectionArray["app_property"] != "") :
                 // Remove potential old association of the new number if it is NOT empty
                 $crEidWithSameMobileNo = "";
                 if ($f_cr_mobile_pda != "") :
                    $crIdWithMobileSameNo = getFieldValueFromId("courier", "cr_mobile_pda", $f_cr_mobile_pda, "cr_id");
                    if ($crIdWithMobileSameNo != "") :
                       updateStmt("courier","cr_id",$crIdWithMobileSameNo,array("cr_mobile_pda", ""));
                       $crEidWithSameMobileNo = getFieldValueFromId("courier", "cr_id", $crIdWithMobileSameNo, "cr_eid");
                       $statusMessage = getLngt("Die Mobilnummer wurde beim folgendem " . wrapPhrase("Transporteur", $objecttypemode) . " entfernt:") . " " . $crEidWithSameMobileNo;
                    endif;
                 endif;
                 $remDb = $db;
                 $db = $dbConnectionArray["app_property"];
                 // Make new association
                 updateStmt("sysadmin.conf_prop", "cp_secval", $f_cr_mobile_pda, array("usr_id", $usr_id_new), "cust_id = '" . $constGlobalDbInstNo . "' AND prop_id = '1' AND cp_secval != ''");
                 $db = $remDb;
                 // Write logdata into log database
                 writeToLogDB("117",$hqId,"",$usr_id,$cr_id_new,"","","MSISDN_OLD=|MSISDN_NEW=" . $f_cr_mobile_pda . "|CR_EID_OLD=" . $crEidWithSameMobileNo);
              endif;

              // Insert courier
              insertStmt("courier", array("cmp_id", $cmp_id_new, "hq_id", $hqId, "usr_id", $usr_id_new,
                                          "cr_sid", $f_cr_sid, "cr_eid", $f_cr_eid, "vht_id_inv", $f_vht_id_inv, 
                                          "cr_maxweight", $f_cr_maxweight, "cr_outlay", $f_cr_outlay, "cr_locationzipcode", $f_cr_locationzipcode, "cr_homezipcode", $f_cr_homezipcode,
                                          "cr_available", $f_cr_available, "cr_availabletime", $f_cr_availabletime, "cr_id_parent", $f_cr_id_parent, "cr_vh_sign", $f_cr_vh_sign,
                                          "cr_imei", $f_cr_imei, "cr_mobile_pda", $f_cr_mobile_pda, "cr_serialno", $f_cr_serialno, "cr_disposition", $f_cr_disposition, "cr_price_show", $f_cr_price_show));
              $cr_id_new = getLastInsertId();
              if ($debug) : echo "cr_id_new : " . $cr_id_new . "<br>"; endif;
              // Insert address                
              $tmpArray = insertAddress($f_ad_street, $f_ad_zipcode, $f_ad_city, "", $f_ad_country, $noValidationOfAddress);
              $ad_id_new = $tmpArray[0];
              if ($debug) : echo "ad_id_new : " . $ad_id_new . "<br>"; endif;
              // Update (the new) company-entry with address-id
              updateStmt("company", "cmp_id", $cmp_id_new, array("ad_id", $ad_id_new));

              // Insert into asset if enabled
              $as_id_new = 0;
              $parAssetsEnabled = getParameterValue("0", "ASSET_MANAGEMENT_ENABLED", "0");
              if ($parAssetsEnabled == "1") :
                 // The courier by himself is an employee from viewpoint of his parent, if does exist. (<=> as_obj_id = $cr_id_parent and as_ref_obj_id = $cr_id_new)
                 // Otherwise the courier will be an operational asset by himself. (<=> as_obj_id = $cr_id_new = as_ref_obj_id) (!!!!)
                 $tmpParentId = $cr_id_new;
                 if ($f_cr_id_parent != "" && is_numeric($f_cr_id_parent) && $f_cr_id_parent > "0") :
                    $tmpParentId = $f_cr_id_parent;
                 endif;
                 $asArr = array("as_obj_type" => "cr", "as_obj_id" => $cr_id_new, "as_location" => $f_ad_zipcode, "as_weekdays" => $f_cr_weekdays,
                                "asr_type" => "owner", "ref_type" => "cr", "ref_id" => $f_cr_id_parent);
                 $resArr = insertAsset($asArr);
                 $as_id_new = $resArr[0];
                 $as_id_ref_new = $resArr[1];
              endif;
              if ($debug) : echo "as_id_new : " . $as_id_new . "<br>"; endif;
              if ($debug) : echo "as_id_ref_new : " . $as_id_ref_new . "<br>"; endif;

              // Automatischer E-Mail-Versand eines systemgenerierten Passwortes ???


              /* 
              // ********** DPF **********
  
              // Check according to personal embargo
              // (NOT included in transaction)
              $constDPFCourierEnabled = getParameterValue("0", "DPF_CR_ENABLED", "0");  // "Meta-Global" <=> hq_id = 0
              if ($constDPFCourierEnabled == '1') :
                 $execEmbargoCheck = "1";
                 $cmpId = $cmp_id_new;
                 $eid = $f_cr_eid;
                 $usrName = $f_usr_name;
                 $usrFirstname = $f_usr_firstname;
                 $adStreet = $f_ad_street;
                 $cmpHsno = $f_cmp_hsno;
                 $adZipcode = $f_ad_zipcode;
                 $adCity = $f_ad_city;
                 // = $f_ad_country;
                 
                 // Check for DPF checksum
                 $oldDpfChecksum = "";
                 $newDpfChecksum = md5($usrFirstname . $usrName . $adStreet . $cmpHsno . $adZipcode . $adCity);
                 updateStmt("company", "cmp_id", $cmp_id_new, array("cmp_dpf_checksum", $newDpfChecksum));
              endif;
  
  
              // ********** HASH **********
              // Check for execute functionality
              if ($GLOBAL_USAGE_HASH) :
                 // Get current global number of THIS database instance
                 $constGlobalDbInstNo = getParameterValue("0", "GLOBAL_UNIQUE_DB_INSTANCE_NO", "0", "0");
                 if ($constGlobalDbInstNo != "" && is_numeric($constGlobalDbInstNo)) :
                    // Generate unique hash value e.g. for newsletter of the courier
                    $tmpHashCR = makeMD5Hash($hqId, $cr_id_new, $currentTime);
                    // Generate unique hash value e.g. for timetracking of the user
                    $tmpHashUSR = makeMD5Hash($hqId, $usr_id_new, $currentTime);
                 
                    // Get database instance connection data of metaobject
                    $constExtDbInst = getExternalMetaDbInst();
                    $db_conn = getDbConnectionSpecial($constExtDbInst, $dbname, $dblogin, $dbpassword);
                    $tmpSqlQuery = "INSERT meta_object.metaobject (mo_id_ref_db,mo_obj_type,mo_obj_id,mo_hash) VALUES ('" . $constGlobalDbInstNo . "','cr','" . $cr_id_new . "','" . $tmpHashCR . "') ";
                    $result = $db_conn->query($tmpSqlQuery);
                    $err = "";
                    if (DB::isError($result)) {$err = "ERR";};
                    if ($err == "ERR") :
                       // Message to system administrator...
                       // $statusMessage = getLngt("Message to system administrator...!");
                    endif;
  
                    $tmpSqlQuery = "INSERT meta_object.metaobject (mo_id_ref_db,mo_obj_type,mo_obj_id,mo_hash) VALUES ('" . $constGlobalDbInstNo . "','usr','" . $usr_id_new . "','" . $tmpHashUSR . "') ";
                    $result = $db_conn->query($tmpSqlQuery);
                    $err = "";
                    if (DB::isError($result)) {$err = "ERR";};
                    if ($err == "ERR") :
                       // Message to system administrator...
                       // $statusMessage = getLngt("Message to system administrator...!");
                    endif;
                 endif;
              endif;
              */

              if ($usr_id_new > 0 && $cmp_id_new > 0 && $cr_id_new > 0 && $ad_id_new > 0 && ($parAssetsEnabled != "1" || ($as_id_new > 0 && $as_id_ref_new >= 0))) :
              
                 // Write logdata into log database
                 writeToLogDB("35",$hqId,"",$usr_id,$cr_id_new,"","","STATUS_NEW=" . $logString);

                 if ($retMode = "1") :
                    $retArray = array($cr_id_new, $cmp_id_new, $ad_id_new, $usr_id_new, $as_id_new, $as_id_ref_new);
                 endif;

                 TA("C");

                 $statusMessage = getLngt("Der Datensatz wurde gespeichert!");
                 $retBool = true;
              else :
                 TA("R");

                 $statusMessage = getLngt("Der Datensatz wurde NICHT gespeichert!");
              endif;
  
              // Reset fields of form-parameters
              // clearParameters($httpVisualVars);
           endif;
        endif;
     endif;
     if ($debug) : echo "statusMessage: " . $statusMessage . "<br>"; endif;
  else :
     $statusMessage = getLngt("Bitte geben Sie alle mit * gekennzeichneten Felder ein!");
  endif;
  
  TA("E");
  if ($retMode = "1") :
     return $retArray;
  endif;
  return $retBool;
}


// Make a copy of a specific courier
// $modifyArr is an associative array with the same or a subset of keys being database field names
function copyCourier ($crIdSrc, $modifyArr = array()) {
	global $db, $PHP_SELF;
	global $f_hq_id, $emp_id, $hq_id;
	$retArray = array();
	if ($crIdSrc == "" || !is_numeric($crIdSrc)) :
	   $retArray = array("301","<err_no>301</err_no>\n","<err_desc>" . getLngt("Die Transporteurs-ID ist leer!") . "</err_desc>\n");
	else :
	   // Get data from the source data set	   	   	
	   $cmpIdSrc = getFieldValueFromId("courier","cr_id",$crIdSrc,"cmp_id");
	   $hqIdSrc = getFieldValueFromId("courier","cr_id",$crIdSrc,"hq_id");
	   $crSrcArr = getCourier($cmpIdSrc, "1");
// echo "VORHER:<br>"; print_r($crSrcArr); echo "<br><br>";
     // Special mappings
     if ($modifyArr["cr_eid_prefix"] != "") :
        $crSrcArr["cr_eid"] = $modifyArr["cr_eid_prefix"] . substr($crSrcArr["cr_eid"],4);
     endif;
     if ($modifyArr["cr_sid_prefix"] != "") :
        $crSrcArr["cr_sid"] = $modifyArr["cr_sid_prefix"] . substr($crSrcArr["cr_sid"],-4);
     endif;
     if ($modifyArr["cmp_comp"] == "") :
        $crSrcArr["cmp_comp"] = $crSrcArr["cmp_comp"] . " SL";
     endif;
     if ($modifyArr["usr_account_prefix"] != "") :
        $crSrcArr["usr_account"] = $modifyArr["usr_account_prefix"] . substr($crSrcArr["cr_sid"],-4);
     endif;
     // Dynamic mappings
     if (count($modifyArr) > 0) :
        $modifyKeyArr = array_keys($modifyArr);
        $modifyKeyArrLen = count($modifyKeyArr);
        for ($i = 0; $i < $modifyKeyArrLen; $i++) :
             $crSrcArr[$modifyKeyArr[$i]] = $modifyArr[$modifyKeyArr[$i]];
        endfor;
     endif;
// echo "NACHHER:<br>"; print_r($crSrcArr); echo "<br><br>";
     // * Insert new courier *
     $idArr = insertCourier($crSrcArr, "1");
     if (count($idArr) > 0) :

        // * Copy vehicle *
        global $f_crvh_id,$f_vht_id,$f_crvh_sort,$f_crvh_id_inv,$f_crvh_sid,$f_crvh_comm_no,$f_crvh_vh_sign,$f_crvh_vh_name,$f_crvh_licence_date,$f_crvh_licence_date_year;
        global $f_crvh_licence_date_month,$f_crvh_owner,$f_crvh_owner_month,$f_crvh_owner_year,$f_crvh_env_badge_level,$f_crvh_prov,$f_crvh_payload,$f_crvh_totalweight;
        global $f_crvh_length,$f_crvh_width,$f_crvh_height,$f_crvh_position,$f_crvh_aperture_height_side,$f_crvh_aperture_height_rear,$f_crvh_mobile;
        global $f_crvh_insurance_name,$f_crvh_insurance_no,$f_crvh_filter,$f_crvh_service, $f_crvh_vhd_disabled;
        global $f_crvh_remark,$f_crvh_freetext_1,$f_crvh_special,$f_crvh_corporate_identity,$f_crvh_funding_state, $f_crvh_funding_residual_value;
        global $f_crvh_funding_final_installment, $f_crvh_funding_final_installment_month, $f_crvh_funding_final_installment_year;
        global $f_crvh_pda_usage, $f_crvh_system_fee, $f_crvh_drivetype;
        global $f_crvh_partner_premium, $f_crvh_partner_text, $f_crvh_partner_commission, $f_crvh_advertising_allowance, $f_crvh_transport_insurance_amount;
        global $f_crvh_transport_insurance_date, $f_crvh_business_liability_insurance_amount, $f_crvh_business_liability_insurance_date, $f_crvh_system_fee_amount;

        $crIdNew = $idArr[0];

        // Get the vehicles of a specified courier for selection
        // IMPORTANT: No virtual removed rows (=> clause crvh.crvh_modify_status != '3')
        $currentTime = getDateTime("0");
        $crvhList = getColVectorFromDB2ArrayByClause("couriervehicle", "crvh_id", "cr_id = '" . $crIdSrc . "' AND crvh_modify_status != '3'");
        $crvhListLen = count($crvhList);
        for ($i = 0; $i < $crvhListLen; $i++) :

            // Get source vehicle
            // getVehicle($crvhList[$i], "crvh.cr_id = '" . $crIdSrc . "' AND cr.hq_id = '" . $hqIdSrc . "'");
            getVehicle($crvhList[$i]);

            // Insert new vehicle
            if ($modifyArr["crvh_sid_prefix"] != "") :
               $f_crvh_sid = $modifyArr["crvh_sid_prefix"] . substr($f_crvh_sid,-4);
            endif;
            if ($modifyArr["crvh_comm_no"] == "") :
               $f_crvh_comm_no = "SL" . $f_crvh_comm_no;
            endif;
/*
echo "crvh_id = " . $crvhList[$i] . "<br>";
echo "f_crvh_sid = " . $f_crvh_sid . "<br>";
echo "f_crvh_comm_no = " . $f_crvh_comm_no . "<br>";
echo "f_crvh_partner_premium = " . $f_crvh_partner_premium . "<br>";
echo "f_crvh_advertising_allowance = " . $f_crvh_advertising_allowance . "<br>";
echo "f_crvh_system_fee_amount = " . $f_crvh_system_fee_amount . "<br>";
*/
            insertStmt("couriervehicle", array("vht_id",$f_vht_id, "cr_id", $crIdNew, "crvh_id_inv", $f_crvh_id_inv, "crvh_sort", $f_crvh_sort,
                                               "crvh_sid", $f_crvh_sid, "crvh_comm_no", $f_crvh_comm_no,
                                               "crvh_vh_sign", $f_crvh_vh_sign, "crvh_vh_name", $f_crvh_vh_name,
                                               "crvh_licence_date", $f_crvh_licence_date, "crvh_owner", $f_crvh_owner, 
                                               "crvh_env_badge_level", $f_crvh_env_badge_level, "crvh_prov", $f_crvh_prov, "crvh_payload", $f_crvh_payload, 
                                               "crvh_totalweight", $f_crvh_totalweight, "crvh_length", $f_crvh_length, 
                                               "crvh_width", $f_crvh_width, "crvh_height", $f_crvh_height, 
                                               "crvh_position", $f_crvh_position, "crvh_aperture_height_side", $f_crvh_aperture_height_side, 
                                               "crvh_aperture_height_rear", $f_crvh_aperture_height_rear, "crvh_mobile", $f_crvh_mobile, 
                                               "crvh_insurance_name", $f_crvh_insurance_name, "crvh_insurance_no", $f_crvh_insurance_no, 
                                               "crvh_filter ", $f_crvh_filter, "crvh_service", $f_crvh_service2, "crvh_special", $f_crvh_special, 
                                               "crvh_vhd_disabled", $f_crvh_vhd_disabled, "crvh_corporate_identity", $f_crvh_corporate_identity, 
                                               "crvh_funding_state", $f_crvh_funding_state, "crvh_funding_final_installment", $f_crvh_funding_final_installment, 
                                               "crvh_funding_residual_value", $f_crvh_funding_residual_value,
                                               "crvh_pda_usage", $f_crvh_pda_usage, "crvh_system_fee", $f_crvh_system_fee, "crvh_drivetype", $f_crvh_drivetype,
                                               "crvh_remark ", $f_crvh_remark, "crvh_freetext_1", $f_crvh_freetext_1,
                                               "crvh_partner_premium ", $f_crvh_partner_premium, "crvh_partner_text", $f_crvh_partner_text,
                                               "crvh_partner_commission ", $f_crvh_partner_commission, "crvh_advertising_allowance", $f_crvh_advertising_allowance,
                                               "crvh_transport_insurance_amount ", $f_crvh_transport_insurance_amount, "crvh_transport_insurance_date", $f_crvh_transport_insurance_date,
                                               "crvh_business_liability_insurance_amount ", $f_crvh_business_liability_insurance_amount, "crvh_business_liability_insurance_date", $f_crvh_business_liability_insurance_date,
                                               "crvh_system_fee_amount ", $f_crvh_system_fee_amount,
                                               "crvh_modify_status", "1", "crvh_modify", $currentTime));

            // $f_crvh_id = getLastInsertID();
        endfor;
     endif;
	endif;
	return $retArray;
}


// Get coordinates for the home zipcode with fallback to address zipcode
function setCrHomeCoordinatesByZipcode ($zipcode = "", $adZipcode = "", $objId = "", $objType = "cr") {
	global $db, $PHP_SELF;
  $retArr = array();  
// echo "zipcode = " . $zipcode . " | adZipcode = " . $adZipcode . "&nbsp;&nbsp;<=>&nbsp;&nbsp;";
  if ($zipcode != "" || $adZipcode != "") :
     $crCurrentHomeZipcode = "";
     if ($objId != "" && is_numeric($objId)) :
        if ($objType == "cmp") :
           $objId = getFieldValueFromId("courier", "cmp_id", $objId, "cr_id");
        elseif ($objType == "usr") :
           $objId = getFieldValueFromId("courier", "usr_id", $objId, "cr_id");
        endif;
        // Get current home zipcode of the courier
        $crCurrentHomeZipcode = getFieldValueFromId("courier", "cr_id", $objId, "cr_homezipcode");
     endif;
     if ($zipcode != "") :
        if ($crCurrentHomeZipcode != $zipcode) :
           $retArr = get_coords("DE", $zipcode, ".", ".", ".", true);
        else :
           $retArr[0] = getFieldValueFromId("courier", "cr_id", $objId, "cr_gps_lat_home");
           $retArr[1] = getFieldValueFromId("courier", "cr_id", $objId, "cr_gps_long_home");
        endif;
     else:
       // Home zipcode does not exist, use fallback zipcode of the address
       // Get current address zipcode of the courier
        $crCurrentAddressZipcode = "";        
        if ($objId != "" && is_numeric($objId)) :
           $cmpId = getFieldValueFromId("courier", "cr_id", $objId, "cmp_id");
           $adId = getFieldValueFromId("company", "cmp_id", $cmpId, "ad_id");
           $crCurrentAddressZipcode = getFieldValueFromId("address", "ad_id", $adId, "ad_zipcode");
        endif;
        if ($adZipcode != "" && ($crCurrentAddressZipcode != $adZipcode || $crCurrentHomeZipcode != "")) :
           $retArr = get_coords("DE", $adZipcode, ".", ".", ".", true);
        else :
           $retArr[0] = getFieldValueFromId("courier", "cr_id", $objId, "cr_gps_lat_home");
           $retArr[1] = getFieldValueFromId("courier", "cr_id", $objId, "cr_gps_long_home");
        endif;
     endif;
  endif;
// echo "crCurrentHomeZipcode = " . $crCurrentHomeZipcode . " | crCurrentAddressZipcode = " . $crCurrentAddressZipcode . "&nbsp;&nbsp;<=>&nbsp;&nbsp;<br>";
  return $retArr;
}
?>