google.load("maps", "2");
var map;
var stores = new Array();
var home;
function initmap() {
	map = new google.maps.Map2(document.getElementById("map"));
	map.addControl(new GLargeMapControl());
	map.setMapType(G_NORMAL_MAP);
	map.setCenter(new google.maps.LatLng(54.6,-4.064941), 5);
}

function get_distance(lat1,lon1,lat2,lon2) {
	var R = 6371; // km
	var dLat = toRad(lat2-lat1);
	var dLon = toRad(lon2-lon1); 
	var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
	        Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) * 
	        Math.sin(dLon/2) * Math.sin(dLon/2); 
	var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
	var d = R * c;
	return d;
}

function toRad(num) {  // convert degrees to radians
  return num * Math.PI / 180;
}

function roundNumber(num, dec) {
	var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
	return result;
}
function callbackFunc(a, b){
	return a - b;
}

function add_markers_to_map(mapObj,postcode) {
	var point;
	var data = {'postcode':postcode};
	var html_array = [];
	var distances_array = [];
	
	$.getJSON('stockist_data.php',data, function(json)
	{
		mapObj.clearOverlays();	
		if(json.markers.length == 0)
		{
			$('#store_info').html('Sorry, we cannot find any stockists for this location');
		}
		else
		{
			var centre = new GLatLng(json.centre.lat,json.centre.lon);

			map.setCenter(centre, 9);
			$('#store_info').html('');
		    for (x in json.markers) {
				var dist = get_distance(json.centre.lat,json.centre.lon,json.markers[x].lat,json.markers[x].lon);
				var html = 	'<p>'+
							'<strong>'+json.markers[x].store_name+'</strong><br />'+
							json.markers[x].address_1+'<br />';
				if (json.markers[x].address_2) html += json.markers[x].address_2+'<br />';
				if (json.markers[x].address_3) html += json.markers[x].address_3+'<br />';
				html += json.markers[x].city+'<br />'+
				json.markers[x].postcode+'<br />'+
				json.markers[x].telephone+'<br />'+
				'Distance: '+roundNumber(dist,1)+' km</p>';
				distances_array[x] = dist;
				html_array[dist] = html;
			
				point = new GLatLng(json.markers[x].lat,json.markers[x].lon);
				stores[x] = new GMarker(point,html);
				stores[x]['html'] = html;
				mapObj.addOverlay(stores[x]);
				GEvent.addListener(stores[x], 'click', function() {
					this.openInfoWindowHtml(this['html']);
				});								
		  	}
	
			//sort in order of distance and siaplay at the bottom
			distances_array = distances_array.sort(callbackFunc);
			for (var i=0; i<distances_array.length; i++)
			{
				distance = distances_array[i];
				html = html_array[distances_array[i]];
				$('#store_info').append(html);
			}
		}
	});	
}

$(document).ready(function() {
	$.ajaxSetup({ 
		timeout: 50000 
	});
	google.setOnLoadCallback(initmap);
	$('#stockist_form').submit(function(){
		add_markers_to_map(map,$('#postcode').val());
		return false;
	});
});

$(window).unload( function () {
	GUnload();
});
