c7a69e835d56ed86f3548dbcc6930b4cb99be27a
[lantea.git] / js / map.js
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
3  * You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5 var gGLMapCanvas, gTrackCanvas, gTrackContext, gGeolocation;
6 var gDebug = false;
7
8 var gMinTrackAccuracy = 1000; // meters
9 var gTrackWidth = 2; // pixels
10 var gTrackColor = "#FF0000";
11 var gCurLocSize = 6; // pixels
12 var gCurLocColor = "#A00000";
13
14 var gMapStyles = {
15   // OSM tile usage policy: http://wiki.openstreetmap.org/wiki/Tile_usage_policy
16   // Find some more OSM ones at http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames#Tile_servers
17   // and http://wiki.openstreetmap.org/wiki/Tiles or http://wiki.openstreetmap.org/wiki/TMS
18   osm_mapnik:
19     {name: "OpenStreetMap (Mapnik)",
20      url: "https://[a-c].tile.openstreetmap.org/{z}/{x}/{y}.png",
21      copyright: 'Map data and imagery &copy; <a href="http://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="http://www.openstreetmap.org/copyright">ODbL/CC-BY-SA</a>'},
22   osm_cyclemap:
23     {name: "Cycle Map (OSM)",
24      url: "https://[a-c].tile.thunderforest.com/cycle/{z}/{x}/{y}.png", // "http://[a-c].tile.opencyclemap.org/cycle/{z}/{x}/{y}.png",
25      copyright: 'Map data and imagery &copy; <a href="http://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="http://www.openstreetmap.org/copyright">ODbL/CC-BY-SA</a>'},
26   osm_transmap:
27     {name: "Transport Map (OSM)",
28      url: "https://[a-c].tile.thunderforest.com/transport/{z}/{x}/{y}.png", // "http://[a-c].tile2.opencyclemap.org/transport/{z}/{x}/{y}.png",
29      copyright: 'Map data and imagery &copy; <a href="http://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="http://www.openstreetmap.org/copyright">ODbL/CC-BY-SA</a>'},
30   osm_germany:
31     {name: "OSM German Style",
32      url: "http://[a-d].tile.openstreetmap.de/tiles/osmde/{z}/{x}/{y}.png", // https is not supported at all
33      copyright: 'Map data and imagery &copy; <a href="http://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="http://www.openstreetmap.org/copyright">ODbL/CC-BY-SA</a>'},
34 //  oepnvkarte: // XXX: toolserver.org does not support CORS at this time :(
35 //    {name: "ÖPNV-Karte (OSM)",
36 //     url: "http://toolserver.org/~cmarqu/hill/{z}/{x}/{y}.png",
37 //     copyright: 'Map data &copy; <a href="http://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="http://www.openstreetmap.org/copyright">ODbL/CC-BY-SA</a>, tiles by <a href="http://memomaps.de">MeMoMaps</a> under <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>.'},
38   mapquest_open:
39     {name: "MapQuest OSM",
40      url: "http://otile[1-4].mqcdn.com/tiles/1.0.0/osm/{z}/{x}/{y}.png", // https has wrong cert, akamai instead of mqcdn
41      copyright: 'Map data &copy; <a href="http://www.openstreetmap.org/">OpenStreetMap</a> and contributors (<a href="http://www.openstreetmap.org/copyright">ODbL/CC-BY-SA</a>), tiles courtesy of <a href="http://www.mapquest.com/">MapQuest</a>.'},
42   mapquest_aerial:
43     {name: "MapQuest Open Aerial",
44      url: "http://otile[1-4].mqcdn.com/tiles/1.0.0/sat/{z}/{x}/{y}.jpg",
45      copyright: 'Tiles Courtesy of <a href="http://www.mapquest.com/">MapQuest</a>, portions Courtesy NASA/JPL-Caltech and U.S. Depart. of Agriculture, Farm Service Agency.'},
46   osm_hot:
47     {name: "OSM HOT style",
48      url: "http://[a-c].tile.openstreetmap.fr/hot/{z}/{x}/{y}.png", // https has CAcert which doesn't work in browsers
49      copyright: 'Map data and imagery &copy; <a href="http://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="http://www.openstreetmap.org/copyright">ODbL/CC-BY-SA</a>'},
50 //  hikebike: // XXX: toolserver.org does not support CORS at this time :(
51 //    {name: "Hike and Bike (OSM)",
52 //     url: "http://toolserver.org/tiles/hikebike/{z}/{x}/{y}.png",
53 //     copyright: 'Map data and imagery &copy; <a href="http://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="http://www.openstreetmap.org/copyright">ODbL/CC-BY-SA</a>'},
54   stamen_toner:
55     {name: "Stamen Toner (B+W)", // https has wrong cert, .ssl.fastly.net instead of .tile.stamen.com
56      url: "http://[a-c].tile.stamen.com/toner/{z}/{x}/{y}.jpg",
57      copyright: 'Map data &copy; <a href="http://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="http://www.openstreetmap.org/copyright">ODbL/CC-BY-SA</a>, tiles by <a href="http://stamen.com">Stamen Design</a>, under <a href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a>.'},
58   stamen_terrain:
59     {name: "Stamen Terrain (USA only)", // https has wrong cert, .ssl.fastly.net instead of .tile.stamen.com
60      url: "http://[a-c].tile.stamen.com/terrain/{z}/{x}/{y}.jpg",
61      copyright: 'Map data &copy; <a href="http://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="http://www.openstreetmap.org/copyright">ODbL/CC-BY-SA</a>, tiles by <a href="http://stamen.com">Stamen Design</a>, under <a href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a>.'},
62   stamen_watercolor:
63     {name: "Stamen Watercolor (artistic)", // https has wrong cert, .ssl.fastly.net instead of .tile.stamen.com
64      url: "http://[a-c].tile.stamen.com/watercolor/{z}/{x}/{y}.jpg",
65      copyright: 'Map data &copy; <a href="http://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="http://www.openstreetmap.org/copyright">ODbL/CC-BY-SA</a>, tiles by <a href="http://stamen.com">Stamen Design</a>, under <a href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a>.'},
66 };
67
68 var gLastMouseX = 0;
69 var gLastMouseY = 0;
70
71 var gLoadingTile;
72
73 var gMapPrefsLoaded = false;
74
75 var gDragging = false;
76 var gDragTouchID, gPinchStartWidth;
77
78 var gGeoWatchID;
79 var gTrack = [];
80 var gLastTrackPoint, gLastDrawnPoint;
81 var gCenterPosition = true;
82
83 var gCurPosMapCache;
84
85 function initMap() {
86   gGeolocation = navigator.geolocation;
87   // Set up canvas context.
88   gGLMapCanvas = document.getElementById("map");
89   try {
90     // Try to grab the standard context. If it fails, fallback to experimental.
91     // We also try to tell it we do not need a depth buffer.
92     gMap.gl = gGLMapCanvas.getContext("webgl", {depth: false}) ||
93               gGLMapCanvas.getContext("experimental-webgl", {depth: false});
94   }
95   catch(e) {}
96   if (!gMap.gl) {
97     // If we don't have a GL context, give up now
98     showGLWarningDialog();
99     gMap.gl = null;
100   }
101   else {
102     // GL context can be lost at any time, handle that.
103     // See http://www.khronos.org/webgl/wiki/HandlingContextLost
104     gGLMapCanvas.addEventListener("webglcontextlost",
105                                   gMap.handleContextLost, false);
106     gGLMapCanvas.addEventListener("webglcontextrestored",
107                                   gMap.handleContextRestored, false);
108   }
109   gTrackCanvas = document.getElementById("track");
110   gTrackContext = gTrackCanvas.getContext("2d");
111
112   //gDebug = true;
113   if (gDebug) {
114     gGeolocation = geofake;
115     var hiddenList = document.getElementsByClassName("debugHide");
116     // last to first - list of elements with that class is changing!
117     for (var i = hiddenList.length - 1; i >= 0; i--) {
118       hiddenList[i].classList.remove("debugHide");
119     }
120   }
121
122   gAction.addEventListener("prefload-done", gMap.initGL, false);
123
124   console.log("map vars set, loading prefs...");
125   loadPrefs();
126 }
127
128 function loadPrefs(aEvent) {
129   if (aEvent && aEvent.type == "prefs-step") {
130     console.log("wait: " + gWaitCounter);
131     if (gWaitCounter == 0) {
132       gAction.removeEventListener(aEvent.type, loadPrefs, false);
133       gMapPrefsLoaded = true;
134       console.log("prefs loaded.");
135
136       gTrackCanvas.addEventListener("mouseup", mapEvHandler, false);
137       gTrackCanvas.addEventListener("mousemove", mapEvHandler, false);
138       gTrackCanvas.addEventListener("mousedown", mapEvHandler, false);
139       gTrackCanvas.addEventListener("mouseout", mapEvHandler, false);
140
141       gTrackCanvas.addEventListener("touchstart", mapEvHandler, false);
142       gTrackCanvas.addEventListener("touchmove", mapEvHandler, false);
143       gTrackCanvas.addEventListener("touchend", mapEvHandler, false);
144       gTrackCanvas.addEventListener("touchcancel", mapEvHandler, false);
145       gTrackCanvas.addEventListener("touchleave", mapEvHandler, false);
146
147       gTrackCanvas.addEventListener("wheel", mapEvHandler, false);
148
149       document.getElementById("body").addEventListener("keydown", mapEvHandler, false);
150
151       document.addEventListener("visibilitychange", visibilityEvHandler, false);
152
153       console.log("Events added.");
154
155       console.log("Init loading tile...");
156       gLoadingTile = new Image();
157       gLoadingTile.onload = function() {
158         console.log("Loading tile loaded.");
159         var throwEv = new CustomEvent("prefload-done");
160         gAction.dispatchEvent(throwEv);
161       };
162       console.log("Set loading tile...");
163       gLoadingTile.src = "style/loading.png";
164     }
165   }
166   else {
167     if (aEvent)
168       gAction.removeEventListener(aEvent.type, loadPrefs, false);
169     gAction.addEventListener("prefs-step", loadPrefs, false);
170     gWaitCounter++;
171     gPrefs.get("active_map_style", function(aValue) {
172       if (aValue && gMapStyles[aValue]) {
173         gMap.activeMap = aValue;
174       }
175       else {
176         gMap.activeMap = "osm_mapnik";
177       }
178       document.getElementById("mapSelector").value = gMap.activeMap;
179       document.getElementById("copyright").innerHTML =
180           gMapStyles[gMap.activeMap].copyright;
181       gWaitCounter--;
182       var throwEv = new CustomEvent("prefs-step");
183       gAction.dispatchEvent(throwEv);
184     });
185     gWaitCounter++;
186     gPrefs.get("position", function(aValue) {
187       if (aValue && aValue.x && aValue.y && aValue.z) {
188         gMap.pos = aValue;
189       }
190       gWaitCounter--;
191       var throwEv = new CustomEvent("prefs-step");
192       gAction.dispatchEvent(throwEv);
193     });
194     gWaitCounter++;
195     gPrefs.get("center_map", function(aValue) {
196       if (aValue === undefined) {
197         document.getElementById("centerCheckbox").checked = true;
198       }
199       else {
200         document.getElementById("centerCheckbox").checked = aValue;
201       }
202       setCentering(document.getElementById("centerCheckbox"));
203       gWaitCounter--;
204       var throwEv = new CustomEvent("prefs-step");
205       gAction.dispatchEvent(throwEv);
206     });
207     gWaitCounter++;
208     gPrefs.get("tracking_enabled", function(aValue) {
209       if (aValue === undefined) {
210         document.getElementById("trackCheckbox").checked = true;
211       }
212       else {
213         document.getElementById("trackCheckbox").checked = aValue;
214       }
215       gWaitCounter--;
216       var throwEv = new CustomEvent("prefs-step");
217       gAction.dispatchEvent(throwEv);
218     });
219     gWaitCounter++;
220     var trackLoadStarted = false;
221     var redrawBase = 100;
222     gTrackStore.getListStepped(function(aTPoint) {
223       if (aTPoint) {
224         // Add in front and return new length.
225         var tracklen = gTrack.unshift(aTPoint);
226         // Redraw track periodically, larger distance the longer it gets
227         // (but clamped to the first value over a certain limit).
228         // Initial paint will do initial track drawing.
229         if (tracklen % redrawBase == 0) {
230           drawTrack();
231           if (redrawBase < 1000) {
232             redrawBase = tracklen;
233           }
234         }
235       }
236       else {
237         // Last point received.
238         drawTrack();
239       }
240       if (!trackLoadStarted) {
241         // We have the most recent point, if present, rest will load async.
242         trackLoadStarted = true;
243         gWaitCounter--;
244         var throwEv = new CustomEvent("prefs-step");
245         gAction.dispatchEvent(throwEv);
246       }
247     });
248   }
249 }
250
251 var gMap = {
252   gl: null,
253   glShaderProgram: null,
254   glVertexPositionAttr: null,
255   glTextureCoordAttr: null,
256   glResolutionAttr: null,
257   glMapTexture: null,
258   glTextures: {},
259   glTxCleanIntervalID: null,
260   glTexturesPerZoomLevel: 0,
261
262   activeMap: "osm_mapnik",
263   tileSize: 256,
264   maxZoom: 18, // The minimum is 0.
265   zoomFactor: null,
266   pos: {
267     x: 35630000.0, // Current position in the map in pixels at the maximum zoom level (18)
268     y: 23670000.0, // The range is 0-67108864 (2^gMap.maxZoom * gMap.tileSize)
269     z: 5           // This could be fractional if supported being between zoom levels.
270   },
271   baseDim: { // Map width, height and tile size in level 18 pixels.
272     wid: null,
273     ht: null,
274     tsize: null,
275   },
276
277   get width() { return gMap.gl ? gMap.gl.drawingBufferWidth : gGLMapCanvas.width; },
278   get height() { return gMap.gl ? gMap.gl.drawingBufferHeight : gGLMapCanvas.height; },
279
280   getVertShaderSource: function() {
281     return 'attribute vec2 aVertexPosition;\n' +
282     'attribute vec2 aTextureCoord;\n\n' +
283     'uniform vec2 uResolution;\n\n' +
284     'varying highp vec2 vTextureCoord;\n\n' +
285     'void main(void) {\n' +
286     // convert the rectangle from pixels to -1.0 to +1.0 (clipspace) 0.0 to 1.0
287     '  vec2 clipSpace = aVertexPosition * 2.0 / uResolution - 1.0;\n' +
288     '  gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1);\n' +
289     '  vTextureCoord = aTextureCoord;\n' +
290     '}'; },
291   getFragShaderSource: function() {
292     return 'varying highp vec2 vTextureCoord;\n\n' +
293     'uniform sampler2D uImage;\n\n' +
294     'void main(void) {\n' +
295     '  gl_FragColor = texture2D(uImage, vTextureCoord);\n' +
296     '}'; },
297
298   initGL: function() {
299     // When called from the event listener, the "this" reference doesn't work, so use the object name.
300     console.log("Initializing WebGL...");
301     if (gMap.gl) {
302       gMap.gl.viewport(0, 0, gMap.gl.drawingBufferWidth, gMap.gl.drawingBufferHeight);
303       gMap.gl.clearColor(0.0, 0.0, 0.0, 0.5);                          // Set clear color to black, fully opaque.
304       gMap.gl.clear(gMap.gl.COLOR_BUFFER_BIT|gMap.gl.DEPTH_BUFFER_BIT);  // Clear the color.
305
306       // Create and initialize the shaders.
307       console.log("Create and compile shaders...");
308       var vertShader = gMap.gl.createShader(gMap.gl.VERTEX_SHADER);
309       var fragShader = gMap.gl.createShader(gMap.gl.FRAGMENT_SHADER);
310       gMap.gl.shaderSource(vertShader, gMap.getVertShaderSource());
311       // Compile the shader program.
312       gMap.gl.compileShader(vertShader);
313       // See if it compiled successfully.
314       if (!gMap.gl.getShaderParameter(vertShader, gMap.gl.COMPILE_STATUS)) {
315         console.log("An error occurred compiling the vertex shader: " + gMap.gl.getShaderInfoLog(vertShader));
316         return null;
317       }
318       gMap.gl.shaderSource(fragShader, gMap.getFragShaderSource());
319       // Compile the shader program.
320       gMap.gl.compileShader(fragShader);
321       // See if it compiled successfully.
322       if (!gMap.gl.getShaderParameter(fragShader, gMap.gl.COMPILE_STATUS)) {
323         console.log("An error occurred compiling the fragment shader: " + gMap.gl.getShaderInfoLog(fragShader));
324         return null;
325       }
326
327       console.log("Create and link shader program...");
328       gMap.glShaderProgram = gMap.gl.createProgram();
329       gMap.gl.attachShader(gMap.glShaderProgram, vertShader);
330       gMap.gl.attachShader(gMap.glShaderProgram, fragShader);
331       gMap.gl.linkProgram(gMap.glShaderProgram);
332       // If creating the shader program failed, alert
333       if (!gMap.gl.getProgramParameter(gMap.glShaderProgram, gMap.gl.LINK_STATUS)) {
334         alert("Unable to initialize the shader program.");
335       }
336       gMap.gl.useProgram(gMap.glShaderProgram);
337       // Get locations of the attributes.
338       gMap.glVertexPositionAttr = gMap.gl.getAttribLocation(gMap.glShaderProgram, "aVertexPosition");
339       gMap.glTextureCoordAttr = gMap.gl.getAttribLocation(gMap.glShaderProgram, "aTextureCoord");
340       gMap.glResolutionAttr = gMap.gl.getUniformLocation(gMap.glShaderProgram, "uResolution");
341
342       console.log("Set up vertex buffer...");
343       var tileVerticesBuffer = gMap.gl.createBuffer();
344       gMap.gl.bindBuffer(gMap.gl.ARRAY_BUFFER, tileVerticesBuffer);
345       // The vertices are the coordinates of the corner points of the square.
346       var vertices = [
347         0.0,  0.0,
348         1.0,  0.0,
349         0.0,  1.0,
350         0.0,  1.0,
351         1.0,  0.0,
352         1.0,  1.0,
353       ];
354       gMap.gl.bufferData(gMap.gl.ARRAY_BUFFER, new Float32Array(vertices), gMap.gl.STATIC_DRAW);
355       gMap.gl.enableVertexAttribArray(gMap.glTextureCoordAttr);
356       gMap.gl.vertexAttribPointer(gMap.glTextureCoordAttr, 2, gMap.gl.FLOAT, false, 0, 0);
357
358       gMap.loadImageToTexture(gLoadingTile, getTileKey("loading", {x: 0, y: 0, z: 0}));
359
360       gMap.gl.uniform2f(gMap.glResolutionAttr, gGLMapCanvas.width, gGLMapCanvas.height);
361
362       // Create a buffer for the position of the rectangle corners.
363       console.log("Set up coord buffer...");
364       var mapVerticesTextureCoordBuffer = gMap.gl.createBuffer();
365       gMap.gl.bindBuffer(gMap.gl.ARRAY_BUFFER, mapVerticesTextureCoordBuffer);
366       gMap.gl.enableVertexAttribArray(gMap.glVertexPositionAttr);
367       gMap.gl.vertexAttribPointer(gMap.glVertexPositionAttr, 2, gMap.gl.FLOAT, false, 0, 0);
368
369       // Call texture cleaning every 30 seconds, for now (is 60 better?).
370       gMap.glTxCleanIntervalID = window.setInterval(gMap.cleanTextures, 30 * 1000);
371     }
372
373     if (!gAppInitDone) {
374       // We may be called when context was lost and destroyed,
375       // only send event when we are in app startup
376       // (gAppInitDone is set to true right after we return this event).
377       var throwEv = new CustomEvent("mapinit-done");
378       gAction.dispatchEvent(throwEv);
379     }
380   },
381
382   draw: function() {
383     gMap.assembleGL();
384     drawTrack();
385   },
386
387   assembleGL: function() {
388     if (!gMap.gl) { return; }
389
390     document.getElementById("zoomLevel").textContent = gMap.pos.z;
391     gMap.zoomFactor = Math.pow(2, gMap.maxZoom - gMap.pos.z);
392     gMap.baseDim.wid = gMap.gl.drawingBufferWidth * gMap.zoomFactor;
393     gMap.baseDim.ht = gMap.gl.drawingBufferHeight * gMap.zoomFactor;
394     gMap.baseDim.tsize = gMap.tileSize * gMap.zoomFactor;
395
396     var xMin = gMap.pos.x - gMap.baseDim.wid / 2; // Corners of the window in level 18 pixels.
397     var yMin = gMap.pos.y - gMap.baseDim.ht / 2;
398     var xMax = gMap.pos.x + gMap.baseDim.wid / 2;
399     var yMax = gMap.pos.y + gMap.baseDim.ht / 2;
400
401     if (gMapPrefsLoaded && mainDB)
402       gPrefs.set("position", gMap.pos);
403
404     // Go through all the tiles in the map, find out if to draw them and do so.
405     for (var x = Math.floor(xMin / gMap.baseDim.tsize); x < Math.ceil(xMax / gMap.baseDim.tsize); x++) {
406       for (var y = Math.floor(yMin / gMap.baseDim.tsize); y < Math.ceil(yMax / gMap.baseDim.tsize); y++) {
407         // Only go to loading step if we haven't loaded the texture.
408         var coords = {x: x, y: y, z: gMap.pos.z};
409         var tileKey = getTileKey(gMap.activeMap, normalizeCoords(coords));
410         if (!gMap.glTextures[tileKey]) {
411           // Initiate loading/drawing of the actual tile.
412           gTileService.get(gMap.activeMap, coords,
413                            function(aImage, aStyle, aCoords, aTileKey) {
414             // Only actually load if this still applies for the current view.
415             if ((aStyle == gMap.activeMap) && (aCoords.z == gMap.pos.z)) {
416               var URL = window.URL;
417               var imgURL = URL.createObjectURL(aImage);
418               var imgObj = new Image();
419               imgObj.onload = function() {
420                 gMap.loadImageToTexture(imgObj, aTileKey);
421                 if (document.hidden != true) { // Only draw if we're actually visible.
422                   window.requestAnimationFrame(function(aTimestamp) { gMap.drawGL() });
423                 }
424                 URL.revokeObjectURL(imgURL);
425               }
426               imgObj.src = imgURL;
427             }
428           });
429         }
430       }
431     }
432     if (document.hidden != true) { // Only draw if we're actually visible.
433       window.requestAnimationFrame(function(aTimestamp) { gMap.drawGL() });
434     }
435   },
436
437   drawGL: function() {
438     var xMin = gMap.pos.x - gMap.baseDim.wid / 2; // Corners of the window in level 18 pixels.
439     var yMin = gMap.pos.y - gMap.baseDim.ht / 2;
440     var xMax = gMap.pos.x + gMap.baseDim.wid / 2;
441     var yMax = gMap.pos.y + gMap.baseDim.ht / 2;
442
443     // Go through all the tiles in the map, find out if to draw them and do so.
444     for (var x = Math.floor(xMin / gMap.baseDim.tsize); x < Math.ceil(xMax / gMap.baseDim.tsize); x++) {
445       for (var y = Math.floor(yMin / gMap.baseDim.tsize); y < Math.ceil(yMax / gMap.baseDim.tsize); y++) {
446         // Rounding the pixel offsets ensures we position the tiles precisely.
447         var xoff = Math.round((x * gMap.baseDim.tsize - xMin) / gMap.zoomFactor);
448         var yoff = Math.round((y * gMap.baseDim.tsize - yMin) / gMap.zoomFactor);
449         // Draw the tile, first find out the actual texture to use.
450         var norm = normalizeCoords({x: x, y: y, z: gMap.pos.z});
451         var tileKey = getTileKey(gMap.activeMap, norm);
452         if (!gMap.glTextures[tileKey]) {
453           tileKey = getTileKey("loading", {x: 0, y: 0, z: 0});
454         }
455         gMap.drawTileGL(xoff, yoff, tileKey);
456       }
457     }
458   },
459
460   resizeAndDraw: function() {
461     var viewportWidth = Math.min(window.innerWidth, window.outerWidth);
462     var viewportHeight = Math.min(window.innerHeight, window.outerHeight);
463     if (gGLMapCanvas && gTrackCanvas) {
464       gGLMapCanvas.width = viewportWidth;
465       gGLMapCanvas.height = viewportHeight;
466       gTrackCanvas.width = viewportWidth;
467       gTrackCanvas.height = viewportHeight;
468       if (gMap.gl) {
469         // Size viewport to canvas size.
470         gMap.gl.viewport(0, 0, gMap.gl.drawingBufferWidth, gMap.gl.drawingBufferHeight);
471         // Clear the color.
472         gMap.gl.clear(gMap.gl.COLOR_BUFFER_BIT);
473         // Make sure the vertex shader get the right resolution.
474         gMap.gl.uniform2f(gMap.glResolutionAttr, gGLMapCanvas.width, gGLMapCanvas.height);
475         // Prepare recalculation of textures to keep for one zoom level.
476         gMap.glTexturesPerZoomLevel = 0;
477       }
478       gMap.draw();
479       showUI();
480     }
481   },
482
483   drawTileGL: function(aLeft, aRight, aTileKey) {
484     gMap.gl.activeTexture(gMap.gl.TEXTURE0);
485     gMap.gl.bindTexture(gMap.gl.TEXTURE_2D, gMap.glTextures[aTileKey]);
486     // Set uImage to refer to TEXTURE0
487     gMap.gl.uniform1i(gMap.gl.getUniformLocation(gMap.glShaderProgram, "uImage"), 0);
488     var x_start = aLeft;
489     var i_width = gMap.tileSize;
490     var y_start = aRight;
491     var i_height = gMap.tileSize;
492     var textureCoordinates = [
493       x_start, y_start,
494       x_start + i_width, y_start,
495       x_start, y_start + i_height,
496       x_start, y_start + i_height,
497       x_start + i_width, y_start,
498       x_start + i_width, y_start + i_height,
499     ];
500     gMap.gl.bufferData(gMap.gl.ARRAY_BUFFER, new Float32Array(textureCoordinates), gMap.gl.STATIC_DRAW);
501
502     // There are 6 indices in textureCoordinates.
503     gMap.gl.drawArrays(gMap.gl.TRIANGLES, 0, 6);
504   },
505
506   loadImageToTexture: function(aImage, aTileKey) {
507     // Create and bind texture.
508     gMap.glTextures[aTileKey] = gMap.gl.createTexture();
509     gMap.gl.bindTexture(gMap.gl.TEXTURE_2D, gMap.glTextures[aTileKey]);
510     // Set params for how the texture minifies and magnifies (wrap params are not needed as we're power-of-two).
511     gMap.gl.texParameteri(gMap.gl.TEXTURE_2D, gMap.gl.TEXTURE_MIN_FILTER, gMap.gl.NEAREST);
512     gMap.gl.texParameteri(gMap.gl.TEXTURE_2D, gMap.gl.TEXTURE_MAG_FILTER, gMap.gl.NEAREST);
513     // Upload the image into the texture.
514     gMap.gl.texImage2D(gMap.gl.TEXTURE_2D, 0, gMap.gl.RGBA, gMap.gl.RGBA, gMap.gl.UNSIGNED_BYTE, aImage);
515   },
516
517   cleanTextures: function() {
518     // Get rid of unneeded textures to save memory.
519     // TODO: Be less aggressive, maybe keep neighboring zoom levels (but x/y coords there are zoom-specific).
520     if (!gMap.glTexturesPerZoomLevel) {
521       // Calculate how many textures we need to keep for one zoom level.
522       // ceil(width/size) gives us the minimum, keep one on either side as well.
523       gMap.glTexturesPerZoomLevel =
524         Math.ceil(gMap.gl.drawingBufferWidth / gMap.tileSize + 2) *
525         Math.ceil(gMap.gl.drawingBufferHeight / gMap.tileSize + 2);
526       console.log("Keeping " + gMap.glTexturesPerZoomLevel + " textures per level");
527     }
528     if (Object.keys(gMap.glTextures).length > gMap.glTexturesPerZoomLevel) {
529       console.log("Cleaning textures... (have " + Object.keys(gMap.glTextures).length + " atm)");
530
531       // Find coordinate ranges for tiles to keep.
532       var tMin = normalizeCoords({x: Math.floor((gMap.pos.x - gMap.baseDim.wid / 2) / gMap.baseDim.tsize) - 1,
533                                   y: Math.floor((gMap.pos.y - gMap.baseDim.ht / 2) / gMap.baseDim.tsize) - 1,
534                                   z: gMap.pos.z});
535       var tMax = normalizeCoords({x: Math.ceil((gMap.pos.x + gMap.baseDim.wid / 2) / gMap.baseDim.tsize) + 1,
536                                   y: Math.ceil((gMap.pos.y + gMap.baseDim.ht / 2) / gMap.baseDim.tsize) + 1,
537                                   z: gMap.pos.z});
538       console.log("In range: " + tMin.x + "," + tMin.y + "," + tMin.z + " - " + tMax.x + "," + tMax.y + "," + tMax.z);
539       for (var tileKey in gMap.glTextures) {
540         var keyMatches = tileKey.match(/([^:]+)::(\d+),(\d+),(\d+)/);
541         if (keyMatches && keyMatches[1] != "loading") {
542           var txData = {
543             style: keyMatches[1],
544             x: keyMatches[2],
545             y: keyMatches[3],
546             z: keyMatches[4],
547           }
548           var delTx = false;
549           if (txData.style != gMap.activeMap) { delTx = true; console.log("Different map style: " + txData.style); }
550           if (!delTx && (txData.z < tMin.z || txData.z > tMax.z)) { delTx = true; console.log("Out-of-range zoom: " + txData.z); }
551           if (tMin.x < tMax.x) {
552             if (!delTx && (txData.x < tMin.x || txData.x > tMax.x)) { delTx = true; console.log("Out-of-range X: " + txData.x); }
553           }
554           else {
555             // We are crossing over the 0 coordinate!
556             if (!delTx && (txData.x < tMin.x && txData.x > tMax.x)) { delTx = true; console.log("Out-of-range X: " + txData.x); }
557           }
558           if (tMin.y < tMax.y) {
559             if (!delTx && (txData.y < tMin.y || txData.y > tMax.y)) { delTx = true; console.log("Out-of-range Y: " + txData.y); }
560           }
561           else {
562             // We are crossing over the 0 coordinate!
563             if (!delTx && (txData.y < tMin.y && txData.y > tMax.y)) { delTx = true; console.log("Out-of-range Y: " + txData.y); }
564           }
565           if (delTx) {
566             // Delete texture from GL and from the array we are holding.
567             gMap.gl.deleteTexture(gMap.glTextures[tileKey]);
568             delete gMap.glTextures[tileKey];
569           }
570         }
571       }
572       console.log("Cleaning complete, " + Object.keys(gMap.glTextures).length + " textures left)");
573     }
574   },
575
576   handleContextLost: function(event) {
577     event.preventDefault();
578     // GL context is gone, let's reset everything that depends on it.
579     clearInterval(gMap.glTxCleanIntervalID);
580     gMap.glTextures = {};
581   },
582
583   handleContextRestored: function(event) {
584     // When GL context is back, init GL again and draw.
585     gMap.initGL();
586     gMap.draw();
587   },
588 }
589
590 // Using scale(x, y) together with drawing old data on scaled canvas would be an improvement for zooming.
591 // See https://developer.mozilla.org/en-US/docs/Canvas_tutorial/Transformations#Scaling
592
593 function zoomIn() {
594   if (gMap.pos.z < gMap.maxZoom) {
595     gMap.pos.z++;
596     gMap.draw();
597   }
598 }
599
600 function zoomOut() {
601   if (gMap.pos.z > 0) {
602     gMap.pos.z--;
603     gMap.draw();
604   }
605 }
606
607 function zoomTo(aTargetLevel) {
608   aTargetLevel = parseInt(aTargetLevel);
609   if (aTargetLevel >= 0 && aTargetLevel <= gMap.maxZoom) {
610     gMap.pos.z = aTargetLevel;
611     gMap.draw();
612   }
613 }
614
615 function gps2xy(aLatitude, aLongitude) {
616   var maxZoomFactor = Math.pow(2, gMap.maxZoom) * gMap.tileSize;
617   var convLat = aLatitude * Math.PI / 180;
618   var rawY = (1 - Math.log(Math.tan(convLat) +
619                            1 / Math.cos(convLat)) / Math.PI) / 2 * maxZoomFactor;
620   var rawX = (aLongitude + 180) / 360 * maxZoomFactor;
621   return {x: Math.round(rawX),
622           y: Math.round(rawY)};
623 }
624
625 function xy2gps(aX, aY) {
626   var maxZoomFactor = Math.pow(2, gMap.maxZoom) * gMap.tileSize;
627   var n = Math.PI - 2 * Math.PI * aY / maxZoomFactor;
628   return {latitude: 180 / Math.PI *
629                     Math.atan(0.5 * (Math.exp(n) - Math.exp(-n))),
630           longitude: aX / maxZoomFactor * 360 - 180};
631 }
632
633 function setMapStyle() {
634   var mapSel = document.getElementById("mapSelector");
635   if (mapSel.selectedIndex >= 0 && gMap.activeMap != mapSel.value) {
636     gMap.activeMap = mapSel.value;
637     gPrefs.set("active_map_style", gMap.activeMap);
638     document.getElementById("copyright").innerHTML =
639         gMapStyles[gMap.activeMap].copyright;
640     if (!gWaitCounter) { // Only do this when prefs are loaded already.
641       showUI();
642       gMap.draw();
643     }
644   }
645 }
646
647 // A sane mod function that works for negative numbers.
648 // Returns a % b.
649 function mod(a, b) {
650   return ((a % b) + b) % b;
651 }
652
653 function normalizeCoords(aCoords) {
654   var zoomFactor = Math.pow(2, aCoords.z);
655   return {x: mod(aCoords.x, zoomFactor),
656           y: mod(aCoords.y, zoomFactor),
657           z: aCoords.z};
658 }
659
660 function getTileKey(aStyle, aNormalizedCoords) {
661   return aStyle + "::" +
662          aNormalizedCoords.x + "," +
663          aNormalizedCoords.y + "," +
664          aNormalizedCoords.z;
665 }
666
667 // Returns true if the tile is outside the current view.
668 function isOutsideWindow(t) {
669   var pos = decodeIndex(t);
670
671   var zoomFactor = Math.pow(2, gMap.maxZoom - pos.z);
672   var wid = gMap.width * zoomFactor;
673   var ht = gMap.height * zoomFactor;
674
675   pos.x *= zoomFactor;
676   pos.y *= zoomFactor;
677
678   var sz = gMap.tileSize * zoomFactor;
679   if (pos.x > gMap.pos.x + wid / 2 || pos.y > gMap.pos.y + ht / 2 ||
680       pos.x + sz < gMap.pos.x - wid / 2 || pos.y - sz < gMap.pos.y - ht / 2)
681     return true;
682   return false;
683 }
684
685 function encodeIndex(x, y, z) {
686   var norm = normalizeCoords({x: x, y: y, z: z});
687   return norm.x + "," + norm.y + "," + norm.z;
688 }
689
690 function decodeIndex(encodedIdx) {
691   var ind = encodedIdx.split(",", 3);
692   return {x: ind[0], y: ind[1], z: ind[2]};
693 }
694
695 function drawTrack() {
696   if (gTrackContext && (document.hidden != true)) { // Only draw if we're actually visible.
697     gLastDrawnPoint = null;
698     gCurPosMapCache = undefined;
699     gTrackContext.clearRect(0, 0, gTrackCanvas.width, gTrackCanvas.height);
700     if (gTrack.length) {
701       for (var i = 0; i < gTrack.length; i++) {
702         drawTrackPoint(gTrack[i].coords.latitude, gTrack[i].coords.longitude,
703                       (i + 1 >= gTrack.length || gTrack[i+1].beginSegment));
704       }
705     }
706   }
707 }
708
709 function drawTrackPoint(aLatitude, aLongitude, lastPoint) {
710   var trackpoint = gps2xy(aLatitude, aLongitude);
711   // lastPoint is for optimizing (not actually executing the draw until the last)
712   trackpoint.optimized = (lastPoint === false);
713   var mappos = {x: Math.round((trackpoint.x - gMap.pos.x) / gMap.zoomFactor + gMap.width / 2),
714                 y: Math.round((trackpoint.y - gMap.pos.y) / gMap.zoomFactor + gMap.height / 2)};
715
716   if (!gLastDrawnPoint || !gLastDrawnPoint.optimized) {
717     gTrackContext.strokeStyle = gTrackColor;
718     gTrackContext.fillStyle = gTrackContext.strokeStyle;
719     gTrackContext.lineWidth = gTrackWidth;
720     gTrackContext.lineCap = "round";
721     gTrackContext.lineJoin = "round";
722   }
723   // This breaks optimiziation, so make sure to reset optimization.
724   if (!gLastDrawnPoint || gLastDrawnPoint == trackpoint) {
725     trackpoint.optimized = false;
726     // Close path if one was open.
727     if (gLastDrawnPoint && gLastDrawnPoint.optimized) {
728       gTrackContext.stroke();
729     }
730   }
731   if (!gLastDrawnPoint || (gLastDrawnPoint == trackpoint) || !gLastDrawnPoint.optimized) {
732     // Start drawing a segment.
733     gTrackContext.beginPath();
734     gTrackContext.arc(mappos.x, mappos.y,
735                       gTrackContext.lineWidth, 0, Math.PI * 2, false);
736     gTrackContext.fill();
737   }
738   else {
739     // Continue drawing segment, close if needed.
740     gTrackContext.lineTo(mappos.x, mappos.y);
741     if (!trackpoint.optimized)
742       gTrackContext.stroke();
743   }
744   gLastDrawnPoint = trackpoint;
745 }
746
747 function drawCurrentLocation(trackPoint) {
748   var locpoint = gps2xy(trackPoint.coords.latitude, trackPoint.coords.longitude);
749   var circleRadius = Math.round(gCurLocSize / 2);
750   var mappos = {x: Math.round((locpoint.x - gMap.pos.x) / gMap.zoomFactor + gMap.width / 2),
751                 y: Math.round((locpoint.y - gMap.pos.y) / gMap.zoomFactor + gMap.height / 2)};
752
753   undrawCurrentLocation();
754
755   // Cache overdrawn area.
756   gCurPosMapCache =
757       {point: locpoint,
758        radius: circleRadius,
759        data: gTrackContext.getImageData(mappos.x - circleRadius,
760                                         mappos.y - circleRadius,
761                                         circleRadius * 2, circleRadius * 2)};
762
763   gTrackContext.strokeStyle = gCurLocColor;
764   gTrackContext.fillStyle = gTrackContext.strokeStyle;
765   gTrackContext.beginPath();
766   gTrackContext.arc(mappos.x, mappos.y,
767                     circleRadius, 0, Math.PI * 2, false);
768   gTrackContext.fill();
769 }
770
771 function undrawCurrentLocation() {
772   if (gCurPosMapCache) {
773     var oldpoint = gCurPosMapCache.point;
774     var oldmp = {x: Math.round((oldpoint.x - gMap.pos.x) / gMap.zoomFactor + gMap.width / 2),
775                  y: Math.round((oldpoint.y - gMap.pos.y) / gMap.zoomFactor + gMap.height / 2)};
776     gTrackContext.putImageData(gCurPosMapCache.data,
777                                oldmp.x - gCurPosMapCache.radius,
778                                oldmp.y - gCurPosMapCache.radius);
779     gCurPosMapCache = undefined;
780   }
781 }
782
783 function calcTrackDuration() {
784   // Get the duration of the track in s.
785   var tDuration = 0;
786   if (gTrack.length > 1) {
787     for (var i = 1; i < gTrack.length; i++) {
788       if (!gTrack[i].beginSegment) {
789         tDuration += (gTrack[i].time - gTrack[i-1].time);
790       }
791     }
792   }
793   return Math.round(tDuration / 1000); // The timestamps are in ms but we return seconds.
794 }
795
796 function calcTrackLength() {
797   // Get the length of the track in km.
798   var tLength = 0;
799   if (gTrack.length > 1) {
800     for (var i = 1; i < gTrack.length; i++) {
801       if (!gTrack[i].beginSegment) {
802         tLength += getPointDistance(gTrack[i-1].coords, gTrack[i].coords);
803       }
804     }
805   }
806   return tLength;
807 }
808
809 function getPointDistance(aGPSPoint1, aGPSPoint2) {
810   // Get the distance in km between the two given GPS points.
811   // See http://stackoverflow.com/questions/365826/calculate-distance-between-2-gps-coordinates
812   // Earth is almost exactly a sphere and we calculate small distances on the surface, so we can do spherical great-circle math.
813   // Also see http://en.wikipedia.org/wiki/Great-circle_distance
814   var R = 6371; // km
815   var dLat = deg2rad(aGPSPoint2.latitude - aGPSPoint1.latitude);
816   var dLon = deg2rad(aGPSPoint2.longitude - aGPSPoint1.longitude);
817   var lat1 = deg2rad(aGPSPoint1.latitude);
818   var lat2 = deg2rad(aGPSPoint2.latitude);
819
820   var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
821           Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2);
822   var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
823   return R * c;
824 }
825
826 function deg2rad(aDegreeValue) {
827   // Convert an angle in degrees to radiants.
828   return aDegreeValue * (Math.PI / 180);
829 }
830
831 var mapEvHandler = {
832   handleEvent: function(aEvent) {
833     var touchEvent = aEvent.type.indexOf('touch') != -1;
834
835     if (touchEvent) {
836       aEvent.stopPropagation();
837     }
838
839     // Bail out if the event is happening on an input.
840     if (aEvent.target.tagName.toLowerCase() == "input")
841       return;
842
843     // Bail out on unwanted map moves, but not zoom or keyboard events.
844     if (aEvent.type.indexOf("mouse") === 0 || aEvent.type.indexOf("touch") === 0) {
845       // Bail out if this is neither a touch nor left-click.
846       if (!touchEvent && aEvent.button != 0)
847         return;
848
849       // Bail out if the started touch can't be found.
850       if (touchEvent && gDragging &&
851           !aEvent.changedTouches.identifiedTouch(gDragTouchID))
852         return;
853     }
854
855     var coordObj = touchEvent ?
856                    aEvent.changedTouches.identifiedTouch(gDragTouchID) :
857                    aEvent;
858
859     switch (aEvent.type) {
860       case "mousedown":
861       case "touchstart":
862         if (touchEvent) {
863           if (aEvent.targetTouches.length == 2) {
864             gPinchStartWidth = Math.sqrt(
865                 Math.pow(aEvent.targetTouches.item(1).clientX -
866                          aEvent.targetTouches.item(0).clientX, 2) +
867                 Math.pow(aEvent.targetTouches.item(1).clientY -
868                          aEvent.targetTouches.item(0).clientY, 2)
869             );
870           }
871           gDragTouchID = aEvent.changedTouches.item(0).identifier;
872           coordObj = aEvent.changedTouches.identifiedTouch(gDragTouchID);
873         }
874         var x = coordObj.clientX - gGLMapCanvas.offsetLeft;
875         var y = coordObj.clientY - gGLMapCanvas.offsetTop;
876
877         if (touchEvent || aEvent.button === 0) {
878           gDragging = true;
879         }
880         gLastMouseX = x;
881         gLastMouseY = y;
882         showUI();
883         break;
884       case "mousemove":
885       case "touchmove":
886         if (touchEvent && aEvent.targetTouches.length == 2) {
887           curPinchStartWidth = Math.sqrt(
888               Math.pow(aEvent.targetTouches.item(1).clientX -
889                        aEvent.targetTouches.item(0).clientX, 2) +
890               Math.pow(aEvent.targetTouches.item(1).clientY -
891                        aEvent.targetTouches.item(0).clientY, 2)
892           );
893           if (!gPinchStartWidth)
894             gPinchStartWidth = curPinchStartWidth;
895
896           if (gPinchStartWidth / curPinchStartWidth > 1.7 ||
897               gPinchStartWidth / curPinchStartWidth < 0.6) {
898             var newZoomLevel = gMap.pos.z + (gPinchStartWidth < curPinchStartWidth ? 1 : -1);
899             if ((newZoomLevel >= 0) && (newZoomLevel <= gMap.maxZoom)) {
900               // Calculate new center of the map - preserve middle of pinch.
901               // This means that pixel distance between old center and middle
902               // must equal pixel distance of new center and middle.
903               var x = (aEvent.targetTouches.item(1).clientX +
904                        aEvent.targetTouches.item(0).clientX) / 2 -
905                       gGLMapCanvas.offsetLeft;
906               var y = (aEvent.targetTouches.item(1).clientY +
907                        aEvent.targetTouches.item(0).clientY) / 2 -
908                       gGLMapCanvas.offsetTop;
909
910               // Zoom factor after this action.
911               var newZoomFactor = Math.pow(2, gMap.maxZoom - newZoomLevel);
912               gMap.pos.x -= (x - gMap.width / 2) * (newZoomFactor - gMap.zoomFactor);
913               gMap.pos.y -= (y - gMap.height / 2) * (newZoomFactor - gMap.zoomFactor);
914
915               if (gPinchStartWidth < curPinchStartWidth)
916                 zoomIn();
917               else
918                 zoomOut();
919
920               // Reset pinch start width and start another pinch gesture.
921               gPinchStartWidth = null;
922             }
923           }
924           // If we are in a pinch, do not drag.
925           break;
926         }
927         var x = coordObj.clientX - gGLMapCanvas.offsetLeft;
928         var y = coordObj.clientY - gGLMapCanvas.offsetTop;
929         if (gDragging === true) {
930           var dX = x - gLastMouseX;
931           var dY = y - gLastMouseY;
932           gMap.pos.x -= dX * gMap.zoomFactor;
933           gMap.pos.y -= dY * gMap.zoomFactor;
934           gMap.draw();
935           showUI();
936         }
937         gLastMouseX = x;
938         gLastMouseY = y;
939         break;
940       case "mouseup":
941       case "touchend":
942         gPinchStartWidth = null;
943         gDragging = false;
944         showUI();
945         break;
946       case "mouseout":
947       case "touchcancel":
948       case "touchleave":
949         //gDragging = false;
950         break;
951       case "wheel":
952         // If we'd want pixels, we'd need to calc up using aEvent.deltaMode.
953         // See https://developer.mozilla.org/en-US/docs/Mozilla_event_reference/wheel
954
955         // Only accept (non-null) deltaY values
956         if (!aEvent.deltaY)
957           break;
958
959         // Debug output: "coordinates" of the point the mouse was over.
960         /*
961         var ptCoord = {x: gMap.pos.x + (x - gMap.width / 2) * gMap.zoomFactor,
962                        y: gMap.pos.y + (x - gMap.height / 2) * gMap.zoomFactor};
963         var gpsCoord = xy2gps(ptCoord.x, ptCoord.y);
964         var pt2Coord = gps2xy(gpsCoord.latitude, gpsCoord.longitude);
965         console.log(ptCoord.x + "/" + ptCoord.y + " - " +
966                     gpsCoord.latitude + "/" + gpsCoord.longitude + " - " +
967                     pt2Coord.x + "/" + pt2Coord.y);
968         */
969
970         var newZoomLevel = gMap.pos.z + (aEvent.deltaY < 0 ? 1 : -1);
971         if ((newZoomLevel >= 0) && (newZoomLevel <= gMap.maxZoom)) {
972           // Calculate new center of the map - same point stays under the mouse.
973           // This means that the pixel distance between the old center and point
974           // must equal the pixel distance of the new center and that point.
975           var x = coordObj.clientX - gGLMapCanvas.offsetLeft;
976           var y = coordObj.clientY - gGLMapCanvas.offsetTop;
977
978           // Zoom factor after this action.
979           var newZoomFactor = Math.pow(2, gMap.maxZoom - newZoomLevel);
980           gMap.pos.x -= (x - gMap.width / 2) * (newZoomFactor - gMap.zoomFactor);
981           gMap.pos.y -= (y - gMap.height / 2) * (newZoomFactor - gMap.zoomFactor);
982
983           if (aEvent.deltaY < 0)
984             zoomIn();
985           else
986             zoomOut();
987         }
988         break;
989       case "keydown":
990         // Allow keyboard control to move and zoom the map.
991         // Should use aEvent.key instead of aEvent.which but needs bug 680830.
992         // See https://developer.mozilla.org/en-US/docs/DOM/Mozilla_event_reference/keydown
993         var dX = 0;
994         var dY = 0;
995         switch (aEvent.which) {
996           case 39: // right
997             dX = -gMap.tileSize / 2;
998           break;
999           case 37: // left
1000             dX = gMap.tileSize / 2;
1001           break;
1002           case 38: // up
1003             dY = gMap.tileSize / 2;
1004           break;
1005           case 40: // down
1006             dY = -gMap.tileSize / 2;
1007           break;
1008           case 87: // w
1009           case 107: // + (numpad)
1010           case 171: // + (normal key)
1011             zoomIn();
1012           break;
1013           case 83: // s
1014           case 109: // - (numpad)
1015           case 173: // - (normal key)
1016             zoomOut();
1017           break;
1018           case 48: // 0
1019           case 49: // 1
1020           case 50: // 2
1021           case 51: // 3
1022           case 52: // 4
1023           case 53: // 5
1024           case 54: // 6
1025           case 55: // 7
1026           case 56: // 8
1027             zoomTo(aEvent.which - 38);
1028           break;
1029           case 57: // 9
1030             zoomTo(9);
1031           break;
1032           case 96: // 0 (numpad)
1033           case 97: // 1 (numpad)
1034           case 98: // 2 (numpad)
1035           case 99: // 3 (numpad)
1036           case 100: // 4 (numpad)
1037           case 101: // 5 (numpad)
1038           case 102: // 6 (numpad)
1039           case 103: // 7 (numpad)
1040           case 104: // 8 (numpad)
1041             zoomTo(aEvent.which - 86);
1042           break;
1043           case 105: // 9 (numpad)
1044             zoomTo(9);
1045           break;
1046           default: // not supported
1047             console.log("key not supported: " + aEvent.which);
1048           break;
1049         }
1050
1051         // Move if needed.
1052         if (dX || dY) {
1053           gMap.pos.x -= dX * gMap.zoomFactor;
1054           gMap.pos.y -= dY * gMap.zoomFactor;
1055           gMap.draw();
1056         }
1057         break;
1058     }
1059   }
1060 };
1061
1062 function visibilityEvHandler() {
1063   // Immediately draw if we just got visible.
1064   if (document.hidden != true) {
1065     gMap.draw();
1066   }
1067   // No need to handle the event where we become invisible as we care only draw
1068   // when we are visible anyhow.
1069 }
1070
1071 var geofake = {
1072   tracking: false,
1073   lastPos: {x: undefined, y: undefined},
1074   watchPosition: function(aSuccessCallback, aErrorCallback, aPrefObject) {
1075     this.tracking = true;
1076     var watchCall = function() {
1077       // calc new position in lat/lon degrees
1078       // 90° on Earth surface are ~10,000 km at the equator,
1079       // so try moving at most 10m at a time
1080       if (geofake.lastPos.x)
1081         geofake.lastPos.x += (Math.random() - .5) * 90 / 1000000
1082       else
1083         geofake.lastPos.x = 48.208174
1084       if (geofake.lastPos.y)
1085         geofake.lastPos.y += (Math.random() - .5) * 90 / 1000000
1086       else
1087         geofake.lastPos.y = 16.373819
1088       aSuccessCallback({timestamp: Date.now(),
1089                         coords: {latitude: geofake.lastPos.x,
1090                                  longitude: geofake.lastPos.y,
1091                                  accuracy: 20}});
1092       if (geofake.tracking)
1093         setTimeout(watchCall, 1000);
1094     };
1095     setTimeout(watchCall, 1000);
1096     return "foo";
1097   },
1098   clearWatch: function(aID) {
1099     this.tracking = false;
1100   }
1101 }
1102
1103 function setCentering(aCheckbox) {
1104   if (gMapPrefsLoaded && mainDB)
1105     gPrefs.set("center_map", aCheckbox.checked);
1106   gCenterPosition = aCheckbox.checked;
1107 }
1108
1109 function setTracking(aCheckbox) {
1110   if (gMapPrefsLoaded && mainDB)
1111     gPrefs.set("tracking_enabled", aCheckbox.checked);
1112   if (aCheckbox.checked)
1113     startTracking();
1114   else
1115     endTracking();
1116 }
1117
1118 function startTracking() {
1119   if (gGeolocation) {
1120     gActionLabel.textContent = "Establishing Position";
1121     gAction.style.display = "block";
1122     gGeoWatchID = gGeolocation.watchPosition(
1123       function(position) {
1124         if (gActionLabel.textContent) {
1125           gActionLabel.textContent = "";
1126           gAction.style.display = "none";
1127         }
1128         // Coords spec: https://developer.mozilla.org/en/XPCOM_Interface_Reference/NsIDOMGeoPositionCoords
1129         var tPoint = {time: position.timestamp,
1130                       coords: {latitude: position.coords.latitude,
1131                                longitude: position.coords.longitude,
1132                                altitude: position.coords.altitude,
1133                                accuracy: position.coords.accuracy,
1134                                altitudeAccuracy: position.coords.altitudeAccuracy,
1135                                heading: position.coords.heading,
1136                                speed: position.coords.speed},
1137                       beginSegment: !gLastTrackPoint};
1138         // Only add point to track is accuracy is good enough.
1139         if (tPoint.coords.accuracy < gMinTrackAccuracy) {
1140           gLastTrackPoint = tPoint;
1141           gTrack.push(tPoint);
1142           try { gTrackStore.push(tPoint); } catch(e) {}
1143           var redrawn = false;
1144           if (gCenterPosition) {
1145             var posCoord = gps2xy(position.coords.latitude,
1146                                   position.coords.longitude);
1147             if (Math.abs(gMap.pos.x - posCoord.x) > gMap.width * gMap.zoomFactor / 4 ||
1148                 Math.abs(gMap.pos.y - posCoord.y) > gMap.height * gMap.zoomFactor / 4) {
1149               gMap.pos.x = posCoord.x;
1150               gMap.pos.y = posCoord.y;
1151               gMap.draw(); // This draws the current point as well.
1152               redrawn = true;
1153             }
1154           }
1155           if (!redrawn)
1156             undrawCurrentLocation();
1157             drawTrackPoint(position.coords.latitude, position.coords.longitude, true);
1158         }
1159         drawCurrentLocation(tPoint);
1160       },
1161       function(error) {
1162         // Ignore erros for the moment, but this is good for debugging.
1163         // See https://developer.mozilla.org/en/Using_geolocation#Handling_errors
1164         if (gDebug)
1165           console.log(error.message);
1166       },
1167       {enableHighAccuracy: true}
1168     );
1169   }
1170 }
1171
1172 function endTracking() {
1173   if (gActionLabel.textContent) {
1174     gActionLabel.textContent = "";
1175     gAction.style.display = "none";
1176   }
1177   if (gGeoWatchID) {
1178     gGeolocation.clearWatch(gGeoWatchID);
1179   }
1180 }
1181
1182 function clearTrack() {
1183   gTrack = [];
1184   gTrackStore.clear();
1185   drawTrack();
1186 }
1187
1188 var gTileService = {
1189   objStore: "tilecache",
1190
1191   ageLimit: 14 * 86400 * 1000, // 2 weeks (in ms)
1192
1193   get: function(aStyle, aCoords, aCallback) {
1194     var norm = normalizeCoords(aCoords);
1195     var dbkey = getTileKey(aStyle, norm);
1196     this.getDBCache(dbkey, function(aResult, aEvent) {
1197       if (aResult) {
1198         // We did get a cached object.
1199         aCallback(aResult.image, aStyle, aCoords, dbkey);
1200         // Look at the timestamp and return if it's not too old.
1201         if (aResult.timestamp + gTileService.ageLimit > Date.now())
1202           return;
1203         // Reload cached tile otherwise.
1204         var oldDate = new Date(aResult.timestamp);
1205         console.log("reload cached tile: " + dbkey + " - " + oldDate.toUTCString());
1206       }
1207       // Retrieve image from the web and store it in the cache.
1208       var XHR = new XMLHttpRequest();
1209       XHR.open("GET",
1210                 gMapStyles[aStyle].url
1211                   .replace("{x}", norm.x)
1212                   .replace("{y}", norm.y)
1213                   .replace("{z}", norm.z)
1214                   .replace("[a-c]", String.fromCharCode(97 + Math.floor(Math.random() * 3)))
1215                   .replace("[a-d]", String.fromCharCode(97 + Math.floor(Math.random() * 4)))
1216                   .replace("[1-4]", 1 + Math.floor(Math.random() * 4)),
1217                 true);
1218       XHR.responseType = "blob";
1219       XHR.addEventListener("load", function () {
1220         if (XHR.status === 200) {
1221           var blob = XHR.response;
1222           aCallback(blob, aStyle, aCoords, dbkey);
1223           gTileService.setDBCache(dbkey, {image: blob, timestamp: Date.now()});
1224         }
1225       }, false);
1226       XHR.send();
1227     });
1228   },
1229
1230   getDBCache: function(aKey, aCallback) {
1231     if (!mainDB)
1232       return;
1233     var transaction = mainDB.transaction([this.objStore]);
1234     var request = transaction.objectStore(this.objStore).get(aKey);
1235     request.onsuccess = function(event) {
1236       aCallback(request.result, event);
1237     };
1238     request.onerror = function(event) {
1239       // Errors can be handled here.
1240       aCallback(undefined, event);
1241     };
1242   },
1243
1244   setDBCache: function(aKey, aValue, aCallback) {
1245     if (!mainDB)
1246       return;
1247     var success = false;
1248     var transaction = mainDB.transaction([this.objStore], "readwrite");
1249     var objStore = transaction.objectStore(this.objStore);
1250     var request = objStore.put(aValue, aKey);
1251     request.onsuccess = function(event) {
1252       success = true;
1253       if (aCallback)
1254         aCallback(success, event);
1255     };
1256     request.onerror = function(event) {
1257       // Errors can be handled here.
1258       if (aCallback)
1259         aCallback(success, event);
1260     };
1261   },
1262
1263   unsetDBCache: function(aKey, aCallback) {
1264     if (!mainDB)
1265       return;
1266     var success = false;
1267     var transaction = mainDB.transaction([this.objStore], "readwrite");
1268     var request = transaction.objectStore(this.objStore).delete(aKey);
1269     request.onsuccess = function(event) {
1270       success = true;
1271       if (aCallback)
1272         aCallback(success, event);
1273     };
1274     request.onerror = function(event) {
1275       // Errors can be handled here.
1276       if (aCallback)
1277         aCallback(success, event);
1278     }
1279   },
1280
1281   clearDB: function(aCallback) {
1282     if (!mainDB)
1283       return;
1284     var success = false;
1285     var transaction = mainDB.transaction([this.objStore], "readwrite");
1286     var request = transaction.objectStore(this.objStore).clear();
1287     request.onsuccess = function(event) {
1288       success = true;
1289       if (aCallback)
1290         aCallback(success, event);
1291     };
1292     request.onerror = function(event) {
1293       // Errors can be handled here.
1294       if (aCallback)
1295         aCallback(success, event);
1296     }
1297   }
1298 };