// Find the coordinates of a location using Google's geocoder function
function findLocation() {
    var geocoder = new GClientGeocoder();
    document.getElementById("searchresult").innerHTML = "Searching ..";
    geocoder.getLatLng(document.getElementById("lookup").value,
        function(point) {
            if (!point) {
                document.getElementById("searchresult").innerHTML = "Not found";
            }
            else {
                document.getElementById("searchresult").innerHTML = "Found. Latitude: " + point.lat() + ", Longitude: " + point.lng();
                map.setCenter(point);
                map.setZoom(6);
            }
        }
    );
}

// Center the map on the point set in the form
function updateCenter() {
    var lat = document.getElementById("lat").value;
    var lng = document.getElementById("lng").value;
    map.panTo(new GLatLng(lat, lng));
}

// Create a single maker on the map
function singleMarker() {
    // Create marker
    marker = new GMarker(map.getCenter(), {draggable: true});
    marker.enableDragging();
    // When the marker is moved, center the map on this point
    // (which in turn updates the form)
    GEvent.addListener(marker, "dragend", function() {
        map.panTo(marker.getPoint());
    });
    map.addOverlay(marker);
    
    // When the map is moved, update the form and move the marker
    GEvent.addListener(map, "moveend", function() {
        var center = map.getCenter();
        document.getElementById("lat").value = center.lat();
        document.getElementById("lng").value = center.lng();
        marker.setPoint(center);
    });

    // If a position is set in the form, move to there and zoom
    if (document.getElementById("lat").value != "") {
        var lat = document.getElementById("lat").value;
        var lng = document.getElementById("lng").value;
        map.setCenter(new GLatLng(lat, lng));
        map.setZoom(6);
    }
    else {
        map.setCenter(new GLatLng(27, 8), 1);
    }
}
