
var directions = 0;
var userloc = 0;
var useraddr;

function mapquery(howmany) {
    var locations = markerpoints['locations'].length;
    if(!howmany) { howmany = 5; }
	if(howmany > locations) { howmany = locations; }

	var addr = document.getElementById("zipcodebox").value;
	if(!addr) { alert('Vult U SVP een postcode of adres in.'); return; }

	var request = GXmlHttp.create();
	request.open("GET", "/js/maps/geocode.cfm?addr=" + encodeURIComponent(addr), true);
	request.onreadystatechange = function() {
	  if (request.readyState == 4) {
	    var response = eval(request.responseText);
		var i;

		if(!response || response.length != 2) { alert('Onbekende postcode.'); return false; }

		userloc = new GLatLng(response[0], response[1]);
		useraddr = addr;

		// Calculate distances to all markerpoints.
		for(i = 0; i < markerpoints['locations'].length; i++) {
			markerpoints['locations'][i].distance = userloc.distanceFrom(markerpoints['locations'][i][0]);
		}
  
		// Sort markerpoints by new distances.
		markerpoints['locations'].sort(function(a, b) {
			return a.distance - b.distance;
		});

		// markerpoints are now in order of distance, so the first
		// N are the N closest. Display 5 closest and target area.
		var bounds = new GLatLngBounds;
		for(i = 0; i < howmany; i++) {
			bounds.extend(markerpoints['locations'][i][0]);
		}
		bounds.extend(userloc);
		map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
		directMarker(markerpoints['locations'][0].marker, true);
	  }
	}
	request.send(null);
	return false; // don't submit form
}

