add an upload button for OSM track upload - still doesn't work right, unfortunately
[lantea.git] / js / ui.js
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/. */
4
5 // Get the best-available indexedDB object.
6 window.indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB;
7 var mainDB;
8
9 var gUIHideCountdown = 0;
10 var gWaitCounter = 0;
11 var gAction, gActionLabel;
12 var gOSMAPIURL = "http://api06.dev.openstreetmap.org/"; // "http://api.openstreetmap.org/";
13
14 window.onload = function() {
15   gAction = document.getElementById("action");
16   gActionLabel = document.getElementById("actionlabel");
17
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   }
25
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
40   document.getElementById("body").addEventListener("keydown", uiEvHandler, false);
41
42   if (navigator.platform.length == "") {
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   }
47
48   initDB();
49   initMap();
50
51   var loopCnt = 0;
52   var waitForInitAndDraw = function() {
53     if ((gWaitCounter <= 0) || (loopCnt > 100)) {
54       if (gWaitCounter <= 0)
55         gWaitCounter = 0;
56       else
57         console.log("Loading failed (waiting for init).");
58
59       gMapPrefsLoaded = true;
60       resizeAndDraw();
61       gActionLabel.textContent = "";
62       gAction.style.display = "none";
63       setTracking(document.getElementById("trackCheckbox"));
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       });
75     }
76     else
77       setTimeout(waitForInitAndDraw, 100);
78     loopCnt++;
79   };
80   waitForInitAndDraw();
81 }
82
83 window.onresize = function() {
84   resizeAndDraw();
85 }
86
87 function initDB() {
88   // Open DB.
89   var request = window.indexedDB.open("MainDB-lantea", 2);
90   request.onerror = function(event) {
91     // Errors can be handled here. Error codes explain in:
92     // https://developer.mozilla.org/en/IndexedDB/IDBDatabaseException#Constants
93     if (gDebug)
94       console.log("error opening mainDB: " + event.target.errorCode);
95   };
96   request.onsuccess = function(event) {
97     mainDB = request.result;
98   };
99   request.onupgradeneeded = function(event) {
100     mainDB = request.result;
101     var ver = mainDB.version || 0; // version is empty string for a new DB
102     if (gDebug)
103       console.log("mainDB has version " + ver + ", upgrade needed.");
104     if (!mainDB.objectStoreNames.contains("prefs")) {
105       // Create a "prefs" objectStore.
106       var prefsStore = mainDB.createObjectStore("prefs");
107     }
108     if (!mainDB.objectStoreNames.contains("track")) {
109       // Create a "track" objectStore.
110       var trackStore = mainDB.createObjectStore("track", {autoIncrement: true});
111     }
112     if (!mainDB.objectStoreNames.contains("tilecache")) {
113       // Create a "tilecache" objectStore.
114       var tilecacheStore = mainDB.createObjectStore("tilecache");
115     }
116     mainDB.onversionchange = function(event) {
117       mainDB.close();
118       mainDB = undefined;
119       initDB();
120     };
121   };
122 }
123
124 function 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
135 function 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
148 function toggleTrackArea() {
149   var fs = document.getElementById("trackArea");
150   if (fs.style.display != "block") {
151     fs.style.display = "block";
152     showUI();
153   }
154   else {
155     fs.style.display = "none";
156   }
157 }
158
159 function toggleSettings() {
160   var fs = document.getElementById("settingsArea");
161   if (fs.style.display != "block") {
162     fs.style.display = "block";
163     showUI();
164   }
165   else {
166     fs.style.display = "none";
167   }
168 }
169
170 function 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
194 var 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":
205       case "keydown":
206         showUI();
207         break;
208     }
209   }
210 };
211
212 function 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
224 function 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
235 function 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";
243         out += '    <trkseg>' + "\n";
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";
259       }
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
271 function saveTrack() {
272   if (gTrack.length) {
273     var outDataURI = "data:application/gpx+xml," +
274                      encodeURIComponent(convertTrack("gpx"));
275     window.open(outDataURI, 'GPX Track');
276   }
277 }
278
279 function saveTrackDump() {
280   if (gTrack.length) {
281     var outDataURI = "data:application/json," +
282                      encodeURIComponent(convertTrack("json"));
283     window.open(outDataURI, 'JSON dump');
284   }
285 }
286
287 function 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
321 function reportUploadStatus(aSuccess, aMessage) {
322   alert(aMessage ? aMessage : (aSuccess ? "success" : "failure"));
323 }
324
325 var 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;
346     var transaction = mainDB.transaction([this.objStore], "readwrite");
347     var objStore = transaction.objectStore(this.objStore);
348     var request = objStore.put(aValue, aKey);
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;
365     var transaction = mainDB.transaction([this.objStore], "readwrite");
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
380 var 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;
411     var transaction = mainDB.transaction([this.objStore], "readwrite");
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;
429     var transaction = mainDB.transaction([this.objStore], "readwrite");
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 };