7fb08b15f66ccdb0fed2fd1fc7836bb4a994b36b
[lantea.git] / js / ui.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 // Get the best-available indexedDB object.
6 var iDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB;
7 var mainDB;
8
9 var gUIHideCountdown = 0;
10
11 window.onload = function() {
12   var mSel = document.getElementById("mapSelector");
13   for (var mapStyle in gMapStyles) {
14     var opt = document.createElement("option");
15     opt.value = mapStyle;
16     opt.text = gMapStyles[mapStyle].name;
17     mSel.add(opt, null);
18   }
19
20   var areas = document.getElementsByClassName('overlayArea');
21   for (var i = 0; i <= areas.length - 1; i++) {
22     areas[i].addEventListener("mouseup", uiEvHandler, false);
23     areas[i].addEventListener("mousemove", uiEvHandler, false);
24     areas[i].addEventListener("mousedown", uiEvHandler, false);
25     areas[i].addEventListener("mouseout", uiEvHandler, false);
26
27     areas[i].addEventListener("touchstart", uiEvHandler, false);
28     areas[i].addEventListener("touchmove", uiEvHandler, false);
29     areas[i].addEventListener("touchend", uiEvHandler, false);
30     areas[i].addEventListener("touchcancel", uiEvHandler, false);
31     areas[i].addEventListener("touchleave", uiEvHandler, false);
32   }
33
34   if (/Mozilla\/5.0 \(Mobile;/.test(navigator.useragent)) {
35     // For Firefox OS, don't display the "save" button.
36     // Do this by setting the debugHide class for testing in debug mode.
37     document.getElementById("saveTrackButton").classList.add("debugHide");
38   }
39
40   initDB();
41   initMap();
42   resizeAndDraw();
43 }
44
45 window.onresize = function() {
46   resizeAndDraw();
47 }
48
49 function initDB() {
50   // Open DB.
51   var request = iDB.open("MainDB", 1);
52   request.onerror = function(event) {
53     // Errors can be handled here. Error codes explain in:
54     // https://developer.mozilla.org/en/IndexedDB/IDBDatabaseException#Constants
55     //document.getElementById("debug").textContent =
56     //  "error opening mainDB: " + event.target.errorCode;
57   };
58   request.onsuccess = function(event) {
59     //document.getElementById("debug").textContent = "mainDB opened.";
60     mainDB = request.result;
61   };
62   request.onupgradeneeded = function(event) {
63     mainDB = request.result;
64     //document.getElementById("debug").textContent = "mainDB upgraded.";
65     // Create a "prefs" objectStore.
66     var prefsStore = mainDB.createObjectStore("prefs");
67     // Create a "track" objectStore.
68     var trackStore = mainDB.createObjectStore("track", {autoIncrement: true});
69     mainDB.onversionchange = function(event) {
70       mainDB.close();
71       mainDB = undefined;
72       initDB();
73     };
74   };
75 }
76
77 function showUI() {
78   if (gUIHideCountdown <= 0) {
79     var areas = document.getElementsByClassName('overlayArea');
80     for (var i = 0; i <= areas.length - 1; i++) {
81       areas[i].classList.remove("hidden");
82     }
83     setTimeout(maybeHideUI, 1000);
84   }
85   gUIHideCountdown = 5;
86 }
87
88 function maybeHideUI() {
89   gUIHideCountdown--;
90   if (gUIHideCountdown <= 0) {
91     var areas = document.getElementsByClassName('overlayArea');
92     for (var i = 0; i <= areas.length - 1; i++) {
93       areas[i].classList.add("hidden");
94     }
95   }
96   else {
97     setTimeout(maybeHideUI, 1000);
98   }
99 }
100
101 function toggleTrackArea() {
102   var fs = document.getElementById("trackArea");
103   if (fs.style.display != "block") {
104     fs.style.display = "block";
105     showUI();
106   }
107   else {
108     fs.style.display = "none";
109   }
110 }
111
112 function toggleSettings() {
113   var fs = document.getElementById("settingsArea");
114   if (fs.style.display != "block") {
115     fs.style.display = "block";
116     showUI();
117   }
118   else {
119     fs.style.display = "none";
120   }
121 }
122
123 function toggleFullscreen() {
124   if ((document.fullScreenElement && document.fullScreenElement !== null) ||
125       (document.mozFullScreenElement && document.mozFullScreenElement !== null) ||
126       (document.webkitFullScreenElement && document.webkitFullScreenElement !== null)) {
127     if (document.cancelFullScreen) {
128       document.cancelFullScreen();
129     } else if (document.mozCancelFullScreen) {
130       document.mozCancelFullScreen();
131     } else if (document.webkitCancelFullScreen) {
132       document.webkitCancelFullScreen();
133     }
134   }
135   else {
136     var elem = document.getElementById("body");
137     if (elem.requestFullScreen) {
138       elem.requestFullScreen();
139     } else if (elem.mozRequestFullScreen) {
140       elem.mozRequestFullScreen();
141     } else if (elem.webkitRequestFullScreen) {
142       elem.webkitRequestFullScreen();
143     }
144   }
145 }
146
147 var uiEvHandler = {
148   handleEvent: function(aEvent) {
149     var touchEvent = aEvent.type.indexOf('touch') != -1;
150
151     switch (aEvent.type) {
152       case "mousedown":
153       case "touchstart":
154       case "mousemove":
155       case "touchmove":
156       case "mouseup":
157       case "touchend":
158         showUI();
159         break;
160     }
161   }
162 };
163
164 function makeISOString(aTimestamp) {
165   // ISO time format is YYYY-MM-DDTHH:mm:ssZ
166   var tsDate = new Date(aTimestamp);
167   return tsDate.getUTCFullYear() + "-" +
168          (tsDate.getUTCMonth() < 10 ? "0" : "") + tsDate.getUTCMonth() + "-" +
169          (tsDate.getUTCDate() < 10 ? "0" : "") + tsDate.getUTCDate() + "T" +
170          (tsDate.getUTCHours() < 10 ? "0" : "") + tsDate.getUTCHours() + ":" +
171          (tsDate.getUTCMinutes() < 10 ? "0" : "") + tsDate.getUTCMinutes() + ":" +
172          (tsDate.getUTCSeconds() < 10 ? "0" : "") + tsDate.getUTCSeconds() + "Z";
173 }
174
175 function saveTrack() {
176   if (gTrack.length) {
177     var out = '<?xml version="1.0" encoding="UTF-8" ?>' + "\n\n";
178     out += '<gpx version="1.0" creator="Lantea" xmlns="http://www.topografix.com/GPX/1/0">' + "\n";
179     out += '  <trk>' + "\n";
180     out += '    <trkseg>' + "\n";
181     for (var i = 0; i < gTrack.length; i++) {
182       if (gTrack[i].beginSegment && i > 0) {
183         out += '    </trkseg>' + "\n";
184         out += '    <trkseg>' + "\n";
185       }
186       out += '      <trkpt lat="' + gTrack[i].coords.latitude + '" lon="' +
187                                     gTrack[i].coords.longitude + '">' + "\n";
188       if (gTrack[i].coords.altitude) {
189         out += '        <ele>' + gTrack[i].coords.altitude + '</ele>' + "\n";
190       }
191       out += '        <time>' + makeISOString(gTrack[i].time) + '</time>' + "\n";
192       out += '      </trkpt>' + "\n";
193     }
194     out += '    </trkseg>' + "\n";
195     out += '  </trk>' + "\n";
196     out += '</gpx>' + "\n";
197     var outDataURI = "data:application/gpx+xml," + encodeURIComponent(out);
198     window.open(outDataURI, 'GPX Track');
199   }
200 }
201
202 function saveTrackDump() {
203   if (gTrack.length) {
204     var out = JSON.stringify(gTrack);
205     var outDataURI = "data:application/json," + encodeURIComponent(out);
206     window.open(outDataURI, 'JSON dump');
207   }
208 }
209
210 var gPrefs = {
211   objStore: "prefs",
212
213   get: function(aKey, aCallback) {
214     if (!mainDB)
215       return;
216     var transaction = mainDB.transaction([this.objStore]);
217     var request = transaction.objectStore(this.objStore).get(aKey);
218     request.onsuccess = function(event) {
219       aCallback(request.result, event);
220     };
221     request.onerror = function(event) {
222       // Errors can be handled here.
223       aCallback(undefined, event);
224     };
225   },
226
227   set: function(aKey, aValue, aCallback) {
228     if (!mainDB)
229       return;
230     var success = false;
231     var transaction = mainDB.transaction([this.objStore], "readwrite");
232     var objStore = transaction.objectStore(this.objStore);
233     var request = objStore.put(aValue, aKey);
234     request.onsuccess = function(event) {
235       success = true;
236       if (aCallback)
237         aCallback(success, event);
238     };
239     request.onerror = function(event) {
240       // Errors can be handled here.
241       if (aCallback)
242         aCallback(success, event);
243     };
244   },
245
246   unset: function(aKey, aCallback) {
247     if (!mainDB)
248       return;
249     var success = false;
250     var transaction = mainDB.transaction([this.objStore], "readwrite");
251     var request = transaction.objectStore(this.objStore).delete(aKey);
252     request.onsuccess = function(event) {
253       success = true;
254       if (aCallback)
255         aCallback(success, event);
256     };
257     request.onerror = function(event) {
258       // Errors can be handled here.
259       if (aCallback)
260         aCallback(success, event);
261     }
262   }
263 };
264
265 var gTrackStore = {
266   objStore: "track",
267
268   getList: function(aCallback) {
269     if (!mainDB)
270       return;
271     var transaction = mainDB.transaction([this.objStore]);
272     var objStore = transaction.objectStore(this.objStore);
273     if (objStore.getAll) { // currently Mozilla-specific
274       objStore.getAll().onsuccess = function(event) {
275         aCallback(event.target.result);
276       };
277     }
278     else { // Use cursor (standard method).
279       var tPoints = [];
280       objStore.openCursor().onsuccess = function(event) {
281         var cursor = event.target.result;
282         if (cursor) {
283           tPoints.push(cursor.value);
284           cursor.continue();
285         }
286         else {
287           aCallback(tPoints);
288         }
289       };
290     }
291   },
292
293   push: function(aValue, aCallback) {
294     if (!mainDB)
295       return;
296     var transaction = mainDB.transaction([this.objStore], "readwrite");
297     var objStore = transaction.objectStore(this.objStore);
298     var request = objStore.add(aValue);
299     request.onsuccess = function(event) {
300       if (aCallback)
301         aCallback(request.result, event);
302     };
303     request.onerror = function(event) {
304       // Errors can be handled here.
305       if (aCallback)
306         aCallback(false, event);
307     };
308   },
309
310   clear: function(aCallback) {
311     if (!mainDB)
312       return;
313     var success = false;
314     var transaction = mainDB.transaction([this.objStore], "readwrite");
315     var request = transaction.objectStore(this.objStore).clear();
316     request.onsuccess = function(event) {
317       success = true;
318       if (aCallback)
319         aCallback(success, event);
320     };
321     request.onerror = function(event) {
322       // Errors can be handled here.
323       if (aCallback)
324         aCallback(success, event);
325     }
326   }
327 };