Index: src/webapp/webclient/js/GnuBoat.js
===================================================================
--- src/webapp/webclient/js/GnuBoat.js	(revision 4ce069e4224fca8f43b386d85f943c2b8672efee)
+++ src/webapp/webclient/js/GnuBoat.js	(revision 4ce069e4224fca8f43b386d85f943c2b8672efee)
@@ -0,0 +1,356 @@
+/*
+
+    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;
+	
+}
+
+/**
+ * @brief Used to display user messages
+ */
+GnuBoat.displayMessage = function(text)
+{
+	$("#message").clear();
+	$(shutdownHint).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("No server set/found");
+		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("No server set/found");
+		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("No server set/found");
+		return;
+	}
+	$("#logfilesForm").empty();
+	$.getJSON(GnuBoat.private.serverBaseUrl +"?request=logfiles", function(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){
+			alert("Failed to upload map: "+ data["errormessage"]);
+			$("#mapTileUploadProgress").hide();
+			$("#mapFileInput").show();
+			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("No server set/found");
+		return;
+	}
+	$.getJSON(GnuBoat.private.serverBaseUrl +"?request=shutdown", function(data){
+		var shutdownTime = data["shutdownstart"];
+		var shutdownDate = Date.parse(shutdownTime);
+		var currentDate = new Date();
+		var shutdownHint = "Shutting down in "+ Math.floor((shutdownDate - currentDate)/1000) +"s at "+ shutdownTime.toLocaleString();
+		if(shutdownTime == -1){
+			shutdownHint = "Failed to initiate shutdown: "+ data["errormessage"];
+		}
+		GnuBoat.displayMessage(shutdownHint);
+	});
+};
+
+/**
+ * @brief Uploads a map and refreshes the maps metadata on success
+ */
+GnuBoat.uploadMap = function(form)
+{
+	if(GnuBoat.private.serverBaseUrl == null){
+		displayMessage("No server set/found");
+		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){
+				alert("Failed to upload map: "+ data["errormessage"]);
+				$("#mapTileUploadProgress").hide();
+				$("#mapFileInput").show();
+				return;
+			}
+			alert("Map upload successfully");
+			$("#mapTileUploadProgress").hide();
+			$("#mapFileInput").show();
+			GnuBoat.getMapInfos();
+		},
+		error: function(jqXHR, exception, errorThrown){
+			alert("Failed to upload map (XHR): "+ exception);
+			$("#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()
+{
+	$("#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
+			},
+		}
+	});
+}
+
+/**
+ * @brief Starts querying the webservice
+ * 
+ * Call initialize() and setServer() before start()
+ */
+GnuBoat.start = function()
+{
+	if(GnuBoat.private.serverBaseUrl == null){
+		GnuBoat.displayMessage("No server set/found");
+		return;
+	}
+	
+	GnuBoat.getMapInfos();
+	GnuBoat.displayDataGet();
+	if(GnuBoat.private.timerDisplay == null)
+		GnuBoat.private.timerDisplay = setInterval(GnuBoat.displayDataGet, 10000);
+	GnuBoat.logfilesLoad();	
+}
+
+/**
+ * @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,
+	// var mapControl = null;
+	mapsMetadata: null,
+	polyline: null,
+	serverBaseUrl: null,
+	timerDisplay: null,
+	
+	openLink: function(target)
+	{
+		window.location=target;
+	},
+	
+	displayDataSet: function(data)
+	{
+		if(!Array.isArray(data) && !(data instanceof Object)){
+			console.log("No data array returned!");
+			console.log(data);
+			return;
+			}
+		if(!("lastvalid" in data)){
+				console.log("No last valid values given!");
+		}
+		else{
+			var lastValid = data["lastvalid"];
+			var keys = ["speedthroughwater", "speedoverground", "waterdepth", "watertemperature", "gpsfix"];
+			for(var i = 0; i < keys.length; i++){
+				var key = keys[i];
+				var value = lastValid[key];
+				if($.isNumeric(value)){
+					var text = value.toFixed(1);
+					if(key == "watertemperature"){
+						text = value.toFixed(0);
+					}
+					$("#display #"+ keys[i] +" #value").text(text);
+				}
+				else if(key == "gpsfix"){
+					$("#display #"+ keys[i] +" #value").text(value);
+				}
+			}
+		}
+		
+		if(!("track" in data)){
+				console.log("No track given!");
+		}
+		else{
+			if(GnuBoat.private.map == null){
+				console.log("No map in use");
+			}
+			else{
+				var track = data["track"];
+				var points = [];
+				for(var time in track){
+					points.push(new L.latLng(track[time]["latitude"], track[time]["longitude"]));
+				}
+				if(points.length > 0){
+					if(!GnuBoat.private.polyline){
+						GnuBoat.private.polyline = L.polyline(points, {color: 'red'}).addTo(GnuBoat.private.map);
+					}
+					else{
+						GnuBoat.private.polyline.setLatLngs(points);
+					}
+					GnuBoat.private.map.fitBounds(GnuBoat.private.polyline.getBounds());
+				}
+			}
+		}
+	},
+	
+	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;
+		
+		var 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.setView([latitudeCenter, longitudeCenter], mapZoomStart);
+		
+		if(GnuBoat.private.mapLayerCurrent != null){
+			GnuBoat.private.map.removeLayer(GnuBoat.private.mapLayerCurrent);
+			GnuBoat.private.mapLayerCurrent = null;
+		}
+		GnuBoat.private.mapLayerCurrent = L.tileLayer(mapMetadata["tiles"][0], {
+			minZoom: mapZoomMin, maxZoom: mapZoomMax,
+			bounds: mapBounds,
+			attribution: mapMetadata["name"],
+			opacity: 0.85
+			}).addTo(GnuBoat.private.map);
+	},
+	
+	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(){ mapSetup(); });
+	},
+};
