mobiparc.js 28 KB

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