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