var map = null;
var latitude = null;
var longitude = null;
var zoom = 2;
var marker = null;

function showGMap() {
	if(jQuery("#street_name").val() =='') return;
	var address = get_address();
  	geocoder.getLocations(address, addAddressToMap);
}
/*
 if(jQuery("#latitude, #longitude").val() != '')
       	var map_center = new GLatLng(jQuery("#latitude"), jQuery("#longitude" );
       else 
       		var map_center = new GLatLng( -33.8615, 151.2124 );
       	alert(map_center);
		map.setCenter(map_center, zoom + 5); //Centralize in Sydney
		*/
function loadGMap() {
    if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("map"));
        map.addControl(new GSmallMapControl());
   if(document.getElementById("latitude").value != '' && document.getElementById("longitude").value != ''){
   		map.setCenter(new GLatLng(document.getElementById("latitude").value,  document.getElementById("longitude").value ), zoom + 15);
		create_marker(map.getCenter());
   }else{
	map.setCenter(new GLatLng( -28.0000, 135.0000 ), zoom +1); //Centralize in Australia
  	}  
    }
    else
        alert("Sorry, the Google Maps API is not compatible with this browser");
}

function interactive_map(){
    loadGMap();
    if(map != null){
        geocoder = new GClientGeocoder();
        GEvent.addListener(map, "click", function(overlay, point) {
            create_marker(point);
        });
    }
}

function set_coordinates(){
	jQuery("#latitude").val(latitude);
    jQuery("#longitude").val(longitude);
}

function create_marker(point) {
	if(marker) {
        marker.setLatLng(point);
}
    else {
        marker = new GMarker(point, { draggable: true,bouncy: false});
		map.addOverlay(marker);
        GEvent.addListener(marker, "drag", register_coords);  
        
	}
	register_coords();
	return marker;
}

function register_coords(){
    latitude = marker.getPoint().lat().toFixed(4);
    longitude = marker.getPoint().lng().toFixed(4);
	set_coordinates();
    document.getElementById("message").innerHTML='<b>Latitude = ' + latitude + ', Longitude = ' + longitude + ' <\/b>';
}
function addAddressToMap(response) {
    if (!response || response.Status.code != 200) {
        map.setCenter(new GLatLng(84.2672,45.0000), zoom);
    }
    else {
        place = response.Placemark[0];
        map.setCenter(new GLatLng(place.Point.coordinates[1],place.Point.coordinates[0]),zoom+15);
        create_marker(map.getCenter());
    }
}

function get_address(){
    return jQuery("#street_number").val() + ' ' +
    jQuery("#street_name").val()+ ' ' +
    jQuery("#carparksspacestreettype").val() + ' ' +
    jQuery("#spacesuburb").val() + ' ' +
    jQuery("#carparksspacestate").val() + ' Australia';
}
window.onload=interactive_map;
