
var map;
var geocoder;
var lastGoto = null;
var markerArray = new Array();

function loadMultipleMarkers(myClass, method, params, callDocument, setCenter) {
	if (map == null) return;
	if (callDocument == null) callDocument = document.URL.split("?")[0];
	//
	var jsonRequest = new Request.JSON({url: callDocument, onComplete: function(jsonObj) {
		jsonObj.points.each(function(pt) {
			
			var markerIcon = new GIcon(G_DEFAULT_ICON);
			markerIcon.iconSize = new GSize(32,32);
			
			if (pt.color == 3) {
				markerIcon.image = "/resources/googlemap/marker/blue-dot.png";
			} else if (pt.color == 5) {
				markerIcon.image = "/resources/googlemap/marker/yellow-dot.png";
			} else {
				markerIcon.image = "/resources/googlemap/marker/red-dot.png";
			}
			
			var marker = new GAjaxMoveMarker(new GLatLng(pt.lat, pt.lng), {draggable: true, icon: markerIcon});
			marker.disableDragging();
			if (pt.info != null) {
				GEvent.addListener(marker, "mouseover", function() {
					marker.openInfoWindowHtml(pt.info);
				});
			}
			if (pt.movable != null) {
				marker.enableDragging();
				marker.ajaxClass = pt.movable[0].phpClass;
				marker.ajaxMethod = pt.movable[0].method;
				marker.ajaxParams = pt.movable[0].params;
				marker.ajaxTargetId = pt.movable[0].targetId;
				GEvent.addListener(marker, "dragend", function(point) {
					marker.execute(point);
				});
			}
			addOrRemoveMarker2(pt.id, marker);
		});
		if (setCenter != false) map.setCenter(new GLatLng(jsonObj.cLat, jsonObj.cLng), Math.abs(jsonObj.cZoom));
    }}).get({'class': myClass, 'method': method, 'params': params});
}

window.addEvent("domready", function() {
	if ($("gmap") == null) return;
	if (!GBrowserIsCompatible()) return;
	//
	map = new GMap2($("gmap"));
	map.addControl(new GLargeMapControl());
	map.addControl(new GMapTypeControl());
	map.setCenter(new GLatLng(46.9, 8.2), 7);
	$try(function(){
		gmap_after_init(map);
	});
});

function addOrRemoveMarker2(id, marker) {
	if (map == null) return;
	if (markerArray[id] != null) {
		map.removeOverlay(markerArray[id]);
		markerArray[id] = null;
	} else {
		markerArray[id] = marker;
		map.addOverlay(marker);
	}
}

function addOrRemoveMarker(id, lat, lng) {
	var marker = new GMarker(new GLatLng(lat, lng));
	addOrRemoveMarker2(id, marker);
}

function mapGoto(lat, lng, zoom) {
	if (map == null) return;
	if (lastGoto != null) {
		map.removeOverlay(lastGoto);
	}
	//
	var point = new GLatLng(lat, lng);
	var icon = new GIcon(G_DEFAULT_ICON, "/resources/icons/nuvola/32x32/apps/kmines.png");
	lastGoto = new GMarker(point, icon);
	map.addOverlay(lastGoto);
	map.setCenter(point, zoom);
}

function getGeocoder() {
	if (!geocoder) {
		geocoder = new GClientGeocoder();
	}
	return geocoder;
}

function searchAndGotoPoint(address) {
	getGeocoder().getLatLng(address, function(point) {
		if (!point) {
			alert(address + " konnte nicht gefunden werden");
		} else {
			mapGoto(point.lat(), point.lng(), map.getZoom());
		}
	});
}
