﻿var map;
var userEntry;
var entriesOverlay = null;
var mapService = {
	loadMap: function(elementId, competitionActive) {
		map = new VEMap(elementId);
		map.HideDashboard();
		map.LoadMap(null, 8, VEMapStyle.Aerial, false);
		if (competitionActive) map.AttachEvent("ondoubleclick", mapService.addEntry);
	},
	unloadMap: function() {
		if (map != null) {
			map.Dispose();
		}
	},
	centerMap: function(lat, lon, radius) {
		if (map != null) {
			var origin = new VELatLong(lat, lon)
			map.SetCenter(origin);
			var target = new VEShape(VEShapeType.Pushpin, origin);
			target.SetCustomIcon('<img src="/content/launch_balloon.gif" title="I am here..." alt="I am here..." />');
			map.AddShape(target);
			var earthRadius = 6371;
			var latitude = (origin.Latitude * Math.PI) / 180;
			var longitude = (origin.Longitude * Math.PI) / 180;
			var d = parseFloat(radius) / earthRadius;
			var points = new Array();
			for (i = 0; i <= 360; i++) {
				var point = new VELatLong(0, 0);
				var bearing = i * Math.PI / 180;
				point.Latitude = Math.asin(Math.sin(latitude) * Math.cos(d) + Math.cos(latitude) * Math.sin(d) * Math.cos(bearing));
				point.Longitude = ((longitude + Math.atan2(Math.sin(bearing) * Math.sin(d) * Math.cos(latitude), Math.cos(d) - Math.sin(latitude) * Math.sin(point.Latitude))) * 180) / Math.PI;
				point.Latitude = (point.Latitude * 180) / Math.PI;
				points.push(point);
			}

			var circle = new VEShape(VEShapeType.Polygon, points);
			circle.HideIcon();
			circle.SetLineColor(new VEColor(255, 27, 34, 0.4));
			circle.SetFillColor(new VEColor(255, 27, 34, 0.1));
			map.AddShape(circle);
			map.SetMapView(points);
		}
	},
	setEntries: function(items) {
		if (map != null) {
			if (entriesOverlay != null) {
				map.DeleteShapeLayer(entriesOverlay);
				entriesOverlay = null;
			}
			if (items != null && items.length > 0) {
				entriesOverlay = new VEShapeLayer();
				var userTemplate = '<strong>Longitude: </strong>{$lon}<br /><strong>Latitude: </strong>{$lat}';
				for (var i = 0; i < items.length; i++) {
					var entry = items[i];
					var itemLatLon = new VELatLong(entry.Latitude, entry.Longitude);
					var convertedCoords = mapService.convertCoords(itemLatLon.toString());
					var inputLocation = new VEShape(VEShapeType.Pushpin, itemLatLon);
					inputLocation.SetCustomIcon('<img src="/content/others_chair.gif" title="@' + entry.UserName + '" alt="@' + entry.UserName + '" />');
					inputLocation.SetTitle('<img style="float: left;" src="' + entry.Image + '" title="@' + entry.UserName + ' alt="@' + entry.UserName + '" /><h3 style="float: left; margin-top: 0pt; margin-left: 10px;">@' + entry.UserName + '</h3>');
					inputLocation.SetDescription(userTemplate.substitute({ lat: convertedCoords[0], lon: convertedCoords[1] }));
					entriesOverlay.AddShape(inputLocation);
				}
				map.AddShapeLayer(entriesOverlay);
				entriesOverlay.Show();
			}
		}
	},
	toggleEntries: function() {
		if (entriesOverlay != null) {
			entriesOverlay.IsVisible() ? entriesOverlay.Hide() : entriesOverlay.Show();
			return entriesOverlay.IsVisible();
		}
		return false;
	},
	toggleView: function() {
		if (map != null) {
			if (map.GetMapStyle() == VEMapStyle.Road) {
				map.SetMapStyle(VEMapStyle.Aerial)
				return false;
			} else {
				map.SetMapStyle(VEMapStyle.Road)
				return true;
			}
		}
	},
	zoom: function(z) {
		if (map != null) {
			map.SetZoomLevel(map.GetZoomLevel() + z);
		}
	},
	addEntry: function(e) {
		if (map != null) {
			var userTemplate = '<strong>Longitude: </strong>{$lon}<br /><strong>Latitude: </strong>{$lat}<br /><br /><a id="your_chair_enter" onclick="addColorbox(this);return false;" href="/competition/addentry?latLong={$coords}">Select this position</a><br /<br /><a id="your_chair_cancel" href="#cancel" onclick="mapService.clearEntry();return false;">Cancel</a>';
			if (e.eventName == "ondoubleclick") {
				mapService.clearEntry();
				var userLatLon = map.PixelToLatLong(new VEPixel(e.mapX, e.mapY));
				var convertedCoords = mapService.convertCoords(userLatLon.toString());
				userEntry = new VEShape(VEShapeType.Pushpin, userLatLon);
				userEntry.SetCustomIcon('<img src="/content/your_chair.gif" title="Your chair" alt="Your chair" />');
				userEntry.SetTitle("<span id=\"your_chair_title\">Enter competition</span>");
				userEntry.SetDescription(userTemplate.substitute({ coords: userLatLon.toString(), lat: convertedCoords[0], lon: convertedCoords[1] }));
				map.AddShape(userEntry);
			}
		}
		return true;
	},
	clearEntry: function() {
		if (map != null) {
			if (userEntry != null) {
				map.DeleteShape(userEntry);
			}
		}
	},
	convertCoords: function(coords) {
		coords = coords.replace(/^\s+/, '');
		var c = coords.split(',');
		var latAbs = Math.abs(Math.round(c[0] * 1000000.));
		var lonAbs = Math.abs(Math.round(c[1] * 1000000.));

		var signlat = 1;
		if (latAbs.value < 0) { signlat = -1; }
		var signlon = 1;
		if (lonAbs.value < 0) { signlon = -1; }

		var lat = ((Math.floor(latAbs / 1000000) * signlat) + '° ' + Math.floor(((latAbs / 1000000) - Math.floor(latAbs / 1000000)) * 60) + '\' ' + (Math.floor(((((latAbs / 1000000) - Math.floor(latAbs / 1000000)) * 60) - Math.floor(((latAbs / 1000000) - Math.floor(latAbs / 1000000)) * 60)) * 100000) * 60 / 100000) + '"');

		if (lat.substr(0, 1) == '-') {
			lat = lat.substr(1) + ' N';
		} else {
			lat += ' N';
		}

		var lon = ((Math.floor(lonAbs / 1000000) * signlon) + '° ' + Math.floor(((lonAbs / 1000000) - Math.floor(lonAbs / 1000000)) * 60) + '\' ' + (Math.floor(((((lonAbs / 1000000) - Math.floor(lonAbs / 1000000)) * 60) - Math.floor(((lonAbs / 1000000) - Math.floor(lonAbs / 1000000)) * 60)) * 100000) * 60 / 100000) + '"');
		if (lon.substr(0, 1) == '-') {
			lon = lon.substr(1) + ' W';
		} else {
			lon += ' E';
		}

		var points = new Array();
		points.push(lat);
		points.push(lon);
		return points;
	}
};

String.prototype.substitute = function(o) {
	return this.replace(/{\$([^{}]*)}/g,
        function(a, b) {
        	var r = o[b];
        	return typeof r === 'string' || typeof r === 'number' ? r : a;
        }
    );
};