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