var map;
var geocoder;
var bounds;
var markers = new Array();
var addresses = new Array();
var processed_addresses = 0;

function init() {
  if (GBrowserIsCompatible()) {
	geocoder = new GClientGeocoder();
  }
}

function load() {
  if (GBrowserIsCompatible()) {
// console.log('loading map');
    map = new GMap2(document.getElementById("map"));
	bounds = new GLatLngBounds();

	map.setCenter(new GLatLng(0,0));
	map.addControl(new GLargeMapControl());
  }
}

// addAddressToMap() is called when the geocoder returns an
// answer.  It adds a marker to the map with an open info window
// showing the nicely formatted version of the address and the country code.
function addAddressToMap(obj, response) {
  // map.clearOverlays();
  if (!response || response.Status.code != 200) {
// console.log('addAddressToMap() - response for '+obj.address+' failed - status code: '+response.Status.code);
	// if we can't find the address, knock the front off until we can
	/*
	current_address = current_address.split(',').slice(1).join(',');
	current_address = current_address.replace(/^\s+/,'').replace(/\s+$/,'');
	if (current_address.match(/,/)!=null) geocoder.getLocations(current_address, addAddressToMap);
	*/
    // alert("Sorry, we were unable to geocode that address");
	// addMessage(obj.message);
  } else {
// console.log('addAddressToMap() - successfully looked up '+obj.address);
    place = response.Placemark[0];
    point = new GLatLng(place.Point.coordinates[1],
                        place.Point.coordinates[0]);
    // map.addOverlay(marker);
	if (obj.is_search_location) {
		// Create our "tiny" marker icon
  		var blueIcon = new GIcon(G_DEFAULT_ICON);
  		blueIcon.image = "blank_marker_green.png";
		
		// Set up our GMarkerOptions object
		markerOptions = { icon:blueIcon };
        marker = new GMarker(point, markerOptions);
		map.setCenter(point);
	}
	else {
		marker = new GMarker(point);
	}
	var txt = '';
	if (obj.message) 
	{
		txt += obj.message+'<br />';
	}
	txt += '<div class="gmarker">'+place.address+'</div>';
	marker.bindInfoWindowHtml(txt);
	markers.push(marker);
	bounds.extend(point);
  }
  processed_addresses++;
  showIt();
}

function addMessage(message) {
	// document.getElementById('mapmessages').innerHTML += '<div>'+message+'<'+'/'+'div>';
}

function setZoom() {
	map.setZoom(map.getBoundsZoomLevel(bounds)-1);
	var clat = (bounds.getNorthEast().lat() + bounds.getSouthWest().lat()) /2;
	var clng = (bounds.getNorthEast().lng() + bounds.getSouthWest().lng()) /2;
	map.setCenter(new GLatLng(clat,clng));
	map.savePosition();
}

function centerAtLocation(address) {
	geocoder.getLocations(address, function(response){
	  // map.clearOverlays();
	  if (!response || response.Status.code != 200) {
	    alert("Sorry, we were unable to geocode that address");
	  } else {
	    place = response.Placemark[0];
	    point = new GLatLng(place.Point.coordinates[1],
	                        place.Point.coordinates[0]);
		map.setCenter(point,5);
	  }
	});
}

function finishUp() {
// console.log('finishUp() - processing '+addresses.length+' addresses')
	for (var i=0; i<addresses.length; i++) {
// console.log('finishUp() - adding '+addresses[i].address+' to map');
		if (typeof addresses[i].lat != 'undefined') {
			// Fakes a Google Maps response for the lats & lons we already know
			addAddressToMap({
				address: addresses[i].address,
				message: addresses[i].message
			}, {
				Placemark: [
					{
						address: addresses[i].address,
						Point: {
							coordinates: [
								addresses[i].lon,
								addresses[i].lat
							]
						}
					}
				],
				Status: {code: 200}
			});
		} else {
			geocoder.getLocations(addresses[i].address, addAddressToMap.bind(addAddressToMap, {
				address: addresses[i].address,
				message: addresses[i].message,
				is_search_location: addresses[i].is_search_location
			}));
		}
	}
}

function getPlaceAndSubmit(theform) {
	var address = theform['location'].value;
	// check the address against the database
	new Ajax.Request('/stores/query.php?address=' + escape(address),
		{
			method: 'get',
			onSuccess: function (transport)
			{
				if (transport.responseText != '') {
					var response = JSON.parse(transport.responseText);
					// then we got lat and lon from database, WHEE
					theform['start_latitude'].value = response.lat;
					theform['start_longitude'].value = response.lon;
					//theform['start_latitude'].value = transport.responseText;
				}
				theform.submit();
			}
		}
	);
	/*geocoder.getLocations(address, function(response){
	  if (!response || response.Status.code != 200) {
		// no address found
	  } else {
	    place = response.Placemark[0];
		theform['start_latitude'].value = place.Point.coordinates[1];
		theform['start_longitude'].value = place.Point.coordinates[0];
	  }*/
	  //theform.submit();
	//});
}

function showIt() {
	if (processed_addresses>=addresses.length) {
		if (markers.length>0) {
			mgr = new GMarkerManager(map);
			mgr.addMarkers(markers, 1);
			mgr.refresh();
			setZoom();
		}
		else {
			// if we don't have any markers on the map, hide it
			document.getElementById('map').style.display='none';
		}
	}
}

init();
