$(document).ready(function() {
	GetMap();
});

var map = null;
var lat = 54.54;
var lng = -4.0;
var zoom = 5;
var reddot = '/assets/images/weather/reddot.gif';
var bluedot = '/assets/images/weather/bluedot.gif';
var redpin = '<div class="redpin"><img src="/assets/images/weather/redpin.png"></div>';

function addPin(sTitle,sCode,lat,lng,sImage) {
	var description = '<div><h4>Postcode: '+sCode+'</h4><br><p>Latitude = '+lat+'</p><p>Longitude = '+lng+'</p></div>';
	var pin = new VEShape(VEShapeType.Pushpin, new VELatLong(lat,lng));
	pin.SetCustomIcon(sImage);
	pin.SetTitle('<div id="locationTitle" class="'+sCode+'"><h3>'+sTitle+'</h3></div>');
	pin.SetDescription(description);
	map.AddShape(pin);
}

function ChangeMapStyle(sStyle) {
	var s=map.GetMapStyle();
	if (s==sStyle) {
		return true;
	} else {
		map.SetMapStyle(sStyle);
	}
}

function MouseClickHandler(e) {
	if(e.elementID != null) {
		var pin = map.GetShapeByID(e.elementID);
		window.location = '/weather/location/'+$('#locationTitle').attr('class');
		return true;
	}
}

function EndZoomHandler(e) {
	map.DeleteAllShapes(); // Clear shapes from map
	var z = map.GetZoomLevel();
	if(z > 8) {
		var view = map.GetMapView();
		latMin = view.BottomRightLatLong.Latitude;
		lngMin = view.TopLeftLatLong.Longitude;
		latMax = view.TopLeftLatLong.Latitude;
		lngMax = view.BottomRightLatLong.Longitude;
		$.getJSON("/weather/locations?zoom="+z+"&latmin="+latMin+"&lngmin="+lngMin+"&latmax="+latMax+"&lngmax="+lngMax,
			function(data){
				$.each(data.items, function(i,item){
					addPin(item.name,item.outcode,item.lat,item.lng,redpin);
				});
			}
		);
	}
}


function UpdLatLng(e) {
	var z = map.GetZoomLevel();
	var x = e.mapX;
	var y = e.mapY;
	LatLng = map.PixelToLatLong(new VEPixel(x,y));
	document.getElementById("cursorLat").innerHTML = (LatLng.Latitude).toFixed(6);
	document.getElementById("cursorLng").innerHTML = (LatLng.Longitude).toFixed(6);
	document.getElementById("zoomLevel").innerHTML = z;
}

function GetMap() {
	map = new VEMap('VirtualEarthMap');
	map.SetDashboardSize(VEDashboardSize.Tiny);
	map.LoadMap(new VELatLong(lat, lng), zoom ,'r' ,false);
	map.AttachEvent("onmousemove",UpdLatLng);
	map.AttachEvent("onendzoom",EndZoomHandler);
	map.AttachEvent("onendpan",EndZoomHandler);
	map.AttachEvent("onclick",MouseClickHandler);
}
