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