Index: src/webapp/webclient/js/GnuBoat.Webclient.js
===================================================================
--- src/webapp/webclient/js/GnuBoat.Webclient.js	(revision 70f328bef4d0f40b5089b53eee8196a33ddb15f6)
+++ src/webapp/webclient/js/GnuBoat.Webclient.js	(revision 70f328bef4d0f40b5089b53eee8196a33ddb15f6)
@@ -0,0 +1,779 @@
+/*
+
+    Copyright (C) 2016 - 2018 EngSaS - Engineering Solutions and Services Langenbach. All rights reserved.
+
+    This library is free software; you can redistribute it and/or
+    modify it under the terms of the GNU Lesser General Public
+    License as published by the Free Software Foundation; either
+    version 2.1 of the License, or (at your option) any later version.
+
+    This library is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+    Lesser General Public License for more details.
+
+    You should have received a copy of the GNU Lesser General Public
+    License along with this library; if not, write to the Free Software
+    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
+    MA 02110-1301  USA.
+
+*/
+
+/** @namespace GnuBoat JavaScript namespace */
+var GnuBoat = GnuBoat || {};
+/** @namespace GnuBoat Webserver JavaScript namespace */
+GnuBoat.Webclient = GnuBoat.Webclient || {};
+
+/**
+ * @brief Sets the webservice base url, used by any other functions
+ */
+GnuBoat.Webclient.setServer = function(baseUrl)
+{
+	if(baseUrl.slice(-1) != "/")
+		baseUrl += "/";
+	GnuBoat.Webclient.private.serverBaseUrl = baseUrl;
+	
+	var link = document.createElement("a");
+	link.setAttribute("href", baseUrl);
+	$("#opencpnHint").empty();
+	$("<p>To connect OpenCPN with the GPSD running on this webservice, use <b>"+ link.hostname +":2947</b> and <b>"+ link.hostname +":2597</b> for the messages recieved on NMEA2000 bus.</p>").appendTo("#opencpnHint");
+}
+
+/**
+ * @brief Fetches the data shown in the display area from the webservice
+ */
+GnuBoat.Webclient.displayDataGet = function()
+{
+	if(GnuBoat.Webclient.private.serverBaseUrl == null){
+		GnuBoat.displayMessage('<span class="error">No server set/found</span>');
+		return;
+	}
+	var gnuboatApi = GnuBoat.Webclient.private.serverBaseUrl;
+	$.getJSON(gnuboatApi, GnuBoat.Webclient.private.displayDataSet);
+};
+
+/**
+ * @brief Gets the metadata of all maps, provided by the tileserver
+ */
+GnuBoat.Webclient.getMapInfos = function()
+{
+	if(GnuBoat.Webclient.private.serverBaseUrl == null){
+		GnuBoat.displayMessage('<span class="error">No server set/found</span>');
+		return;
+	}
+	$.getJSON(GnuBoat.Webclient.private.serverBaseUrl +"tileserver.php?/index.json", GnuBoat.Webclient.private.mapInfos);
+};
+
+/**
+ * @brief Fetches the list of available logfiles and adds them to the log file download form
+ */
+GnuBoat.Webclient.logfilesLoad = function()
+{
+	if(GnuBoat.Webclient.private.serverBaseUrl == null){
+		GnuBoat.displayMessage('<span class="error">No server set/found</span>');
+		return;
+	}
+	$("#logfilesForm").empty();
+	$.getJSON(GnuBoat.Webclient.private.serverBaseUrl +"?request=logfiles", function(data){
+		GnuBoat.Webclient.private.updateMapModus(data);
+		if(!Array.isArray(data) || data.length < 1){
+			$("<p>No Logfiles found!</p>").appendTo("#logfilesForm");
+			console.log(data);
+			return;
+		}
+		if(("error" in data) && data["error"] == 1){
+			GnuBoat.displayMessage('<span class="error">Failed to get log files: '+ data["errormessage"] +'</span>');
+			$("<p>No Logfiles found!</p>").appendTo("#logfilesForm");
+			console.log(data);
+			return;
+		}
+		$("<select id=\"logfilesSelect\" name=\"logfilesSelected[]\" class=\"pure-input-1\" multiple></select>").appendTo("#logfilesForm");
+		$("<input type=\"submit\" class=\"pure-button pure-button-primary\" name=\"logfilesDownload\" value=\"Download\"/>").appendTo("#logfilesForm");
+		data.forEach(function(value, index){
+			$("<option value=\""+ value +"\">"+ value +"</option>").appendTo("#logfilesSelect");
+		});
+	});
+};
+/**
+ * @brief Sends a shutdown request to the webservice
+ */
+GnuBoat.Webclient.shutdown = function()
+{
+	if(GnuBoat.Webclient.private.serverBaseUrl == null){
+		GnuBoat.displayMessage('<span class="error">No server set/found</span>');
+		return;
+	}
+	$.getJSON(GnuBoat.Webclient.private.serverBaseUrl +"?request=shutdown", function(data){
+		var shutdownTime = data["shutdownstart"];
+		var shutdownDate = Date.parse(shutdownTime);
+		var currentDate = new Date();
+		var shutdownHint = '<span class="info">Shutting down in '+ Math.floor((shutdownDate - currentDate)/1000) +"s at "+ shutdownTime.toLocaleString() +"</span>";
+		if(shutdownTime == -1){
+			shutdownHint = '<span class="error">Failed to initiate shutdown: '+ data["errormessage"] +"</span>";
+		}
+		GnuBoat.displayMessage(shutdownHint);
+	});
+};
+
+/**
+ * @brief Uploads a map and refreshes the maps metadata on success
+ */
+GnuBoat.Webclient.uploadMap = function(form)
+{
+	if(GnuBoat.Webclient.private.serverBaseUrl == null){
+		displayMessage('<span class="error">No server set/found</span>');
+		return;
+	}
+	$("#mapFileInput").hide();
+	$("#mapTileUploadProgress").show();
+	$.ajax({
+		type: 'POST',
+		url: GnuBoat.Webclient.private.serverBaseUrl +'?request=map',
+		data: new FormData($("#mapTileUpload")[0]),
+		contentType: false,
+		processData: false,
+		success: function(data){
+			if(("error" in data) && data["error"] == 1){
+				GnuBoat.displayMessage('<span class="error">Failed to upload map: '+ data["errormessage"] +'</span>');
+				$("#mapTileUploadProgress").hide();
+				$("#mapFileInput").show();
+				return;
+			}
+			GnuBoat.displayMessage('<span class="error">Map upload successfully</span>');
+			$("#mapTileUploadProgress").hide();
+			$("#mapFileInput").show();
+			GnuBoat.Webclient.getMapInfos();
+		},
+		error: function(jqXHR, exception, errorThrown){
+			GnuBoat.displayMessage('<span class="error">Failed to upload map (XHR): '+ exception +'</span>');
+			$("#mapTileUploadProgress").hide();
+			$("#mapFileInput").show();
+		}
+	}).progress(function(e){
+		$("#mapTileUploadProgress").attr({value: e.oloaded, max: e.total});
+	});
+};
+
+/**
+ * @brief Setups up GnuBoat to be able to start() after configured a server with setServer().
+ */
+GnuBoat.Webclient.initialize = function()
+{
+	$("#mapModusSelect").change(function(){ GnuBoat.Webclient.private.mapModusChanged(); });
+	$("#mapTileUploadProgress").hide();
+	$("#logfilesReload").click(GnuBoat.Webclient.logfilesLoad);
+	$("#shutdownButton").click(GnuBoat.Webclient.shutdown);
+
+	$("#mapTileUpload").validate({
+		rules: {
+			mapFile: {
+				required: true
+			},
+			mapName: {
+				required: true
+			}
+		},
+		submitHandler: function(form){
+			GnuBoat.Webclient.uploadMap(form);
+		}
+	});
+	
+	$("#logfilesForm").validate({
+		rules: {
+			logfilesSelect: {
+				required: true
+			},
+		}
+	});
+	
+	$("#rendering").empty();
+	var width = $("#rendering").width();
+	var height = $("#rendering").height();
+
+	var fieldOfView = 75;
+	
+	GnuBoat.Webclient.private.renderScene = new THREE.Scene();
+	GnuBoat.Webclient.private.renderScene.background = new THREE.Color(0xEEEEEE);
+	
+	GnuBoat.Webclient.private.renderCamera = new THREE.PerspectiveCamera(75, width/height, 0.1, 1000000);
+	GnuBoat.Webclient.private.renderCamera.up = new THREE.Vector3(0, 0, 1);
+	GnuBoat.Webclient.private.renderCamera.position.set(-0.01, -0.01, 15000);
+	GnuBoat.Webclient.private.renderCamera.lookAt(GnuBoat.Webclient.private.renderScene.position);
+	
+	GnuBoat.Webclient.private.renderRenderer = new THREE.WebGLRenderer();
+	GnuBoat.Webclient.private.renderRenderer.setSize(width, height);
+	GnuBoat.Webclient.private.renderRenderer.setPixelRatio( window.devicePixelRatio );
+	document.getElementById("rendering").appendChild(GnuBoat.Webclient.private.renderRenderer.domElement);
+	
+	GnuBoat.Webclient.private.renderControls = new THREE.OrbitControls( GnuBoat.Webclient.private.renderCamera, GnuBoat.Webclient.private.renderRenderer.domElement );
+	GnuBoat.Webclient.private.renderControls.zoomSpeed = 2;
+}
+
+/**
+ * @brief Starts querying the webservice
+ * 
+ * Call initialize() and setServer() before start()
+ */
+GnuBoat.Webclient.start = function()
+{
+	if(GnuBoat.Webclient.private.serverBaseUrl == null){
+		GnuBoat.displayMessage('<span class="error">No server set/found</span>');
+		return;
+	}
+	
+	GnuBoat.Webclient.getMapInfos();
+	GnuBoat.Webclient.displayDataGet();
+	if(GnuBoat.Webclient.private.timerDisplay == null)
+		GnuBoat.Webclient.private.timerDisplay = setInterval(GnuBoat.Webclient.displayDataGet, 10000);
+	GnuBoat.Webclient.logfilesLoad();
+	
+	GnuBoat.Webclient.private.animate();
+}
+
+/**
+ * @brief Stops querying the webservice
+ */
+GnuBoat.Webclient.stop = function()
+{
+	if(GnuBoat.Webclient.private.timerDisplay != null){
+		clearInterval(GnuBoat.Webclient.private.timerDisplay);
+		GnuBoat.Webclient.private.timerDisplay = null;
+	}
+}
+
+/**
+ * @brief Private methods and properties of GnuBoat
+ */
+GnuBoat.Webclient.private = {
+	map: null,
+	mapLayerCurrent: null,
+	mapPolylines: [],
+	mapControl: null,
+	mapsMetadata: null,
+	mapBounds: null,
+	mapModusLive: true,
+	mapHotlineGradientDefault: { absolute: false, palette: { 0.0: 'green', 0.5: 'yellow', 1.0: 'red' } },
+	dataMappings: {
+		speedthroughwater: {display: true, map: true, mapActive: false, titleLong: "Speed Through Water", titleShort: "STW", unit: "kts"},
+		speedoverground:  {display: true, map: true, mapActive: false, titleLong: "Speed Over Ground", titleShort: "SOG", unit: "kts"},
+		waterdepth: {
+			display: true, map: true, mapActive: true, titleLong: "Waterdepth", titleShort: "Depth", unit: "m",
+			gradient: {
+				absolute: true,
+				palette: { 0: 'DarkBlue', 2: 'DodgerBlue', 6: 'LightBlue', 10: 'AliceBlue'},
+			}
+		},
+		watertemperature: {display: true, map: true, mapActive: false, titleLong: "Watertemperature", titleShort: "Water", unit: "°C"},
+		gpsfix: {display: true, map: false, mapActive: false, titleLong: "GPS Fix", titleShort: "Fix", unit: ""},
+	},
+	serverBaseUrl: null,
+	timerDisplay: null,
+	renderScene: null,
+	renderCamera: null,
+	renderRenderer: null,
+	renderMapBounds: null,
+	renderGrid: null,
+	renderControls: null,
+	renderCloud: null,
+	
+	openLink: function(target)
+	{
+		window.location=target;
+	},
+	
+	displayDataSet: function(data)
+	{
+// 		if(!Array.isArray(data) || data.length < 1){
+// 			console.log("No data array returned!");
+// 			console.log(data);
+// 			return;
+// 		}
+		if(("error" in data) && data["error"] == 1){
+			GnuBoat.displayMessage('<span class="error">Failed to get display data and tracks: '+ data["errormessage"] +'</span>');
+			return;
+		}
+
+		var keysDisplay = [];
+		for(var key in GnuBoat.Webclient.private.dataMappings){
+			if(GnuBoat.Webclient.private.dataMappings[key]["display"] === true)
+				keysDisplay.push(key);
+		}
+
+		if(!("lastvalid" in data)){
+				console.log("No last valid values given!");
+		}
+		else{
+			var lastValid = data["lastvalid"];
+			for(var i = 0; i < keysDisplay.length; i++){
+				var key = keysDisplay[i];
+				var value = lastValid[key];
+				if($.isNumeric(value)){
+					var text = value.toFixed(1);
+					if(key == "watertemperature"){
+						text = value.toFixed(0);
+					}
+					$("#display #"+ key +" #value").text(text);
+				}
+				else if(key == "gpsfix"){
+					$("#display #"+ key +" #value").text(value);
+				}
+			}
+		}
+		
+		// map displays logged data
+		if(!GnuBoat.Webclient.private.mapModusLive)
+			return;
+		else if(!("track" in data)){
+			console.log("No track given!");
+			return;
+		}
+		GnuBoat.Webclient.private.mapAddTracks(data["track"]);
+	},
+	
+	mapSetup: function ()
+	{
+		var mapMetadataIndex = $("#mapSelect").val();
+		if(GnuBoat.Webclient.private.mapsMetadata == null){
+			console.log("No mapsMetadata set");
+			return;
+		}
+		if(mapMetadataIndex < 0 || mapMetadataIndex >= GnuBoat.Webclient.private.mapsMetadata.length){
+			console.log("Map metadata is outside of range :"+ mapMetadataIndex.toString());
+			console.log(mapsMetadata);
+			return;
+		}
+		var mapMetadata = GnuBoat.Webclient.private.mapsMetadata[mapMetadataIndex];
+		
+		var latitudeTop = mapMetadata["bounds"][3];
+		var latitudeBottom = mapMetadata["bounds"][1];
+		var longitudeLeft = mapMetadata["bounds"][0];
+		var longitudeRight = mapMetadata["bounds"][2];
+		
+		var mapZoomMin = mapMetadata["minzoom"];
+		var mapZoomMax = mapMetadata["maxzoom"];
+		
+		var latitudeCenter = (latitudeTop - latitudeBottom)/2 + latitudeBottom;
+		var longitudeCenter = (longitudeLeft - longitudeRight)/2 + longitudeRight;
+		var mapZoomStart = (mapZoomMax - mapZoomMin)/2 + mapZoomMin;
+		
+		GnuBoat.Webclient.private.mapBounds = new L.LatLngBounds(
+				new L.LatLng(latitudeBottom, longitudeLeft),
+				new L.LatLng(latitudeTop, longitudeRight));
+		
+		if(GnuBoat.Webclient.private.map == null){
+			// only initialize the map (viewport) once
+			GnuBoat.Webclient.private.map = L.map('mapViewport');
+			GnuBoat.Webclient.private.map.on('overlayadd', function(layerObject){ GnuBoat.Webclient.private.mapOverlayLegendSwitch(layerObject.layer); });
+			GnuBoat.Webclient.private.map.on('overlayremove', function(layerObject){ GnuBoat.Webclient.private.mapOverlayLegendSwitch(layerObject.layer); });
+		}
+		GnuBoat.Webclient.private.map.setView([latitudeCenter, longitudeCenter], mapZoomStart);
+		
+		if(GnuBoat.Webclient.private.mapLayerCurrent != null){
+			GnuBoat.Webclient.private.map.removeLayer(GnuBoat.Webclient.private.mapLayerCurrent);
+			if(GnuBoat.Webclient.private.mapControl)
+				GnuBoat.Webclient.private.mapControl.removeLayer(GnuBoat.Webclient.private.mapLayerCurrent);
+			GnuBoat.Webclient.private.mapLayerCurrent = null;
+		}
+		GnuBoat.Webclient.private.mapLayerCurrent = L.tileLayer(mapMetadata["tiles"][0], {
+			minZoom: mapZoomMin, maxZoom: mapZoomMax,
+			bounds: GnuBoat.Webclient.private.mapBounds,
+			attribution: mapMetadata["name"],
+			opacity: 0.85
+			}).addTo(GnuBoat.Webclient.private.map);
+		if(GnuBoat.Webclient.private.mapControl != null)
+			GnuBoat.Webclient.private.mapControl.addBaseLayer(GnuBoat.Webclient.private.mapLayerCurrent, "Map");
+		else{
+			GnuBoat.Webclient.private.mapControl = L.control.layers({"Map": GnuBoat.Webclient.private.mapLayerCurrent}, GnuBoat.Webclient.private.mapOverlaysToList(), {hideSingleBase: true, sortLayers: true, }).addTo(GnuBoat.Webclient.private.map);
+		}
+		
+		// configure render scene for new map
+		GnuBoat.Webclient.private.renderSetupMap();
+	},
+	
+	mapInfos: function(data)
+	{
+		GnuBoat.Webclient.private.mapsMetadata = data;
+		
+		$("#mapSelect").empty();
+		var selected = "selected";
+		data.forEach(function(value, index){
+			$("<option value=\""+ index.toString() +"\" "+ selected +">"+ value["name"] +"</option>").appendTo("#mapSelect");
+			selected = "";
+		});
+		
+		GnuBoat.Webclient.private.mapSetup();
+		$("#mapSelect").change(function(){ GnuBoat.Webclient.private.mapSetup(); });
+	},
+	
+	mapOverlaysToList: function()
+	{
+		var overlays = {};
+		for(var key in GnuBoat.Webclient.private.mapPolylines){
+			overlays[key] = GnuBoat.Webclient.private.mapPolylines[key];
+		}
+		return overlays;
+	},
+	
+	renderSetupMap: function()
+	{
+		if(GnuBoat.Webclient.private.mapBounds == null)
+			return;
+
+		// add map bounds
+		if(GnuBoat.Webclient.private.renderMapBounds != null)
+			GnuBoat.Webclient.private.renderScene.remove(GnuBoat.Webclient.private.renderMapBounds);
+		var m1 = GnuBoat.Webclient.private.mercator(GnuBoat.Webclient.private.mapBounds.getSouth(), GnuBoat.Webclient.private.mapBounds.getWest());
+		var m2 = GnuBoat.Webclient.private.mercator(GnuBoat.Webclient.private.mapBounds.getSouth(), GnuBoat.Webclient.private.mapBounds.getEast());
+		var m3 = GnuBoat.Webclient.private.mercator(GnuBoat.Webclient.private.mapBounds.getNorth(), GnuBoat.Webclient.private.mapBounds.getEast());
+		var m4 = GnuBoat.Webclient.private.mercator(GnuBoat.Webclient.private.mapBounds.getNorth(), GnuBoat.Webclient.private.mapBounds.getWest());
+		var geometryMapBounds = new THREE.Geometry();
+		var materialMapBounds = new THREE.LineBasicMaterial({color: 0x66BD66, linewidth: 1});
+		// z is greator 0, to draw the map boundings over the grid
+		var vertex = new THREE.Vector3(0, 0, 2);
+		geometryMapBounds.vertices.push(vertex);
+		vertex = new THREE.Vector3(m2.x - m1.x, m2.y - m1.y, 2);
+		geometryMapBounds.vertices.push(vertex);
+		vertex = new THREE.Vector3(m3.x - m1.x, m3.y - m1.y, 2);
+		geometryMapBounds.vertices.push(vertex);
+		vertex = new THREE.Vector3(m4.x - m1.x, m4.y - m1.y, 2);
+		geometryMapBounds.vertices.push(vertex);
+		GnuBoat.Webclient.private.renderMapBounds = new THREE.LineLoop(geometryMapBounds, materialMapBounds);
+		GnuBoat.Webclient.private.renderScene.add(GnuBoat.Webclient.private.renderMapBounds);
+
+		// add 500m grid
+		if(GnuBoat.Webclient.private.renderGrid != null)
+			GnuBoat.Webclient.private.renderScene.remove(GnuBoat.Webclient.private.renderGrid);
+		geometryMapBounds.computeBoundingBox();	
+		var maxLength = Math.max(geometryMapBounds.boundingBox.getSize().x, geometryMapBounds.boundingBox.getSize().y);
+		GnuBoat.Webclient.private.renderGrid = new THREE.GridHelper(maxLength, Math.round(maxLength / 500.0), 0xCCCCCC, 0xCCCCCC);
+		GnuBoat.Webclient.private.renderGrid.geometry.rotateX( Math.PI / 2 );
+		GnuBoat.Webclient.private.renderGrid.translateX(maxLength / 2.0);
+		GnuBoat.Webclient.private.renderGrid.translateY(maxLength / 2.0);
+		GnuBoat.Webclient.private.renderScene.add(GnuBoat.Webclient.private.renderGrid);
+		
+		var distance = 150;
+		var fieldOfView = 2 * Math.atan(maxLength / (2.0 * distance) ) * 180.0 / Math.PI;
+		GnuBoat.Webclient.private.renderCamera.position.set(-10, -5, 100);
+		GnuBoat.Webclient.private.renderCamera.fov = fieldOfView;
+		GnuBoat.Webclient.private.renderCamera.lookAt(GnuBoat.Webclient.private.renderScene.position);
+		GnuBoat.Webclient.private.renderCamera.zoom = 5;
+		GnuBoat.Webclient.private.renderCamera.updateProjectionMatrix();
+	},
+	
+	drawDensityEstimation: function(densityPoints, gradient, maximum, minimum)
+	{
+		var colors = GnuBoat.Webclient.private.gradientToRenderColors(gradient, maximum, minimum);
+		// converting all indizes into numbers to sort them correctly
+		// in descending order e.g. 10, 2, 1, 0 and not 2, 10, 1, 0
+		var colorsIndizes = Object.getOwnPropertyNames(colors);
+		colorsIndizes.sort(function(a, b){
+			a = +a;
+			b = +b;
+			return a-b;
+		});
+		var colorsCount = colorsIndizes.length;
+		
+		var material = new THREE.PointsMaterial({vertexColors: THREE.VertexColors, size: 5});
+		var geometry = new THREE.Geometry();
+		var mercatorSouthWest = {x: 0, y: 0};
+		if(GnuBoat.Webclient.private.mapBounds != null)
+			mercatorSouthWest = GnuBoat.Webclient.private.mercator(GnuBoat.Webclient.private.mapBounds.getSouth(), GnuBoat.Webclient.private.mapBounds.getWest());
+		
+		for(var i = 0; i < densityPoints.length; i++){
+			var mercator = GnuBoat.Webclient.private.mercator(densityPoints[i].latitude, densityPoints[i].longitude);
+			var vertex = new THREE.Vector3(mercator.x - mercatorSouthWest.x, mercator.y - mercatorSouthWest.y, (densityPoints[i].depth * -1) + maximum);
+			var step = (densityPoints[i].depth - minimum)/(maximum-minimum);
+			var color = new THREE.Color(0x000000);
+			for(var j = 0; j < colorsCount; j++){
+				if(j < colorsCount - 1)
+					color = colors[colorsIndizes[j]];
+				if(step <= colorsIndizes[j+1]){
+					color = colors[colorsIndizes[j]];
+					break;
+				}
+			}
+			geometry.vertices.push(vertex);
+			geometry.colors.push(color);
+		}
+		// point cloud
+		if(GnuBoat.Webclient.private.renderCloud != null)
+			GnuBoat.Webclient.private.renderScene.remove(GnuBoat.Webclient.private.renderCloud);
+		GnuBoat.Webclient.private.renderCloud = new THREE.Points(geometry, material);
+		GnuBoat.Webclient.private.renderScene.add(GnuBoat.Webclient.private.renderCloud);
+	},
+	
+	animate: function()
+	{
+		requestAnimationFrame(GnuBoat.Webclient.private.animate);
+		if(GnuBoat.Webclient.private.renderCloud != null){
+			var scaleZ = $("#renderScaleZ").val();
+			if(GnuBoat.Webclient.private.renderCloud.scale.z != scaleZ)
+				GnuBoat.Webclient.private.renderCloud.scale.set(1, 1, scaleZ);
+		}
+		
+		GnuBoat.Webclient.private.renderControls.update();
+		GnuBoat.Webclient.private.renderRenderer.render(GnuBoat.Webclient.private.renderScene, GnuBoat.Webclient.private.renderCamera);
+	},
+	
+	mercator: function(latitude, longitude)
+	{
+		var result = {};
+		
+		var earthRadius = 6378137.0;
+		
+		result["x"] = longitude / 180.0 * Math.PI * earthRadius;
+		result["y"] = Math.log(Math.tan(latitude / 180.0 * Math.PI / 2.0 + Math.PI / 4.0)) * earthRadius;
+
+		return result;
+	},
+	
+	updateMapModus: function(data)
+	{
+		var selected = $("#mapModusSelect").val();
+		$("#mapModusSelect").empty();
+		var selectedFound = false;
+		if(selected != null && Array.isArray(data)){
+			data.forEach(function(value, index){
+				if(value == selected)
+					selectedFound = true;
+			});
+		}
+		var selectedString = "";
+		if(!selectedFound)
+			selectedString = " selected";
+		$('<option value="live"'+ selectedString +'>Live View</option>').appendTo("#mapModusSelect");
+		if(!Array.isArray(data) || data.length < 1){
+			console.log(data);
+			return;
+		}
+		if(("error" in data) && data["error"] == 1){
+			GnuBoat.displayMessage('<span class="error">Failed to upload map: '+ data["errormessage"] +'</span>');
+			return;
+		}
+		data.forEach(function(value, index){
+			var selectedString = "";
+			if(value == selected)
+				selectedString = " selected";
+			$("<option value=\""+ value +"\""+ selected +">"+ value +"</option>").appendTo("#mapModusSelect");
+		});
+	},
+	
+	mapModusChanged: function()
+	{
+		var modus = $("#mapModusSelect").val();
+		// live modus is automatically activated on displayDataSet
+		if(modus == "live"){
+			GnuBoat.Webclient.private.mapModusLive = true;
+			return;
+		}
+		// remove overlays
+		if(GnuBoat.Webclient.private.mapControl != null){
+			for(var key in GnuBoat.Webclient.private.dataMappings){
+				if(GnuBoat.Webclient.private.dataMappings[key]["map"] === true)
+					if(key in GnuBoat.Webclient.private.mapPolylines){
+						GnuBoat.Webclient.private.mapControl.removeLayer(GnuBoat.Webclient.private.mapPolylines[key]);
+						GnuBoat.Webclient.private.mapPolylines[key].remove();
+						delete GnuBoat.Webclient.private.mapPolylines[key];
+					}
+			}
+		}
+		GnuBoat.Webclient.private.mapModusLive = false;
+		$.post({
+			url: GnuBoat.Webclient.private.serverBaseUrl +'?request=replay',
+			data: { logfile: modus },
+			success: function(data){
+// 				if(!Array.isArray(data) || data.length < 1){
+// 					console.log("No data array returned!");
+// 					console.log(data);
+// 					return;
+// 				}
+				if(("error" in data) && data["error"] == 1){
+					GnuBoat.displayMessage('<span class="error">Failed to get logged tracks: '+ data["errormessage"] +'</span>');
+					return;
+				}
+				if(!("track" in data)){
+					console.log("No track given!");
+					return;
+				}
+				GnuBoat.Webclient.private.mapAddTracks(data["track"]);
+			}
+		});
+	},
+	
+	mapAddTracks: function(track)
+	{
+		if(GnuBoat.Webclient.private.map == null){
+			console.log("No map in use");
+			return;
+		}
+		
+		$("#mapLegend").empty();
+		var maximas = [];
+		var minimas = [];
+		var points = [];
+		var densityPoints = [];
+		
+		var keysMap = [];
+		for(var key in GnuBoat.Webclient.private.dataMappings){
+			if(GnuBoat.Webclient.private.dataMappings[key]["map"] === true)
+				keysMap.push(key);
+		}
+		for(var i = 0; i < keysMap.length; i++){
+			points[keysMap[i]] = [];
+		}
+		
+		// getting maximas, minimums for normalization and the tracks themselves
+		for(var time in track){
+			for(var i = 0; i < keysMap.length; i++){
+				var key = keysMap[i];
+				var value = track[time][key];
+				if(!$.isNumeric(value))
+					continue;
+				if(!(key in maximas))
+					maximas[key] = value
+				else if(maximas[key] < value)
+					maximas[key] = value;
+				if(!(key in minimas))
+					minimas[key] = value
+				else if(minimas[key] > value)
+					minimas[key] = value;
+				points[key].push(new L.latLng(track[time]["latitude"], track[time]["longitude"], value));
+				if(key == "waterdepth")
+					densityPoints.push({latitude: track[time]["latitude"], longitude: track[time]["longitude"], depth: value});
+			}
+		}
+		for(var i = 0; i < keysMap.length; i++){
+			var key = keysMap[i];
+			if(points[key].length > 0){
+				var palette = GnuBoat.Webclient.private.mapHotlineGradientDefault.palette;
+				var paletteLegend = GnuBoat.Webclient.private.mapHotlineGradientDefault.palette;
+				if("gradient" in GnuBoat.Webclient.private.dataMappings[key]){
+					palette = GnuBoat.Webclient.private.gradientToPalette(GnuBoat.Webclient.private.dataMappings[key]["gradient"], maximas[key], minimas[key]);
+					// use original palette, to use absolute values, if possible
+					paletteLegend = GnuBoat.Webclient.private.dataMappings[key]["gradient"]["palette"];
+				}
+				
+				var legendTable = $('<table id="'+ key +'" class="hidden"></table>');
+				$("<tr><th colspan=2>"+ GnuBoat.Webclient.private.dataMappings[key]["titleShort"] +" in "+ GnuBoat.Webclient.private.dataMappings[key]["unit"] +"</th></tr>").appendTo(legendTable);
+				$("<tr><th>Level</th><th>Color</th></tr>").appendTo(legendTable);
+				// converting all indizes into numbers to sort them correctly
+				// e.g. 0, 1, 2, 10 and not 0, 1, 10, 2
+				var indizes = Object.getOwnPropertyNames(paletteLegend);
+				indizes.sort(function(a, b){
+					a = +a;
+					b = +b;
+					return a-b;
+				});
+				for(var j=0; j < indizes.length; j++){
+					var index = indizes[j];
+					$('<tr><td class="level">'+ index.toString() +'</td><td style="background-color: '+ paletteLegend[index] +'"></td></tr>').appendTo(legendTable);
+				}
+				$('<tr><td colspan="2">Extrema: '+ maximas[key].toString() +' / '+ minimas[key].toString() +'</td></tr>').appendTo(legendTable);
+				
+				var hotlineOptions = {
+					weight: 3,
+					outlineWidth: 0,
+					min: minimas[key],
+					max: maximas[key],
+					palette: palette,
+				};
+				
+				legendTable.appendTo("#mapLegend");
+			
+				if(key in GnuBoat.Webclient.private.mapPolylines){
+					GnuBoat.Webclient.private.mapPolylines[key].setStyle(hotlineOptions);
+					GnuBoat.Webclient.private.mapPolylines[key].setLatLngs(points[key]);
+					if(GnuBoat.Webclient.private.map.hasLayer(GnuBoat.Webclient.private.mapPolylines[key]))
+						GnuBoat.Webclient.private.mapOverlayLegendSwitch(GnuBoat.Webclient.private.mapPolylines[key]);
+					GnuBoat.Webclient.private.mapPolylines[key].unbindPopup();
+				}
+				else{
+					GnuBoat.Webclient.private.mapPolylines[key] = L.hotline(points[key], hotlineOptions);
+					if(GnuBoat.Webclient.private.mapControl){
+						var name = GnuBoat.Webclient.private.dataMappings[key]["titleLong"] +" in "+ GnuBoat.Webclient.private.dataMappings[key]["unit"] +" ("+ GnuBoat.Webclient.private.dataMappings[key]["titleShort"] +")";
+						GnuBoat.Webclient.private.mapControl.addOverlay(GnuBoat.Webclient.private.mapPolylines[key], name);
+					}
+					if(GnuBoat.Webclient.private.dataMappings[key]["mapActive"] === true)
+						GnuBoat.Webclient.private.mapPolylines[key].addTo(GnuBoat.Webclient.private.map);
+				}
+				GnuBoat.Webclient.private.mapPolylines[key].bindPopup(legendTable[0].outerHTML);
+			}
+		}
+		var gradient = GnuBoat.Webclient.private.mapHotlineGradientDefault.palette;
+		if("gradient" in GnuBoat.Webclient.private.dataMappings["waterdepth"])
+			gradient = GnuBoat.Webclient.private.dataMappings["waterdepth"]["gradient"];
+		GnuBoat.Webclient.private.drawDensityEstimation(densityPoints, gradient, maximas["waterdepth"], minimas["waterdepth"]);
+	},
+	
+	gradientToPalette: function(gradient, maximum, minimum)
+	{
+		if(!("palette" in gradient)){
+			return GnuBoat.Webclient.private.mapHotlineGradientDefault.palette;
+		}
+		if(!("absolute" in gradient) || !gradient.absolute){
+			// palette is already relative
+			return gradient.palette;
+		}
+		var range = maximum - minimum;
+		if(range == 0){
+			console.log("Range is zero --> Could not make gradient relative");
+			return  GnuBoat.Webclient.private.mapHotlineGradientDefault.palette;
+		}
+		var palette = {};
+		var addedStop = false;
+		for(var indexAbs in gradient.palette){
+			var indexRel = (indexAbs - minimum)/range;
+			if(indexRel < 0){
+				// add the nearest minimum value (which might be configured smaller than minimum)
+				indexRel = 0;
+				palette[indexRel] = gradient.palette[indexAbs];
+				addedStop = true;
+			}
+			else if(indexRel < 1){
+				palette[indexRel] = gradient.palette[indexAbs];
+				addedStop = true;
+			}
+			else{
+				// add first index > 1 as the maximum value at 1
+				indexRel = 1;
+				palette[indexRel] = gradient.palette[indexAbs];
+				addedStop = true;
+				break;
+			}
+		}
+		if(!addedStop)
+			return GnuBoat.Webclient.private.mapHotlineGradientDefault.palette;
+		return palette;
+	},
+	
+	gradientToRenderColors: function(gradient, maximum, minimum)
+	{
+		var paletteRelative = GnuBoat.Webclient.private.gradientToPalette(gradient, maximum, minimum);
+
+		var colors = {};
+		for(var index in paletteRelative)
+			colors[index] = new THREE.Color(paletteRelative[index].toLowerCase());
+
+		return colors;
+	},
+
+	mapOverlayLegendSwitch: function(layer)
+	{
+		var overlayKey = null;
+		for(var key in GnuBoat.Webclient.private.mapPolylines){
+			if(GnuBoat.Webclient.private.mapPolylines.hasOwnProperty(key)){
+				if(GnuBoat.Webclient.private.mapPolylines[key] === layer){
+					overlayKey = key;
+					break;
+				}
+			}
+		}
+		// ECMAScript 6
+// 		var overlayKey = Object.keys(GnuBoat.Webclient.private.mapPolylines).find(key => GnuBoat.Webclient.private.mapPolylines[key] === overlay);
+		if(overlayKey == null)
+			return;
+		if(overlayKey){
+			$("#mapLegend #"+ overlayKey).toggleClass("hidden");
+		}
+	},
+};
Index: src/webapp/webclient/js/GnuBoat.js
===================================================================
--- src/webapp/webclient/js/GnuBoat.js	(revision b8b5e774e7bc5a634ac5fcbf6d9cfe9a987e3c58)
+++ 	(revision )
@@ -1,787 +1,0 @@
-/*
-
-    Copyright (C) 2016 - 2017 EngSaS - Engineering Solutions and Services Langenbach. All rights reserved.
-
-    This library is free software; you can redistribute it and/or
-    modify it under the terms of the GNU Lesser General Public
-    License as published by the Free Software Foundation; either
-    version 2.1 of the License, or (at your option) any later version.
-
-    This library is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-    Lesser General Public License for more details.
-
-    You should have received a copy of the GNU Lesser General Public
-    License along with this library; if not, write to the Free Software
-    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
-    MA 02110-1301  USA.
-
-*/
-
-/** @namespace GnuBoat JavaScript namespace */
-var GnuBoat = GnuBoat || {};
-
-/**
- * @brief Sets the webservice base url, used by any other functions
- */
-GnuBoat.setServer = function(baseUrl)
-{
-	if(baseUrl.slice(-1) != "/")
-		baseUrl += "/";
-	GnuBoat.private.serverBaseUrl = baseUrl;
-	
-	var link = document.createElement("a");
-	link.setAttribute("href", baseUrl);
-	$("#opencpnHint").empty();
-	$("<p>To connect OpenCPN with the GPSD running on this webservice, use <b>"+ link.hostname +":2947</b> and <b>"+ link.hostname +":2597</b> for the messages recieved on NMEA2000 bus.</p>").appendTo("#opencpnHint");
-}
-
-/**
- * @brief Used to display user messages
- */
-GnuBoat.displayMessage = function(text)
-{
-	$("#message").empty();
-	$(text).appendTo("#message");
-	location.hash = "#messages";
-}
-
-/**
- * @brief Fetches the data shown in the display area from the webservice
- */
-GnuBoat.displayDataGet = function()
-{
-	if(GnuBoat.private.serverBaseUrl == null){
-		GnuBoat.displayMessage('<span class="error">No server set/found</span>');
-		return;
-	}
-	var gnuboatApi = GnuBoat.private.serverBaseUrl;
-	$.getJSON(gnuboatApi, GnuBoat.private.displayDataSet);
-};
-
-/**
- * @brief Gets the metadata of all maps, provided by the tileserver
- */
-GnuBoat.getMapInfos = function()
-{
-	if(GnuBoat.private.serverBaseUrl == null){
-		GnuBoat.displayMessage('<span class="error">No server set/found</span>');
-		return;
-	}
-	$.getJSON(GnuBoat.private.serverBaseUrl +"tileserver.php?/index.json", GnuBoat.private.mapInfos);
-};
-
-/**
- * @brief Fetches the list of available logfiles and adds them to the log file download form
- */
-GnuBoat.logfilesLoad = function()
-{
-	if(GnuBoat.private.serverBaseUrl == null){
-		GnuBoat.displayMessage('<span class="error">No server set/found</span>');
-		return;
-	}
-	$("#logfilesForm").empty();
-	$.getJSON(GnuBoat.private.serverBaseUrl +"?request=logfiles", function(data){
-		GnuBoat.private.updateMapModus(data);
-		if(!Array.isArray(data) || data.length < 1){
-			$("<p>No Logfiles found!</p>").appendTo("#logfilesForm");
-			console.log(data);
-			return;
-		}
-		if(("error" in data) && data["error"] == 1){
-			GnuBoat.displayMessage('<span class="error">Failed to get log files: '+ data["errormessage"] +'</span>');
-			$("<p>No Logfiles found!</p>").appendTo("#logfilesForm");
-			console.log(data);
-			return;
-		}
-		$("<select id=\"logfilesSelect\" name=\"logfilesSelected[]\" class=\"pure-input-1\" multiple></select>").appendTo("#logfilesForm");
-		$("<input type=\"submit\" class=\"pure-button pure-button-primary\" name=\"logfilesDownload\" value=\"Download\"/>").appendTo("#logfilesForm");
-		data.forEach(function(value, index){
-			$("<option value=\""+ value +"\">"+ value +"</option>").appendTo("#logfilesSelect");
-		});
-	});
-};
-/**
- * @brief Sends a shutdown request to the webservice
- */
-GnuBoat.shutdown = function()
-{
-	if(GnuBoat.private.serverBaseUrl == null){
-		GnuBoat.displayMessage('<span class="error">No server set/found</span>');
-		return;
-	}
-	$.getJSON(GnuBoat.private.serverBaseUrl +"?request=shutdown", function(data){
-		var shutdownTime = data["shutdownstart"];
-		var shutdownDate = Date.parse(shutdownTime);
-		var currentDate = new Date();
-		var shutdownHint = '<span class="info">Shutting down in '+ Math.floor((shutdownDate - currentDate)/1000) +"s at "+ shutdownTime.toLocaleString() +"</span>";
-		if(shutdownTime == -1){
-			shutdownHint = '<span class="error">Failed to initiate shutdown: '+ data["errormessage"] +"</span>";
-		}
-		GnuBoat.displayMessage(shutdownHint);
-	});
-};
-
-/**
- * @brief Uploads a map and refreshes the maps metadata on success
- */
-GnuBoat.uploadMap = function(form)
-{
-	if(GnuBoat.private.serverBaseUrl == null){
-		displayMessage('<span class="error">No server set/found</span>');
-		return;
-	}
-	$("#mapFileInput").hide();
-	$("#mapTileUploadProgress").show();
-	$.ajax({
-		type: 'POST',
-		url: GnuBoat.private.serverBaseUrl +'?request=map',
-		data: new FormData($("#mapTileUpload")[0]),
-		contentType: false,
-		processData: false,
-		success: function(data){
-			if(("error" in data) && data["error"] == 1){
-				GnuBoat.displayMessage('<span class="error">Failed to upload map: '+ data["errormessage"] +'</span>');
-				$("#mapTileUploadProgress").hide();
-				$("#mapFileInput").show();
-				return;
-			}
-			GnuBoat.displayMessage('<span class="error">Map upload successfully</span>');
-			$("#mapTileUploadProgress").hide();
-			$("#mapFileInput").show();
-			GnuBoat.getMapInfos();
-		},
-		error: function(jqXHR, exception, errorThrown){
-			GnuBoat.displayMessage('<span class="error">Failed to upload map (XHR): '+ exception +'</span>');
-			$("#mapTileUploadProgress").hide();
-			$("#mapFileInput").show();
-		}
-	}).progress(function(e){
-		$("#mapTileUploadProgress").attr({value: e.oloaded, max: e.total});
-	});
-};
-
-/**
- * @brief Setups up GnuBoat to be able to start() after configured a server with setServer().
- */
-GnuBoat.initialize = function()
-{
-	$("#mapModusSelect").change(function(){ GnuBoat.private.mapModusChanged(); });
-	$("#mapTileUploadProgress").hide();
-	$("#logfilesReload").click(GnuBoat.logfilesLoad);
-	$("#shutdownButton").click(GnuBoat.shutdown);
-
-	$("#mapTileUpload").validate({
-		rules: {
-			mapFile: {
-				required: true
-			},
-			mapName: {
-				required: true
-			}
-		},
-		submitHandler: function(form){
-			GnuBoat.uploadMap(form);
-		}
-	});
-	
-	$("#logfilesForm").validate({
-		rules: {
-			logfilesSelect: {
-				required: true
-			},
-		}
-	});
-	
-	$("#rendering").empty();
-	var width = $("#rendering").width();
-	var height = $("#rendering").height();
-
-	var fieldOfView = 75;
-	
-	GnuBoat.private.renderScene = new THREE.Scene();
-	GnuBoat.private.renderScene.background = new THREE.Color(0xEEEEEE);
-	
-	GnuBoat.private.renderCamera = new THREE.PerspectiveCamera(75, width/height, 0.1, 1000000);
-	GnuBoat.private.renderCamera.up = new THREE.Vector3(0, 0, 1);
-	GnuBoat.private.renderCamera.position.set(-0.01, -0.01, 15000);
-	GnuBoat.private.renderCamera.lookAt(GnuBoat.private.renderScene.position);
-	
-	GnuBoat.private.renderRenderer = new THREE.WebGLRenderer();
-	GnuBoat.private.renderRenderer.setSize(width, height);
-	GnuBoat.private.renderRenderer.setPixelRatio( window.devicePixelRatio );
-	document.getElementById("rendering").appendChild(GnuBoat.private.renderRenderer.domElement);
-	
-	GnuBoat.private.renderControls = new THREE.OrbitControls( GnuBoat.private.renderCamera, GnuBoat.private.renderRenderer.domElement );
-	GnuBoat.private.renderControls.zoomSpeed = 2;
-}
-
-/**
- * @brief Starts querying the webservice
- * 
- * Call initialize() and setServer() before start()
- */
-GnuBoat.start = function()
-{
-	if(GnuBoat.private.serverBaseUrl == null){
-		GnuBoat.displayMessage('<span class="error">No server set/found</span>');
-		return;
-	}
-	
-	GnuBoat.getMapInfos();
-	GnuBoat.displayDataGet();
-	if(GnuBoat.private.timerDisplay == null)
-		GnuBoat.private.timerDisplay = setInterval(GnuBoat.displayDataGet, 10000);
-	GnuBoat.logfilesLoad();
-	
-	GnuBoat.private.animate();
-}
-
-/**
- * @brief Stops querying the webservice
- */
-GnuBoat.stop = function()
-{
-	if(GnuBoat.private.timerDisplay != null){
-		clearInterval(GnuBoat.private.timerDisplay);
-		GnuBoat.private.timerDisplay = null;
-	}
-}
-
-/**
- * @brief Private methods and properties of GnuBoat
- */
-GnuBoat.private = {
-	map: null,
-	mapLayerCurrent: null,
-	mapPolylines: [],
-	mapControl: null,
-	mapsMetadata: null,
-	mapBounds: null,
-	mapModusLive: true,
-	mapHotlineGradientDefault: { absolute: false, palette: { 0.0: 'green', 0.5: 'yellow', 1.0: 'red' } },
-	dataMappings: {
-		speedthroughwater: {display: true, map: true, mapActive: false, titleLong: "Speed Through Water", titleShort: "STW", unit: "kts"},
-		speedoverground:  {display: true, map: true, mapActive: false, titleLong: "Speed Over Ground", titleShort: "SOG", unit: "kts"},
-		waterdepth: {
-			display: true, map: true, mapActive: true, titleLong: "Waterdepth", titleShort: "Depth", unit: "m",
-			gradient: {
-				absolute: true,
-				palette: { 0: 'DarkBlue', 2: 'DodgerBlue', 6: 'LightBlue', 10: 'AliceBlue'},
-			}
-		},
-		watertemperature: {display: true, map: true, mapActive: false, titleLong: "Watertemperature", titleShort: "Water", unit: "°C"},
-		gpsfix: {display: true, map: false, mapActive: false, titleLong: "GPS Fix", titleShort: "Fix", unit: ""},
-	},
-	serverBaseUrl: null,
-	timerDisplay: null,
-	renderScene: null,
-	renderCamera: null,
-	renderRenderer: null,
-	renderMapBounds: null,
-	renderGrid: null,
-	renderControls: null,
-	renderCloud: null,
-	
-	openLink: function(target)
-	{
-		window.location=target;
-	},
-	
-	displayDataSet: function(data)
-	{
-// 		if(!Array.isArray(data) || data.length < 1){
-// 			console.log("No data array returned!");
-// 			console.log(data);
-// 			return;
-// 		}
-		if(("error" in data) && data["error"] == 1){
-			GnuBoat.displayMessage('<span class="error">Failed to get display data and tracks: '+ data["errormessage"] +'</span>');
-			return;
-		}
-
-		var keysDisplay = [];
-		for(var key in GnuBoat.private.dataMappings){
-			if(GnuBoat.private.dataMappings[key]["display"] === true)
-				keysDisplay.push(key);
-		}
-
-		if(!("lastvalid" in data)){
-				console.log("No last valid values given!");
-		}
-		else{
-			var lastValid = data["lastvalid"];
-			for(var i = 0; i < keysDisplay.length; i++){
-				var key = keysDisplay[i];
-				var value = lastValid[key];
-				if($.isNumeric(value)){
-					var text = value.toFixed(1);
-					if(key == "watertemperature"){
-						text = value.toFixed(0);
-					}
-					$("#display #"+ key +" #value").text(text);
-				}
-				else if(key == "gpsfix"){
-					$("#display #"+ key +" #value").text(value);
-				}
-			}
-		}
-		
-		// map displays logged data
-		if(!GnuBoat.private.mapModusLive)
-			return;
-		else if(!("track" in data)){
-			console.log("No track given!");
-			return;
-		}
-		GnuBoat.private.mapAddTracks(data["track"]);
-	},
-	
-	mapSetup: function ()
-	{
-		var mapMetadataIndex = $("#mapSelect").val();
-		if(GnuBoat.private.mapsMetadata == null){
-			console.log("No mapsMetadata set");
-			return;
-		}
-		if(mapMetadataIndex < 0 || mapMetadataIndex >= GnuBoat.private.mapsMetadata.length){
-			console.log("Map metadata is outside of range :"+ mapMetadataIndex.toString());
-			console.log(mapsMetadata);
-			return;
-		}
-		var mapMetadata = GnuBoat.private.mapsMetadata[mapMetadataIndex];
-		
-		var latitudeTop = mapMetadata["bounds"][3];
-		var latitudeBottom = mapMetadata["bounds"][1];
-		var longitudeLeft = mapMetadata["bounds"][0];
-		var longitudeRight = mapMetadata["bounds"][2];
-		
-		var mapZoomMin = mapMetadata["minzoom"];
-		var mapZoomMax = mapMetadata["maxzoom"];
-		
-		var latitudeCenter = (latitudeTop - latitudeBottom)/2 + latitudeBottom;
-		var longitudeCenter = (longitudeLeft - longitudeRight)/2 + longitudeRight;
-		var mapZoomStart = (mapZoomMax - mapZoomMin)/2 + mapZoomMin;
-		
-		GnuBoat.private.mapBounds = new L.LatLngBounds(
-				new L.LatLng(latitudeBottom, longitudeLeft),
-				new L.LatLng(latitudeTop, longitudeRight));
-		
-		if(GnuBoat.private.map == null){
-			// only initialize the map (viewport) once
-			GnuBoat.private.map = L.map('mapViewport');
-			GnuBoat.private.map.on('overlayadd', function(layerObject){ GnuBoat.private.mapOverlayLegendSwitch(layerObject.layer); });
-			GnuBoat.private.map.on('overlayremove', function(layerObject){ GnuBoat.private.mapOverlayLegendSwitch(layerObject.layer); });
-		}
-		GnuBoat.private.map.setView([latitudeCenter, longitudeCenter], mapZoomStart);
-		
-		if(GnuBoat.private.mapLayerCurrent != null){
-			GnuBoat.private.map.removeLayer(GnuBoat.private.mapLayerCurrent);
-			if(GnuBoat.private.mapControl)
-				GnuBoat.private.mapControl.removeLayer(GnuBoat.private.mapLayerCurrent);
-			GnuBoat.private.mapLayerCurrent = null;
-		}
-		GnuBoat.private.mapLayerCurrent = L.tileLayer(mapMetadata["tiles"][0], {
-			minZoom: mapZoomMin, maxZoom: mapZoomMax,
-			bounds: GnuBoat.private.mapBounds,
-			attribution: mapMetadata["name"],
-			opacity: 0.85
-			}).addTo(GnuBoat.private.map);
-		if(GnuBoat.private.mapControl != null)
-			GnuBoat.private.mapControl.addBaseLayer(GnuBoat.private.mapLayerCurrent, "Map");
-		else{
-			GnuBoat.private.mapControl = L.control.layers({"Map": GnuBoat.private.mapLayerCurrent}, GnuBoat.private.mapOverlaysToList(), {hideSingleBase: true, sortLayers: true, }).addTo(GnuBoat.private.map);
-		}
-		
-		// configure render scene for new map
-		GnuBoat.private.renderSetupMap();
-	},
-	
-	mapInfos: function(data)
-	{
-		GnuBoat.private.mapsMetadata = data;
-		
-		$("#mapSelect").empty();
-		var selected = "selected";
-		data.forEach(function(value, index){
-			$("<option value=\""+ index.toString() +"\" "+ selected +">"+ value["name"] +"</option>").appendTo("#mapSelect");
-			selected = "";
-		});
-		
-		GnuBoat.private.mapSetup();
-		$("#mapSelect").change(function(){ GnuBoat.private.mapSetup(); });
-	},
-	
-	mapOverlaysToList: function()
-	{
-		var overlays = {};
-		for(var key in GnuBoat.private.mapPolylines){
-			overlays[key] = GnuBoat.private.mapPolylines[key];
-		}
-		return overlays;
-	},
-	
-	renderSetupMap: function()
-	{
-		if(GnuBoat.private.mapBounds == null)
-			return;
-
-		// add map bounds
-		if(GnuBoat.private.renderMapBounds != null)
-			GnuBoat.private.renderScene.remove(GnuBoat.private.renderMapBounds);
-		var m1 = GnuBoat.private.mercator(GnuBoat.private.mapBounds.getSouth(), GnuBoat.private.mapBounds.getWest());
-		var m2 = GnuBoat.private.mercator(GnuBoat.private.mapBounds.getSouth(), GnuBoat.private.mapBounds.getEast());
-		var m3 = GnuBoat.private.mercator(GnuBoat.private.mapBounds.getNorth(), GnuBoat.private.mapBounds.getEast());
-		var m4 = GnuBoat.private.mercator(GnuBoat.private.mapBounds.getNorth(), GnuBoat.private.mapBounds.getWest());
-		var geometryMapBounds = new THREE.Geometry();
-		var materialMapBounds = new THREE.LineBasicMaterial({color: 0x66BD66, linewidth: 1});
-		// z is greator 0, to draw the map boundings over the grid
-		var vertex = new THREE.Vector3(0, 0, 2);
-		geometryMapBounds.vertices.push(vertex);
-		vertex = new THREE.Vector3(m2.x - m1.x, m2.y - m1.y, 2);
-		geometryMapBounds.vertices.push(vertex);
-		vertex = new THREE.Vector3(m3.x - m1.x, m3.y - m1.y, 2);
-		geometryMapBounds.vertices.push(vertex);
-		vertex = new THREE.Vector3(m4.x - m1.x, m4.y - m1.y, 2);
-		geometryMapBounds.vertices.push(vertex);
-		GnuBoat.private.renderMapBounds = new THREE.LineLoop(geometryMapBounds, materialMapBounds);
-		GnuBoat.private.renderScene.add(GnuBoat.private.renderMapBounds);
-
-		// add 500m grid
-		if(GnuBoat.private.renderGrid != null)
-			GnuBoat.private.renderScene.remove(GnuBoat.private.renderGrid);
-		geometryMapBounds.computeBoundingBox();	
-		var maxLength = Math.max(geometryMapBounds.boundingBox.getSize().x, geometryMapBounds.boundingBox.getSize().y);
-		GnuBoat.private.renderGrid = new THREE.GridHelper(maxLength, Math.round(maxLength / 500.0), 0xCCCCCC, 0xCCCCCC);
-		GnuBoat.private.renderGrid.geometry.rotateX( Math.PI / 2 );
-		GnuBoat.private.renderGrid.translateX(maxLength / 2.0);
-		GnuBoat.private.renderGrid.translateY(maxLength / 2.0);
-		GnuBoat.private.renderScene.add(GnuBoat.private.renderGrid);
-		
-		var distance = 150;
-		var fieldOfView = 2 * Math.atan(maxLength / (2.0 * distance) ) * 180.0 / Math.PI;
-		GnuBoat.private.renderCamera.position.set(-10, -5, 100);
-		GnuBoat.private.renderCamera.fov = fieldOfView;
-		GnuBoat.private.renderCamera.lookAt(GnuBoat.private.renderScene.position);
-		GnuBoat.private.renderCamera.zoom = 5;
-		GnuBoat.private.renderCamera.updateProjectionMatrix();
-	},
-	
-	drawDensityEstimation: function(densityPoints, gradient, maximum, minimum)
-	{
-		var colors = GnuBoat.private.gradientToRenderColors(gradient, maximum, minimum);
-		// converting all indizes into numbers to sort them correctly
-		// in descending order e.g. 10, 2, 1, 0 and not 2, 10, 1, 0
-		var colorsIndizes = Object.getOwnPropertyNames(colors);
-		colorsIndizes.sort(function(a, b){
-			a = +a;
-			b = +b;
-			return a-b;
-		});
-		var colorsCount = colorsIndizes.length;
-		
-		var material = new THREE.PointsMaterial({vertexColors: THREE.VertexColors, size: 5});
-		var geometry = new THREE.Geometry();
-		var mercatorSouthWest = {x: 0, y: 0};
-		if(GnuBoat.private.mapBounds != null)
-			mercatorSouthWest = GnuBoat.private.mercator(GnuBoat.private.mapBounds.getSouth(), GnuBoat.private.mapBounds.getWest());
-		
-		for(var i = 0; i < densityPoints.length; i++){
-			var mercator = GnuBoat.private.mercator(densityPoints[i].latitude, densityPoints[i].longitude);
-			var vertex = new THREE.Vector3(mercator.x - mercatorSouthWest.x, mercator.y - mercatorSouthWest.y, (densityPoints[i].depth * -1) + maximum);
-			var step = (densityPoints[i].depth - minimum)/(maximum-minimum);
-			var color = new THREE.Color(0x000000);
-			for(var j = 0; j < colorsCount; j++){
-				if(j < colorsCount - 1)
-					color = colors[colorsIndizes[j]];
-				if(step <= colorsIndizes[j+1]){
-					color = colors[colorsIndizes[j]];
-					break;
-				}
-			}
-			geometry.vertices.push(vertex);
-			geometry.colors.push(color);
-		}
-		// point cloud
-		if(GnuBoat.private.renderCloud != null)
-			GnuBoat.private.renderScene.remove(GnuBoat.private.renderCloud);
-		GnuBoat.private.renderCloud = new THREE.Points(geometry, material);
-		GnuBoat.private.renderScene.add(GnuBoat.private.renderCloud);
-	},
-	
-	animate: function()
-	{
-		requestAnimationFrame(GnuBoat.private.animate);
-		if(GnuBoat.private.renderCloud != null){
-			var scaleZ = $("#renderScaleZ").val();
-			if(GnuBoat.private.renderCloud.scale.z != scaleZ)
-				GnuBoat.private.renderCloud.scale.set(1, 1, scaleZ);
-		}
-		
-		GnuBoat.private.renderControls.update();
-		GnuBoat.private.renderRenderer.render(GnuBoat.private.renderScene, GnuBoat.private.renderCamera);
-	},
-	
-	mercator: function(latitude, longitude)
-	{
-		var result = {};
-		
-		var earthRadius = 6378137.0;
-		
-		result["x"] = longitude / 180.0 * Math.PI * earthRadius;
-		result["y"] = Math.log(Math.tan(latitude / 180.0 * Math.PI / 2.0 + Math.PI / 4.0)) * earthRadius;
-
-		return result;
-	},
-	
-	updateMapModus: function(data)
-	{
-		var selected = $("#mapModusSelect").val();
-		$("#mapModusSelect").empty();
-		var selectedFound = false;
-		if(selected != null && Array.isArray(data)){
-			data.forEach(function(value, index){
-				if(value == selected)
-					selectedFound = true;
-			});
-		}
-		var selectedString = "";
-		if(!selectedFound)
-			selectedString = " selected";
-		$('<option value="live"'+ selectedString +'>Live View</option>').appendTo("#mapModusSelect");
-		if(!Array.isArray(data) || data.length < 1){
-			console.log(data);
-			return;
-		}
-		if(("error" in data) && data["error"] == 1){
-			GnuBoat.displayMessage('<span class="error">Failed to upload map: '+ data["errormessage"] +'</span>');
-			return;
-		}
-		data.forEach(function(value, index){
-			var selectedString = "";
-			if(value == selected)
-				selectedString = " selected";
-			$("<option value=\""+ value +"\""+ selected +">"+ value +"</option>").appendTo("#mapModusSelect");
-		});
-	},
-	
-	mapModusChanged: function()
-	{
-		var modus = $("#mapModusSelect").val();
-		// live modus is automatically activated on displayDataSet
-		if(modus == "live"){
-			GnuBoat.private.mapModusLive = true;
-			return;
-		}
-		// remove overlays
-		if(GnuBoat.private.mapControl != null){
-			for(var key in GnuBoat.private.dataMappings){
-				if(GnuBoat.private.dataMappings[key]["map"] === true)
-					if(key in GnuBoat.private.mapPolylines){
-						GnuBoat.private.mapControl.removeLayer(GnuBoat.private.mapPolylines[key]);
-						GnuBoat.private.mapPolylines[key].remove();
-						delete GnuBoat.private.mapPolylines[key];
-					}
-			}
-		}
-		GnuBoat.private.mapModusLive = false;
-		$.post({
-			url: GnuBoat.private.serverBaseUrl +'?request=replay',
-			data: { logfile: modus },
-			success: function(data){
-// 				if(!Array.isArray(data) || data.length < 1){
-// 					console.log("No data array returned!");
-// 					console.log(data);
-// 					return;
-// 				}
-				if(("error" in data) && data["error"] == 1){
-					GnuBoat.displayMessage('<span class="error">Failed to get logged tracks: '+ data["errormessage"] +'</span>');
-					return;
-				}
-				if(!("track" in data)){
-					console.log("No track given!");
-					return;
-				}
-				GnuBoat.private.mapAddTracks(data["track"]);
-			}
-		});
-	},
-	
-	mapAddTracks: function(track)
-	{
-		if(GnuBoat.private.map == null){
-			console.log("No map in use");
-			return;
-		}
-		
-		$("#mapLegend").empty();
-		var maximas = [];
-		var minimas = [];
-		var points = [];
-		var densityPoints = [];
-		
-		var keysMap = [];
-		for(var key in GnuBoat.private.dataMappings){
-			if(GnuBoat.private.dataMappings[key]["map"] === true)
-				keysMap.push(key);
-		}
-		for(var i = 0; i < keysMap.length; i++){
-			points[keysMap[i]] = [];
-		}
-		
-		// getting maximas, minimums for normalization and the tracks themselves
-		for(var time in track){
-			for(var i = 0; i < keysMap.length; i++){
-				var key = keysMap[i];
-				var value = track[time][key];
-				if(!$.isNumeric(value))
-					continue;
-				if(!(key in maximas))
-					maximas[key] = value
-				else if(maximas[key] < value)
-					maximas[key] = value;
-				if(!(key in minimas))
-					minimas[key] = value
-				else if(minimas[key] > value)
-					minimas[key] = value;
-				points[key].push(new L.latLng(track[time]["latitude"], track[time]["longitude"], value));
-				if(key == "waterdepth")
-					densityPoints.push({latitude: track[time]["latitude"], longitude: track[time]["longitude"], depth: value});
-			}
-		}
-		for(var i = 0; i < keysMap.length; i++){
-			var key = keysMap[i];
-			if(points[key].length > 0){
-				var palette = GnuBoat.private.mapHotlineGradientDefault.palette;
-				var paletteLegend = GnuBoat.private.mapHotlineGradientDefault.palette;
-				if("gradient" in GnuBoat.private.dataMappings[key]){
-					palette = GnuBoat.private.gradientToPalette(GnuBoat.private.dataMappings[key]["gradient"], maximas[key], minimas[key]);
-					// use original palette, to use absolute values, if possible
-					paletteLegend = GnuBoat.private.dataMappings[key]["gradient"]["palette"];
-				}
-				
-				var legendTable = $('<table id="'+ key +'" class="hidden"></table>');
-				$("<tr><th colspan=2>"+ GnuBoat.private.dataMappings[key]["titleShort"] +" in "+ GnuBoat.private.dataMappings[key]["unit"] +"</th></tr>").appendTo(legendTable);
-				$("<tr><th>Level</th><th>Color</th></tr>").appendTo(legendTable);
-				// converting all indizes into numbers to sort them correctly
-				// e.g. 0, 1, 2, 10 and not 0, 1, 10, 2
-				var indizes = Object.getOwnPropertyNames(paletteLegend);
-				indizes.sort(function(a, b){
-					a = +a;
-					b = +b;
-					return a-b;
-				});
-				for(var j=0; j < indizes.length; j++){
-					var index = indizes[j];
-					$('<tr><td class="level">'+ index.toString() +'</td><td style="background-color: '+ paletteLegend[index] +'"></td></tr>').appendTo(legendTable);
-				}
-				$('<tr><td colspan="2">Extrema: '+ maximas[key].toString() +' / '+ minimas[key].toString() +'</td></tr>').appendTo(legendTable);
-				
-				var hotlineOptions = {
-					weight: 3,
-					outlineWidth: 0,
-					min: minimas[key],
-					max: maximas[key],
-					palette: palette,
-				};
-				
-				legendTable.appendTo("#mapLegend");
-			
-				if(key in GnuBoat.private.mapPolylines){
-					GnuBoat.private.mapPolylines[key].setStyle(hotlineOptions);
-					GnuBoat.private.mapPolylines[key].setLatLngs(points[key]);
-					if(GnuBoat.private.map.hasLayer(GnuBoat.private.mapPolylines[key]))
-						GnuBoat.private.mapOverlayLegendSwitch(GnuBoat.private.mapPolylines[key]);
-					GnuBoat.private.mapPolylines[key].unbindPopup();
-				}
-				else{
-					GnuBoat.private.mapPolylines[key] = L.hotline(points[key], hotlineOptions);
-					if(GnuBoat.private.mapControl){
-						var name = GnuBoat.private.dataMappings[key]["titleLong"] +" in "+ GnuBoat.private.dataMappings[key]["unit"] +" ("+ GnuBoat.private.dataMappings[key]["titleShort"] +")";
-						GnuBoat.private.mapControl.addOverlay(GnuBoat.private.mapPolylines[key], name);
-					}
-					if(GnuBoat.private.dataMappings[key]["mapActive"] === true)
-						GnuBoat.private.mapPolylines[key].addTo(GnuBoat.private.map);
-				}
-				GnuBoat.private.mapPolylines[key].bindPopup(legendTable[0].outerHTML);
-			}
-		}
-		var gradient = GnuBoat.private.mapHotlineGradientDefault.palette;
-		if("gradient" in GnuBoat.private.dataMappings["waterdepth"])
-			gradient = GnuBoat.private.dataMappings["waterdepth"]["gradient"];
-		GnuBoat.private.drawDensityEstimation(densityPoints, gradient, maximas["waterdepth"], minimas["waterdepth"]);
-	},
-	
-	gradientToPalette: function(gradient, maximum, minimum)
-	{
-		if(!("palette" in gradient)){
-			return GnuBoat.private.mapHotlineGradientDefault.palette;
-		}
-		if(!("absolute" in gradient) || !gradient.absolute){
-			// palette is already relative
-			return gradient.palette;
-		}
-		var range = maximum - minimum;
-		if(range == 0){
-			console.log("Range is zero --> Could not make gradient relative");
-			return  GnuBoat.private.mapHotlineGradientDefault.palette;
-		}
-		var palette = {};
-		var addedStop = false;
-		for(var indexAbs in gradient.palette){
-			var indexRel = (indexAbs - minimum)/range;
-			if(indexRel < 0){
-				// add the nearest minimum value (which might be configured smaller than minimum)
-				indexRel = 0;
-				palette[indexRel] = gradient.palette[indexAbs];
-				addedStop = true;
-			}
-			else if(indexRel < 1){
-				palette[indexRel] = gradient.palette[indexAbs];
-				addedStop = true;
-			}
-			else{
-				// add first index > 1 as the maximum value at 1
-				indexRel = 1;
-				palette[indexRel] = gradient.palette[indexAbs];
-				addedStop = true;
-				break;
-			}
-		}
-		if(!addedStop)
-			return GnuBoat.private.mapHotlineGradientDefault.palette;
-		return palette;
-	},
-	
-	gradientToRenderColors: function(gradient, maximum, minimum)
-	{
-		var paletteRelative = GnuBoat.private.gradientToPalette(gradient, maximum, minimum);
-
-		var colors = {};
-		for(var index in paletteRelative)
-			colors[index] = new THREE.Color(paletteRelative[index].toLowerCase());
-
-		return colors;
-	},
-
-	mapOverlayLegendSwitch: function(layer)
-	{
-		var overlayKey = null;
-		for(var key in GnuBoat.private.mapPolylines){
-			if(GnuBoat.private.mapPolylines.hasOwnProperty(key)){
-				if(GnuBoat.private.mapPolylines[key] === layer){
-					overlayKey = key;
-					break;
-				}
-			}
-		}
-		// ECMAScript 6
-// 		var overlayKey = Object.keys(GnuBoat.private.mapPolylines).find(key => GnuBoat.private.mapPolylines[key] === overlay);
-		if(overlayKey == null)
-			return;
-		if(overlayKey){
-			$("#mapLegend #"+ overlayKey).toggleClass("hidden");
-		}
-	},
-};
