mobiparc.js 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944
  1. //$(function () {
  2. // JS s'execute: Retire l'avertissement 'Javascript est requis'
  3. document.body.classList.remove("nojs");
  4. if ('serviceWorker' in navigator) {
  5. console.log("[ServiceWorker] Installe");
  6. navigator.serviceWorker.register('../sw.js');
  7. }
  8. Handlebars.registerHelper('lower', function (options) {
  9. return options.fn(this).toLowerCase();
  10. });
  11. Handlebars.registerHelper('repuri', function (find, replace, options) {
  12. return encodeURI(options.fn(this).replace(find, replace).toString());
  13. });
  14. Handlebars.registerHelper('todate', function (options) {
  15. var d = options.fn(this);
  16. var dt = new Date(Number.parseInt(d)*1);
  17. return dt.toLocaleString();
  18. });
  19. Handlebars.registerHelper('timestamp', function (options) {
  20. return Number.parseInt(options.fn(this));
  21. });
  22. Handlebars.registerHelper('if_eq', function (a, opts) {
  23. var b = localStorage.hasOwnProperty("contact") ? localStorage.getItem("contact"): "";
  24. if (a === b) // Or === depending on your needs
  25. return opts.fn(this);
  26. else
  27. return opts.inverse(this);
  28. });
  29. // Main <div>
  30. var main = document.getElementsByClassName('main')[0];
  31. // ???
  32. var template = Handlebars.compile(document.getElementById(getUrldest()).innerHTML);
  33. function createGuid() {
  34. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  35. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  36. return v.toString(16);
  37. });
  38. }
  39. function uuidv4() {
  40. return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
  41. (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
  42. )
  43. }
  44. var contacts;
  45. function callback(response) {
  46. contacts = response;
  47. // localStorage.setItem("contacts", JSON.stringify(response))
  48. }
  49. $.ajax({
  50. url: "data/contacts.json", success: function (result) {
  51. callback(result);
  52. }
  53. });
  54. try {
  55. getLocation();
  56. }
  57. catch (e) {
  58. console.log("error loc");
  59. }
  60. Date.prototype.getWeekNumber = function () {
  61. var d = new Date(Date.UTC(this.getFullYear(), this.getMonth(), this.getDate()));
  62. var dayNum = d.getUTCDay() || 7;
  63. d.setUTCDate(d.getUTCDate() + 4 - dayNum);
  64. var yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
  65. return Math.ceil((((d - yearStart) / 86400000) + 1) / 7)
  66. };
  67. $('.bt-menu').on('click', 'svg', function () {
  68. $(this).closest('nav').find('div:not(:first)').toggleClass('sidebar');
  69. });
  70. $(document).on('click', '.sidebar', function () {
  71. $(this).closest('nav').find('div:not(:first)').toggleClass('sidebar');
  72. });
  73. //param first
  74. //suppression
  75. //gestion offline
  76. if (navigator.onLine) {
  77. $(".data-sync").removeAttr("disabled");
  78. }
  79. else {
  80. if (!$(".data-sync").is(":disabled"))
  81. {
  82. $(".data-sync").attr("disabled")
  83. }
  84. }
  85. //syncro
  86. $(".data-sync").on("click", function () {
  87. var db = open.result;
  88. var txs = db.transaction("anomalies", "readonly");
  89. var stores = txs.objectStore("anomalies");
  90. console.log("post all : ");
  91. stores.openCursor().onsuccess = function (event) {
  92. //var data = { data: event.target.result };
  93. var cursor = event.target.result;
  94. if (cursor) {
  95. //cursor.model = "anomaly";
  96. cursor.value.model = "anomaly";
  97. var id = cursor.value.tstamp;
  98. var posting = $.post("/api/canalbis", { data: JSON.stringify(cursor.value) });
  99. // Put the results in a div
  100. posting.done(function (data) {
  101. if (data == 'ole') {
  102. var tx = db.transaction("anomalies", "readwrite");
  103. var store = tx.objectStore("anomalies");
  104. store.delete(id).onsuccess = function (evt) {
  105. $('.sync-result').append("Sync ok anomalie : " + id + "<br>");
  106. };
  107. }
  108. });
  109. cursor.continue();
  110. }
  111. else {
  112. console.log("end anomalies");
  113. }
  114. //$.post("/api/canalbis", { data: JSON.stringify({anomaly: event.target.result}) });
  115. // main.innerHTML = template(data);
  116. };
  117. txs = db.transaction("vannes", "readonly");
  118. stores = txs.objectStore("vannes");
  119. console.log("post all : ");
  120. stores.openCursor().onsuccess = function (event) {
  121. var cursor = event.target.result;
  122. if (cursor) {
  123. //cursor.model = "anomaly";
  124. cursor.value.model = "valve";
  125. var id = cursor.value.tstamp;
  126. var posting = $.post("/api/canalbis", { data: JSON.stringify(cursor.value) });
  127. // Put the results in a div
  128. posting.done(function (data) {
  129. if (data == 'ole') {
  130. var tx = db.transaction("vannes", "readwrite");
  131. var store = tx.objectStore("vannes");
  132. store.delete(id).onsuccess = function (evt) {
  133. $('.sync-result').append("Sync ok vanne : " + id +"<br>");
  134. };
  135. }
  136. });
  137. cursor.continue();
  138. }
  139. else {
  140. console.log("end valve");
  141. }
  142. //var data = { data: event.target.result };
  143. //$.post("/api/canalbis", { data: JSON.stringify({ valve: event.target.result }) });
  144. // main.innerHTML = template(data);
  145. };
  146. txs = db.transaction("interventions", "readonly");
  147. stores = txs.objectStore("interventions");
  148. console.log("post all : ");
  149. //stores.getAll().onsuccess = function (event) {
  150. stores.openCursor().onsuccess = function (event) {
  151. var cursor = event.target.result;
  152. if (cursor) {
  153. //cursor.model = "anomaly";
  154. cursor.value.model = "interventions";
  155. var id = cursor.value.tstamp;
  156. var posting = $.post("/api/canalbis", { data: JSON.stringify(cursor.value) });
  157. // Put the results in a div
  158. posting.done(function (data) {
  159. if (data == 'ole') {
  160. var tx = db.transaction("interventions", "readwrite");
  161. var store = tx.objectStore("interventions");
  162. store.delete(id).onsuccess = function (evt) {
  163. $('.sync-result').append("Sync ok intervention : " + id + "<br>");
  164. };
  165. }
  166. });
  167. cursor.continue();
  168. }
  169. else {
  170. console.log("end interventions");
  171. }
  172. };
  173. txs = db.transaction("niveaux", "readonly");
  174. stores = txs.objectStore("niveaux");
  175. console.log("post all : ");
  176. //stores.getAll().onsuccess = function (event) {
  177. stores.openCursor().onsuccess = function (event) {
  178. var cursor = event.target.result;
  179. if (cursor) {
  180. //cursor.model = "anomaly";
  181. cursor.value.model = "level";
  182. var id = cursor.value.tstamp;
  183. var posting = $.post("/api/canalbis", { data: JSON.stringify(cursor.value) });
  184. // Put the results in a div
  185. posting.done(function (data) {
  186. if (data == 'ole') {
  187. var tx = db.transaction("niveaux", "readwrite");
  188. var store = tx.objectStore("niveaux");
  189. store.delete(id).onsuccess = function (evt) {
  190. $('.sync-result').append("Sync ok niveau : " + id + "<br>");
  191. };}
  192. });
  193. cursor.continue();
  194. }
  195. else {
  196. console.log("end level");
  197. }
  198. //var data = { data: event.target.result };
  199. //$.post("/api/canalbis", { data: JSON.stringify({level: event.target.result}) });
  200. // main.innerHTML = template(data);
  201. };
  202. //location.reload();
  203. })
  204. $(window).on('hashchange', function () {
  205. var href = $(this).attr('href');
  206. $('html, body').animate({ scrollTop: 0 }, 200);
  207. var urldest = getUrldest();
  208. template = Handlebars.compile(document.getElementById(urldest).innerHTML);
  209. try {
  210. getLocation();
  211. }
  212. catch (e) {
  213. console.log("error loc");
  214. }
  215. if (urldest != 'interventions' && urldest != 'contacts') {
  216. $(".main").empty();
  217. try {
  218. var db = open.result;
  219. var txs = db.transaction(urldest, "readonly");
  220. var stores = txs.objectStore(urldest);
  221. console.log("Got all " + urldest + ": ");
  222. stores.getAll().onsuccess = function (event) {
  223. var data = { data: event.target.result };
  224. main.innerHTML = template(data);
  225. };
  226. //console.log(data);
  227. // $(".main").html(template({}));
  228. }
  229. catch (e) {
  230. main.innerHTML = template({});
  231. }
  232. }
  233. if (urldest == 'interventions') {
  234. //$.ajax({
  235. // url: "", success: function (result) {
  236. var contactInter = contacts;
  237. console.log(contactInter);
  238. if (localStorage.hasOwnProperty("contact")) contactInter.intervention = localStorage.getItem("contact");
  239. $(".main").html(template(contactInter));
  240. // }
  241. //});
  242. }
  243. if (urldest == 'contacts') {
  244. //$.ajax({
  245. // url: "", success: function (result) {
  246. $(".main").html(template(contacts));
  247. // }
  248. //});
  249. }
  250. });
  251. var imgdata;
  252. //a finir
  253. $("body").on("click", ".btn-duplicate", function (event) {
  254. event.preventDefault();
  255. // var copie = $('#img-group-1').clone();
  256. var copie = $('.input-group-img').find('div:first-child').clone();
  257. var inputlenght = createGuid(); //$('.input-file-img').length + 1;
  258. var grpId = $(copie).attr('id') + "-" + inputlenght;
  259. $(copie).attr('id', grpId);
  260. console.log(inputlenght);
  261. var inputName = $(copie).find('.input-file-img').attr('name') + "-" + inputlenght;
  262. $(copie).find('.input-file-img').val('');
  263. $(copie).find('.input-file-img').attr('name', inputName);
  264. var hiddenName = $(copie).find('.hidden-file-img').attr('name') + "-" + inputlenght;
  265. $(copie).find('.hidden-file-img').attr('name', hiddenName);
  266. $(copie).find('.hidden-file-img').val('');
  267. $(copie).find('img').attr('src', '');
  268. copie.appendTo('.input-group-img');
  269. var imginputs = document.querySelectorAll('.input-file-img');
  270. Array.from(imginputs).forEach(img => {
  271. img.addEventListener('change', handleFileSelect, false);
  272. });
  273. });
  274. $("body").on("click", ".file-del", function (event) {
  275. event.preventDefault();
  276. if ($(this).closest('div').attr('id') == 'img-group') {
  277. $(this).closest('div').find('img').attr('src', '');
  278. $(this).closest('div').find('.input-file-img').val('');
  279. $(this).closest('div').find('.hidden-file-img').val('');
  280. }
  281. else $(this).closest('div').remove();
  282. });
  283. $("body").on("click", ".intervention-start, .intervention-end", function (event) {
  284. console.log("intervention");
  285. var data = new Object();
  286. data.tstamp = Date.now();
  287. data.user = JSON.parse(localStorage.getItem("params")).user;
  288. data.event = $(this).data("type");
  289. var db = open.result;
  290. var txs = db.transaction("interventions", "readwrite");
  291. var stores = txs.objectStore("interventions");
  292. stores.put(data);
  293. })
  294. $("body").on("click", ".data-del", function (event) {
  295. // console.log($(this).data("id") + " " + $(this).data("type"));
  296. var id = $(this).data("id");
  297. var datatype = $(this).data("type");
  298. //console.log(id + " " + datatype);
  299. var r = confirm("Supprimer cet élément!");
  300. if (r == true) {
  301. var db = open.result;
  302. var tx = db.transaction(datatype, "readwrite");
  303. var store = tx.objectStore(datatype);
  304. store.delete(id).onsuccess = function (evt) {
  305. // console.log(id + " " + datatype);
  306. location.reload();
  307. };
  308. }
  309. });
  310. $("body").on("click", ".send-message", function (event) {
  311. event.preventDefault();
  312. var form = $(this).closest("form");
  313. function getLocation() {
  314. if (navigator.geolocation) {
  315. navigator.geolocation.getCurrentPosition(showPosition);
  316. } else {
  317. return "Geolocation is not supported by this browser.";
  318. }
  319. }
  320. function showPosition(position) {
  321. //{ lat: position.coords.latitude, lng : position.coords.longitude };
  322. $("input[name='lat']:hidden").val(position.coords.latitude);
  323. $("input[name='lng']:hidden").val(position.coords.longitude);
  324. }
  325. var pp = getLocation();
  326. //var data = form.serializeArray().reduce(function (a, x) { a[x.name] = x.value; return a; }, { tstamp: Date.now(), file: imgdata });
  327. var data = form.serializeArray().reduce(function (a, x) { a[x.name] = x.value; return a; }, { tstamp: Date.now()});
  328. var request = indexedDB.open("Contenu", 3);
  329. request.onerror = function () {
  330. form.find(".send-result").html("Une erreur c'est produite.");
  331. };
  332. request.onsuccess = function () {
  333. var db = request.result;
  334. var tx = db.transaction("emails", "readwrite");
  335. var store = tx.objectStore("emails");
  336. store.put(data);
  337. form.find(".send-result").html("Votre message est pris en compte.");
  338. }
  339. });
  340. //$(function () {
  341. $(".modal-open, .modal-background, .modal-close").click(function () {
  342. console.log("modal");
  343. $(".modal-content,.modal-background").toggleClass("active");
  344. if ($(this).hasClass("modal-close")) location.reload();// $(this).closest("form").find(".send-result").html("");
  345. });
  346. /* retour haut de page*/
  347. //document.addEventListener('DOMContentLoaded', function () {
  348. window.onscroll = function (ev) {
  349. document.getElementById("cRetour").className = (window.pageYOffset > 100) ? "cVisible" : "cInvisible";
  350. };
  351. //});
  352. $('#cRetour').on('click', function () {
  353. $('html, body').animate({ scrollTop: 0 }, 200);
  354. });
  355. $(".main").empty();
  356. var urldest = getUrldest();
  357. try{
  358. var db = open.result;
  359. var txs = db.transaction(urldest, "readonly");
  360. var stores = txs.objectStore(urldest);
  361. console.log("Got all " + urldest + ": ");
  362. stores.getAll().onsuccess = function (event) {
  363. var data = { data: event.target.result };
  364. main.innerHTML = template(data);
  365. };}
  366. catch (e) {
  367. main.innerHTML = template({});
  368. }
  369. $("body").on("click", ".del", function (event) {
  370. var del = $(this);
  371. var r = confirm("Supprimer la selection!");
  372. if (r == true) {
  373. $(del).prop("disabled",true);
  374. $(".ui-selected").each(function () {
  375. var elt = $(this);
  376. var id = $(elt).data("id");
  377. var datatype = $(elt).data("type");
  378. //console.log(id + " " + datatype);
  379. var db = open.result;
  380. var tx = db.transaction(datatype, "readwrite");
  381. var store = tx.objectStore(datatype);
  382. store.delete(id).onsuccess = function (evt) {
  383. // console.log(id + " " + datatype);
  384. $(elt).remove();
  385. };
  386. });
  387. }
  388. });
  389. ///////////////////////});
  390. /**
  391. * Checks that an element has a non-empty `name` and `value` property.
  392. * @param {Element} element the element to check
  393. * @return {Bool} true if the element is an input, false if not
  394. */
  395. var isValidElement = function isValidElement(element) {
  396. return element.name && element.value;
  397. };
  398. /**
  399. * Checks if an element’s value can be saved (e.g. not an unselected checkbox).
  400. * @param {Element} element the element to check
  401. * @return {Boolean} true if the value should be added, false if not
  402. */
  403. var isValidValue = function isValidValue(element) {
  404. return !['checkbox', 'radio'].includes(element.type) || element.checked;
  405. };
  406. /**
  407. * Checks if an input is a checkbox, because checkboxes allow multiple values.
  408. * @param {Element} element the element to check
  409. * @return {Boolean} true if the element is a checkbox, false if not
  410. */
  411. var isCheckbox = function isCheckbox(element) {
  412. return element.type === 'checkbox';
  413. };
  414. //var isHidden = function isHidden(element) {
  415. // return element.type === 'hidden';
  416. //};
  417. /**
  418. * Checks if an input is a `select` with the `multiple` attribute.
  419. * @param {Element} element the element to check
  420. * @return {Boolean} true if the element is a multiselect, false if not
  421. */
  422. var isMultiSelect = function isMultiSelect(element) {
  423. return element.options && element.multiple;
  424. };
  425. /**
  426. * Retrieves the selected options from a multi-select as an array.
  427. * @param {HTMLOptionsCollection} options the options for the select
  428. * @return {Array} an array of selected option values
  429. */
  430. var getSelectValues = function getSelectValues(options) {
  431. return [].reduce.call(options, function (values, option) {
  432. return option.selected ? values.concat(option.value) : values;
  433. }, []);
  434. };
  435. /**
  436. * A more verbose implementation of `formToJSON()` to explain how it works.
  437. *
  438. * NOTE: This function is unused, and is only here for the purpose of explaining how
  439. * reducing form elements works.
  440. *
  441. * @param {HTMLFormControlsCollection} elements the form elements
  442. * @return {Object} form data as an object literal
  443. */
  444. var formToJSON_deconstructed = function formToJSON_deconstructed(elements) {
  445. // This is the function that is called on each element of the array.
  446. var reducerFunction = function reducerFunction(data, element) {
  447. // Add the current field to the object.
  448. data[element.name] = element.value;
  449. // For the demo only: show each step in the reducer’s progress.
  450. console.log(JSON.stringify(data));
  451. return data;
  452. };
  453. // This is used as the initial value of `data` in `reducerFunction()`.
  454. var reducerInitialValue = {};
  455. // To help visualize what happens, log the inital value, which we know is `{}`.
  456. console.log('Initial `data` value:', JSON.stringify(reducerInitialValue));
  457. // Now we reduce by `call`-ing `Array.prototype.reduce()` on `elements`.
  458. var formData = [].reduce.call(elements, reducerFunction, reducerInitialValue);
  459. // The result is then returned for use elsewhere.
  460. return formData;
  461. };
  462. /**
  463. * Retrieves input data from a form and returns it as a JSON object.
  464. * @param {HTMLFormControlsCollection} elements the form elements
  465. * @return {Object} form data as an object literal
  466. */
  467. var formToJSON = function formToJSON(elements) {
  468. return [].reduce.call(elements, function (data, element) {
  469. // Make sure the element has the required properties and should be added.
  470. if (isValidElement(element) && isValidValue(element)) {
  471. /*
  472. * Some fields allow for more than one value, so we need to check if this
  473. * is one of those fields and, if so, store the values as an array.
  474. */
  475. if (isCheckbox(element)) {
  476. data[element.name] = (data[element.name] || []).concat(element.value);
  477. } else if (isMultiSelect(element)) {
  478. data[element.name] = getSelectValues(element);
  479. } else {
  480. data[element.name] = element.value;
  481. }
  482. }
  483. return data;
  484. }, {});
  485. };
  486. var indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB || window.shimIndexedDB;
  487. // Open (or create) the database
  488. var open = indexedDB.open("CanalBis", 3);
  489. // Create the schema
  490. open.onupgradeneeded = function () {
  491. var db = open.result;
  492. //creation anomalies
  493. var store = db.createObjectStore("anomalies", { keyPath: "tstamp" });
  494. //creation niveaux
  495. var store = db.createObjectStore("niveaux", { keyPath: "tstamp" });
  496. //creation vannes
  497. var store = db.createObjectStore("vannes", { keyPath: "tstamp" });
  498. //creation interventions
  499. var store = db.createObjectStore("interventions", { keyPath: "tstamp" });
  500. };
  501. /**
  502. * A handler function to prevent default submission and run our custom script.
  503. * @param {Event} event the submit event triggered by the user
  504. * @return {void}
  505. */
  506. var form;
  507. var handleFormSubmit = function handleFormSubmit(event) {
  508. // Stop the form from submitting since we’re handling that with AJAX.
  509. event.preventDefault();
  510. // Call our function to get the form data.
  511. var data = formToJSON(form.elements);
  512. // Demo only: print the form data onscreen as a formatted JSON object.
  513. var dataContainer = document.getElementsByClassName('results-display')[0];
  514. // Use `JSON.stringify()` to make the output valid, human-readable JSON.
  515. dataContainer.textContent = JSON.stringify(data, null, " ");
  516. // ...this is where we’d actually do something with the form data...
  517. if ($(form).hasClass("param")) {
  518. localStorage.setItem("params", JSON.stringify(data));
  519. //console.log("localstorage");
  520. }
  521. if ($(form).hasClass("anomalie")) {
  522. data.tstamp = Date.now();
  523. data.user = localStorage.hasOwnProperty("params") ? JSON.parse(localStorage.getItem("params")).user : "";
  524. var db = open.result;
  525. var txs = db.transaction("anomalies", "readwrite");
  526. var stores = txs.objectStore("anomalies");
  527. stores.put(data);
  528. $(".main").empty();
  529. console.log("Got all anomalies: ");
  530. stores.getAll().onsuccess = function (event) {
  531. var data = { data: event.target.result };
  532. var template = Handlebars.compile(document.getElementById("anomalies").innerHTML);
  533. $(".main").html(template(data));
  534. };
  535. }
  536. if ($(form).hasClass("vanne")) {
  537. data.tstamp = Date.now();
  538. data.user = JSON.parse(localStorage.getItem("params")).user;
  539. data.campaign = JSON.parse(localStorage.getItem("params")).year_week;
  540. var db = open.result;
  541. var txs = db.transaction("vannes", "readwrite");
  542. var stores = txs.objectStore("vannes");
  543. stores.put(data);
  544. $(".main").empty();
  545. console.log("Got all vannes: ");
  546. stores.getAll().onsuccess = function (event) {
  547. var data = { data: event.target.result };
  548. var template = Handlebars.compile(document.getElementById("vannes").innerHTML);
  549. $(".main").html(template(data));
  550. };
  551. }
  552. if ($(form).hasClass("niveau")) {
  553. data.tstamp = Date.now();
  554. data.user = JSON.parse(localStorage.getItem("params")).user;
  555. data.campaign = JSON.parse(localStorage.getItem("params")).year_week;
  556. var db = open.result;
  557. var txs = db.transaction("niveaux", "readwrite");
  558. var stores = txs.objectStore("niveaux");
  559. stores.put(data);
  560. $(".main").empty();
  561. console.log("Got all niveaux: ");
  562. stores.getAll().onsuccess = function (event) {
  563. var data = { data: event.target.result };
  564. var template = Handlebars.compile(document.getElementById("niveaux").innerHTML);
  565. $(".main").html(template(data));
  566. };
  567. }
  568. console.log(data);
  569. };
  570. /*
  571. * This is where things actually get started. We find the form element using
  572. * its class name, then attach the `handleFormSubmit()` function to the
  573. * `submit` event.
  574. */
  575. function handleFileSelect(evt) {
  576. console.log(evt.target.name);
  577. console.log(evt.target.id);
  578. var preview = $(this).closest('div').find('.img-preview');
  579. var hidden = $(this).closest('div').find('.hidden-file-img');
  580. console.log(evt.target.files);
  581. var files = evt.target.files; // FileList object
  582. // use the 1st file from the list
  583. var f = files[0];
  584. var reader = new FileReader();
  585. // Closure to capture the file information.
  586. reader.onload = (function (theFile) {
  587. return function (e) {
  588. $(hidden).val( e.target.result); //{ data: e.target.result, name: f.name };
  589. $(preview).attr('src', e.target.result);
  590. };
  591. })(f);
  592. // Read in the image file as a data URL.
  593. reader.readAsDataURL(f);
  594. //console.log(reader.readAsDataURL(f))
  595. }
  596. function getLocation() {
  597. if (navigator.geolocation) {
  598. navigator.geolocation.getCurrentPosition(showPosition);
  599. } else {
  600. return "Geolocation is not supported by this browser.";
  601. }
  602. }
  603. function showPosition(position) {
  604. $("input[name='coordinates']").val(position.coords.latitude + "," + position.coords.longitude);
  605. console.log(position.coords);
  606. }
  607. function getUrldest() {
  608. return (window.location.href.replace("index.html","") == "http://localhost:56343/" ? "index" : window.location.hash.slice(1));
  609. }
  610. new MutationObserver(function (mutations, observer) {
  611. //gestion des mise element selectable
  612. $(".selectable > tbody").selectable({
  613. filter: "tr",
  614. stop: function () {
  615. $(".del").removeAttr("disabled");
  616. }
  617. });
  618. $(".select-contact").change(function () {
  619. console.log("contact");
  620. var contact = $(this).find("option:selected").val();
  621. localStorage.setItem("contact", contact);
  622. var result = contacts;
  623. result.intervention = contact;
  624. console.log(result);
  625. var template = Handlebars.compile(document.getElementById("interventions").innerHTML);
  626. $(".main").html(template(result));
  627. });
  628. document.getElementsByClassName('results-display')[0].innerHTML = null;
  629. if ($(".main").find(".data-form").length){
  630. form = $(".main").find(".data-form")[0];
  631. form.addEventListener('submit', handleFormSubmit);
  632. var today = new Date();
  633. if ($(".main").find("#year_week").length) document.getElementById('year_week').value = today.getFullYear() + "_" + today.getWeekNumber();
  634. //if ($(".main").find("#imgfile").length) document.getElementById('imgfile').addEventListener('change', handleFileSelect, false);
  635. //if ($(".input-file-img").length)
  636. // document.querySelector('.input-file-img').addEventListener('change', handleFileSelect, false);
  637. //{
  638. //$(".input-file-img").each(function (index) {
  639. // document.querySelector('.input-file-img').addEventListener('change', handleFileSelect, false);
  640. // });
  641. var imginputs = document.querySelectorAll('.input-file-img');
  642. Array.from(imginputs).forEach(img => {
  643. img.addEventListener('change', handleFileSelect, false); });
  644. //}
  645. if (localStorage.hasOwnProperty('params')) { }
  646. else {
  647. // console.log("no local");
  648. if (!$(form).hasClass("param") && !$(form).hasClass("anomalie")) {
  649. $(".main .data-form").toggle();
  650. alert("Vous devez d'abord définir les paramètres de la campagne");
  651. //console.log("pas param");
  652. }
  653. }
  654. }
  655. //observer.disconnect();
  656. }).observe(document.querySelector('section.main'), { childList: true });
  657. //});