var FORM_ID="f4f26";	// FORMation text feld, das die "Geo-Koordinaten" enthalten soll.

var map;		// the google map
var marker;		// the marker (or undef)

var geo_input;		// the DOM <INPUT> element 

var lat;
var lng;

function debug(text)
{
	document.getElementById("debug").innerHTML += text+"<br />";
}



function read_form()
{
	return geo_input.value.split("/");
}
function update_form(lat,lng)
{
	geo_input.value=lat.toFixed(4) + " / " + lng.toFixed(4);
}



function marker_dragend_event()
{
	var point=marker.getPoint();
	update_form(point.lat(),point.lng());
}


function create_marker(point)
{
	marker=new GMarker(point,{draggable: true});
	map.addOverlay(marker);
	GEvent.addListener(marker,"dragend",marker_dragend_event);
	
}

function map_click_event(x_marker,point)
{
	if (marker)
	{
		marker.setPoint(point);
	}
	else
	{
		create_marker(point);
	}
	update_form(point.lat(),point.lng());
}

function geo_input_changed(event)
{
	var ll=read_form();
	if (ll.length==2)
	{
		var point=new GLatLng(ll[0],ll[1]);
		map.setCenter(point);
		if (marker)
		{
			marker.setPoint(point);
		}
		else
		{
			create_marker(point);
		}
	}
}


function reopenmap()
{
	document.getElementById("openmap").firstChild.nodeValue="Google Map schließen";
	document.getElementById("openmap").onclick=closemap;
	document.getElementById("map").style.display="block"
}


function closemap()
{
	document.getElementById("openmap").onclick=reopenmap;
	document.getElementById("openmap").firstChild.nodeValue="Geoposition mit Google Maps suchen";
	document.getElementById("map").style.display="none"
}

function geopicker_start()
{
	try
	{
		if (!GBrowserIsCompatible())
		{
			debug("map: browser not compatible");
			return;
		}
	}
	catch (e)
	{
		debug("google map api not loaded. ("+e+")");
		return;
	}


	geo_input = document.getElementById(FORM_ID);
	if (!geo_input)
	{
		debug("formular input $FORM_ID not found");
		return;
	}


	
	var mapdiv=document.getElementById("map")
	mapdiv.style.width="500px";
	mapdiv.style.height="300px";

	map=new GMap2 (mapdiv);

	var ll=read_form();
	if (ll.length==2)
	{
		var point=new GLatLng(ll[0],ll[1]);
		map.setCenter(point,10);
		create_marker(point);
	}
	else
	{
		map.setCenter(new GLatLng(51,10),5);
	}
	map.addControl(new GSmallMapControl());		// buttons pfeile + -
	map.addControl(new GMapTypeControl());		// buttons map satellite hybrid
	GEvent.addListener (map,"click",map_click_event);

	geo_input.onchange=geo_input_changed;
	document.getElementById("openmap").onclick=closemap;
	document.getElementById("openmap").firstChild.nodeValue="Google Map schließen";
}




