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