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