/***
 * Custom icon
 */
var icon = new GIcon();
icon.image = home_url+"documents/maps/ts_logo.png";
icon.iconSize = new GSize(26, 22);
icon.iconAnchor = new GPoint(19, 20);
icon.infoWindowAnchor = new GPoint(19, 22);

var iconSoon = new GIcon();
iconSoon.image = home_url+"documents/maps/ts_logo_soon.png";
iconSoon.iconSize = new GSize(20, 17);
iconSoon.iconAnchor = new GPoint(14, 15);
iconSoon.infoWindowAnchor = new GPoint(14, 17);

/***
 * Startup
 */
var map;
var gdir;
var geocoder = null;
var addressMarker;
var setDirectionsExtraInfo = '';
var geEnabled = false;
var ge;

function load() {
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("map"));
		map.addControl(new GLargeMapControl());
		map.addControl(new GMenuMapTypeControl());
		map.addMapType(G_PHYSICAL_MAP);
		geocoder = new GClientGeocoder();

		gdir = new GDirections(map, document.getElementById("directions_info"));
		GEvent.addListener(gdir, "load", onGDirectionsLoad);
		GEvent.addListener(gdir, "error", handleErrors);

		if (debug) {
			var myEventListener = GEvent.bind(map, "click", this, function(marker, point) {
				if (point) {
					document.getElementById("message").innerHTML = point;
				}
			});
		}

		map.setCenter(new GLatLng(main_pos[0], main_pos[1]), main_zoom);
		map.setMapType(G_PHYSICAL_MAP);

		addShops();
	}
}

function enableEarth() {
	if (G_SATELLITE_3D_MAP == map.getCurrentMapType()) { //If already enabled, switch back to normal.
		map.setMapType(G_PHYSICAL_MAP);
	} else {
		if (!geEnabled) { //Only try to initialise on the first attempt.
			map.addMapType(G_SATELLITE_3D_MAP);
			map.getEarthInstance(getEarthInstanceCB);
			geEnabled = true;
		}
		map.setMapType(G_SATELLITE_3D_MAP);
	}
}

function getEarthInstanceCB(object) {
	ge = object;
	if (ge != null) {
		ge.getLayerRoot().enableLayerById(ge.LAYER_ROADS, true); //LAYER_TERRAIN LAYER_ROADS LAYER_BUILDINGS LAYER_BORDERS
		ge.getLayerRoot().enableLayerById(ge.LAYER_BORDERS, true); //LAYER_TERRAIN LAYER_ROADS LAYER_BUILDINGS LAYER_BORDERS
	}
}

/***
 * Misc (unnecessary)
 */
function createMarker(point, details) {
	var marker = new GMarker(point, icon);
	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(details);
	});
	map.addOverlay(marker);
}

function gotoPoint(point, details, zoom, silent) {
	if (G_SATELLITE_3D_MAP == map.getCurrentMapType()) {
	} else {
		map.setMapType(G_HYBRID_MAP);
	}
	map.setCenter(point, zoom);

	if (!silent) {
		var marker = new GMarker(point);
		map.addOverlay(marker);
		marker.openInfoWindowHtml(details);
	}
}

function showAddress(address, zoom, silent) {
	if (geocoder) {
		geocoder.getLatLng(
			address,
			function(point) {
				if (!point) {
					if (debug) alert(address + " not found");
				} else {
					gotoPoint(point, address, zoom, silent);
				}
			}
		);
	}
}

function markAddress(address, details) {
	if (geocoder) {
		geocoder.getLatLng(
			address,
			function(point) {
				if (!point) {
					if (debug) alert(address + " not found");
				} else {
					createMarker(point, details);
				}
			}
		);
	}
}

/***
 * Shops
 */
function markShop(shopDetails) {
	var point = new GLatLng(shops[shopDetails].pnt[0], shops[shopDetails].pnt[1]);
	var details = shops[shopDetails].add;
	if (shops[shopDetails].sta !== 1) {
		var iconToUse = iconSoon;
	} else {
		var iconToUse = icon;
	}
	shops[shopDetails].marker = new GMarker(point, iconToUse);
	GEvent.addListener(shops[shopDetails].marker, "click", function() {
		shops[shopDetails].marker.openInfoWindowHtml(details);
	});
	map.addOverlay(shops[shopDetails].marker);
}

function addShops() {
	for (shopDetails in shops) {
		markShop(shopDetails);
	}
}

/***
 * Directions
 */
function setDirections(fromAddress, toAddress, locale) {
	mapShrink();
	document.getElementById('directions_info').innerHTML = '<a href="#" class="b bs" onclick="mapExpand();">x</a>';
	document.getElementById('directions_info').innerHTML += setDirectionsExtraInfo;

	if (debug) document.getElementById('message').innerHTML += '<div>from: ' + fromAddress + " to: " + toAddress + " locale: " + locale + '</div>\n';

	gdir.load("from: " + fromAddress + " to: " + toAddress, { "locale": locale });
}

function handleErrors() {
	if (debug) {
		if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS) {
			alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
		} else if (gdir.getStatus().code == G_GEO_SERVER_ERROR) {
			alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);
		} else if (gdir.getStatus().code == G_GEO_MISSING_QUERY) {
			alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);
		} else if (gdir.getStatus().code == G_UNAVAILABLE_ADDRESS) {
			//Doc bug... this is either not defined, or Doc is wrong
			alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + gdir.getStatus().code);
		} else if (gdir.getStatus().code == G_GEO_BAD_KEY) {
			alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);
		} else if (gdir.getStatus().code == G_GEO_BAD_REQUEST) {
			alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
		} else {
			alert("An unknown error occurred.");
		}
	}
}

function onGDirectionsLoad(){ 
	//mapShrink();
}

function calcDist(starting_location, locale) {
  if (geocoder) {
	geocoder.getLatLng(
	  starting_location,
	  function(point) {
		if (!point) {
		  if (debug) alert(starting_location + " not found");
		} else {
			var closest_name = null;
			var closest_dist = 10000;
			for (shopDetails in shops) {
				var p = new GLatLng(shops[shopDetails].pnt[0], shops[shopDetails].pnt[1]);
				var distance = point.distanceFrom(p) / 1000;
				if (distance < closest_dist) {
					closest_name = shopDetails;
					closest_dist = distance;
				}
			}
			if (debug) document.getElementById('message').innerHTML += '<div>Closest shop as the crow flies: '+shops[closest_name].nam+': '+closest_dist.toFixed(1)+'km</div>\n';
			setDirectionsExtraInfo = '<span id="nearestShop">Your nearest shop is <em>'+shops[closest_name].nam+'</em></span>';
			setDirections(starting_location, shops[closest_name].pnt[0]+', '+shops[closest_name].pnt[1], locale);
		}
	  }
	);
  }
}

function mapExpand() {
	$('#directions_info').hide();
	$('#map').animate({ width: '100%' }, 'slow', function(){ map.checkResize(); });
}

function mapShrink() {
	$('#map').animate({ width: '37em' }, 'fast', function(){ $('#directions_info').show(); map.checkResize(); });
}

function shop_focus(shop_name) {
	mapExpand();
	shops[shop_name].marker.openInfoWindowHtml(shops[shop_name].add);
}

/***
 * Postcode country hints
 */
//This is only currently good for UK postcodes
var formatPostcode = function(postcode){
	var pattern = /([a-zA-Z]{1,2}[\d]{1,2})[ ]*([\d]{1,2}[a-zA-Z]{2})/ig
	if (postcode.length <=9 && postcode.length > 4 && postcode.match(pattern)) {
		postcode = postcode.replace(pattern, "$1 $2");
	}
	return postcode.toUpperCase();
}

function chkZip(v){
	v = formatPostcode(v);
	var reg=/^.*, ?[a-zA-Z]{2}$/;
	if (v.search(reg)==-1) {
		var r = v+', '+ln_country_default;
	} else {
		var r = v;
	}
	return r;
}

window.onload = load;
window.onunload = GUnload;