//FIRST, TELL THE BROWSERS TO REACT TO THE EVENT
//http://www.howtocreate.co.uk/tutorials/index.php?tut=0&part=17
if( document.captureEvents ) {
    //non IE
    if( Event.KEYUP ) {
        //NS 4, NS 6+, Mozilla 0.9+
        document.captureEvents( Event.KEYUP );
    }
}
/* this next line tells the browser to detect a keyup
event over the whole document and when it detects it,
it should run the event handler function 'alertkey' */
document.onkeyup = function (e) {
    if( !e ) {
        //if the browser did not pass the event information to the
        //function, we will have to obtain it from the event register
        if( window.event ) {
            //DOM
            e = window.event;
        } else {
            //TOTAL FAILURE, WE HAVE NO WAY OF REFERENCING THE EVENT
            return;
        }
    }
    if( typeof( e.which ) == 'number' ) {
        //NS 4, NS 6+, Mozilla 0.9+, Opera
        e = e.which;
    } else if( typeof( e.keyCode ) == 'number'  ) {
        //IE, NS 6+, Mozilla 0.9+
        e = e.keyCode;
    } else if( typeof( e.charCode ) == 'number'  ) {
        //also NS 6+, Mozilla 0.9+
        e = e.charCode;
    } else {
        //TOTAL FAILURE, WE HAVE NO WAY OF OBTAINING THE KEY CODE
        return;
    }
    //window.alert('The key pressed has keycode ' + e + ' and is key ' + String.fromCharCode( e ) );
}

      function MoreControl() {}
      MoreControl.prototype = new GControl();

      MoreControl.prototype.initialize = function(map) {
        var container = document.createElement("div");
        container.style.border = "2px solid black";
        container.style.fontSize = "12px";
        container.style.fontFamily = "Arial, sans-serif";
        container.style.width="80px";
        container.style.backgroundColor = "#ffffff";
        container.style.color="#000000";
        container.style.textAlign = "center";
        container.innerHTML = "Mehr...";

        map.getContainer().appendChild(container);

        GEvent.addDomListener(container, "mouseover", function() {
          map.addControl(layerControl);
        });

        return container;
      }

      MoreControl.prototype.getDefaultPosition = function() {
        return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(210, 7));
      }

      // ==== The "Layer" control displays the "More..." plus the checkboxes ====
      // ==== The checkbox info is passed in the "opts" parameter ====
      function LayerControl(opts) {
        this.opts = opts;
      }
      LayerControl.prototype = new GControl();

      LayerControl.prototype.initialize = function(map) {
        var container = document.createElement("div");

        container.style.border = "2px solid black";
        container.style.fontSize = "12px";
        container.style.fontFamily = "Arial, sans-serif";
        container.style.width="90px";
        container.style.color="#000000";
        container.style.backgroundColor = "#ffffff";
        container.innerHTML = '<center><b>Mehr...<\/b><\/center>';
        container.style.textAlign = "left";
        for (var i=0; i<this.opts.length; i++) {
          if (layers[i].Visible) {
            var c = 'checked';
          } else {
            var c = '';
          }

          container.innerHTML += '<input type="checkbox" onclick="toggleLayer('+i+')" ' +c+ ' /> '+this.opts[i]+'<br>';
        }

        map.getContainer().appendChild(container);

        // === This doesn't do what I want. It kills the control if I mouseover a checkbox ===
        // === If you know how to do this better, let me know ===

        //GEvent.addDomListener(container, "mouseout", function() {
        //  map.removeControl(layerControl);
        //});

        setTimeout("map.removeControl(layerControl)",5000);


        return container;
      }

      LayerControl.prototype.getDefaultPosition = function() {
        return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(250, 7));
      }
     // ==== toggleLayer adds and removes the layers ====
      function toggleLayer(i) {
        if (layers[i].Visible) {
          layers[i].hide();
        } else {
          if(layers[i].Added) {
            layers[i].show();
          } else {
            map.addOverlay(layers[i]);
            layers[i].Added = true;
          }
        }
        layers[i].Visible = !layers[i].Visible;
      }

GMap2.prototype.gLargeMapControl = null;
GMap2.prototype.gSmallMapControl = null;
GMap2.prototype.gSmallZoomControl = null;
GMap2.prototype.gMapTypeControl = null;
//GMap2.prototype.gOverviewMapControl = null;  //new OverviewMapControl

function initMap (start_long, start_lat, start_zoom, start_map_type, c_glmc, c_gsmc, c_gszc, c_gmtc, left_top, right_bottom)
{
	// general map initialisation

	// creating  controls but not yet adding them to the map
	map.gLargeMapControl = new GLargeMapControl();
	map.gSmallMapControl = new GSmallMapControl();
	map.gSmallZoomControl = new GSmallZoomControl();
	map.gMapTypeControl = new GMapTypeControl();

	// add some controls
	if (c_glmc == 1){ map.addControl(map.gLargeMapControl) };
	if (c_gsmc == 1){ map.addControl(map.gSmallMapControl) };
	if (c_gszc == 1){ map.addControl(map.gSmallZoomControl) };
	if (c_gmtc == 1){ map.addControl(map.gMapTypeControl) };
	// === Create the MoreControl(), and do addControl() it ===
	var topRight = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(250,7));
    map.addControl(new MoreControl(), topRight);

	// Enable doubleclick zoomer
    map.enableDoubleClickZoom();
	// Enable ScrollWheel zoomer
 	map.enableScrollWheelZoom();

	//map.registerKeyHandlers( window );

	if (start_zoom == 'auto')
		start_zoom = map.getZoomFromPoints(left_top, right_bottom);

	// go to starting point
	map.setCenter(new GLatLng(start_lat, start_long), start_zoom);

	// maptypes are saved as an integer and not as one of these non-working constans
	if (start_map_type < G_DEFAULT_MAP_TYPES.length) {
		map.setMapType(G_DEFAULT_MAP_TYPES[start_map_type]);
	}
}

// is set to 1 if a refresh of the "bubbles" is needed, i.e. when the user dragged or zoomed
GMap2.prototype.waiting = 0;
// 1, if script is waiting for xml-response
GMap2.prototype.busy = 0;
// global array which contains the coordinates of all markers on the map
GMap2.prototype.overlayList = new Array();
// place for some config values needed - this is a temporary solution
GMap2.prototype.atlasConfig = new Array('hallo');


// this function checks, if there is a marker at a certain point at the map
GMap2.prototype.isMarker = function (point)
{
	var found = false;
	for (var i=0;i<this.overlayList.length;i++) {
		if (this.overlayList[i].x == point.x && this.overlayList[i].y == point.y) {found = true; break;}
	}
	return found;
}

// this function is to create a marker with the required attributes
GMap2.prototype.createMarker = function (point, infohtml, markerOptions) {
	var marker = new GMarker(point, markerOptions);
							
	GEvent.addListener(marker, "click", function() {
	marker.openInfoWindowHtml(infohtml);
	});

	return marker;
}

// workaround the buggy MapType implementation (see http://groups-beta.google.com/group/Google-Maps-API/browse_thread/thread/2be31ffce3d7aec8/08963d4abe8e13b7)
GMap2.prototype.getCurrentMapTypeNumber = function () {
	var type=-1;
	for(var ix=0;ix<G_DEFAULT_MAP_TYPES.length;ix++)
	{
		if(G_DEFAULT_MAP_TYPES[ix]==this.getCurrentMapType())
			type=ix;
	}
	return type;
}

// don't see http://groups-beta.google.com/group/Google-Maps-API/browse_thread/thread/7d6b450fa6893a9c/3197341a7c5facdf?q=Lokkju&rnum=9&hl=en#3197341a7c5facdf for information about this function
GMap2.prototype.getZoomFromPoints = function (p1,p2)
{
	var NorthEastLng;
	var NorthEastLat;
	var SouthWestLng;
	var SouthWestLat;
	if(p1.lng() > p2.lng()) {
		NorthEastLng=p1.lng();
		SouthWestLng=p2.lng();
	} else {
		NorthEastLng=p2.lng();
		SouthWestLng=p1.lng();
	}
	if(p1.lat() > p2.lat()) {
		NorthEastLat=p1.lat();
		SouthWestLat=p2.lat();
	} else {
		NorthEastLat=p2.lat();
		SouthWestLat=p1.lat();
	}
	var b = new GLatLngBounds(new GLatLng(SouthWestLat, SouthWestLng), new GLatLng(NorthEastLat, NorthEastLng));
	var z = this.getBoundsZoomLevel(b);
	return z;
}

GLatLng.prototype.x2sec = function () {
	var plus=Math.abs(this.lng());
	var degr=Math.floor(plus);
	var minu=Math.floor(60*(plus-degr));
	var sec=Math.floor(60*(60*(plus-degr)-minu));
	var compass="?";
	if (minu<10) {minu="0"+minu};
	if (sec<10) {sec="0"+sec};
	if (this.lng()<0) {compass="W"} else {compass="E"}
	return ""+degr+"&deg; "+minu+"' "+sec+'" '+compass;
}

GLatLng.prototype.y2sec = function () {
	var plus=Math.abs(this.lat());
	var degr=Math.floor(plus);
	var minu=Math.floor(60*(plus-degr));
	var sec=Math.floor(60*(60*(plus-degr)-minu));
	var compass="?";
	if (minu<10) {minu="0"+minu};
	if (sec<10) {sec="0"+sec};
	if (this.lat()<0) {compass="S"} else {compass="N"}
	return ""+degr+"&deg; "+minu+"' "+sec+'" '+compass;
}

GMap2.prototype.prepareForFindCoords = function ()
{
	// for "find coordinates"
	GEvent.addListener(map, 'click', function(overlay, point) {
		if (point)
		{
			map.clearOverlays();
			var loc = new GMarker(point);
			map.addOverlay(loc);
			map.panTo(point);
			loc.openInfoWindowHtml('<span class="gen" style="white-space: nowrap;">' + L_LONG + ': ' + point.x2sec() + '<br />' + L_LAT + ': ' + point.y2sec() + '<br /><a href="javascript:void(0)" onclick="setThisAsMyLocation(' + point.lng() + ', ' + point.lat() + ', ' + map.getZoom() + ', ' + map.getCurrentMapTypeNumber() + ')">' + L_CHOOSE_THIS + '</a></span>');
		}
	});
	GEvent.addListener(map, 'zoomend', function(oldZoomLevel, newZoomLevel) {
		if (newZoomLevel) {
			document.getElementById('zoom').value = newZoomLevel;
		}
	});
	GEvent.addListener(map, 'maptypechanged', function() {
		document.getElementById('maptype').value = this.getCurrentMapTypeNumber();
	});
}

GMap2.prototype.prepareForViewMap = function ()
{
	// when the usercoordinates are displayed
	var bounds = map.getBounds();
	putUsersIntoMap(bounds);
	GEvent.addListener(map, 'zoomend', function (oldZoomLevel, newZoomLevel) {
		overlayList = new Array();
		map.waiting = 1;
	});
	GEvent.addListener(map, 'moveend', function () {
		map.waiting = 1;
	});

	var loop = window.setInterval("start()", 500);
}

GMap2.prototype.prepareForShowDistance = function (p_id, p_long, p_lat, p_username, p_year, p_month, p_day)
{
    if (parseFloat(p_id))
    {
        var point1 = new GPoint(parseFloat(p_long), parseFloat(p_lat));
		if (parseInt(p_year))
		{
			// blaues ICON für Kalendereinträge
			var blueIcon = new GIcon(G_DEFAULT_ICON);
			blueIcon.image = "http://www.fiestaforum.de/images/blue-dot.png";
			blueIcon.iconSize = new GSize(35,35);
			markerOptions = { icon:blueIcon };
			var marker1 = map.createMarker(point1, '<br><a href="' + CAL_EVENT + '&id=' + p_id + '&cl_d=' + p_day + '&cl_m=' + p_month + '&cl_y=' + p_year + '" class="gen">' + p_username + '</a>',markerOptions);
		}
		else
		{
			var marker1 = map.createMarker(point1, '<br><a href="' + U_PROFILE_G + '&u=' + p_id + '" class="gen">' + p_username + '</a>','');
		}
		
        map.addOverlay(marker1);

        var point2 = new GPoint(parseFloat(LONGITUDE), parseFloat(LATITUDE));
        var marker2 = map.createMarker(point2, '<br><span class="gen">' + L_YOUR_LOCATION + '</span>','');
        map.addOverlay(marker2);

		var polyline = new GPolyline([point1, point2], "#ff0000", 3);
		map.addOverlay(polyline);

        var centerLong = point1.x + (point2.x - point1.x) / 2;
        var centerLat = point1.y + (point2.y - point1.y) / 2;
        map.setCenter(new GLatLng(centerLat, centerLong), map.getZoomFromPoints(marker1.getPoint(), marker2.getPoint()));
    }
}

GMap2.prototype.prepareForAdminPanel = function ()
{
	map.prepareForViewMap();
	map.disableInfoWindow();
	window.clearInterval(loop);
	GEvent.addListener(map, 'maptypechanged', function () {
		document.getElementById('atlas_start_mode').value = map.getCurrentMapTypeNumber();
	});
	GEvent.addListener(map, 'zoomend', function (oldZ, newZ) {
		document.getElementById('atlas_zoom').value = newZ;
	});
	GEvent.addListener(map, 'moveend', function () {
		var center = map.getCenter();
		document.getElementById('atlas_start_long').value = center.lng();
		document.getElementById('atlas_start_lat').value = center.lat();
	});
}


function start ()
{
	if (map.busy == 0 && map.waiting == 1) putUsersIntoMap();
}

function putUsersIntoMap ()
{
	map.busy = 1;
	map.waiting = 0;
	var bounds = map.getBounds();
	var SouthWest = bounds.getSouthWest();
	var NorthEast = bounds.getNorthEast();
	var minX = SouthWest.lng();
	var maxX = NorthEast.lng();
	var minY = SouthWest.lat();
	var maxY = NorthEast.lat();
	var mapWidth = maxX - minX;
	var mapHeight = maxY - minX;
	request = GXmlHttp.create();
	request.open('GET', U_XML_ADRESS + "&minx=" + (minX - 0.5 * mapWidth) + "&miny=" + (minY - 0.5 * mapHeight) + "&maxx=" + (maxX + 0.5 * mapWidth) + "&maxy=" + (maxY + 0.5 * mapHeight), true);
	request.onreadystatechange = function ()
		{
			if (request.readyState == 4)
			{
				xmlDoc = request.responseXML;
				var markers = xmlDoc.documentElement.getElementsByTagName("m");
				//document.write(request.responseText);
				//alert(markers.length);
				//alert(U_XML_ADRESS + "&minx=" + (minX - 0.5 * mapWidth) + "&miny=" + (minY - 0.5 * mapHeight) + "&maxx=" + (maxX + 0.5 * mapWidth) + "&maxy=" + (maxY + 0.5 * mapHeight));
				for (var i=0;i<markers.length;i++)
				{
					var point = new GPoint(parseFloat(markers[i].getAttribute("lng")),  parseFloat(markers[i].getAttribute("ltd")));
					if (map.isMarker(point)) var IsM = 1; else var IsM = 0;
					var infohtml = '';

					for (var j=0;j<markers[i].childNodes.length;j++)
					{
						var markerOptions = '';
						
						if (markers[i].childNodes[j].nodeName.toLowerCase() == "u")
						{
							var username = markers[i].childNodes[j].firstChild.nodeValue;
							var userid = markers[i].childNodes[j].getAttribute("id");
							var distance = markers[i].childNodes[j].getAttribute("dist");
							var avatar = markers[i].childNodes[j].getAttribute("img");
							var awidth = markers[i].childNodes[j].getAttribute("x");
							var aheight = markers[i].childNodes[j].getAttribute("y");

							distance = (distance == '') ? '' : distance + " km";

							var userlink = document.createElement("a");
							userlink.setAttribute("href", U_PROFILE_G + '&u=' + userid);
							userlink.appendChild(document.createTextNode(username));

							if (IsM == 0)
							{	
								if (avatar != '')
								{
								infohtml = infohtml + '<img src="' + avatar +'" width="' + awidth + '" height="' + aheight + '" ><br />';
								}
								infohtml = infohtml + "<br />";
								infohtml = infohtml + '<a href="' + U_PROFILE_G + '&u=' + userid + '" class="gen">' + username + '</a>';
							}
						}
						// Begin Calendar on Map
						if (markers[i].childNodes[j].nodeName.toLowerCase() == "c") //for Calendar!
						{
							var subject = markers[i].childNodes[j].firstChild.nodeValue;
							var id = markers[i].childNodes[j].getAttribute("id");
							var distance = markers[i].childNodes[j].getAttribute("dist");
							var year = markers[i].childNodes[j].getAttribute("y");
							var month = markers[i].childNodes[j].getAttribute("m");
							var day = markers[i].childNodes[j].getAttribute("d");

							distance = (distance == '') ? '' : distance + " km";

							var userlink = document.createElement("a");
							userlink.setAttribute("href", CAL_EVENT + '&id=' + id);
							userlink.appendChild(document.createTextNode(subject));
							
								// blaues ICON für Kalendereinträge
								var blueIcon = new GIcon(G_DEFAULT_ICON);
								blueIcon.image = "http://www.fiestaforum.de/images/blue-dot.png";
								blueIcon.iconSize = new GSize(35,35);
								markerOptions = { icon:blueIcon };

							if (IsM == 0)
							{	
								infohtml = infohtml + "<br />";
								infohtml = infohtml + '<a href="' + CAL_EVENT + '&id=' + id + '&cl_d=' + day + '&cl_m=' + month + '&cl_y=' + year + '" class="gen">' + subject + '</a>';
							}
						}
						// End Calendar on Map
					} // each user

					if (IsM == 0)
					{
						var marker = map.createMarker(point, infohtml, markerOptions);
						map.addOverlay(marker);
						map.overlayList.push(point);
					}
				} // each marker

				map.busy = 0;

			} // end if status = 4
		} // end function

	request.send(null);
}

// copies the coordinates into the parent window
function setThisAsMyLocation(slong, slat, szoom, stype)
{
	if (opener.document.getElementById('user_long')) {opener.document.getElementById('user_long').value = slong;}
	if (opener.document.getElementById('user_lat')) {opener.document.getElementById('user_lat').value = slat;}
	opener.focus();
	window.close();
	return true;
}

// added
function showAddress(address) {
  if (geocoder) {
	geocoder.getLatLng(
	  address,
	  function(point) {
		if (!point) {
		  alert(address + " " + GEOCODER_NOT_FOUND);
		} else {
			if(modus == 3){
				map.clearOverlays();
				var loc = new GMarker(point);
				map.addOverlay(loc);
				map.setCenter(point, 10);
				loc.openInfoWindowHtml('<span class="gen" style="white-space: nowrap;">' + L_LONG + ': ' + point.x2sec() + '<br />' + L_LAT + ': ' + point.y2sec() + '<br /><a href="javascript:void(0)" onclick="setThisAsMyLocation(' + point.lng() + ', ' + point.lat() + ', ' + map.getZoom() + ', ' + map.getCurrentMapTypeNumber() + ')">' + L_CHOOSE_THIS + '</a></span>');
			} /*else {
				map.setCenter(point, 13);
				var marker = new GMarker(point);
				map.addOverlay(marker);
				marker.openInfoWindowHtml(address + "<br />L&auml;ngengrad: " + point.lng() + "<br />Breitengrad: " + point.lat());
			}*/
		}
	  }
	);
  }
}
