
var map;
var geocoder;
var marker = null;



function createMarker ( point ) {

	if ( marker ) {
		map.removeOverlay ( marker );
	}

	mymarker = new GMarker ( point, {draggable: true} );

   marker = mymarker;
	map.addOverlay ( marker );

	var lat = Math.round ( point.lat()*100000 )/100000;
	var lon = Math.round ( point.lng()*100000 )/100000;
	document.getElementById("adresse").getElementsByTagName("input").item(1).value = lon;
	document.getElementById("adresse").getElementsByTagName("input").item(0).value = lat;

	GEvent.addListener ( mymarker, "dragend", function() {
		var point = mymarker.getPoint();
		var lat = Math.round ( point.lat()*100000 )/100000;
		var lon = Math.round ( point.lng()*100000 )/100000;
		document.getElementById("adresse").getElementsByTagName("input").item(1).value = lon;
		document.getElementById("adresse").getElementsByTagName("input").item(0).value = lat;
	});

	GEvent.addListener ( mymarker, "click", function() {

	});

}



function showAddress ( strasse, ort, land ) {

	var address = strasse + ", " + ort + ", " + land;

	geocoder.getLatLng ( address, function(point) {
		if (!point) {
			alert(address + " nicht gefunden!");
		} else {
			map.setCenter(point, 14);
			createMarker(point);
		}
	});

}




function load() {

	if ( !document.getElementById("adresse") ) {
		return;
	}

	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("map"));
		map.addControl ( new GMapTypeControl() );
		map.addControl ( new GSmallMapControl() );
		geocoder = new GClientGeocoder();

		var lon = document.getElementById("adresse").getElementsByTagName("input").item(1).value;
		var lat = document.getElementById("adresse").getElementsByTagName("input").item(0).value;

		if ( lon && lat ) {
			map.setCenter ( new GLatLng(lat, lon), 10);
			createMarker ( new GLatLng(lat, lon) );
		} else {
			map.setCenter ( new GLatLng(46.68112, 7.86037), 10);
		}


		GEvent.addListener(map, "click", function(marker, point) {
			createMarker ( point );
		});

	} else {
			alert("Sorry, 'Google Maps' are not compatible with your browser");
	}
}


