
//
// gmap-search.js
//

var map              = null;

var icon             = new GIcon();
	icon.image           = "http://www.google.com/mapfiles/marker.png";
	icon.shadow          = "http://www.google.com/mapfiles/shadow50.png";
	icon.iconSize        = new GSize(20, 34);
	icon.shadowSize      = new GSize(37, 34);
	icon.iconAnchor      = new GPoint(10, 34);

var bounds           = new GLatLngBounds();
var HTML             = new Array();
var DEL_RADIUS       = new Array();
var COUNT            = 0;
var localPostcode    = null;
var localPoint       = null;

// Set a marker on an existent map.
function setMarker (lat,long) {
	if(!lat || !long){
		COUNT++;
		return;
	}
	point = new GLatLng(lat,long);
	var marker = createMarker(point);
	if(marker){
		map.addOverlay(marker);
		if(localPostcode && (COUNT == 1)){
			marker.setImage("http://www.google.com/mapfiles/dd-start.png");	
		}

		bounds.extend(point);
		map.setCenter(bounds.getCenter(), 7);
	}
}

// Create a new map
function mapLoad () {
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("map"));
		map.setCenter(new GLatLng(53.800651, -4.064941), 9, G_HYBRID_MAP);
		map.setUIToDefault();
	}
}

// Create the marker and set up the event window
function createMarker (point) {

	// If we need to get supplier that deliver to the user's postcode
	if (localPostcode) {

		// If this isn't the user's postcode it must be a supplier
		if (COUNT > 0) {
			// Get the distance to the user (as the crow flies)
			var distanceK = ((localPoint).distanceFrom(point)/1000).toFixed(1);
			var distanceM = (((localPoint).distanceFrom(point)/1000) * 0.621).toFixed(1);
			var deliver = (distanceK - DEL_RADIUS[COUNT]);
			
			// Only display the marker if the user is within their delivery radius
			if (deliver <= 0) {
				var marker = new GMarker(point);
				if (HTML[COUNT]) {				
					marker.bindInfoWindowHtml(HTML[COUNT]);
				}
				COUNT++;
				return marker;
			// Do not display supplier's details if the user is outside of their delivery radius
			} else {
				document.getElementById('result_'+COUNT).style.display='none';
				COUNT++;
				return null;
			}

		// This must be the user's postcode as it's the first in the array
		} else {
			localPoint = point;
			var marker = new GMarker(point);
			if (HTML[COUNT]) {
				marker.bindInfoWindowHtml(HTML[COUNT]);
			}
			COUNT++;
			return marker;
		}

	// If there has not been a user postcode supplied
	} else {
		var marker = new GMarker(point);
		if (HTML[COUNT]) {
			marker.bindInfoWindowHtml(HTML[COUNT]);
		}
		COUNT++;
		return marker;
	}

}
