Merge branch 'master' of github.com:KaiRo-at/lantea
[lantea.git] / js / ui.js
CommitLineData
a7393a71
RK
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/. */
23cd2dcc 4
41e2dba2 5// Get the best-available objects for indexedDB and requestAnimationFrame.
3d99a6fd 6window.indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB;
41e2dba2 7window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
993fd081 8
41e2dba2 9var mainDB;
16e4f664 10var gAppInitDone = false;
7a549148 11var gUIHideCountdown = 0;
4b1d0915 12var gWaitCounter = 0;
68afcd96 13var gAction, gActionLabel;
c4d0569c 14var gOSMAPIURL = "http://api.openstreetmap.org/";
7a549148 15
b47b4a65 16window.onload = function() {
68afcd96
RK
17 gAction = document.getElementById("action");
18 gActionLabel = document.getElementById("actionlabel");
19
b47b4a65
RK
20 var mSel = document.getElementById("mapSelector");
21 for (var mapStyle in gMapStyles) {
22 var opt = document.createElement("option");
23 opt.value = mapStyle;
24 opt.text = gMapStyles[mapStyle].name;
25 mSel.add(opt, null);
26 }
23cd2dcc 27
ecde0af2 28 var areas = document.getElementsByClassName("overlayArea");
7a549148
RK
29 for (var i = 0; i <= areas.length - 1; i++) {
30 areas[i].addEventListener("mouseup", uiEvHandler, false);
31 areas[i].addEventListener("mousemove", uiEvHandler, false);
32 areas[i].addEventListener("mousedown", uiEvHandler, false);
33 areas[i].addEventListener("mouseout", uiEvHandler, false);
34
35 areas[i].addEventListener("touchstart", uiEvHandler, false);
36 areas[i].addEventListener("touchmove", uiEvHandler, false);
37 areas[i].addEventListener("touchend", uiEvHandler, false);
38 areas[i].addEventListener("touchcancel", uiEvHandler, false);
39 areas[i].addEventListener("touchleave", uiEvHandler, false);
40 }
41
1222624d
RK
42 document.getElementById("body").addEventListener("keydown", uiEvHandler, false);
43
8e901dce 44 if (navigator.platform.length == "") {
b91b74a7
RK
45 // For Firefox OS, don't display the "save" button.
46 // Do this by setting the debugHide class for testing in debug mode.
47 document.getElementById("saveTrackButton").classList.add("debugHide");
c4d0569c
RK
48 }
49
43255174
RK
50 // Without OAuth, the login data is useless
51 //document.getElementById("uploadSettingsArea").classList.remove("debugHide");
52 // As login data is useless for now, always enable upload button
53 document.getElementById("uploadTrackButton").disabled = false;
54
c4d0569c 55 if (gDebug) {
43255174 56 // Note that GPX upload returns an error 500 on the dev API right now.
c4d0569c 57 gOSMAPIURL = "http://api06.dev.openstreetmap.org/";
b91b74a7 58 }
7a549148 59
582d50fc
RK
60 gAction.addEventListener("dbinit-done", initMap, false);
61 gAction.addEventListener("mapinit-done", postInit, false);
62 console.log("starting DB init...");
993fd081 63 initDB();
582d50fc 64}
4b1d0915 65
582d50fc
RK
66function postInit(aEvent) {
67 gAction.removeEventListener(aEvent.type, postInit, false);
68 console.log("init done, draw map.");
69 gMapPrefsLoaded = true;
16e4f664 70 gAppInitDone = true;
14acbcf7
RK
71 //gMap.resizeAndDraw(); <-- HACK: This triggers bug 1001853, work around with a delay.
72 window.setTimeout(gMap.resizeAndDraw, 100);
582d50fc
RK
73 gActionLabel.textContent = "";
74 gAction.style.display = "none";
75 setTracking(document.getElementById("trackCheckbox"));
76 gPrefs.get(gDebug ? "osm_dev_user" : "osm_user", function(aValue) {
77 if (aValue) {
78 document.getElementById("uploadUser").value = aValue;
79 document.getElementById("uploadTrackButton").disabled = false;
4b1d0915 80 }
582d50fc
RK
81 });
82 gPrefs.get(gDebug ? "osm_dev_pwd" : "osm_pwd", function(aValue) {
83 var upwd = document.getElementById("uploadPwd");
84 if (aValue)
85 document.getElementById("uploadPwd").value = aValue;
86 });
b47b4a65
RK
87}
88
89window.onresize = function() {
ac6286bd 90 gMap.resizeAndDraw();
b47b4a65
RK
91}
92
582d50fc 93function initDB(aEvent) {
993fd081 94 // Open DB.
582d50fc
RK
95 if (aEvent)
96 gAction.removeEventListener(aEvent.type, initDB, false);
1222624d 97 var request = window.indexedDB.open("MainDB-lantea", 2);
993fd081
RK
98 request.onerror = function(event) {
99 // Errors can be handled here. Error codes explain in:
100 // https://developer.mozilla.org/en/IndexedDB/IDBDatabaseException#Constants
915d4271
RK
101 if (gDebug)
102 console.log("error opening mainDB: " + event.target.errorCode);
993fd081
RK
103 };
104 request.onsuccess = function(event) {
993fd081 105 mainDB = request.result;
582d50fc
RK
106 var throwEv = new CustomEvent("dbinit-done");
107 gAction.dispatchEvent(throwEv);
993fd081
RK
108 };
109 request.onupgradeneeded = function(event) {
110 mainDB = request.result;
a8634d37 111 var ver = mainDB.version || 0; // version is empty string for a new DB
915d4271
RK
112 if (gDebug)
113 console.log("mainDB has version " + ver + ", upgrade needed.");
114 if (!mainDB.objectStoreNames.contains("prefs")) {
a8634d37
RK
115 // Create a "prefs" objectStore.
116 var prefsStore = mainDB.createObjectStore("prefs");
915d4271
RK
117 }
118 if (!mainDB.objectStoreNames.contains("track")) {
a8634d37
RK
119 // Create a "track" objectStore.
120 var trackStore = mainDB.createObjectStore("track", {autoIncrement: true});
121 }
915d4271 122 if (!mainDB.objectStoreNames.contains("tilecache")) {
a8634d37
RK
123 // Create a "tilecache" objectStore.
124 var tilecacheStore = mainDB.createObjectStore("tilecache");
125 }
993fd081
RK
126 mainDB.onversionchange = function(event) {
127 mainDB.close();
128 mainDB = undefined;
129 initDB();
130 };
131 };
132}
133
7a549148
RK
134function showUI() {
135 if (gUIHideCountdown <= 0) {
136 var areas = document.getElementsByClassName('overlayArea');
137 for (var i = 0; i <= areas.length - 1; i++) {
138 areas[i].classList.remove("hidden");
139 }
140 setTimeout(maybeHideUI, 1000);
141 }
142 gUIHideCountdown = 5;
143}
144
145function maybeHideUI() {
146 gUIHideCountdown--;
147 if (gUIHideCountdown <= 0) {
148 var areas = document.getElementsByClassName('overlayArea');
149 for (var i = 0; i <= areas.length - 1; i++) {
150 areas[i].classList.add("hidden");
151 }
152 }
153 else {
154 setTimeout(maybeHideUI, 1000);
155 }
156}
157
993fd081
RK
158function toggleTrackArea() {
159 var fs = document.getElementById("trackArea");
160 if (fs.style.display != "block") {
161 fs.style.display = "block";
7a549148 162 showUI();
993fd081
RK
163 }
164 else {
165 fs.style.display = "none";
166 }
167}
168
b47b4a65 169function toggleSettings() {
993fd081 170 var fs = document.getElementById("settingsArea");
b47b4a65
RK
171 if (fs.style.display != "block") {
172 fs.style.display = "block";
7a549148 173 showUI();
b47b4a65
RK
174 }
175 else {
176 fs.style.display = "none";
177 }
178}
99631a75 179
c5378747
RK
180function toggleFullscreen() {
181 if ((document.fullScreenElement && document.fullScreenElement !== null) ||
182 (document.mozFullScreenElement && document.mozFullScreenElement !== null) ||
183 (document.webkitFullScreenElement && document.webkitFullScreenElement !== null)) {
184 if (document.cancelFullScreen) {
185 document.cancelFullScreen();
186 } else if (document.mozCancelFullScreen) {
187 document.mozCancelFullScreen();
188 } else if (document.webkitCancelFullScreen) {
189 document.webkitCancelFullScreen();
190 }
191 }
192 else {
193 var elem = document.getElementById("body");
194 if (elem.requestFullScreen) {
195 elem.requestFullScreen();
196 } else if (elem.mozRequestFullScreen) {
197 elem.mozRequestFullScreen();
198 } else if (elem.webkitRequestFullScreen) {
199 elem.webkitRequestFullScreen();
200 }
201 }
202}
203
43255174
RK
204function showUploadDialog() {
205 var dia = document.getElementById("dialogArea");
206 var areas = dia.children;
207 for (var i = 0; i <= areas.length - 1; i++) {
208 areas[i].style.display = "none";
209 }
210 document.getElementById("uploadDialog").style.display = "block";
211 document.getElementById("uploadTrackButton").disabled = true;
212 dia.classList.remove("hidden");
213}
214
ecde0af2
RK
215function showGLWarningDialog() {
216 var dia = document.getElementById("dialogArea");
217 var areas = dia.children;
218 for (var i = 0; i <= areas.length - 1; i++) {
219 areas[i].style.display = "none";
220 }
221 document.getElementById("noGLwarning").style.display = "block";
222 dia.classList.remove("hidden");
223}
224
43255174
RK
225function cancelDialog() {
226 document.getElementById("dialogArea").classList.add("hidden");
227 document.getElementById("uploadTrackButton").disabled = false;
228}
229
7a549148
RK
230var uiEvHandler = {
231 handleEvent: function(aEvent) {
232 var touchEvent = aEvent.type.indexOf('touch') != -1;
233
234 switch (aEvent.type) {
235 case "mousedown":
236 case "touchstart":
237 case "mousemove":
238 case "touchmove":
239 case "mouseup":
240 case "touchend":
1222624d 241 case "keydown":
7a549148
RK
242 showUI();
243 break;
244 }
245 }
246};
247
8389557a
RK
248function setUploadField(aField) {
249 switch (aField.id) {
250 case "uploadUser":
c4d0569c 251 gPrefs.set(gDebug ? "osm_dev_user" : "osm_user", aField.value);
8389557a
RK
252 document.getElementById("uploadTrackButton").disabled = !aField.value.length;
253 break;
254 case "uploadPwd":
c4d0569c 255 gPrefs.set(gDebug ? "osm_dev_pwd" : "osm_pwd", aField.value);
8389557a
RK
256 break;
257 }
258}
259
99631a75
RK
260function makeISOString(aTimestamp) {
261 // ISO time format is YYYY-MM-DDTHH:mm:ssZ
262 var tsDate = new Date(aTimestamp);
362a6833 263 // Note that .getUTCMonth() returns a number between 0 and 11 (0 for January)!
99631a75 264 return tsDate.getUTCFullYear() + "-" +
362a6833 265 (tsDate.getUTCMonth() < 9 ? "0" : "") + (tsDate.getUTCMonth() + 1 ) + "-" +
99631a75
RK
266 (tsDate.getUTCDate() < 10 ? "0" : "") + tsDate.getUTCDate() + "T" +
267 (tsDate.getUTCHours() < 10 ? "0" : "") + tsDate.getUTCHours() + ":" +
268 (tsDate.getUTCMinutes() < 10 ? "0" : "") + tsDate.getUTCMinutes() + ":" +
269 (tsDate.getUTCSeconds() < 10 ? "0" : "") + tsDate.getUTCSeconds() + "Z";
270}
271
8389557a
RK
272function convertTrack(aTargetFormat) {
273 var out = "";
274 switch (aTargetFormat) {
275 case "gpx":
276 out += '<?xml version="1.0" encoding="UTF-8" ?>' + "\n\n";
277 out += '<gpx version="1.0" creator="Lantea" xmlns="http://www.topografix.com/GPX/1/0">' + "\n";
278 if (gTrack.length) {
279 out += ' <trk>' + "\n";
993fd081 280 out += ' <trkseg>' + "\n";
8389557a
RK
281 for (var i = 0; i < gTrack.length; i++) {
282 if (gTrack[i].beginSegment && i > 0) {
283 out += ' </trkseg>' + "\n";
284 out += ' <trkseg>' + "\n";
285 }
286 out += ' <trkpt lat="' + gTrack[i].coords.latitude + '" lon="' +
287 gTrack[i].coords.longitude + '">' + "\n";
288 if (gTrack[i].coords.altitude) {
289 out += ' <ele>' + gTrack[i].coords.altitude + '</ele>' + "\n";
290 }
291 out += ' <time>' + makeISOString(gTrack[i].time) + '</time>' + "\n";
292 out += ' </trkpt>' + "\n";
293 }
294 out += ' </trkseg>' + "\n";
295 out += ' </trk>' + "\n";
993fd081 296 }
8389557a
RK
297 out += '</gpx>' + "\n";
298 break;
299 case "json":
300 out = JSON.stringify(gTrack);
301 break;
302 default:
303 break;
304 }
305 return out;
306}
307
308function saveTrack() {
309 if (gTrack.length) {
310 var outDataURI = "data:application/gpx+xml," +
311 encodeURIComponent(convertTrack("gpx"));
99631a75
RK
312 window.open(outDataURI, 'GPX Track');
313 }
314}
993fd081 315
4b12da3a
RK
316function saveTrackDump() {
317 if (gTrack.length) {
8389557a
RK
318 var outDataURI = "data:application/json," +
319 encodeURIComponent(convertTrack("json"));
4b12da3a
RK
320 window.open(outDataURI, 'JSON dump');
321 }
322}
323
8389557a 324function uploadTrack() {
6ddefbf9 325 // Hide all areas in the dialog.
43255174
RK
326 var dia = document.getElementById("dialogArea");
327 var areas = dia.children;
328 for (var i = 0; i <= areas.length - 1; i++) {
329 areas[i].style.display = "none";
330 }
6ddefbf9
RK
331 // Reset all the fields in the status area.
332 document.getElementById("uploadStatusCloseButton").disabled = true;
333 document.getElementById("uploadInProgress").style.display = "block";
334 document.getElementById("uploadSuccess").style.display = "none";
d0c62ee0 335 document.getElementById("uploadFailed").style.display = "none";
6ddefbf9 336 document.getElementById("uploadError").style.display = "none";
d0c62ee0 337 document.getElementById("uploadErrorMsg").textContent = "";
6ddefbf9 338 // Now show the status area.
43255174
RK
339 document.getElementById("uploadStatus").style.display = "block";
340
8389557a 341 // See http://wiki.openstreetmap.org/wiki/Api06#Uploading_traces
43255174
RK
342 var trackBlob = new Blob([convertTrack("gpx")],
343 { "type" : "application/gpx+xml" });
8389557a
RK
344 var formData = new FormData();
345 formData.append("file", trackBlob);
43255174
RK
346 var desc = document.getElementById("uploadDesc").value;
347 formData.append("description",
348 desc.length ? desc : "Track recorded via Lantea Maps");
8389557a 349 //formData.append("tags", "");
43255174
RK
350 formData.append("visibility",
351 document.getElementById("uploadVisibility").value);
0494a6db
RK
352 // Do an empty POST request first, so that we don't send everything,
353 // then ask for credentials, and then send again.
354 var hXHR = new XMLHttpRequest();
355 hXHR.onreadystatechange = function() {
fdaf08db 356 if (hXHR.readyState == 4 && (hXHR.status == 200 || hXHR.status == 400)) {
0494a6db
RK
357 // 400 is Bad Request, but that's expected as this was empty.
358 // So far so good, init actual upload.
359 var XHR = new XMLHttpRequest();
360 XHR.onreadystatechange = function() {
361 if (XHR.readyState == 4 && XHR.status == 200) {
362 // Everthing looks fine.
363 reportUploadStatus(true);
364 } else if (XHR.readyState == 4 && XHR.status != 200) {
365 // Fetched the wrong page or network error...
366 reportUploadStatus(false);
367 }
368 };
369 XHR.open("POST", gOSMAPIURL + "api/0.6/gpx/create", true);
370 // Cross-Origin XHR doesn't allow username/password (HTTP Auth).
371 // So, we'll ask the user for entering credentials with rather ugly UI.
372 XHR.withCredentials = true;
373 try {
374 XHR.send(formData); // Send actual form data.
375 }
376 catch (e) {
377 reportUploadStatus(false, e);
378 }
379 } else if (hXHR.readyState == 4 && hXHR.status != 200) {
380 // Fetched the wrong page or network error...
8389557a
RK
381 reportUploadStatus(false);
382 }
383 };
0494a6db 384 hXHR.open("POST", gOSMAPIURL + "api/0.6/gpx/create", true);
43255174
RK
385 // Cross-Origin XHR doesn't allow username/password (HTTP Auth).
386 // So, we'll ask the user for entering credentials with rather ugly UI.
0494a6db 387 hXHR.withCredentials = true;
8389557a 388 try {
0494a6db 389 hXHR.send(); // Empty request, see above.
8389557a
RK
390 }
391 catch (e) {
392 reportUploadStatus(false, e);
393 }
394}
395
396function reportUploadStatus(aSuccess, aMessage) {
43255174
RK
397 document.getElementById("uploadStatusCloseButton").disabled = false;
398 document.getElementById("uploadInProgress").style.display = "none";
399 if (aSuccess) {
400 document.getElementById("uploadSuccess").style.display = "block";
401 }
402 else if (aMessage) {
403 document.getElementById("uploadErrorMsg").textContent = aMessage;
404 document.getElementById("uploadError").style.display = "block";
405 }
406 else {
407 document.getElementById("uploadFailed").style.display = "block";
408 }
8389557a
RK
409}
410
993fd081
RK
411var gPrefs = {
412 objStore: "prefs",
413
414 get: function(aKey, aCallback) {
415 if (!mainDB)
416 return;
417 var transaction = mainDB.transaction([this.objStore]);
418 var request = transaction.objectStore(this.objStore).get(aKey);
419 request.onsuccess = function(event) {
420 aCallback(request.result, event);
421 };
422 request.onerror = function(event) {
423 // Errors can be handled here.
424 aCallback(undefined, event);
425 };
426 },
427
428 set: function(aKey, aValue, aCallback) {
429 if (!mainDB)
430 return;
431 var success = false;
d4ccddb8 432 var transaction = mainDB.transaction([this.objStore], "readwrite");
993fd081 433 var objStore = transaction.objectStore(this.objStore);
3610c22d 434 var request = objStore.put(aValue, aKey);
993fd081
RK
435 request.onsuccess = function(event) {
436 success = true;
437 if (aCallback)
438 aCallback(success, event);
439 };
440 request.onerror = function(event) {
441 // Errors can be handled here.
442 if (aCallback)
443 aCallback(success, event);
444 };
445 },
446
447 unset: function(aKey, aCallback) {
448 if (!mainDB)
449 return;
450 var success = false;
d4ccddb8 451 var transaction = mainDB.transaction([this.objStore], "readwrite");
993fd081
RK
452 var request = transaction.objectStore(this.objStore).delete(aKey);
453 request.onsuccess = function(event) {
454 success = true;
455 if (aCallback)
456 aCallback(success, event);
457 };
458 request.onerror = function(event) {
459 // Errors can be handled here.
460 if (aCallback)
461 aCallback(success, event);
462 }
463 }
464};
465
466var gTrackStore = {
467 objStore: "track",
468
469 getList: function(aCallback) {
470 if (!mainDB)
471 return;
472 var transaction = mainDB.transaction([this.objStore]);
473 var objStore = transaction.objectStore(this.objStore);
474 if (objStore.getAll) { // currently Mozilla-specific
475 objStore.getAll().onsuccess = function(event) {
476 aCallback(event.target.result);
477 };
478 }
479 else { // Use cursor (standard method).
480 var tPoints = [];
481 objStore.openCursor().onsuccess = function(event) {
482 var cursor = event.target.result;
483 if (cursor) {
484 tPoints.push(cursor.value);
485 cursor.continue();
486 }
487 else {
488 aCallback(tPoints);
489 }
490 };
491 }
492 },
493
6ddefbf9
RK
494 getListStepped: function(aCallback) {
495 if (!mainDB)
496 return;
497 var transaction = mainDB.transaction([this.objStore]);
498 var objStore = transaction.objectStore(this.objStore);
499 // Use cursor in reverse direction (so we get the most recent position first)
500 objStore.openCursor(null, "prev").onsuccess = function(event) {
501 var cursor = event.target.result;
502 if (cursor) {
503 aCallback(cursor.value);
504 cursor.continue();
505 }
506 else {
507 aCallback(null);
508 }
509 };
510 },
511
993fd081
RK
512 push: function(aValue, aCallback) {
513 if (!mainDB)
514 return;
d4ccddb8 515 var transaction = mainDB.transaction([this.objStore], "readwrite");
993fd081
RK
516 var objStore = transaction.objectStore(this.objStore);
517 var request = objStore.add(aValue);
518 request.onsuccess = function(event) {
519 if (aCallback)
520 aCallback(request.result, event);
521 };
522 request.onerror = function(event) {
523 // Errors can be handled here.
524 if (aCallback)
525 aCallback(false, event);
526 };
527 },
528
529 clear: function(aCallback) {
530 if (!mainDB)
531 return;
532 var success = false;
d4ccddb8 533 var transaction = mainDB.transaction([this.objStore], "readwrite");
993fd081
RK
534 var request = transaction.objectStore(this.objStore).clear();
535 request.onsuccess = function(event) {
536 success = true;
537 if (aCallback)
538 aCallback(success, event);
539 };
540 request.onerror = function(event) {
541 // Errors can be handled here.
542 if (aCallback)
543 aCallback(success, event);
544 }
545 }
546};