var prev = null;
var map = null;

function initialize() 
{
	var latlng = new google.maps.LatLng(52.09, 4.60);
	var myOptions = 
	{
		zoom: 8,
		center: latlng,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	};
	var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
	this.map = map; 
	return map;
}

function enableClicks()
{
	google.maps.event.addListener(map, 'click', function(event) 
	{
		removeMarker(prev);
		placeMarker(event.latLng);
	});
}

function placeMarker(location)
{
	  var clickedLocation = new google.maps.LatLng(location);
	  var marker = new google.maps.Marker({
	      position: location, 
	      map: map
	  });

	  prev = marker;
	  map.setCenter(location);
	  setLatLngFields(location);
	  reverseGeocode();
}

function resetMarker()
{
	document.getElementById("google_map_item_address").value = "";
	removeMarker(prev);
}

function removeMarker(marker)
{
	if(marker)
		marker.setMap(null);
}

function setLatLngFields(location)
{
	document.getElementById("google_map_item_lat").value = location.lat();
	document.getElementById("google_map_item_lng").value = location.lng();
}

function translateLatLng()
{
	var lat = document.getElementById("google_map_item_lat").value;
	var lng = document.getElementById("google_map_item_lng").value;

	if(lat != null && lng != null)
	{
		if(lat != 0 && lng != 0)
		{
			removeMarker(prev);
			var latlng = new google.maps.LatLng(lat, lng);
			placeMarker(latlng);
			reverseGeocode();
		}
	}
}

function geocode()
{

	geocoder = new google.maps.Geocoder();
	var address = document.getElementById("google_map_item_address").value;
	
	geocoder.geocode({ 'address': address}, function(results, status) 
	{
        if(status == google.maps.GeocoderStatus.OK) 
        {
        	removeMarker(prev);
        	placeMarker(results[0].geometry.location);
        	setLatLngFields(results[0].geometry.location);
        } 
        else 
        {
        	alert("Geocode was not successful for the following reason: " + status);
        }
	});
}

function reverseGeocode()
{
	var lat = document.getElementById("google_map_item_lat").value;
	var lng = document.getElementById("google_map_item_lng").value;
	
	geocoder = new google.maps.Geocoder();
	var latlng = new google.maps.LatLng(lat, lng);
	
	geocoder.geocode({'latLng': latlng}, function(results, status) 
	{
		switch(status)
		{
			case google.maps.GeocoderStatus.OK:
				document.getElementById("google_map_item_address").value = results[0].formatted_address;
				break;
			case google.maps.GeocoderStatus.ZERO_RESULTS:
				document.getElementById("google_map_item_address").value = "";
				break;
			default:
				alert("Geocoder failed due to: " + status);
		}
	});
}

