var map = null;
var geocoder = null;

function initialize() {

	map = new GMap2($('registerMap'));
	
	map.enableScrollWheelZoom();
	
//	map.setCenter(new GLatLng(37.4419, -122.1419), 13);
	geocoder = new GClientGeocoder();
	
	$('regLocation').addEvent('change', findLocation);
	
	if($('regLocation').length) {
		findLocation();
	}
	
	// check location is set before submitting form
	$('register').addEvent('submit', function(e) {
		e.stop();
		// check hidden lat field
		if(e.target.regLat.value) {
			this.submit();
//			alert('send');
		} else if(findLocation()) {
			this.submit();
//			alert('send');
		} else {
			return;
		}
	
	});
	
	if($('regLat').value && $('regLon').value) {
		renderMap(new GLatLng($('regLat').value, $('regLon').value));
	}
	
}
	


function findLocation() {
	
	if($('regLocation').value.trim() == "") {
		alert('Please enter your location');
		return false;
	}
	
	if (geocoder) {
		// we should grab this from elsewhere...
		geocoder.setBaseCountryCode($('iso_id').value);

		// expand upon disambiguation to display options...
		geocoder.getLocations($('regLocation').value, function(locations) {
			
			var disamb = locations;
			
			if(disamb.Status.code == 602) {
				window.alert('No places found. Please try searching again.');
				$('regLocation').empty();
				return false;
			} else {
				
				$('regLocation').value = disamb.Placemark[0].address;
				
				var coords = disamb.Placemark[0].Point.coordinates;
				
				var point = new GLatLng(coords[1], coords[0]);
				
//				map.setCenter(point, 15);
//				map.clearOverlays();
//				map.addOverlay(new GMarker(point));
				
				renderMap(point);
				
				$('regLon').value = coords[0];
				$('regLat').value  = coords[1];
				
			}
			
			return true;
			
		});

	}
	
}

function renderMap (point) {
	
	map.setCenter(point, 15);
	map.clearOverlays();
	map.addOverlay(new GMarker(point));
	
}

window.addEvent('domready', function(ev) { 
	// console.log('the dom is ready'); 
	initialize(); 
});
