google.load("maps", "2");

// google maps var
var map = null;
// google geocoder
var geocoder = null;
// if set specifies the address that was search for. JSON
var searchAddress = null;
// if set specifies an arrach of centre details results. JSON
var centres = null;
// if set specifies an arrach of location details results. JSON
var locations = null;


/**
 * Initialise the google objects
 */
function initialize() {
	if (GBrowserIsCompatible()) {
		map = new google.maps.Map2($("googleMap"));    

		var customUI = map.getDefaultUI();
	 	map.setUI(customUI);

		geocoder = new google.maps.ClientGeocoder();
//		geocoder.setBaseCountryCode('uk');
	}
}


/**
 * add a location marker
 * @parame object location google placemark
 */
function addLocationMarker(location) {

	var point = new google.maps.LatLng(location.Point.coordinates[1], location.Point.coordinates[0]);

	var customIcon = new google.maps.Icon(G_DEFAULT_ICON);
	customIcon.image = WEB_ROOT +"images/blue-dot.png";

	var markerOptions = { title: location.address, icon:customIcon };
	marker = new GMarker(point, markerOptions);
	
	google.maps.Event.addListener(marker,"click", function() {
		var myHTML = '<a href="'+ WEB_ROOT +'?lat='+ location.Point.coordinates[1] +'&amp;lng='+ location.Point.coordinates[0] +'&amp;address='+ location.address +'">'+ location.address +'</a>';
		map.openInfoWindowHtml(point, myHTML, {maxWidth:'200px'});
	});

	map.addOverlay(marker);
}


function initSearchInput() {
	
	var defaultValue = "postcode or town/city";
	$('q').value = defaultValue;
	$('q').setStyle('color', '#aaa');
	$('q').addEvent('focus', function() {
		if ($('q').value == defaultValue) {
			$('q').value = '';
			$('q').setStyle('color', '#000');
		}
	});
}

// NB: This function is converted from PHP in index.php
function isUkCoordinate(latitude, longitude) {
	// These are just estimates
	if (latitude < 59.0 && latitude > 49.5 && longitude > -11.0 && longitude < 2.5) {
		return true;
	}
	return false;
}

/**
 * Initialise everything
 */
window.addEvent('domready', function() {

	initialize();
	initSearchInput()

	var customIcon = new google.maps.Icon(G_DEFAULT_ICON);

	// if centres defined display centre markers
	if (centres) {
		var sumOfDistance = 0
		for (var i = 0; i < centres.length; i++) {
			// change marker icon if gold
			if (centres[i].isgold == '1') {
				customIcon.image = WEB_ROOT +"images/green-dot.png";
			} else {
				customIcon.image = WEB_ROOT +"images/pink-dot.png";
			}
			var markerOptions = { title: centres[i].name, icon:customIcon};
			var point = new google.maps.LatLng(centres[i].Latitude, centres[i].Longitude);
			var marker = new google.maps.Marker(point, markerOptions);
			marker.bindInfoWindow(document.getElementById('markerInfo'+ centres[i].client_id));
			map.addOverlay(marker);
			
			sumOfDistance += parseInt(centres[i].distance)
		}
	}


	if (locations) {
		for (var i = 0; i < locations.length; i++) {
			addLocationMarker(locations[i]);
		}
	}


	// if searchAddress defined then set that as centre, and add marker
	if (searchAddress) {
		var point = new google.maps.LatLng(searchAddress.latitude, searchAddress.longitude)

		var averageDistance = (sumOfDistance/centres.length);
		zoom = 8;
		if (averageDistance < 15) zoom = 9
		if (averageDistance < 10) zoom = 10
		if (averageDistance < 5) zoom = 11
		if (averageDistance < 2) zoom = 12

//		console.log("averageDistance = "+ averageDistance);
//		console.log("zoom = "+zoom);

		map.setCenter(point, zoom);

//		customIcon.image = WEB_ROOT +"images/green-dot.png";
//		var markerOptions = { title: searchAddress.address, icon:customIcon };
//		var marker = new google.maps.Marker(point, markerOptions);
//		map.addOverlay(marker);
	} else {
		var placePoint = new google.maps.LatLng(54.7, -2.5474009)
		map.setCenter(placePoint, 5);
	}


	// add an event to search for submit
	$('search').addEvent('submit', function(e){
		// Prevent the submit event
		new Event(e).stop();
		
		// remove space from postcode as google isn;t as accurate with a postcode with a space in. NB this alos removes spaced from town/city names, but doesn't seem o cause a problem
		var address = $('q').value.replace(/ /g, '') +", UK";
		map.clearOverlays();

		geocoder.getLocations(
			address,
			function(response) {
				var html = '<div class="top"></div>';
				// NB This HTML is repeated on the index.php page, if changed remember to change both!
				switch (response.Status.code) {
					case G_GEO_SUCCESS:
						if (response.Placemark.length == 1) {
							var lat = response.Placemark[0].Point.coordinates[1]
							var lng = response.Placemark[0].Point.coordinates[0]
							if (isUkCoordinate(lat, lng)) {
								// using timeout here, stop FF from not putting page into history
								str = 'location.href = WEB_ROOT +"?lat='+ lat +'&lng='+ lng +'&address='+ $('q').value +'"';
								window.setTimeout(str, 10)
								break;
							}
						} else {
							var buffer = new Array();
							for (var i = 0; i < response.Placemark.length; i++) {
								var lat = response.Placemark[i].Point.coordinates[1];
								var lng = response.Placemark[i].Point.coordinates[0];
								if (isUkCoordinate(lat, lng)) {
									buffer.push('<li><a href="'+ WEB_ROOT +'?lat='+ lat +'&amp;lng='+ lng +'&amp;address='+ response.Placemark[i].address +'">'+ response.Placemark[i].address +'</a></li>');
									addLocationMarker(response.Placemark[i]);
								}
							}
							
							if (buffer.length >= 1) {
								var placePoint = new google.maps.LatLng(54.7, -2.5474009)
								map.setCenter(placePoint, 5);
								html += '<p><strong>We have found multiple places that match your search. Did you mean one of the following?</strong></p>'
								html += '<ul>';
								html += buffer.join('');
								html += '</ul>';
								break;
							}
						}
						// No break is deliberate - we need to fall through if results are not within UK
						
					case G_GEO_UNKNOWN_ADDRESS :
						html += "<p><strong>Cannot find '"+ address +"'</strong></p>";
						break;
					default :
						html = "<p><strong>Error '"+ response.Status.code +"'</strong></p>";
						break;
				}
				
				html += '<div class="bottom"></div>';
				$('searchResults').innerHTML = html
			}
		)
	});
});