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