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