// Takes the entry in ID#addressInput, requests a geocode for it, and then
// passes it on to searchLocationsNear with the coordinates.
//
// In the event no geocode can be found, it sets up an alert error.
// var map;
var geocoder;

function findDealers() {
	var address = $('#address').val();
	var radius = $('#radius').val();
	searchLocations(address, radius);
}

function searchLocations(address, radius) {
	//alert("zipcode=" + address + ", radius=" + radius + ", geocoder=" + geocoder);
	geocoder.getLatLng(address, function(latlng) {
		if (!latlng) {
			alert(address + ' not found');
		} else {
			searchLocationsNear(latlng, radius);
		}
	});
}

function searchLocationsNear(center,radius) {
	var searchUrl = 'find_nearest_dealer.php?latitude=' + center.lat()
			+ '&longitude=' + center.lng() + '&radius=' + radius;
	GDownloadUrl(searchUrl, function(data) {
		var xml = GXml.parse(data);
		var markers = xml.documentElement.getElementsByTagName('marker');
		// map.clearOverlays();

		// var bounds = new GLatLngBounds();
		var content = "";
		if (markers.length == 0) {
			$('#dialog').dialog( 'option', 'title', 'No Dealers in Specified Area' );
			content = "<span>Please contact us at (877) 274-6773 so that we may better serve you.</span>";
		}
		else {
			content = content + "<div style=\"font-style:italic;font-size:smaller;\">" +
							    "There " + 
							    ((markers.length == 1) ? "is " : "are ") + 
							    markers.length + 
							    ((markers.length == 1) ? " dealer" : " dealer") +
							    " within " + radius + " miles:</div><br/>";
			var title = ( markers.length == 1 ) ? 'Nearest Dealer' : 'Nearest Dealers';
			$('#dialog').dialog( 'option', 'title', title );
			for ( var i = 0; i < markers.length; i++) {
				var name = markers[i].getAttribute('name');
				var address = markers[i].getAttribute('address');
				var city = markers[i].getAttribute('city');
				var state = markers[i].getAttribute('state');
				var postalCode = markers[i].getAttribute('postalCode');
				var distance = Math.round(parseFloat(markers[i].getAttribute('distance')));
				var phone = markers[i].getAttribute('phone');
				var point = new GLatLng(parseFloat(markers[i]
						.getAttribute('latitude')), parseFloat(markers[i]
						.getAttribute('longitude')));
	
				var eol = ( i + 1 < markers.length ) ? '<br/><br/>' : '';
				content = content 
					+ '<span style=\"font-weight:bold;">' + name 
					+ '</span> <span style=\"font-size:small; font-style:italic;\">' 
					+ distance + ' miles</span>' + '<br/>' + address + '<br/>'
					+ city + ', ' + state + ' ' + postalCode
					+ '<br/>' + phone + eol;
				
				// map.addOverlay(marker);
				// bounds.extend(point);
			}
		}
		$('#dealerResult').html( content );
		$('#dialog').dialog('open');
		// map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
	});
}

