var postalPattern = new RegExp("^[1-9][0-9]{3}( )?[A-Za-z]{2}$");

function initializeGeocoding() {
	geocoder = new GClientGeocoder();
}

function lookupCoordinates() {
	
	// Test if proximitySearch is available
	if ($("#proximitySearch").is(':checked')) {
		
		// Test if form contains lookup
		var form = $("#searchForm")[0];
		if ( form.finishedGeoLookup ) {
			// Already a lookup is performed, continue
			return true;
		} else {
		
			// Get zipcode for lookup
			var postalCode = $("#postalCode").val();
			
			// Test if postalCode is valid
			if ( ( postalCode.length > 0 ) && ( postalPattern.test(postalCode) ) ) {
			
				// Dynamic load google API
				callGoogleApi( function() {
					performLookupGeo();
				});
				
				
			} else {
				message = msgInvalidPostalCode;
				message = message.replace("#POSTALCODE#", postalCode);
				alert( message );
			}
			
			// Lookup performed (a-sync), or failed
			return false;
		} 
	} else {
		// No lookup
		
		// Ensure field are empty 
		$("#lat").attr("value", "");
		$("#lng").attr("value", "");
		
		// Continue
		return true;
	}
}

function performLookupGeo() {

	var form = $("#searchForm")[0];
	var postalCode = $("#postalCode").val();
	
	// Test if geocoder is not available
	if (geocoder) 
	{
		address = postalCode + ", NL";
		
		// Create object to support sync call of async routine
		geocoder.getLatLng(address, function(point){
			if (!point) {
				message = msgNoLocationDetails;
				message = message.replace("#POSTALCODE#", postalCode);
				alert( message );
			} else {
				
				// Update form
				$("#lat").attr("value", point.lat());
				$("#lng").attr("value", point.lng());
				
				// Initiate new submit
				form.finishedGeoLookup = true;
				form.submit();
			}				
		});
	} else {
		alert( msgFailureLocationLookup );
	}
}
