lib.js 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549
  1. /*
  2. Copyright (c) 2013 Mapo developers and contributors <mapo.tizen@gmail.com>
  3. This file is part of Mapo.
  4. This program is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation, either version 3 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. /*
  16. * Application Global variables
  17. */
  18. var web = "http://notabug.org/tizen/mapo";
  19. web = "http://rzr.github.io/";
  20. var gEmail = "mapo.tizen@gmail.com";
  21. // The map of the application
  22. var map = null;
  23. // The boolean which provide the connection state of the application
  24. var isReady = true;
  25. var isAdvanced = false;
  26. var isOnline = navigator.onLine;
  27. var isLoaded = false;
  28. var isDownloaded = false;
  29. var gLocationDate = null;
  30. /*
  31. * Recording Global Variable
  32. */
  33. // Directory where the recording document is placed
  34. var docDir;
  35. // Name of the recording document
  36. var doc;
  37. // The file where the records are placed
  38. var file;
  39. // Boolean which provide the information if a file has been recorded
  40. var fileRecorded = false;
  41. var url_openlayers = "http://openlayers.org/api/OpenLayers.js";
  42. // var url_gmaps = "http://maps.google.com/maps/api/js?v=3.2&sensor=false";
  43. var url_gmaps = 'http://maps.googleapis.com/maps/api/js?v=3.2&signed_in=true&callback=handleLoadedGmaps';
  44. /*
  45. * General Manager
  46. */
  47. /**
  48. * Quit the application
  49. */
  50. function exit() {
  51. if ('undefined' !== typeof (tizen)) {
  52. tizen.application.getCurrentApplication().exit();
  53. } else {
  54. log("exit:");
  55. }
  56. }
  57. /**
  58. * Show a message
  59. *
  60. * @param message
  61. */
  62. function log(message) {
  63. var text = "# ";
  64. try {
  65. var json = JSON.stringify(message);
  66. text += json;
  67. } catch (e) {
  68. text += "not json: " + message;
  69. }
  70. if (isAdvanced) {
  71. console.log(text);
  72. var element = document.getElementById("console");
  73. element.innerHTML += "<pre>" + text + "</pre>";
  74. }
  75. }
  76. function logMap(data) {
  77. for (i = 0; i < data.length; i++) {
  78. log("#" + i + " key:" + data[i].key);
  79. for (j = 0; j < data[i].value.length; j++) {
  80. log(" value#" + j + ":" + data[i].value[j]);
  81. }
  82. }
  83. }
  84. // upstream: https://gist.github.com/kamranzafar/3136584#comment-1244934
  85. function toast(message, delay) {
  86. if (typeof (b) === 'undefined') {
  87. delay = 2000;
  88. }
  89. var $toast = $('<div class="ui-loader ui-overlay-shadow ui-body-e ui-corner-all"><h3>'
  90. + message + '</h3></div>');
  91. $toast.css({
  92. display : 'block',
  93. background : '#fff',
  94. opacity : 0.90,
  95. position : 'fixed',
  96. padding : '7px',
  97. 'text-align' : 'center',
  98. width : '270px',
  99. left : ($(window).width() - 284) / 2,
  100. top : $(window).height() / 2 - 20
  101. });
  102. var removeToast = function() {
  103. $(this).remove();
  104. };
  105. $toast.click(removeToast);
  106. $toast.appendTo($.mobile.pageContainer).delay(delay);
  107. $toast.fadeOut(400, removeToast);
  108. }
  109. function handleError(message) {
  110. message = "error: " + message;
  111. log(message);
  112. toast(message);
  113. return message;
  114. }
  115. function handleException(e) {
  116. return handleError(e.name);
  117. }
  118. function handleSuccess() {
  119. return log("success: ");
  120. }
  121. function handleFailure() {
  122. return log("failure: ");
  123. }
  124. /*
  125. * Storage Manager
  126. */
  127. /**
  128. * Store the coordinates values in the local storage
  129. */
  130. function storeData() {
  131. localStorage.setItem('lat', $('#lat').val());
  132. localStorage.setItem('lon', $('#lon').val());
  133. localStorage.setItem('dms', $('#dms').val());
  134. }
  135. /**
  136. * Store the settings values in the local storage
  137. */
  138. function storeSettings() {
  139. log("#{ storeSettings: " + isOnline);
  140. localStorage.setItem('connection', $('#switchOnline').val());
  141. localStorage.setItem('energySaving', $('#switchEnergy').val());
  142. localStorage.setItem('timeout', $('#selectorTimeout').val());
  143. localStorage.setItem('downloaded', isDownloaded);
  144. isAdvanced = $('#switchDeveloper').val();
  145. localStorage.setItem('develmode', isAdvanced );
  146. log("#} storeSettings: " + isOnline);
  147. }
  148. function store() {
  149. var i = 0;
  150. var r = $.Deferred();
  151. storeData();
  152. storeSettings();
  153. for (i = 0; i < localStorage.length; i++) {
  154. log(i + " -- " + localStorage.key(i) + " : "
  155. + localStorage.getItem(localStorage.key(i)));
  156. }
  157. r.resolve();
  158. return r;
  159. }
  160. /**
  161. * Store the data before quitting the application
  162. */
  163. function quit() {
  164. log("#{ exit");
  165. store().done(exit);
  166. log("#} exit");
  167. }
  168. /*
  169. * Set Manager
  170. */
  171. /**
  172. * Modify the latitude value
  173. *
  174. * @param lat :
  175. * new latitude value
  176. */
  177. function setLat(lat) {
  178. if (document.getElementById("lat").value !== lat) {
  179. document.getElementById("lat").value = lat;
  180. }
  181. }
  182. /**
  183. * Modify the longitude value
  184. *
  185. * @param lon :
  186. * new longitude value
  187. */
  188. function setLon(lon) {
  189. if (document.getElementById("lon").value !== lon) {
  190. document.getElementById("lon").value = lon;
  191. }
  192. }
  193. function makeMessageShort() {
  194. var tag = fromLatLonToTag($("#lat").val(), $("#lon").val());
  195. var message = web + "#" + tag + " I am at " + "#" + tag;
  196. return message;
  197. }
  198. function makeTwitterUrl() {
  199. var tag = fromLatLonToTag($("#lat").val(), $("#lon").val());
  200. var url = web + "%23" + tag;
  201. var message = " I am at " + "#" + tag;
  202. var baseurl = 'https://twitter.com/intent/tweet?&via=TizenHelper&url=${web}&text=${message}';
  203. url = baseurl.replace("${web}", url);
  204. message = encodeURIComponent(message);
  205. url = url.replace("${message}", message);
  206. return url;
  207. }
  208. /*
  209. * Link Manager
  210. */
  211. /**
  212. * Get the OpenStreetMap link with the corresponding latitude and longitude
  213. *
  214. * @returns url
  215. */
  216. function getLink(provider) {
  217. var lat = $("#lat").val();
  218. var lon = $("#lon").val();
  219. var url = web;
  220. var message = null;
  221. var tag = null;
  222. switch (provider) {
  223. case 'OSM':
  224. url = "http://www.openstreetmap.org/?&zoom=10&layers=mapnik&lat=${lat}&lon=${lon}";
  225. break;
  226. case 'GM':
  227. url = "http://maps.google.com/maps?&z=10&ll=${lat},${lon}";
  228. break;
  229. case 'img':
  230. url = 'http://maps.googleapis.com/maps/api/staticmap?size=264x150&zoom=13&center=${lat},${lon}';
  231. break;
  232. case 'HERE':
  233. url = "http://maps.nokia.com/${lat},${lon},16,0,0,normal.day";
  234. break;
  235. case 'bing':
  236. url = "http://www.bing.com/maps/?v=2&style=r&lvl=13&cp=48.11~${lat}~${lon}&style=r&lvl=4";
  237. break;
  238. case 'twitter':
  239. url = makeTwitterUrl();
  240. break;
  241. default:
  242. tag = fromLatLonToTag(lat, lon);
  243. url = provider;
  244. break;
  245. }
  246. url = url.replace("${lon}", lon);
  247. url = url.replace("${lat}", lat);
  248. url = url.replace("${tag}", tag);
  249. url = url.replace("${url}", web);
  250. url = url.replace("${web}", web);
  251. return url;
  252. }
  253. /**
  254. * Use the Internet Application Control to go to OSM link with the browser
  255. */
  256. function goToURL(provider) {
  257. var i = 0;
  258. var j = 0;
  259. var url = getLink(provider);
  260. log(url);
  261. if ('undefined' !== typeof (tizen)) {
  262. if (isOnline) {
  263. var appControl = new tizen.ApplicationControl(
  264. "http://tizen.org/appcontrol/operation/view", url, null);
  265. var appControlReplyCallback = {
  266. onsuccess : logMap,
  267. onfailure : handleFailure
  268. }
  269. tizen.application.launchAppControl(appControl, null, function() {
  270. log("launch internet application control succeed");
  271. }, function(e) {
  272. log("launch internet application control failed. reason: "
  273. + e.message);
  274. }, appControlReplyCallback);
  275. } else {
  276. handleError("Please connect your application online in the settings"
  277. + " if you want to open a browser")
  278. }
  279. } else {
  280. window.open(url);
  281. }
  282. }
  283. /**
  284. * update links TODO: check if needed ?
  285. */
  286. function updateLinks() {
  287. $('#OSMLink').attr('href', getOSMLink());
  288. }
  289. /*
  290. * Map Manager
  291. */
  292. /**
  293. * get the size of the map (width, height) according to the dimension of the
  294. * screen
  295. *
  296. * @returns [ width, height ]
  297. */
  298. function getMapSize() {
  299. var viewHeight = $(window).height();
  300. var viewWidth = $(window).width();
  301. var header = $("div[data-role='header']:visible:visible");
  302. var footer = $("div[data-role='footer']:visible:visible");
  303. var navbar = $("div[data-role='navbar']:visible:visible");
  304. var content = $("div[data-role='content']:visible:visible");
  305. var contentHeight = viewHeight - header.outerHeight()
  306. - navbar.outerHeight() - footer.outerHeight();
  307. var contentWidth = viewWidth - 30;
  308. return [ contentWidth, contentHeight ];
  309. }
  310. /**
  311. * Modify the dimension of the map according to getMapSize()
  312. */
  313. function setMapSize(size) {
  314. size = getMapSize();
  315. $('#myMap').css("width", size[0]);
  316. $('#myMap').css("height", size[1]);
  317. }
  318. function initIcon() {
  319. var size = new OpenLayers.Size(21, 25);
  320. var offset = new OpenLayers.Pixel(-(size.w / 2), -size.h);
  321. return new OpenLayers.Icon('http://www.openlayers.org/dev/img/marker.png',
  322. size, offset);
  323. }
  324. function loadTrace(data) {
  325. var i = 0;
  326. log("loadTrace data : " + data['dates'][0]);
  327. var icon = initIcon();
  328. log("tab lons = " + data['lons']);
  329. log("tab lats = " + data['lats']);
  330. log("tab dates = " + data['dates']);
  331. for (i = 0; i < data['dates'].length; i++) {
  332. var lon = parseFloat(data['lons'][i]);
  333. var lat = parseFloat(data['lats'][i]);
  334. var date = data['dates'][i];
  335. log("data['dates'][" + i + "] = " + date);
  336. log("data['lons'][" + i + "] = " + lon);
  337. log("data['lat'][" + i + "] = " + lat);
  338. log("lat before : " + lat);
  339. log("lon before : " + lon);
  340. var lonlat = new OpenLayers.LonLat(lon, lat).transform('EPSG:4326',
  341. 'EPSG:3857');
  342. var mark = new OpenLayers.Marker(lonlat, icon);
  343. trace.addMarker(mark);
  344. }
  345. map.addLayer(trace);
  346. }
  347. /**
  348. * Load the OpenLayers map with different OpenStreetMap and Google maps' layers
  349. * TODO: check if needed ?
  350. */
  351. function loadMap() {
  352. log("#{ loadMap: " + OpenLayers);
  353. if (OpenLayers === null) {
  354. log("error: OpenLayers " + isDownloaded);
  355. return;
  356. }
  357. var latCenter = $("#lat").val();
  358. var lonCenter = $("#lon").val();
  359. var zoom = $("#zoom").val();
  360. var layers = [ new OpenLayers.Layer.OSM("OpenStreetMap") ];
  361. log("# is gmaps available ? " + gmaps + "/" + gmaps);
  362. if (gmaps !== null) {
  363. var array = [ new OpenLayers.Layer.Google("Google Satellite", {
  364. type : google.maps.MapTypeId.SATELLITE,
  365. numZoomLevels : 22,
  366. })
  367. , new OpenLayers.Layer.Google("Google Physical", {
  368. type : google.maps.MapTypeId.TERRAIN
  369. }), new OpenLayers.Layer.Google("Google Hybrid", {
  370. type : google.maps.MapTypeId.HYBRID,
  371. numZoomLevels : 20
  372. }),
  373. new OpenLayers.Layer.Google("Google Streets", {
  374. numZoomLevels : 20
  375. }) ];
  376. // layers = array.concat(layers);
  377. layers = layers.concat(array);
  378. }
  379. log("# add ui " + layers);
  380. map = new OpenLayers.Map('myMap', {
  381. projection : 'EPSG:3857',
  382. layers : layers,
  383. center : new OpenLayers.LonLat(lonCenter, latCenter).transform(
  384. 'EPSG:4326', 'EPSG:3857'),
  385. zoom : zoom,
  386. controls : [ new OpenLayers.Control.TouchNavigation(),
  387. new OpenLayers.Control.PanZoom(),
  388. new OpenLayers.Control.ArgParser() ]
  389. });
  390. if (isAdvanced)
  391. map.addControl(new OpenLayers.Control.LayerSwitcher());
  392. if (fileRecorded) { // TODO : Data vide : data([0])?.length!=0 or
  393. // fileRecorded
  394. // var trace = new OpenLayers.Layer.Markers( "Latest recorded trace"
  395. // );
  396. // map.removeLayer(trace);
  397. var markers = map.getLayersByName("Last recorded trace");
  398. if (markers.length != 0) {
  399. var previousTrace = markers[0];
  400. log("trace = " + previousTrace.name);
  401. previousTrace.destroy();
  402. }
  403. trace = new OpenLayers.Layer.Markers("Last recorded trace");
  404. // readFile().done(loadTrace);
  405. readFile();
  406. // setTimeout(
  407. // // log("result 0 : "+result[0]);
  408. // // log("result 1 : "+result[1]);
  409. // loadTrace
  410. // , 5000);
  411. }
  412. log("#} loadMap: " + OpenLayers);
  413. }
  414. /*
  415. * Refresh Manager
  416. */
  417. /**
  418. * Refresh all the application according to the coordinates and the settings
  419. */
  420. function refresh() {
  421. log("#{ refresh: " + OpenLayers);
  422. if (isOnline) {
  423. isReady = (OpenLayers !== null);
  424. } else {
  425. isReady = false;
  426. }
  427. log("isReady=" + isReady);
  428. if (isReady) {
  429. $('#myMap').empty();
  430. setMapSize();
  431. loadMap();
  432. } else {
  433. // isOnline = navigator.onLine;
  434. // $('#switchOnline').val(isOnline ? 'online' : 'offline');
  435. $('#myMap').empty();
  436. $('#myMap')
  437. .html(
  438. "<p align='center'>"
  439. + "Please connect your application online in the settings"
  440. + " if you want to load the map</p>");
  441. }
  442. // isOffline $('#switchOffline').val() // TODO
  443. updateDMS();
  444. if (gLocationDate != null) {
  445. var lat = $("#lat").val();
  446. var lon = $("#lon").val();
  447. var text = "Last update:<br/>" //
  448. + gLocationDate.toString() //
  449. + "<br/>" + "#" + fromLatLonToTag(lat, lon) //
  450. ;
  451. $('#locationInfo').html(text);
  452. }
  453. // var locationInfo = document.getElementById("locationInfo");
  454. // locationInfo.innerHTML = fromLatLonToDMS(lat, lon);
  455. log("#} refresh: " + isReady);
  456. }
  457. /*
  458. * Initialization Manager
  459. */
  460. /**
  461. * Recover in the local storage the coordinates values from the preceding use
  462. */
  463. function initData() {
  464. log("#{ initData");
  465. if (localStorage.getItem('lat') !== null) {
  466. $('#lat').val(localStorage.getItem('lat'));
  467. }
  468. if (localStorage.getItem('lon') !== null) {
  469. $('#lon').val(localStorage.getItem('lon'));
  470. }
  471. if (localStorage.getItem('dms') !== null) {
  472. $('#dms').val(localStorage.getItem('dms'));
  473. } // not needed
  474. storeData();
  475. log("#} initData");
  476. }
  477. /**
  478. * Recover in the local storage the setting values from the preceding use
  479. */
  480. function initSettings() {
  481. log("#{ initSettings: " + isOnline);
  482. if (null !== localStorage.getItem('connection')) {
  483. isOnline = (localStorage.getItem('connection') == 'online');
  484. }
  485. $('#switchOnline').val(isOnline ? 'online' : 'offline');
  486. if (localStorage.getItem('energySaving') !== null) {
  487. $('#switchEnergy').val(localStorage.getItem('energySaving'));
  488. }
  489. if (localStorage.getItem('timeout') !== null) {
  490. $('#selectorTimeout').attr('value', localStorage.getItem('timeout'));
  491. }
  492. if (localStorage.getItem('downloaded') !== null) {
  493. isDownloaded = localStorage.getItem('downloaded');
  494. }
  495. if (localStorage.getItem('develmode') !== null) {
  496. isAdvanced = localStorage.getItem('develmode');
  497. }
  498. $('#switchDeveloper').val(isAdvanced ? 'on' : 'off');
  499. storeSettings();
  500. log("#} initSettings: " + isReady);
  501. }
  502. /*
  503. * Coordinates transformation Manager
  504. */
  505. /**
  506. * Transform the latitude/longitude into DMS coordinate
  507. *
  508. * @param lat :
  509. * latitude
  510. * @param lon :
  511. * longitude
  512. * @returns dms : DMS coordinate
  513. */
  514. function fromLatLonToDMS(lat, lon) {
  515. var latitude = lat;
  516. var longitude = lon;
  517. var dms = "";
  518. var NS = "";
  519. if (latitude >= 0) {
  520. NS += "N";
  521. } else {
  522. latitude = -latitude;
  523. NS += "S";
  524. }
  525. var dLat = parseInt(latitude, 10);
  526. var mLat = parseInt((latitude - dLat) * 60, 10);
  527. var sLat = parseInt((latitude - dLat) * 60 * 60 - 60 * mLat, 10);
  528. dms += NS + " " + dLat + "° " + mLat + "' " + sLat + "\" ";
  529. var EW = "";
  530. if (longitude >= 0) {
  531. EW += "E";
  532. } else {
  533. EW += "W";
  534. longitude = -longitude;
  535. }
  536. var dLon = parseInt(longitude, 10);
  537. var mLon = parseInt((longitude - dLon) * 60, 10);
  538. var sLon = parseInt((longitude - dLon) * 60 * 60 - 60 * mLon, 10);
  539. dms += EW + " " + dLon + "° " + mLon + "' " + sLon + "\"";
  540. // text = NS+" "+d+"° "+m+"' "+s+"\" "+EW+" "+d+"° "+m+"' "+s+"\"";
  541. return dms;
  542. }
  543. /** @return string in this form : N26d21m28sE127d47m1s **/
  544. function fromLatLonToTag(lat, lon) {
  545. var result = "";
  546. var latitude = lat;
  547. var longitude = lon;
  548. var NS = "";
  549. if (latitude >= 0) {
  550. NS += "N";
  551. } else {
  552. latitude = -latitude;
  553. NS += "S";
  554. }
  555. var dLat = parseInt(latitude, 10);
  556. var mLat = parseInt((latitude - dLat) * 60, 10);
  557. var sLat = parseInt((latitude - dLat) * 60 * 60 - 60 * mLat, 10);
  558. result += NS + dLat + "d" + mLat + "m" + sLat + "s";
  559. var EW = "";
  560. if (longitude >= 0) {
  561. EW += "E";
  562. } else {
  563. EW += "W";
  564. longitude = -longitude;
  565. }
  566. var dLon = parseInt(longitude, 10);
  567. var mLon = parseInt((longitude - dLon) * 60, 10);
  568. var sLon = parseInt((longitude - dLon) * 60 * 60 - 60 * mLon, 10);
  569. result += EW + dLon + "d" + mLon + "m" + sLon + "s";
  570. return result;
  571. }
  572. /**
  573. * Transform the DMS into latitude/longitude coordinates
  574. *
  575. * @param dms :
  576. * DMS coordinate
  577. */
  578. function setDMS(input) {
  579. var re = /^([NS])\s*([0-9.\-]+)\s*°\s*([0-9.\-]+)\s*\'\s*([0-9.\-]+)\s*\"\s*([EW])\s*([0-9.\-]+)\s*°\s*([0-9.\-]+)\s*\'\s*([0-9.\-]+)\s*\"\s*$/;
  580. if (re.test(input)) {
  581. log("setTag: ok " + input );
  582. var lat = (parseFloat(RegExp.$2) + parseFloat(RegExp.$3) / 60 + parseFloat(RegExp.$4)
  583. / (60 * 60)).toFixed(6);
  584. if (RegExp.$1 == 'S') {
  585. lat = -lat;
  586. }
  587. lat = lat.toString();
  588. setLat(lat);
  589. var lon = (parseFloat(RegExp.$6) + parseFloat(RegExp.$7) / 60 + parseFloat(RegExp.$8)
  590. / (60 * 60)).toFixed(6);
  591. if (RegExp.$5 == 'W') {
  592. lon = -lon;
  593. }
  594. lon = lon.toString();
  595. setLon(lon);
  596. refresh();
  597. }
  598. }
  599. /** @arg input : string in this form : N28d7m11sW1d37m48s **/
  600. function setTag(input) {
  601. var res;
  602. var re = /^#([NS])([0-9.\-]+)d([0-9.\-]+)m([0-9.\-]+)s([EW])([0-9.\-]+)d([0-9.\-]+)m([0-9.\-]+)s$/;
  603. res = re.test(input);
  604. if (res) {
  605. var lat = (parseFloat(RegExp.$2) + parseFloat(RegExp.$3) / 60 + parseFloat(RegExp.$4)
  606. / (60 * 60)).toFixed(6);
  607. if (RegExp.$1 == 'S') {
  608. lat = -lat;
  609. }
  610. lat = lat.toString();
  611. setLat(lat);
  612. var lon = (parseFloat(RegExp.$6) + parseFloat(RegExp.$7) / 60 + parseFloat(RegExp.$8)
  613. / (60 * 60)).toFixed(6);
  614. if (RegExp.$5 == 'W') {
  615. lon = -lon;
  616. }
  617. lon = lon.toString();
  618. setLon(lon);
  619. refresh();
  620. }
  621. return res;
  622. }
  623. /*
  624. * Coordinates Manager
  625. */
  626. /**
  627. * Modify the DMS value using the transformation's function fromLatLonToDMS
  628. */
  629. function updateDMS() {
  630. var lat = $("#lat").val();
  631. var lon = $("#lon").val();
  632. var text = fromLatLonToDMS(lat, lon);
  633. $('#dms').val(text);
  634. }
  635. function setLatLon() {
  636. setDMS($('#dms').val());
  637. }
  638. /**
  639. * Validate or not the DMS coordinate according to the form of the regular
  640. * expression
  641. *
  642. * @param dms :
  643. * DMS coordinates
  644. * @returns Validation
  645. */
  646. function validateDMS(input) {
  647. var re = /^([NS])\s*([0-9.\-]+)\s*[°ºDd]\s*([0-9.\-]+)\s*\'\s*([0-9.\-]+)\s*\"\s*([EW])\s*([0-9.\-]+)\s*[°ºDd]\s*([0-9.\-]+)\s*\'\s*([0-9.\-]+)\s*\"\s*$/;
  648. return (re.test(input));
  649. } //TODO: merge with setDMS
  650. /**
  651. * Validate or not the latitudes and longitudes coordinates according to the
  652. * form of the regular expression
  653. *
  654. * @param latOrLon
  655. * @returns Validation
  656. */
  657. function validateLatOrLon(latOrLon) {
  658. if (/^[0-9.\-]+$/.test(latOrLon)) {
  659. return true;
  660. } else {
  661. return false;
  662. }
  663. }
  664. /**
  665. * Function called when the latitude value changes Calculate the new DMS
  666. * coordinate
  667. */
  668. function changeLat() {
  669. var lat = $('#lat').val();
  670. if (validateLatOrLon(lat)) {
  671. $('#lat').val(parseFloat($('#lat').val()).toFixed(6).toString());
  672. refresh();
  673. storeData();
  674. } else {
  675. handleError("Latitude coordinate invalid : " + lat);
  676. initData();
  677. }
  678. }
  679. /**
  680. * Function called when the longitude value changes Calculate the new DMS
  681. * coordinate
  682. */
  683. function changeLon() {
  684. var lon = $('#lon').val();
  685. if (validateLatOrLon(lon)) {
  686. $('#lon').val(parseFloat($('#lon').val()).toFixed(6).toString());
  687. refresh();
  688. storeData();
  689. } else {
  690. handleError("Lontitude coordinate invalid : " + lon);
  691. initData();
  692. }
  693. }
  694. /**
  695. * Function called when the DMS value changes Calculate the new latitude and
  696. * longitude coordinates
  697. */
  698. function changeDMS() {
  699. var dms = $('#dms').val();
  700. if (validateDMS(dms)) {
  701. setLatLon();
  702. storeData();
  703. } else {
  704. alert("DMS coordinate invalid : " + dms);
  705. initData();
  706. }
  707. }
  708. /*
  709. * Location Manager
  710. */
  711. /**
  712. * Function called when the getCurrentPosition succeded Refresh the application
  713. */
  714. function handleShowLocation(position) {
  715. var lat = position.coords.latitude.toFixed(6).toString();
  716. var lon = position.coords.longitude.toFixed(6).toString();
  717. gLocationDate = new Date(position.timestamp);
  718. setLat(lat);
  719. setLon(lon);
  720. refresh();
  721. isLocated = true;
  722. }
  723. /**
  724. * Function called when the getCurrentPosition failed Show the error
  725. *
  726. * @param error
  727. */
  728. function handleErrorLocation(error) {
  729. var locationInfo = document.getElementById("locationInfo");
  730. switch (error.code) {
  731. case error.PERMISSION_DENIED:
  732. locationInfo.innerHTML = "error: User denied the request for Geolocation.";
  733. break;
  734. case error.POSITION_UNAVAILABLE:
  735. locationInfo.innerHTML = "error: Location information is unavailable.";
  736. break;
  737. case error.TIMEOUT:
  738. locationInfo.innerHTML = "error: The request to get user location timed out.";
  739. break;
  740. case error.UNKNOWN_ERROR:
  741. default:
  742. locationInfo.innerHTML = "error: An unknown error occurred.";
  743. break;
  744. }
  745. toast("Check settings and press update to track position", 4000);
  746. isLocated = false;
  747. }
  748. /**
  749. * Get the current position according to the GPS' device
  750. */
  751. function getLocation(isUpdate) {
  752. if (navigator.geolocation) {
  753. if (isUpdate) {
  754. navigator.geolocation.getCurrentPosition(handleShowLocation,
  755. handleErrorLocation, {
  756. enableHighAccuracy : $('#switchEnergy').val() == 'off'
  757. });
  758. } else {
  759. navigator.geolocation.watchPosition(updateMapCenter,
  760. handleErrorLocation, {
  761. enableHighAccuracy : $('#switchEnergy').val() == 'off'
  762. });
  763. }
  764. } else {
  765. document.getElementById("locationInfo").innerHTML = "Geolocation is not supported by this browser.";
  766. }
  767. }
  768. function updateMapCenter(position) {
  769. var latCenter = position.coords.latitude.toFixed(6).toString();
  770. var lonCenter = position.coords.longitude.toFixed(6).toString();
  771. map.setCenter(new OpenLayers.LonLat(lonCenter, latCenter).transform('EPSG:4326', 'EPSG:3857'));
  772. }
  773. /*
  774. * Recording manager
  775. */
  776. /**
  777. * Function called when the file resolution succeded Create the recording file
  778. * in the corresponding directory
  779. *
  780. * @param dir :
  781. * directory where the file is placed
  782. */
  783. function handleResolveSuccess(dir) {
  784. docDir = dir;
  785. var date = new Date();
  786. var dateFile = "" + date.getFullYear().toString() + "-"
  787. + date.getMonth().toString() + "-" + date.getDate().toString()
  788. + "-" + date.getHours().toString() + "-"
  789. + date.getMinutes().toString() + "-" + date.getSeconds().toString();
  790. dateFile = (new Date).getTime();
  791. // log(dateFile);
  792. doc = 'mapo-' + dateFile + ".csv.txt";
  793. docDir.createFile(doc);
  794. $('#locationInfo').html("Track recording in file:<br/>" + doc);
  795. }
  796. /**
  797. * Function called when the file resolution failed Show the error
  798. *
  799. * @param e :
  800. * error
  801. */
  802. function handleResolveError(e) {
  803. handleError('resolve: ' + e.message);
  804. }
  805. /**
  806. * Resolve the file
  807. */
  808. function resolveFile() {
  809. try {
  810. file = docDir.resolve(doc);
  811. } catch (exc) {
  812. log('Could not resolve file: ' + exc.message);
  813. // Stop in case of any errors
  814. return;
  815. }
  816. }
  817. /**
  818. * Function called when the record failed, writing or reading Show the error
  819. *
  820. * @param e :
  821. * error
  822. */
  823. function handleErrorStream(e) {
  824. var msg = '';
  825. switch (e.code) {
  826. case FileError.QUOTA_EXCEEDED_ERR:
  827. msg = 'QUOTA_EXCEEDED_ERR';
  828. break;
  829. case FileError.NOT_FOUND_ERR:
  830. msg = 'NOT_FOUND_ERR';
  831. break;
  832. case FileError.SECURITY_ERR:
  833. msg = 'SECURITY_ERR';
  834. break;
  835. case FileError.INVALID_MODIFICATION_ERR:
  836. msg = 'INVALID_MODIFICATION_ERR';
  837. break;
  838. case FileError.INVALID_STATE_ERR:
  839. msg = 'INVALID_STATE_ERR';
  840. break;
  841. default:
  842. msg = 'Unknown Error';
  843. break;
  844. }
  845. handleError(msg);
  846. }
  847. /**
  848. * Function called when the writing succeeded Add the position at the end of the
  849. * file
  850. *
  851. * @param fileStream :
  852. * Stream to write
  853. */
  854. function handleStreamWrite(stream) {
  855. try {
  856. var date = (new Date).getTime();
  857. var lat = $("#lat").val();
  858. var lon = $("#lon").val();
  859. var line = "" + date + ";" + lat + ";" + lon + "\n";
  860. stream.write(line);
  861. stream.close();
  862. } catch (exc) {
  863. handleError('io: could not write to file: ' + exc.message);
  864. }
  865. }
  866. /**
  867. * Try to write the record into the file
  868. */
  869. function writeRecord() {
  870. try {
  871. file.openStream('a', handleStreamWrite, handleErrorStream);
  872. } catch (exc) {
  873. handleError('io: could not write to file: ' + exc.message);
  874. }
  875. }
  876. /**
  877. * Function called when the reading succeded
  878. *
  879. * @param fileStream :
  880. * Stream to read
  881. */
  882. function handleStreamRead(fileStream) {
  883. try {
  884. log('File size: ' + file.fileSize);
  885. var contents = fileStream.read(fileStream.bytesAvailable);
  886. fileStream.close();
  887. log('file contents: ' + contents);
  888. } catch (exc) {
  889. handleError('io: Could not read from file: ' + exc.message);
  890. }
  891. }
  892. /**
  893. * Try to read the file
  894. */
  895. function readRecord() {
  896. try {
  897. file.openStream('r', handleStreamRead, handleRecordError);
  898. } catch (exc) {
  899. handleError('io: Could not write to file: ' + exc.message);
  900. }
  901. }
  902. /**
  903. * Function called when getPosition got successfully the position Resolve the
  904. * file, write and read the records
  905. *
  906. * @param position
  907. */
  908. function handleRecordPosition(position) {
  909. if ($('#switchRecord').val() == "start") {
  910. handleShowLocation(position);
  911. resolveFile();
  912. writeRecord();
  913. readRecord();
  914. }
  915. }
  916. /**
  917. * Function called when getPosition failed to get the position Show the error
  918. *
  919. * @param error
  920. */
  921. function handleErrorPosition(error) {
  922. $('#switchRecord').val('stop').slider('refresh');
  923. var errorInfo = document.getElementById("locationInfo");
  924. switch (error.code) {
  925. case error.PERMISSION_DENIED:
  926. errorInfo.innerHTML = "User denied the request for Geolocation.";
  927. break;
  928. case error.POSITION_UNAVAILABLE:
  929. errorInfo.innerHTML = "Location information is unavailable.";
  930. break;
  931. case error.TIMEOUT:
  932. errorInfo.innerHTML = "The request to get user location timed out.";
  933. break;
  934. case error.UNKNOWN_ERROR:
  935. errorInfo.innerHTML = "An unknown error occurred.";
  936. break;
  937. }
  938. }
  939. /**
  940. * Get the recording position
  941. */
  942. function getPosition() {
  943. navigator.geolocation.getCurrentPosition(handleRecordPosition, log, {
  944. enableHighAccuracy : false,
  945. timeout : 2000,
  946. maximumAge : Ininity
  947. });
  948. navigator.geolocation.getCurrentPosition(handleRecordPosition,
  949. handleErrorPosition, {
  950. enableHighAccuracy : $('#switchEnergy').val() == 'off'
  951. });
  952. }
  953. /**
  954. * Function called when the record of a trace has been launched Record the
  955. * position whith a timeout predefined in the settings
  956. */
  957. function record() {
  958. if (navigator.geolocation) {
  959. var intervalID;
  960. if ($('#switchRecord').val() == "start") {
  961. tizen.filesystem.resolve('documents', handleResolveSuccess,
  962. handleResolveError, 'rw');
  963. getPosition();
  964. intervalID = setInterval(getPosition,
  965. $('#selectorTimeout').val() * 1000);
  966. } else {
  967. clearInterval(intervalID);
  968. $('#locationInfo').html("Trace recorded in the file:<br/>" + doc);
  969. fileRecorded = true;
  970. }
  971. } else {
  972. document.getElementById("locationInfo").innerHTML = "Geolocation is not supported.";
  973. }
  974. }
  975. /**
  976. * Extract from a file composed by the last recorded trace all the dates,
  977. * latitudes and lontitudes and place its in data TODO: test if parse CSV as
  978. * "date,la,lo\n"
  979. */
  980. function readFile() {
  981. // var deferred = $.Deferred();
  982. try {
  983. file = docDir.resolve(doc);
  984. log('File size: ' + file.fileSize);
  985. } catch (exceptionResolve) {
  986. log('error: Could not resolve file: ' + exceptionResolve.message);
  987. // Stop in case of any errors
  988. return;
  989. }
  990. try {
  991. file.readAsText(
  992. // success callback - display the contents of the file
  993. function(contents) {
  994. // log('File contents:' + contents);
  995. var lines = contents.split("\n");
  996. var re = /^([0-9.:\-]+),([0-9.\-]+),([0-9.\-]+)$/;
  997. var data = [];
  998. var dates = [];
  999. var lats = [];
  1000. var lons = [];
  1001. var iData = 0;
  1002. for (var iLines = 0; iLines < lines.length; iLines++) {
  1003. if (re.test(lines[iLines])) {
  1004. log("line " + iLines + ": " + lines[iLines]);
  1005. var parts = lines[iLines].split(";");
  1006. for (var iParts = 0; iParts < parts.length; iParts++) {
  1007. log(" part " + iParts + ": " + parts[iParts]);
  1008. if ((iParts % 3) == 0) {
  1009. dates[iData] = parts[iParts];
  1010. log(" date " + iData + ": " + dates[iData]);
  1011. } else if ((iParts % 3) == 1) {
  1012. lats[iData] = parts[iParts];
  1013. log(" lat " + iData + ": " + lats[iData]);
  1014. } else {
  1015. lons[iData] = parts[iParts];
  1016. log(" lon " + iData + ": " + lons[iData]);
  1017. }
  1018. }
  1019. iData++;
  1020. }
  1021. }
  1022. data['dates'] = dates;
  1023. data['lats'] = lats;
  1024. data['lons'] = lons;
  1025. log("readfile data" + data['dates'][0]);
  1026. loadTrace(data);
  1027. },
  1028. // error callback
  1029. handleRecordError);
  1030. } catch (exceptionRead) {
  1031. handleError("io: readAsText() exception:" + exceptionRead.message);
  1032. }
  1033. // deferred.resolve();
  1034. // return deferred; // [data, referred]
  1035. }
  1036. /*
  1037. * Social Manager
  1038. */
  1039. function makeMessage() {
  1040. var message = "I am at this place:\n" //
  1041. + "#" + fromLatLonToTag($("#lat").val(), $("#lon").val()) + " \n" //
  1042. + "Latitude=" + $("#lat").val() + " \n" //
  1043. + "Longitude = " + $("#lon").val() + " \n" //
  1044. + "( " + $('#dms').val() + ")\n " + " \n" //
  1045. + getLink('OSM') + " \n" + web + " \n";
  1046. return message;
  1047. }
  1048. /**
  1049. * Use the Email Application Control to share a position by Email
  1050. */
  1051. function sendEmail() {
  1052. var email = gEmail;
  1053. var message = makeMessage();
  1054. var subject = "Mapo current position is ...";
  1055. if ('undefined' !== typeof (tizen)) {
  1056. if (isOnline) {
  1057. var appControl = new tizen.ApplicationControl(
  1058. "http://tizen.org/appcontrol/operation/compose", //
  1059. null, null, null, [
  1060. new tizen.ApplicationControlData(
  1061. "http://tizen.org/appcontrol/data/subject",
  1062. [ subject ]),
  1063. new tizen.ApplicationControlData(
  1064. "http://tizen.org/appcontrol/data/to",
  1065. [ email ]),
  1066. new tizen.ApplicationControlData(
  1067. "http://tizen.org/appcontrol/data/text",
  1068. [ message ]) ]);
  1069. tizen.application.launchAppControl(appControl, "tizen.email", //
  1070. handleSuccess, handleException);
  1071. } else {
  1072. alert("Please connect your application online in the settings"
  1073. + " if you want to send an email");
  1074. }
  1075. } else {
  1076. var url = "mailto:" + email + "?subject=" + subject + "&body="
  1077. + message;
  1078. window.open(url);
  1079. }
  1080. }
  1081. function sendMessage() {
  1082. var message = makeMessage();
  1083. var appControl = new tizen.ApplicationControl(
  1084. "http://tizen.org/appcontrol/operation/compose", null, null, null,
  1085. [
  1086. new tizen.ApplicationControlData(
  1087. "http://tizen.org/appcontrol/data/messagetype",
  1088. [ "sms" ]),
  1089. new tizen.ApplicationControlData(
  1090. "http://tizen.org/appcontrol/data/text",
  1091. [ message ]) ]);
  1092. tizen.application.launchAppControl(appControl, "tizen.messages", //
  1093. handleSuccess, handleException);
  1094. }
  1095. /*
  1096. * Settings Manager
  1097. */
  1098. function settings() {
  1099. var url = "http://tizen.org/appcontrol/operation/setting";
  1100. var id = "com.samsung.setting";
  1101. var appControl = new tizen.ApplicationControl(url);
  1102. tizen.application.launchAppControl(appControl, id, handleSuccess,
  1103. handleException);
  1104. }
  1105. function settingsLocation() {
  1106. var url = "http://tizen.org/appcontrol/operation/setting/location";
  1107. var id = "org.tizen.setting-location";
  1108. var appControl = new tizen.ApplicationControl(url);
  1109. tizen.application.launchAppControl(appControl, id, handleSuccess,
  1110. handleException);
  1111. }
  1112. function handleCapture(input) {
  1113. log($('#capture').val()); // fakepath
  1114. log("TODO: save to file using tag filename");
  1115. }
  1116. /*
  1117. * Caller Manager : may not be needed
  1118. */
  1119. function call() {
  1120. log("TODO");
  1121. exit();
  1122. var appControl = new tizen.ApplicationControl(
  1123. "http://tizen.org/appcontrol/operation/dial", null, null);
  1124. tizen.application.launchAppControl(appControl, "tizen.phone",
  1125. handleSuccess, handleException, null);
  1126. }
  1127. function caller() {
  1128. log("TODO");
  1129. exit();
  1130. var appControl = new tizen.ApplicationControl(
  1131. "http://tizen.org/appcontrol/operation/call",
  1132. null,
  1133. null,
  1134. null,
  1135. [ new tizen.ApplicationControlData(
  1136. "http://tizen.org/appcontrol/data/call/type", [ "voice" ]) ]);
  1137. tizen.application.launchAppControl(appControl, "tizen.call", //
  1138. handleSuccess, handleException);
  1139. }
  1140. /*
  1141. * Contact Manager
  1142. */
  1143. /**
  1144. * Use the Contact Application Control to add a contact with the corresponding
  1145. * position
  1146. */
  1147. function createContact() {
  1148. log("#{ createContact");
  1149. var addressbook = tizen.contact.getDefaultAddressBook();
  1150. var groups = addressbook.getGroups();
  1151. var idMapo = "-1";
  1152. for (var i = 0; i < groups.length; i++) {
  1153. log(groups[i].name);
  1154. if (groups[i].name == 'Mapo') {
  1155. idMapo = groups[i].id;
  1156. }
  1157. }
  1158. var group;
  1159. if (idMapo != "-1") {
  1160. group = addressbook.getGroup(idMapo);
  1161. log('Group already exists ' + group.id);
  1162. } else {
  1163. group = new tizen.ContactGroup('Mapo');
  1164. addressbook.addGroup(group);
  1165. log('Group added with id ' + group.id);
  1166. }
  1167. // TODO: edit contact is present
  1168. var contact = new tizen.Contact({
  1169. emails : [ new tizen.ContactEmailAddress(gEmail) ],
  1170. urls : [ new tizen.ContactWebSite(getLink('OSM'), 'HOMEPAGE') ],
  1171. notes : [ 'Position: lat=' + $("#lat").val() + ' lon='
  1172. + $("#lon").val() ],
  1173. organizations : [ new tizen.ContactOrganization({
  1174. name : "Mapo"
  1175. }) ],
  1176. groupIds : [ group.id ]
  1177. });
  1178. addressbook.add(contact);
  1179. var appControl = new tizen.ApplicationControl(
  1180. "http://tizen.org/appcontrol/operation/social/edit",
  1181. null,
  1182. "vnd.tizen.item.type/vnd.tizen.contact",
  1183. null,
  1184. [
  1185. new tizen.ApplicationControlData(
  1186. "http://tizen.org/appcontrol/data/social/item_type",
  1187. [ "person" ]),
  1188. new tizen.ApplicationControlData(
  1189. "http://tizen.org/appcontrol/data/social/item_id",
  1190. [ contact.personId ]) ]);
  1191. tizen.application.launchAppControl(appControl, null, function() {
  1192. log("contact: launch service succeeded");
  1193. }, function(e) {
  1194. handleError("contact: launch service failed. Reason: " + e);
  1195. });
  1196. log("#} createContact");
  1197. }
  1198. /*
  1199. * Calendar Manager
  1200. */
  1201. /**
  1202. * Use the Contact Application Control to add an event in the calendar with the
  1203. * corresponding date
  1204. */
  1205. function createCalendarEvent() {
  1206. var calendar = tizen.calendar.getDefaultCalendar("EVENT");
  1207. var date = new Date();
  1208. var event = new tizen.CalendarEvent({
  1209. description : "Mapo Event",
  1210. summary : "Mapo",
  1211. startDate : new tizen.TZDate(date.getFullYear().toString(), date
  1212. .getMonth().toString(), date.getDate().toString(), date
  1213. .getHours().toString(), date.getSeconds().toString()),
  1214. duration : new tizen.TimeDuration(1, "HOURS"),
  1215. location : 'Position: lat=' + $("#lat").val() + ' lon='
  1216. + $("#lon").val()
  1217. });
  1218. calendar.add(event);
  1219. var url = "http://tizen.org/appcontrol/operation/social/edit";
  1220. var appControl = new tizen.ApplicationControl(url, null, null, null, [
  1221. new tizen.ApplicationControlData(
  1222. "http://tizen.org/appcontrol/data/social/item_type",
  1223. [ "event" ]),
  1224. new tizen.ApplicationControlData(
  1225. "http://tizen.org/appcontrol/data/social/item_id",
  1226. [ event.id.uid ]) ]);
  1227. tizen.application.launchAppControl(appControl, "tizen.calendar",
  1228. function() {
  1229. log("success: " + url);
  1230. }, function(e) {
  1231. handleError("launch service failed. Reason: " + e);
  1232. });
  1233. }
  1234. /*
  1235. * Settings Manager
  1236. */
  1237. /**
  1238. * Function called when the online swith is activated or desactived Verify if
  1239. * the the device has a connection before connecting the application
  1240. */
  1241. function switchOnline() {
  1242. log("#{ switchOnline: " + isOnline);
  1243. log($('#switchOnline').val());
  1244. isOnline = ("online" === $('#switchOnline').val());
  1245. if (isOnline && !navigator.onLine)
  1246. log("connect system's wifi before");
  1247. if (isOnline) {
  1248. isReady = (null === OpenLayers);
  1249. if (!isReady || (null === gmaps)) {
  1250. download();
  1251. }
  1252. } else {
  1253. isReady = false;
  1254. }
  1255. refresh();
  1256. log("#} switchOnline: " + isOnline);
  1257. }
  1258. function switchDeveloper() {
  1259. isAdvanced = ("on" === $('#switchDeveloper').val());
  1260. var attribute = (isAdvanced) ? "visible" : "hidden";
  1261. $("#logView").css("visibility", attribute);
  1262. $("#recordView").css("visibility", attribute);
  1263. log("logging...");
  1264. }
  1265. /**
  1266. * Use the tactil swipe to change between every pages TODO : blink ?
  1267. */
  1268. function swipePage() {
  1269. $('div.ui-page').live("swipeleft", function() {
  1270. var nextpage = $(this).next('div[data-role="page"]');
  1271. // swipe using id of next page if exists
  1272. if (nextpage.length > 0) {
  1273. $.mobile.changePage(nextpage, {
  1274. transition : "slide",
  1275. reverse : false
  1276. });
  1277. }
  1278. });
  1279. $('div.ui-page').live("swiperight", function() {
  1280. var prevpage = $(this).prev('div[data-role="page"]');
  1281. // swipe using id of next page if exists
  1282. if (prevpage.length > 0) {
  1283. $.mobile.changePage(prevpage, {
  1284. transition : "slide",
  1285. reverse : true
  1286. });
  1287. }
  1288. });
  1289. }
  1290. function handleLoadedGmaps() {
  1291. log("#{ handleLoadedGmaps: + " + google);
  1292. gmaps = google;
  1293. isDownloaded = true;
  1294. refresh();
  1295. log("#} handleLoadedGmaps: + " + isDownloaded);
  1296. }
  1297. function downloadScriptsBody() {
  1298. log("#{ downloadScriptsBody: " + OpenLayers);
  1299. {
  1300. var element = document.createElement("script");
  1301. element.type = 'text/javascript';
  1302. element.src = url_openlayers;
  1303. document.body.appendChild(element);
  1304. }
  1305. {
  1306. var element = document.createElement("script");
  1307. element.type = 'text/javascript';
  1308. element.src = url_gmaps;
  1309. document.body.appendChild(element);
  1310. }
  1311. log("#} downloadScriptsBody: " + OpenLayers);
  1312. }
  1313. function download() {
  1314. log("#{ download: " + OpenLayers);
  1315. if (null == OpenLayers) {
  1316. $.getScript(url_openlayers, function() {
  1317. log("download:" + OpenLayers);
  1318. refresh();
  1319. $.getScript(url_gmaps, function() {
  1320. handleLoadedGmaps();
  1321. });
  1322. });
  1323. } else if (null == google) {
  1324. $.getScript(url_gmaps, function() {
  1325. handleLoadedGmaps();
  1326. });
  1327. } else {
  1328. handleLoadedGmaps();
  1329. }
  1330. // isLoaded = true; // TODO?
  1331. log("#} download: " + OpenLayers);
  1332. }
  1333. function initScripts() {
  1334. log("#{ initScripts: " + OpenLayers);
  1335. log("# isDownloaded=" + isDownloaded);
  1336. if (false === isDownloaded) {
  1337. download();
  1338. } else {
  1339. download();
  1340. refresh();
  1341. }
  1342. log("#} initScripts: " + OpenLayers);
  1343. }
  1344. /**
  1345. * Initialize the data from the preceding use
  1346. */
  1347. function start() {
  1348. log("#{ start: " + OpenLayers);
  1349. $("#picture").hide()
  1350. $("#capture").change(handleCapture);
  1351. initData();
  1352. initSettings();
  1353. initScripts();
  1354. switchDeveloper();
  1355. changeLat();
  1356. changeLon();
  1357. log(window.location.hash);
  1358. if (window.location.hash) {
  1359. setTag(window.location.hash);
  1360. } else {
  1361. setTimeout(getLocation, 4000);
  1362. }
  1363. // refresh();
  1364. if (false) { // TODO: buggy flash screen
  1365. swipePage();
  1366. }
  1367. // refresh();
  1368. log("#} start: " + OpenLayers);
  1369. }