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