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