really enable upload
[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 // For now, only show the upload UI on Firefox OS.
47 document.getElementById("uploadTrackButton").classList.remove("debugHide");
48 // Without OAuth, the login data is useless
49 //document.getElementById("uploadSettingsArea").classList.remove("debugHide");
d762398b 50 // As login data is useless for now, always enable upload button
2e357fd6 51 document.getElementById("uploadTrackButton").disabled = false;
c4d0569c
RK
52 }
53
54 if (gDebug) {
55 gOSMAPIURL = "http://api06.dev.openstreetmap.org/";
b91b74a7 56 }
7a549148 57
993fd081 58 initDB();
b47b4a65 59 initMap();
4b1d0915
RK
60
61 var loopCnt = 0;
62 var waitForInitAndDraw = function() {
63 if ((gWaitCounter <= 0) || (loopCnt > 100)) {
64 if (gWaitCounter <= 0)
65 gWaitCounter = 0;
66 else
915d4271 67 console.log("Loading failed (waiting for init).");
4b1d0915
RK
68
69 gMapPrefsLoaded = true;
70 resizeAndDraw();
68afcd96
RK
71 gActionLabel.textContent = "";
72 gAction.style.display = "none";
4b1d0915 73 setTracking(document.getElementById("trackCheckbox"));
c4d0569c 74 gPrefs.get(gDebug ? "osm_dev_user" : "osm_user", function(aValue) {
8389557a
RK
75 if (aValue) {
76 document.getElementById("uploadUser").value = aValue;
77 document.getElementById("uploadTrackButton").disabled = false;
78 }
79 });
c4d0569c 80 gPrefs.get(gDebug ? "osm_dev_pwd" : "osm_pwd", function(aValue) {
8389557a
RK
81 var upwd = document.getElementById("uploadPwd");
82 if (aValue)
83 document.getElementById("uploadPwd").value = aValue;
84 });
4b1d0915
RK
85 }
86 else
87 setTimeout(waitForInitAndDraw, 100);
88 loopCnt++;
89 };
90 waitForInitAndDraw();
b47b4a65
RK
91}
92
93window.onresize = function() {
94 resizeAndDraw();
95}
96
993fd081
RK
97function initDB() {
98 // Open DB.
1222624d 99 var request = window.indexedDB.open("MainDB-lantea", 2);
993fd081
RK
100 request.onerror = function(event) {
101 // Errors can be handled here. Error codes explain in:
102 // https://developer.mozilla.org/en/IndexedDB/IDBDatabaseException#Constants
915d4271
RK
103 if (gDebug)
104 console.log("error opening mainDB: " + event.target.errorCode);
993fd081
RK
105 };
106 request.onsuccess = function(event) {
993fd081
RK
107 mainDB = request.result;
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
7a549148
RK
204var uiEvHandler = {
205 handleEvent: function(aEvent) {
206 var touchEvent = aEvent.type.indexOf('touch') != -1;
207
208 switch (aEvent.type) {
209 case "mousedown":
210 case "touchstart":
211 case "mousemove":
212 case "touchmove":
213 case "mouseup":
214 case "touchend":
1222624d 215 case "keydown":
7a549148
RK
216 showUI();
217 break;
218 }
219 }
220};
221
8389557a
RK
222function setUploadField(aField) {
223 switch (aField.id) {
224 case "uploadUser":
c4d0569c 225 gPrefs.set(gDebug ? "osm_dev_user" : "osm_user", aField.value);
8389557a
RK
226 document.getElementById("uploadTrackButton").disabled = !aField.value.length;
227 break;
228 case "uploadPwd":
c4d0569c 229 gPrefs.set(gDebug ? "osm_dev_pwd" : "osm_pwd", aField.value);
8389557a
RK
230 break;
231 }
232}
233
99631a75
RK
234function makeISOString(aTimestamp) {
235 // ISO time format is YYYY-MM-DDTHH:mm:ssZ
236 var tsDate = new Date(aTimestamp);
237 return tsDate.getUTCFullYear() + "-" +
238 (tsDate.getUTCMonth() < 10 ? "0" : "") + tsDate.getUTCMonth() + "-" +
239 (tsDate.getUTCDate() < 10 ? "0" : "") + tsDate.getUTCDate() + "T" +
240 (tsDate.getUTCHours() < 10 ? "0" : "") + tsDate.getUTCHours() + ":" +
241 (tsDate.getUTCMinutes() < 10 ? "0" : "") + tsDate.getUTCMinutes() + ":" +
242 (tsDate.getUTCSeconds() < 10 ? "0" : "") + tsDate.getUTCSeconds() + "Z";
243}
244
8389557a
RK
245function convertTrack(aTargetFormat) {
246 var out = "";
247 switch (aTargetFormat) {
248 case "gpx":
249 out += '<?xml version="1.0" encoding="UTF-8" ?>' + "\n\n";
250 out += '<gpx version="1.0" creator="Lantea" xmlns="http://www.topografix.com/GPX/1/0">' + "\n";
251 if (gTrack.length) {
252 out += ' <trk>' + "\n";
993fd081 253 out += ' <trkseg>' + "\n";
8389557a
RK
254 for (var i = 0; i < gTrack.length; i++) {
255 if (gTrack[i].beginSegment && i > 0) {
256 out += ' </trkseg>' + "\n";
257 out += ' <trkseg>' + "\n";
258 }
259 out += ' <trkpt lat="' + gTrack[i].coords.latitude + '" lon="' +
260 gTrack[i].coords.longitude + '">' + "\n";
261 if (gTrack[i].coords.altitude) {
262 out += ' <ele>' + gTrack[i].coords.altitude + '</ele>' + "\n";
263 }
264 out += ' <time>' + makeISOString(gTrack[i].time) + '</time>' + "\n";
265 out += ' </trkpt>' + "\n";
266 }
267 out += ' </trkseg>' + "\n";
268 out += ' </trk>' + "\n";
993fd081 269 }
8389557a
RK
270 out += '</gpx>' + "\n";
271 break;
272 case "json":
273 out = JSON.stringify(gTrack);
274 break;
275 default:
276 break;
277 }
278 return out;
279}
280
281function saveTrack() {
282 if (gTrack.length) {
283 var outDataURI = "data:application/gpx+xml," +
284 encodeURIComponent(convertTrack("gpx"));
99631a75
RK
285 window.open(outDataURI, 'GPX Track');
286 }
287}
993fd081 288
4b12da3a
RK
289function saveTrackDump() {
290 if (gTrack.length) {
8389557a
RK
291 var outDataURI = "data:application/json," +
292 encodeURIComponent(convertTrack("json"));
4b12da3a
RK
293 window.open(outDataURI, 'JSON dump');
294 }
295}
296
8389557a
RK
297function uploadTrack() {
298 // See http://wiki.openstreetmap.org/wiki/Api06#Uploading_traces
299 var trackBlob = new Blob([convertTrack("gpx")], { "type" : "application/gpx+xml" });
300 var formData = new FormData();
301 formData.append("file", trackBlob);
302 formData.append("description", "Track recorded via Lantea Maps");
303 //formData.append("tags", "");
304 formData.append("visibility", "private");
305 var XHR = new XMLHttpRequest();
306 XHR.onreadystatechange = function() {
8389557a
RK
307 if (XHR.readyState == 4 && XHR.status == 200) {
308 // so far so good
309 reportUploadStatus(true);
310 } else if (XHR.readyState == 4 && XHR.status != 200) {
311 // fetched the wrong page or network error...
312 reportUploadStatus(false);
313 }
314 };
c4d0569c
RK
315 XHR.open("POST", gOSMAPIURL + "api/0.6/gpx/create", true);
316 // Cross-Origin XHR doesn't allow username/password (HTTP Auth), so need to look into OAuth.
317 // But for now, we'll ask the user for entering credentials with this.
318 XHR.withCredentials = true;
8389557a
RK
319 try {
320 XHR.send(formData);
321 }
322 catch (e) {
323 reportUploadStatus(false, e);
324 }
325}
326
327function reportUploadStatus(aSuccess, aMessage) {
328 alert(aMessage ? aMessage : (aSuccess ? "success" : "failure"));
329}
330
993fd081
RK
331var gPrefs = {
332 objStore: "prefs",
333
334 get: function(aKey, aCallback) {
335 if (!mainDB)
336 return;
337 var transaction = mainDB.transaction([this.objStore]);
338 var request = transaction.objectStore(this.objStore).get(aKey);
339 request.onsuccess = function(event) {
340 aCallback(request.result, event);
341 };
342 request.onerror = function(event) {
343 // Errors can be handled here.
344 aCallback(undefined, event);
345 };
346 },
347
348 set: function(aKey, aValue, aCallback) {
349 if (!mainDB)
350 return;
351 var success = false;
d4ccddb8 352 var transaction = mainDB.transaction([this.objStore], "readwrite");
993fd081 353 var objStore = transaction.objectStore(this.objStore);
3610c22d 354 var request = objStore.put(aValue, aKey);
993fd081
RK
355 request.onsuccess = function(event) {
356 success = true;
357 if (aCallback)
358 aCallback(success, event);
359 };
360 request.onerror = function(event) {
361 // Errors can be handled here.
362 if (aCallback)
363 aCallback(success, event);
364 };
365 },
366
367 unset: function(aKey, aCallback) {
368 if (!mainDB)
369 return;
370 var success = false;
d4ccddb8 371 var transaction = mainDB.transaction([this.objStore], "readwrite");
993fd081
RK
372 var request = transaction.objectStore(this.objStore).delete(aKey);
373 request.onsuccess = function(event) {
374 success = true;
375 if (aCallback)
376 aCallback(success, event);
377 };
378 request.onerror = function(event) {
379 // Errors can be handled here.
380 if (aCallback)
381 aCallback(success, event);
382 }
383 }
384};
385
386var gTrackStore = {
387 objStore: "track",
388
389 getList: function(aCallback) {
390 if (!mainDB)
391 return;
392 var transaction = mainDB.transaction([this.objStore]);
393 var objStore = transaction.objectStore(this.objStore);
394 if (objStore.getAll) { // currently Mozilla-specific
395 objStore.getAll().onsuccess = function(event) {
396 aCallback(event.target.result);
397 };
398 }
399 else { // Use cursor (standard method).
400 var tPoints = [];
401 objStore.openCursor().onsuccess = function(event) {
402 var cursor = event.target.result;
403 if (cursor) {
404 tPoints.push(cursor.value);
405 cursor.continue();
406 }
407 else {
408 aCallback(tPoints);
409 }
410 };
411 }
412 },
413
414 push: function(aValue, aCallback) {
415 if (!mainDB)
416 return;
d4ccddb8 417 var transaction = mainDB.transaction([this.objStore], "readwrite");
993fd081
RK
418 var objStore = transaction.objectStore(this.objStore);
419 var request = objStore.add(aValue);
420 request.onsuccess = function(event) {
421 if (aCallback)
422 aCallback(request.result, event);
423 };
424 request.onerror = function(event) {
425 // Errors can be handled here.
426 if (aCallback)
427 aCallback(false, event);
428 };
429 },
430
431 clear: function(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).clear();
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};