<?php

include_once("../include/global.inc.php");
include_once("../include/auth.inc.php");

$usr_type = getFieldValueFromId("user", "usr_id", $usr_id, "usr_type");
if ($usr_type != "1"):
  $die_text = "Keine Berechtigung";
  if ($usr_type == "2"):
    $csc_id = getFieldValueFromId("employee", "usr_id", $usr_id, "csc_id");
    $cs_id = getFieldValueFromId("costcenter", "csc_id", $csc_id, "cs_id");
    if (getParameterValue("0", "MASK_JB_MAP_VIEW_ENABLED_" . $cs_id, "0") != "1"):
      die($die_text);
    endif;
  else:
    die($die_text);
  endif;
endif;

include_once ("../include/image.inc.php");
include_once ("../locating/xServer.inc.php");
$standalone = "1";  // has to be set before including "ranking.inc.php"
include_once ("../include/ranking.inc.php");
$hq_id = $_SESSION['hq_id'];
if ($hq_id == "") : $hq_id = $HTTP_SESSION_VARS['hq_id']; endif;
list ($jb_id) = getHttpVars(array("jb_id"));
if ($jb_id != ""):
  $hq_id = getFieldValueFromId("job", "jb_id", $jb_id, "hq_id");
endif;
include_once ("../locating/map.inc.php");
$allCoords = array();
$today = getdate();

function getCoordsOffset($x, $y) {
	global $allCoords;

  $xx = round($x, 5);
  $yy = round($y, 5);
	
	foreach ($allCoords as $coords) {
		if ($coords[0] == $xx && $coords[1] == $yy):
		  return $coords[2]++;
		endif;
	}
	$allCoords[] = array($xx, $yy, 1);
	return 0;
}

// Makes an image more transparent
function getTransparency2 ($im, $scalingFactorPercent = "0", $imVhtSizeX = "200", $imVhtSizeY = "200") {

   if ($im) :
      // Get size of the original image
      $imSizeX = imagesx($im);
      $imSizeY = imagesy($im);

      // Create a new white temporary image for merging with original image
      // $imTmp = @imagecreate ($imSizeX, $imSizeY) or die ("Cannot Initialize new GD image stream");
      $imTmp = @imagecreate ($imVhtSizeX, $imVhtSizeY) or die ("Cannot Initialize new GD image stream");
      imagecolorallocate ($imTmp, 237, 237, 237);
      // int ImageCopy ( int dst_im, int src_im, int dst_x, int dst_y, int src_x, int src_y, int src_w, int src_h);
      imagecopymerge ( $im, $imTmp, 0, 0, 0, 0, $imSizeX, $imSizeY, $scalingFactorPercent);
//      $index = imagecolorexact($im, 255, 255, 255);
//      imagecolortransparent($im, $index); 
//      $transpCol = imagecolorallocate ($im, 255, 255, 255);
//      imagecolortransparent($im, $transpCol);
   endif;
   
   return $im;
}	

// Display courier image with vehicle icon
function generateVehicleImage ($jb_id, $crSid, $vhtID = "2", $crGpsTime = "00-00-00 00:00:00", $cr_occupied, $cr_locationzipcode) {
  global $hqMnemonic, $searchCrSid, $cancel_man;

//echo $crSid."<br>\n". $vhtID ."<br>\n". $crGpsTime ."<br>\n". $cr_occupied;
  $availCol = "red";
  if ($cr_occupied != 1):
    $availCol = "green";
    if (in_array($crSid, $cancel_man))
      $availCol = "pink";
    for ($i = 0; $i <= 4; $i++):
      if (!is_numeric(substr($cr_locationzipcode, $i, 1))):
        $availCol = "orange";
        break;
      endif;
    endfor;
  endif;
//echo "$crSid, $cr_locationzipcode, $availCol \n";
	
  $vhtFileName = "";
  if ($vhtID == "2") : $vhtFileName = "pkw_" . $availCol . ".png"  ; endif;
  if ($vhtID == "3") : $vhtFileName = "kombi_" . $availCol . ".png"  ; endif;
  if ($vhtID == "4") : $vhtFileName = "kasten_" . $availCol . ".png"  ; endif;
  if ($vhtID == "5") : $vhtFileName = "bus_" . $availCol . ".png"  ; endif;
  if ($vhtID == "6") : $vhtFileName = "grbus_" . $availCol . ".png"  ; endif;
  if ($vhtID == "7") : $vhtFileName = "lkw_" . $availCol . ".png"  ; endif;
  if ($vhtID > "7")  : $vhtFileName = "lkw_" . $availCol . ".png"  ; endif;

  if ($vhtFileName != "") :
     $imVht = @ImageCreateFromPNG ("../images/" . $vhtFileName);
 
     $imVhtSizeX = imagesx($imVht);
     $imVhtSizeY = imagesy($imVht);
  
     // Set transparency of the vehicle icon
     $currSeconds = mktime(date("H"), date("i"), date("s"), date("m"), date("d"), date("Y"));
     $crGpsTimeSeconds = mktime(substr($crGpsTime,11,2), substr($crGpsTime,14,2), substr($crGpsTime,17,2), substr($crGpsTime,5,2), substr($crGpsTime,8,2), substr($crGpsTime,0,4));
     $diffMinutes = (($currSeconds - $crGpsTimeSeconds) / 60);
     $transparencyScaleVehicleIcon = min((floor($diffMinutes / 15) * 10) - 10, 80);
     // $boxPointsArray = imagettftext ($im, 10, 0, 300, 500, $lineColBlack, $textFontPath, $transparencyScaleVehicleIcon);
     // setTextBox ($im, $boxPointsArray, "2", $lineColBlack);
     if ($transparencyScaleVehicleIcon > 0) :
        $imVht = getTransparency2($imVht, $transparencyScaleVehicleIcon, $imVhtSizeX, $imVhtSizeY);
     endif;

     // Search for a special vehicle
     if ($searchCrSid != "" && strtolower($crSid) == strtolower($searchCrSid)) :
        // Zuppel the box ... :-)
        $boxPointsArray[0] += 2; $boxPointsArray[5] += 2; $boxPointsArray[6] += 2; $boxPointsArray[7] += 2;

        $lineColRed = imagecolorallocate ($imVht, 255, 0, 0);
        setTextBox ($imVht, $boxPointsArray, "2", $lineColRed);
     endif;

     $imMark = @ImageCreateFromPNG ("../images/marker_white_big.png");     
     imagealphablending($imMark, true);
     imagesavealpha($imMark, true);

     $lineCol = imagecolorallocate ($imMark, 0, 0, 0);
     $crSidNo = ereg_replace("[^[:digit:]+]","",$crSid);
     imagettftext ($imMark, 8, 0, 10, 12, $lineCol, "../include/arial.ttf", $crSidNo);     
     
     $posx = (imagesy($imMark) - $imVhtSizeX) / 2 + 2;
     $posy = (imagesx($imMark) - $imVhtSizeY) / 2 + 2;
     imagecopy($imMark, $imVht, $posx, $posy, 0, 0, $imVhtSizeX, $imVhtSizeY);
     imagepng($imMark, "../temp/captchas/" . $jb_id . $crSid . ".png");
     return array($imVhtSizeX, $imVhtSizeY);
  endif;
}

function generateStationImage ($jb_id, $tr_sort, $tr_status) {
  $imgFilename = "../temp/captchas/" . $jb_id . "-" . $tr_sort . ".png";

  $imMark = ($tr_status == 1 ? @ImageCreateFromPNG ("../images/marker_green.png") : @ImageCreateFromPNG ("../images/marker_red.png"));
  imagealphablending($imMark, true);
  imagesavealpha($imMark, true);
  $lineCol = imagecolorallocate ($imMark, 0, 0, 0);
  $x = 11;
  if ($tr_sort > 9)
    $x = 8;
  imagettftext ($imMark, 8, 0, $x, 14, $lineCol, "../include/arial.ttf", $tr_sort);
  imagepng($imMark, $imgFilename);

  return $imgFilename;
}

$errorMsg = "";

$hq_marker = "../images/marker_sb.png";
if ($hq_id >= 100)
  $hq_marker = "../images/marker_ht.png";
$lat = 0;
$long = 0;

// Zentrale
$sqlquery = "SELECT hq_gps_long, hq_gps_lat FROM headquarters WHERE hq_id = '$hq_id'";
$markers_javascript = "";
$res = $db->query($sqlquery);
if (DB::isError($res))
  die ("$PHP_SELF: '$sqlquery' : " . $res->getMessage());
if ($row = $res->fetch_assoc()):
  $lat = $row["hq_gps_lat"];
  $long = $row["hq_gps_long"];
  $markers_javascript .= "setMarker($long, $lat, '$hq_marker', size1, offset1, popupSize1, '&nbsp;Zentrale', 'central');\n";
endif;
$res->free();

// Wenn ein Auftrag angegeben und dieser bereits einen Fahrer hat, dann nur diesen in die Liste der Fahrer übernehmen
$cr_sid = "";
$customer_special = false;
if ($usr_type == 2 || $usr_id == 10041): //HTM18156 || admin_m
  $cr_sid = getParameterValue("0", "MASK_JB_MAP_VIEW_COURIERS_" . $cs_id, "0");
  if ($usr_id == 10041)
    $cr_sid = "M047','M048','M072','M099";
  $customer_special = true;
endif;

$cancel_man = array();
if ($jb_id != ""):
  $jb_status_clause = " AND NOT (jb_status IN (8,9))";
  if ($usr_type == 2)
    $jb_status_clause = " AND jb_status = 1";
  $sqlquery = "SELECT cr_id, cr_sid, hq_id FROM job WHERE jb_id = '$jb_id'" . $jb_status_clause;
//echo $sqlquery . "<br>\n";
  $res = $db->query($sqlquery);
  if (DB::isError($res))
    die ("$PHP_SELF: '$sqlquery' : " . $res->getMessage());
  if ($row = $res->fetch_assoc()):
    $cr_id = trim($row["cr_id"]);
    $cr_sid = trim($row["cr_sid"]);
    $hq_id = trim($row["hq_id"]);
  endif;
  $res->free();
  // die ablehnenden Fahrer (logo_id = 11) sollen in einer anderen Farbe aufgeführt werden
  // Testaufträge: SELECT *, COUNT(*) FROM log, phoenix.job WHERE logo_id = 11 AND phoenix_log.log.hq_id = 3 AND log_createtime > "2016-11-03 00:00:00" AND phoenix_log.log.jb_id = phoenix.job.jb_id AND phoenix.job.jb_status = 9 GROUP BY phoenix.job.jb_id
  $sqlquery = "SELECT cr_sid FROM phoenix_log.log WHERE jb_id = " . $jb_id . " AND logo_id = 11";
  $res = $db->query($sqlquery);
  if (DB::isError($res)) reportDie ("$PHP_SELF: '$sqlquery'" . $res->getMessage());
  while ($row = $res->fetch_assoc()):
    $cancel_man[] = $row["cr_sid"];
  endwhile;
  $res->free();
endif;

//$is_occupied = array();
//$sqlQuery = "SELECT DISTINCT cr_sid FROM job WHERE jb_status = 1";
//$res = $db->query($sqlQuery);
//if (DB::isError($res)) reportDie ("$PHP_SELF: '$sqlQuery': " . $res->getMessage());
//while ($row = $res->fetch_assoc()):
//  $is_occupied[$row["cr_sid"]] = 1;
//endwhile;
//$res->free();

$hq_id_refresh = $hq_id;
if ($cr_sid == ""):
  list ($cr_sid) = getHttpVars(array("cr_sid"));
  $hq_id_refresh = 0;
endif;
$sqlquery = "SELECT cr_sid, vht_id, cr_locationzipcode, cr_available, cr_availabletime, cr_gps_long, cr_gps_lat, cr_gps_time, cr_gps_type, cr_mobile_pda, usr_phone, usr_phone2 FROM courier, user WHERE courier.hq_id = '$hq_id' AND (cr_sid != '' AND NOT(cr_sid IS NULL)) AND cr_gps_time > '" . $start_time . "' AND courier.usr_id = user.usr_id"; //AND cr_available = 1 ORDER BY cr_gps_time, cr_sid";
$show_couriers = 1;
if (trim($cr_sid) != "" || $usr_type == "2"):
  $sqlquery = "SELECT cr_sid, vht_id, cr_locationzipcode, cr_availabletime, cr_gps_long, cr_gps_lat, cr_gps_time, cr_gps_type, cr_mobile_pda, usr_phone, usr_phone2 FROM courier, user WHERE cr_sid IN ('$cr_sid') AND cr_gps_time > '" . $start_time . "' AND courier.usr_id = user.usr_id";
  if ($jb_id != ""):
    $locatingStateArray = checkLocatingState($cr_id);
    if ($locatingStateArray[0] == "1")
      $show_couriers = 0;
  endif;
endif;
//echo $sqlquery . "<br>\n";
$res = $db->query($sqlquery);
if (DB::isError($res)) die ("$PHP_SELF: '$sqlquery' : " . $res->getMessage());

$i = 1;
$cr_sid_list = "";
while ($row = $res->fetch_assoc()):
  $imgSize = generateVehicleImage($jb_id, $row["cr_sid"], $row["vht_id"], $row["cr_gps_time"], $is_occupied[$row["cr_sid"]], $row["cr_locationzipcode"]);
  $markers_javascript .=
    ($jb_id != "" && $usr_type == "1"
    ? "if (typeof vht_id_str['" . $row["cr_sid"] . "'] != 'undefined' && !cr_sid_is_blocked('" . $row["cr_sid"] . "'))\n"
    : "") .
    "  setMarker(". $row["cr_gps_long"] . ", " . $row["cr_gps_lat"] . ", '../temp/captchas/" . $jb_id . $row["cr_sid"] . ".png', size2.clone(), offset2.clone(), popupSize2.clone(),\n" .  
    mk_text($row["cr_locationzipcode"], $row["cr_availabletime"], $row["cr_gps_time"], $row["cr_gps_type"], $row["cr_available"], $row["cr_sid"], $row["vht_id"], $row["cr_mobile_pda"], $row["usr_phone"], $row["usr_phone2"], $jb_id) .
    ", 'couriers');\n";
  $cr_sid_list .= ($cr_sid_list == "" ? "\'" : ",\'") . $row["cr_sid"] . "\'";
  if (trim($cr_sid) != ""):
    $lat = $row["cr_gps_lat"];
    $long = $row["cr_gps_long"];
  endif;
endwhile;
$res->free();

// Stationen eines Auftrages
if ($jb_id != ""):
  $sqlquery = "SELECT ad_street, ad_zipcode, ad_city, ad_country, tr_sort, tr_comp, tr_comp2, tr_hsno, tr_remark, tr_person, tr_phone, tr_status, tr_sign, tr_signname, tr_ware_from_to, " .
    "tr_finishtime, tr_commission_no, tr_status, tr_finishtime FROM tour, address WHERE jb_id = $jb_id AND tour.ad_id = address.ad_id ORDER BY tr_sort";
  $res = $db->query($sqlquery);
  if (DB::isError($res)) die ("$PHP_SELF: '$sqlquery' : " . $res->getMessage());
  while ($row = $res->fetch_assoc()):
    $imgFilename = generateStationImage($jb_id, $row["tr_sort"], $row["tr_status"]);
    $coords = XSfindAddress($row["ad_country"], $row["ad_zipcode"], $row["ad_city"], $row["ad_street"], $row["tr_hsno"]);
    if ($coords[0][0] != 100):
//      $errorMsg .= "&nbsp;Fehlerhafte Adresse in Station [" . $row["tr_sort"] . "]: [" .
//        $row["ad_zipcode"] . " " . $row["ad_city"] . " " . $row["ad_street"] . " " . $row["tr_hsno"] . "]\n";
    else:
      $finishMsg = "<br>\\nNoch nicht erledigt";
      if ($row["tr_status"] == 1):
        $finishMsg = "<br>\\nErledigt um " . formDate($row["tr_finishtime"]);
      endif;
      $offsetAdd = getCoordsOffset($coords[0][1], $coords[0][2]) * 13;
      $markers_javascript .= "var specialOffset" . $row["tr_sort"] . " = new OpenLayers.Pixel(" . (-9 + $offsetAdd) . ", " . (-28 + ($offsetAdd * -1)) . ");\n";
      $markers_javascript .= "setMarker(". $coords[0][1] . ", " . $coords[0][2] . ", '$imgFilename', size3.clone(), specialOffset" . $row["tr_sort"] . ", popupSize3.clone(),\n" .  
         "  '<center>" . str_replace("'", "\'", $row["tr_comp"]) . " " . str_replace("'", "\'", $row["tr_comp2"]) . "<br>\\n" . str_replace("'", "\'", $row["ad_street"]) . " " . str_replace("'", "\'", $row["tr_hsno"]) . "<br>\\n" . str_replace("'", "\'", $row["ad_zipcode"]) . " " . str_replace("'", "\'", $row["ad_city"]) . "<br>\\n" . $finishMsg . "</center>', 'stations');\n";
    endif;
  endwhile;
  $res->free();
endif;

$sqlquery = "SELECT ad_street, ad_zipcode, ad_city, ad_country, stk_name, stk_hsno FROM stock, address WHERE stock.ad_id > 0 AND stock.ad_id = address.ad_id";
$res = $db->query($sqlquery);
if (DB::isError($res)) die ("$PHP_SELF: '$sqlquery' : " . $res->getMessage());
while ($row = $res->fetch_assoc()):
  $imgFilename = "../images/marker_stock.png";
  $coords = XSfindAddress($row["ad_country"], $row["ad_zipcode"], $row["ad_city"], $row["ad_street"], $row["stk_hsno"]);
  if ($coords[0][0] != 100):
//    $errorMsg .= "&nbsp;Fehlerhafte Adresse in Lager [" . $row["stk_name"] . "]: [" .
//      $row["ad_zipcode"] . " " . $row["ad_city"] . " " . $row["ad_street"] . " " . $row["stk_hsno"] . "]\n";
  else:
  $markers_javascript .= "setMarker(". $coords[0][1] . ", " . $coords[0][2] . ", '$imgFilename', size3.clone(), offset3.clone(), popupSize3.clone(),\n" .  
       "  '<center>" . $row["stk_name"] . "<br>\\n" . $row["ad_street"] . " " . $row["stk_hsno"] . "<br>\\n" . $row["ad_zipcode"] . " " . $row["ad_city"] . "<br>\\n</center>', 'stocks');\n";
  endif;
endwhile;
$res->free();
//echo $_SERVER['HTTP_USER_AGENT'];
//$heightCorr = 0;
//$widthCorr = 0;
$heightCorr = 120;
$widthCorr = 4;
if(stristr($_SERVER['HTTP_USER_AGENT'], 'Firefox/4')):
  $heightCorr = 139;
  $widthCorr = 4;
endif;
if(stristr($_SERVER['HTTP_USER_AGENT'], 'Firefox/3')):
  $heightCorr = 140;
  $widthCorr = 5;
endif;
if(stristr($_SERVER['HTTP_USER_AGENT'], 'Firefox/2')):
  $heightCorr = 116;
  $widthCorr = 4;
endif;
if(stristr($_SERVER['HTTP_USER_AGENT'], 'Firefox/20')):
  $heightCorr = 120;
  $widthCorr = 4;
endif;

//echo $heightCorr;
//echo $widthCorr;

?>

<html>
<head>
<title>KARTENDARSTELLUNG
<?php
if ($jb_id != ""):
  echo " Auftrag Nr. " . $jb_id;
endif;
?>
</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta name="description" content="votian"> <meta name="keywords" content="votian"><link rel="stylesheet" type="text/css" href="../css/phoenix.css">
<script src="../js/jquery.js"></script>
<!--
<script src="http://www.openlayers.org/api/OpenLayers.js"></script>
-->
<script src="../include/openlayers/OpenLayers.js"></script>
<!--
<script src="http://www.openstreetmap.org/openlayers/OpenStreetMap.js"></script>
<script src='http://maps.google.com/maps?file=api&amp;v=2&amp;key=ABQIAAAA3HdfrnxFAPWyY-aiJUxmqRTJQa0g3IQ9GZqIMmInSLzwtGDKaBQ0KYLwBEKSM7F9gCevcsIf6WPuIQ'></script>
<script src="http://api.maps.yahoo.com/ajaxymap?v=3.0&appid=euzuro-openlayers"></script>
-->
<?php
if ($jb_id != "")
  echo
    "<script src=\"../include/lib_courier.js\" type=\"text/javascript\"></script>" .
    "<script type=\"text/javascript\">\n" .
    "<!--\n" .
    "var vht_id_str = new Array();\n" .
    $vht_id_str_js .
    $cr_id_order_list_blocked_js .
    "function setCourier(jb_id,cr_sid)\n" .
    "{\n" .
    "  addmsg = vht_id_str[cr_sid];\n" .
//    "  var penalty = 0;" .
//    "  if (this.document.reset_cr_availabletime_form.reset_cr_availabletime.checked) {" .
//    "    addmsg = \"\n(Freimeldezeit von \" + this.document.reset_cr_availabletime_form.cur_cr_sid.value + \" wird aktualisiert)\" +  addmsg;" .
//    "    penalty = 1;" .
//    "  }" .
    "  if (confirm(\"Auftrag \" + jb_id + \" dem Transporteur \" + cr_sid + \" zuweisen?\" + addmsg)) {\n" .
//    "    this.opener.setCourier(jb_id,cr_sid,penalty);" .
//    "    alert ('../include/ajaxReqMap.php' + '&cr_sid=' + cr_sid + '&hq_id=' + hq_id + '&customer_special=$customer_special' + '&jb_id=$jb_id' + '&f_act=setCourier');\n" .
    "    ajaxRequestGet('../include/ajaxReqMap.php', 'cr_sid=' + cr_sid + '&hq_id=' + hq_id + '&customer_special=$customer_special' + '&jb_id=$jb_id' + '&f_act=setCourier');\n" .
    "    self.close();\n" .
    "  };\n" .
    "};\n" .
    "function cr_sid_is_blocked(cr_sid)\n" .
    "{\n" .
    "  for (var i = 0; i < cr_id_order_list_blocked.length; i++)\n" .
    "    if (cr_id_order_list_blocked[i] == cr_sid)\n" .
    "      return true;\n" .
    "  return false;\n" .
    "}\n" .
    "-->\n\n" .
    "</script>\n";
?>
<noscript>
  <center>
  <b><br>JavaScript ist nicht verf&uuml;gbar. Bitte aktivieren Sie JavaScript<br><br>
        in Ihrem Browser, damit diese Seite ordnungsgem&auml;&szlig; funktioniert!</b><br><br>
  </center>
</noscript>
</head>
<body>

<div style="display: table; height: 100%; #position: relative; overflow: hidden; margin:auto;">
<div style=" #position: absolute; #top: 50%;display: table-cell; vertical-align: middle;">
<div style=" #position: relative; #top: -50%; border: 2px solid black;">
<div id="map" style="width:1007px; height:675px; vertical-align:middle;">

<script type="text/javascript">

// JQuery.Request (GET)
function ajaxRequestGet(url, data) {
  $.ajax({
     type: "GET",
     url: url,
     data: data,
     async: false,
     cache: false,
     success: function(msg){eval(msg);}
  });
}

function popupWindow(url,title,config) {

  var widthPopupWin = screen.width - 80;
  var heightPopupWin = screen.height - 180;
  var leftPopupWin = (screen.width / 2) - (widthPopupWin / 2);
  var topPopupWin = (screen.height / 2) - (heightPopupWin / 2);
  var popup;
  popup = window.open(url,title,
    "dependent=yes,width=" + widthPopupWin + ",height=" +
    heightPopupWin +",left=" + leftPopupWin + ",top=" + topPopupWin +
    ",scrollbars=yes");  
  
}

/********************************************************************************/
// Quelle für event-handling: http://forum.openstreetmap.org/viewtopic.php?id=5537
function setMarker(lon, lat, markerFile, iconSize, offset, popupSize, txt, layerName){

  var icon = new OpenLayers.Icon(markerFile, iconSize, offset);
  var lonLat = new OpenLayers.LonLat(lon, lat).transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject());
  var popup = new OpenLayers.Popup.AnchoredBubble("chicken", lonLat, popupSize, txt, icon, true);
  var feature = new OpenLayers.Feature(layerName, lonLat.clone(), popup);
  feature.closeBox = true;
//    feature.popupClass = OpenLayers.Class(OpenLayers.Popup.AnchoredBubble);
//    feature.data.size = new OpenLayers.Size(100, 80);
//    feature.data.popupContentHTML = txt;
//    feature.data.overflow = "hidden";
  var marker = new OpenLayers.Marker(lonLat.clone(), icon.clone());
  marker.feature = feature;
  var markerClick = function(evt) {
    if (this.popup == null) {
        this.popup = this.createPopup(this.closeBox);
        map.addPopup(this.popup);
        this.popup.setSize(popupSize.clone());
        this.popup.setContentHTML(txt);
        this.popup.show();
    } else {
        this.popup.toggle();
    }
    OpenLayers.Event.stop(evt);
  };
  marker.events.register("mousedown", feature, markerClick);
  if (layerName == 'central')
    central.addMarker(marker);
  if (layerName == 'couriers')
    couriers.addMarker(marker);
  if (layerName == 'stations')
    stations.addMarker(marker);
  if (layerName == 'stocks')
    stocks.addMarker(marker);
}

var crSidList = <?php echo "'" . $cr_sid_list . "'"; ?>;
var hq_id = <?php echo "'" . $hq_id_refresh . "'"; ?>;
var prevRetValue = new Array();

function updateLayer(layerName) {
	var tmpMarker;
	var tmpUrl;
	var tmpArr;
	var crSid;

//alert ('../include/ajaxReqMap.php?cr_sid=' + crSidList + '&hq_id=' + hq_id + '&customer_special=<?php echo $customer_special; ?>' + '&jb_id=<?php echo $jb_id; ?>' + '&f_act=');
  ajaxRequestGet('../include/ajaxReqMap.php', 'cr_sid=' + crSidList + '&hq_id=' + hq_id + '&customer_special=<?php echo $customer_special; ?>' + '&jb_id=<?php echo $jb_id; ?>' + '&f_act=');

//console.log(couriers.markers.length);
  for (var i = 0; i < couriers.markers.length; i++) {
//console.log(i);
  	tmpMarker = couriers.markers[i];
  	tmpUrl = tmpMarker.icon.url;
//console.log(tmpUrl);
    tmpArr = tmpUrl.split("/");
//console.log(tmpArr[tmpArr.length - 1]);
    if (tmpArr[tmpArr.length - 1].length > 12)
      crSid = tmpArr[tmpArr.length - 1].substr(8, tmpArr[tmpArr.length - 1].length - 12);
    else
      crSid = tmpArr[tmpArr.length - 1].substr(0, tmpArr[tmpArr.length - 1].length - 4);
//console.log(crSid);
    if (typeof prevRetValue[crSid] == "undefined") {
    	prevRetValue[crSid] = new Array(0);
    }
    if (prevRetValue[crSid][0] != retValue[crSid][0]) {
      couriers.removeMarker(tmpMarker);
      tmpMarker.feature.destroy();
      tmpMarker.destroy();
      setMarker(retValue[crSid][2], retValue[crSid][1], tmpUrl, size2.clone(), offset2.clone(), popupSize2.clone(), retValue[crSid][3], 'couriers');
      prevRetValue[crSid][0] = retValue[crSid][0];
    }
  }
//console.log("setTimeout");
  self.setTimeout("updateLayer('couriers')", 10000);
}

/********************************************************************************/

document.getElementById('map').setAttribute('style', 'width:' + (screen.availWidth - <?php echo $widthCorr; ?>) + '; height:' + (screen.availHeight - <?php echo $heightCorr; ?>) + '; vertical-align:middle;');

var lon = <?php echo $long; ?>;
var lat = <?php echo $lat; ?>;
var zoom = 11;
var map = new OpenLayers.Map('map',
    { controls:
      [ new OpenLayers.Control.KeyboardDefaults(),
        new OpenLayers.Control.MouseDefaults(),
        new OpenLayers.Control.LayerSwitcher(),
        new OpenLayers.Control.PanZoomBar(),
        new OpenLayers.Control.ScaleLine(),
        new OpenLayers.Control.MousePosition(),
        new OpenLayers.Control.Attribution()
      ],
      maxExtent: new OpenLayers.Bounds(-20037508.34,-20037508.34,20037508.34,20037508.34),
      restrictedExtent: new OpenLayers.Bounds(-1337508.34, 4037508.34, 4837508.34, 9037508.34),
      maxResolution: 156543.0399,
//      minScale: 100000,
//      maxScale: 10000000,
//      numZoomLevels: 13,
      units: 'm',
      projection: new OpenLayers.Projection("EPSG:900913"),
      displayProjection: new OpenLayers.Projection("EPSG:4326")
    });
//var mapnik_layer = new OpenLayers.Layer.OSM.Mapnik("OSM Mapnik");
//var tah_layer = new OpenLayers.Layer.OSM.Osmarender("OSM Tiles@Home");
//var google_layer = new OpenLayers.Layer.Google("Google Streets", {'sphericalMercator': true});
// add Bing layer
//var yahoo_layer = new OpenLayers.Layer.Yahoo("Yahoo Street", {'sphericalMercator': true});
//map.addLayers([yahoo_layer, mapnik_layer, tah_layer]);
//map.addLayers([mapnik_layer, yahoo_layer]);
map.addLayers([
  new OpenLayers.Layer.OSM("Google Streets",
    ["https://mt0.google.com/vt/lyrs=m&x=${x}&y=${y}&z=${z}", "https://mt1.google.com/vt/lyrs=m&x=${x}&y=${y}&z=${z}", "https://mt2.google.com/vt/lyrs=m&x=${x}&y=${y}&z=${z}", "https://mt3.google.com/vt/lyrs=m&x=${x}&y=${y}&z=${z}"],
    { attribution: '' } )
]);
map.addLayers([
  new OpenLayers.Layer.OSM("Google Hybrid",
    ["https://mt0.google.com/vt/lyrs=s,h&x=${x}&y=${y}&z=${z}", "https://mt1.google.com/vt/lyrs=s,h&x=${x}&y=${y}&z=${z}", "https://mt2.google.com/vt/lyrs=s,h&x=${x}&y=${y}&z=${z}", "https://mt3.google.com/vt/lyrs=s,h&x=${x}&y=${y}&z=${z}"],
    { attribution: '' } )
]);
map.addLayers([
  new OpenLayers.Layer.OSM("OSM Mapnik",
    ["https://a.tile.openstreetmap.org/${z}/${x}/${y}.png", "https://b.tile.openstreetmap.org/${z}/${x}/${y}.png", "https://c.tile.openstreetmap.org/${z}/${x}/${y}.png"],
    { attribution: "&copy; <a href=\"http://osm.org/copyright\">OpenStreetMap</a> contributors" } )
]);
map.addLayers([
  new OpenLayers.Layer.OSM("OSM Mapnik german style",
    ["https://a.tile.openstreetmap.de/tiles/osmde/${z}/${x}/${y}.png", "https://b.tile.openstreetmap.de/tiles/osmde/${z}/${x}/${y}.png", "https://c.tile.openstreetmap.de/tiles/osmde/${z}/${x}/${y}.png"],
    { attribution: '<a href="http://www.openstreetmap.org/">Karte hergestellt aus OpenStreetMap-Daten</a> | Lizenz: <a rel="license" href="http://opendatacommons.org/licenses/odbl/">Open Database License (ODbL)</a>' } )
]);

map.setCenter (new OpenLayers.LonLat(lon, lat).transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject()), zoom);

//var newll = new OpenLayers.Layer.Text( "PLZs", { location:"zipcode.txt", projection: new OpenLayers.Projection("EPSG:4326") } );
//map.addLayer(newll);

//OpenLayers.Lang.setCode("de");
//alert (OpenLayers.Lang.getCode());

var central = new OpenLayers.Layer.Markers("Zentrale");
map.addLayer(central);
var couriers = new OpenLayers.Layer.Markers("Transporteure");
map.addLayer(couriers);
<?php
if ($jb_id != ""):
  echo "var stations = new OpenLayers.Layer.Markers(\"Stationen\");";
  echo "map.addLayer(stations);";
endif;
?>
var stocks = new OpenLayers.Layer.Markers("Läger");
map.addLayer(stocks);

var size1 = new OpenLayers.Size(28,28);
var popupSize1 = new OpenLayers.Size(60,20);
var offset1 = new OpenLayers.Pixel(-9, -28);
var size2 = new OpenLayers.Size(42,39);
var popupSize2 = new OpenLayers.Size(165,130);
var offset2 = new OpenLayers.Pixel(-6, -38);
var size3 = new OpenLayers.Size(28,28);
var popupSize3 = new OpenLayers.Size(140,118);
var offset3 = new OpenLayers.Pixel(-9, -28);

<?php echo $markers_javascript; ?>

central.setVisibility(false);
<?php
if ($jb_id != "" && $show_couriers == 0):
  echo "couriers.setVisibility(false);";
endif;
?>
stocks.setVisibility(false);

<?php
if ($jb_id != ""):
  echo "map.zoomToExtent(stations.getDataExtent());";
else:
  echo "map.zoomToExtent(couriers.getDataExtent());";
endif;
?>

self.setTimeout("updateLayer('couriers')", 10000);

</script>

<script type="text/javascript">

function clearSearchCrSid() {	
  document.forms[0].searchCrSid.value='';
};

</script>

</div>
</div>
<!--
<form action="../locating/map_courier.php" method="post">
-->
  <div>
<center>	
  	&nbsp; <?php echo $errorMsg ?>
<!--
    <input type="submit" value="Aktualisieren">
-->
<center>
  </div>
<!--
</form>
-->
</div>
</div>

</body>
</html>
