add an upload button for OSM track upload - still doesn't work right, unfortunately
[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;
8389557a 12var gOSMAPIURL = "http://api06.dev.openstreetmap.org/"; // "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");
46 }
7a549148 47
993fd081 48 initDB();
b47b4a65 49 initMap();
4b1d0915
RK
50
51 var loopCnt = 0;
52 var waitForInitAndDraw = function() {
53 if ((gWaitCounter <= 0) || (loopCnt > 100)) {
54 if (gWaitCounter <= 0)
55 gWaitCounter = 0;
56 else
915d4271 57 console.log("Loading failed (waiting for init).");
4b1d0915
RK
58
59 gMapPrefsLoaded = true;
60 resizeAndDraw();
68afcd96
RK
61 gActionLabel.textContent = "";
62 gAction.style.display = "none";
4b1d0915 63 setTracking(document.getElementById("trackCheckbox"));
8389557a
RK
64 gPrefs.get("osm_user", function(aValue) {
65 if (aValue) {
66 document.getElementById("uploadUser").value = aValue;
67 document.getElementById("uploadTrackButton").disabled = false;
68 }
69 });
70 gPrefs.get("osm_pwd", function(aValue) {
71 var upwd = document.getElementById("uploadPwd");
72 if (aValue)
73 document.getElementById("uploadPwd").value = aValue;
74 });
4b1d0915
RK
75 }
76 else
77 setTimeout(waitForInitAndDraw, 100);
78 loopCnt++;
79 };
80 waitForInitAndDraw();
b47b4a65
RK
81}
82
83window.onresize = function() {
84 resizeAndDraw();
85}
86
993fd081
RK
87function initDB() {
88 // Open DB.
1222624d 89 var request = window.indexedDB.open("MainDB-lantea", 2);
993fd081
RK
90 request.onerror = function(event) {
91 // Errors can be handled here. Error codes explain in:
92 // https://developer.mozilla.org/en/IndexedDB/IDBDatabaseException#Constants
915d4271
RK
93 if (gDebug)
94 console.log("error opening mainDB: " + event.target.errorCode);
993fd081
RK
95 };
96 request.onsuccess = function(event) {
993fd081
RK
97 mainDB = request.result;
98 };
99 request.onupgradeneeded = function(event) {
100 mainDB = request.result;
a8634d37 101 var ver = mainDB.version || 0; // version is empty string for a new DB
915d4271
RK
102 if (gDebug)
103 console.log("mainDB has version " + ver + ", upgrade needed.");
104 if (!mainDB.objectStoreNames.contains("prefs")) {
a8634d37
RK
105 // Create a "prefs" objectStore.
106 var prefsStore = mainDB.createObjectStore("prefs");
915d4271
RK
107 }
108 if (!mainDB.objectStoreNames.contains("track")) {
a8634d37
RK
109 // Create a "track" objectStore.
110 var trackStore = mainDB.createObjectStore("track", {autoIncrement: true});
111 }
915d4271 112 if (!mainDB.objectStoreNames.contains("tilecache")) {
a8634d37
RK
113 // Create a "tilecache" objectStore.
114 var tilecacheStore = mainDB.createObjectStore("tilecache");
115 }
993fd081
RK
116 mainDB.onversionchange = function(event) {
117 mainDB.close();
118 mainDB = undefined;
119 initDB();
120 };
121 };
122}
123
7a549148
RK
124function showUI() {
125 if (gUIHideCountdown <= 0) {
126 var areas = document.getElementsByClassName('overlayArea');
127 for (var i = 0; i <= areas.length - 1; i++) {
128 areas[i].classList.remove("hidden");
129 }
130 setTimeout(maybeHideUI, 1000);
131 }
132 gUIHideCountdown = 5;
133}
134
135function maybeHideUI() {
136 gUIHideCountdown--;
137 if (gUIHideCountdown <= 0) {
138 var areas = document.getElementsByClassName('overlayArea');
139 for (var i = 0; i <= areas.length - 1; i++) {
140 areas[i].classList.add("hidden");
141 }
142 }
143 else {
144 setTimeout(maybeHideUI, 1000);
145 }
146}
147
993fd081
RK
148function toggleTrackArea() {
149 var fs = document.getElementById("trackArea");
150 if (fs.style.display != "block") {
151 fs.style.display = "block";
7a549148 152 showUI();
993fd081
RK
153 }
154 else {
155 fs.style.display = "none";
156 }
157}
158
b47b4a65 159function toggleSettings() {
993fd081 160 var fs = document.getElementById("settingsArea");
b47b4a65
RK
161 if (fs.style.display != "block") {
162 fs.style.display = "block";
7a549148 163 showUI();
b47b4a65
RK
164 }
165 else {
166 fs.style.display = "none";
167 }
168}
99631a75 169
c5378747
RK
170function toggleFullscreen() {
171 if ((document.fullScreenElement && document.fullScreenElement !== null) ||
172 (document.mozFullScreenElement && document.mozFullScreenElement !== null) ||
173 (document.webkitFullScreenElement && document.webkitFullScreenElement !== null)) {
174 if (document.cancelFullScreen) {
175 document.cancelFullScreen();
176 } else if (document.mozCancelFullScreen) {
177 document.mozCancelFullScreen();
178 } else if (document.webkitCancelFullScreen) {
179 document.webkitCancelFullScreen();
180 }
181 }
182 else {
183 var elem = document.getElementById("body");
184 if (elem.requestFullScreen) {
185 elem.requestFullScreen();
186 } else if (elem.mozRequestFullScreen) {
187 elem.mozRequestFullScreen();
188 } else if (elem.webkitRequestFullScreen) {
189 elem.webkitRequestFullScreen();
190 }
191 }
192}
193
7a549148
RK
194var uiEvHandler = {
195 handleEvent: function(aEvent) {
196 var touchEvent = aEvent.type.indexOf('touch') != -1;
197
198 switch (aEvent.type) {
199 case "mousedown":
200 case "touchstart":
201 case "mousemove":
202 case "touchmove":
203 case "mouseup":
204 case "touchend":
1222624d 205 case "keydown":
7a549148
RK
206 showUI();
207 break;
208 }
209 }
210};
211
8389557a
RK
212function setUploadField(aField) {
213 switch (aField.id) {
214 case "uploadUser":
215 gPrefs.set("osm_user", aField.value);
216 document.getElementById("uploadTrackButton").disabled = !aField.value.length;
217 break;
218 case "uploadPwd":
219 gPrefs.set("osm_pwd", aField.value);
220 break;
221 }
222}
223
99631a75
RK
224function makeISOString(aTimestamp) {
225 // ISO time format is YYYY-MM-DDTHH:mm:ssZ
226 var tsDate = new Date(aTimestamp);
227 return tsDate.getUTCFullYear() + "-" +
228 (tsDate.getUTCMonth() < 10 ? "0" : "") + tsDate.getUTCMonth() + "-" +
229 (tsDate.getUTCDate() < 10 ? "0" : "") + tsDate.getUTCDate() + "T" +
230 (tsDate.getUTCHours() < 10 ? "0" : "") + tsDate.getUTCHours() + ":" +
231 (tsDate.getUTCMinutes() < 10 ? "0" : "") + tsDate.getUTCMinutes() + ":" +
232 (tsDate.getUTCSeconds() < 10 ? "0" : "") + tsDate.getUTCSeconds() + "Z";
233}
234
8389557a
RK
235function convertTrack(aTargetFormat) {
236 var out = "";
237 switch (aTargetFormat) {
238 case "gpx":
239 out += '<?xml version="1.0" encoding="UTF-8" ?>' + "\n\n";
240 out += '<gpx version="1.0" creator="Lantea" xmlns="http://www.topografix.com/GPX/1/0">' + "\n";
241 if (gTrack.length) {
242 out += ' <trk>' + "\n";
993fd081 243 out += ' <trkseg>' + "\n";
8389557a
RK
244 for (var i = 0; i < gTrack.length; i++) {
245 if (gTrack[i].beginSegment && i > 0) {
246 out += ' </trkseg>' + "\n";
247 out += ' <trkseg>' + "\n";
248 }
249 out += ' <trkpt lat="' + gTrack[i].coords.latitude + '" lon="' +
250 gTrack[i].coords.longitude + '">' + "\n";
251 if (gTrack[i].coords.altitude) {
252 out += ' <ele>' + gTrack[i].coords.altitude + '</ele>' + "\n";
253 }
254 out += ' <time>' + makeISOString(gTrack[i].time) + '</time>' + "\n";
255 out += ' </trkpt>' + "\n";
256 }
257 out += ' </trkseg>' + "\n";
258 out += ' </trk>' + "\n";
993fd081 259 }
8389557a
RK
260 out += '</gpx>' + "\n";
261 break;
262 case "json":
263 out = JSON.stringify(gTrack);
264 break;
265 default:
266 break;
267 }
268 return out;
269}
270
271function saveTrack() {
272 if (gTrack.length) {
273 var outDataURI = "data:application/gpx+xml," +
274 encodeURIComponent(convertTrack("gpx"));
99631a75
RK
275 window.open(outDataURI, 'GPX Track');
276 }
277}
993fd081 278
4b12da3a
RK
279function saveTrackDump() {
280 if (gTrack.length) {
8389557a
RK
281 var outDataURI = "data:application/json," +
282 encodeURIComponent(convertTrack("json"));
4b12da3a
RK
283 window.open(outDataURI, 'JSON dump');
284 }
285}
286
8389557a
RK
287function uploadTrack() {
288 // See http://wiki.openstreetmap.org/wiki/Api06#Uploading_traces
289 var trackBlob = new Blob([convertTrack("gpx")], { "type" : "application/gpx+xml" });
290 var formData = new FormData();
291 formData.append("file", trackBlob);
292 formData.append("description", "Track recorded via Lantea Maps");
293 //formData.append("tags", "");
294 formData.append("visibility", "private");
295 var XHR = new XMLHttpRequest();
296 XHR.onreadystatechange = function() {
297 if (XHR.readyState == 4) {/*
298 gLog.appendChild(document.createElement("li"))
299 .appendChild(document.createTextNode(aURL + " - " + XHR.status +
300 " " + XHR.statusText));*/
301 }
302 if (XHR.readyState == 4 && XHR.status == 200) {
303 // so far so good
304 reportUploadStatus(true);
305 } else if (XHR.readyState == 4 && XHR.status != 200) {
306 // fetched the wrong page or network error...
307 reportUploadStatus(false);
308 }
309 };
310 XHR.open("POST", gOSMAPIURL + "api/0.6/gpx/create", true,
311 document.getElementById("uploadUser").value,
312 document.getElementById("uploadPwd").value);
313 try {
314 XHR.send(formData);
315 }
316 catch (e) {
317 reportUploadStatus(false, e);
318 }
319}
320
321function reportUploadStatus(aSuccess, aMessage) {
322 alert(aMessage ? aMessage : (aSuccess ? "success" : "failure"));
323}
324
993fd081
RK
325var gPrefs = {
326 objStore: "prefs",
327
328 get: function(aKey, aCallback) {
329 if (!mainDB)
330 return;
331 var transaction = mainDB.transaction([this.objStore]);
332 var request = transaction.objectStore(this.objStore).get(aKey);
333 request.onsuccess = function(event) {
334 aCallback(request.result, event);
335 };
336 request.onerror = function(event) {
337 // Errors can be handled here.
338 aCallback(undefined, event);
339 };
340 },
341
342 set: function(aKey, aValue, aCallback) {
343 if (!mainDB)
344 return;
345 var success = false;
d4ccddb8 346 var transaction = mainDB.transaction([this.objStore], "readwrite");
993fd081 347 var objStore = transaction.objectStore(this.objStore);
3610c22d 348 var request = objStore.put(aValue, aKey);
993fd081
RK
349 request.onsuccess = function(event) {
350 success = true;
351 if (aCallback)
352 aCallback(success, event);
353 };
354 request.onerror = function(event) {
355 // Errors can be handled here.
356 if (aCallback)
357 aCallback(success, event);
358 };
359 },
360
361 unset: function(aKey, aCallback) {
362 if (!mainDB)
363 return;
364 var success = false;
d4ccddb8 365 var transaction = mainDB.transaction([this.objStore], "readwrite");
993fd081
RK
366 var request = transaction.objectStore(this.objStore).delete(aKey);
367 request.onsuccess = function(event) {
368 success = true;
369 if (aCallback)
370 aCallback(success, event);
371 };
372 request.onerror = function(event) {
373 // Errors can be handled here.
374 if (aCallback)
375 aCallback(success, event);
376 }
377 }
378};
379
380var gTrackStore = {
381 objStore: "track",
382
383 getList: function(aCallback) {
384 if (!mainDB)
385 return;
386 var transaction = mainDB.transaction([this.objStore]);
387 var objStore = transaction.objectStore(this.objStore);
388 if (objStore.getAll) { // currently Mozilla-specific
389 objStore.getAll().onsuccess = function(event) {
390 aCallback(event.target.result);
391 };
392 }
393 else { // Use cursor (standard method).
394 var tPoints = [];
395 objStore.openCursor().onsuccess = function(event) {
396 var cursor = event.target.result;
397 if (cursor) {
398 tPoints.push(cursor.value);
399 cursor.continue();
400 }
401 else {
402 aCallback(tPoints);
403 }
404 };
405 }
406 },
407
408 push: function(aValue, aCallback) {
409 if (!mainDB)
410 return;
d4ccddb8 411 var transaction = mainDB.transaction([this.objStore], "readwrite");
993fd081
RK
412 var objStore = transaction.objectStore(this.objStore);
413 var request = objStore.add(aValue);
414 request.onsuccess = function(event) {
415 if (aCallback)
416 aCallback(request.result, event);
417 };
418 request.onerror = function(event) {
419 // Errors can be handled here.
420 if (aCallback)
421 aCallback(false, event);
422 };
423 },
424
425 clear: function(aCallback) {
426 if (!mainDB)
427 return;
428 var success = false;
d4ccddb8 429 var transaction = mainDB.transaction([this.objStore], "readwrite");
993fd081
RK
430 var request = transaction.objectStore(this.objStore).clear();
431 request.onsuccess = function(event) {
432 success = true;
433 if (aCallback)
434 aCallback(success, event);
435 };
436 request.onerror = function(event) {
437 // Errors can be handled here.
438 if (aCallback)
439 aCallback(success, event);
440 }
441 }
442};