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