mobiparc.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  1. 
  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("activite", "readonly");
  89. var stores = txs.objectStore("activite");
  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 = "activite";
  97. var id = cursor.value.tstamp;
  98. var posting = $.post("/api/mobiparc", { 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("activite", "readwrite");
  103. var store = tx.objectStore("activite");
  104. store.delete(id).onsuccess = function (evt) {
  105. $('.sync-result').append("Sync ok activite : " + id + "<br>");
  106. };
  107. }
  108. });
  109. cursor.continue();
  110. }
  111. else {
  112. console.log("end activite");
  113. }
  114. };
  115. })
  116. // Recharge dynamiquement le contenu HTML à chaque changement d'url
  117. $(window).on('hashchange', function () {
  118. var href = $(this).attr('href');
  119. $('html, body').animate({ scrollTop: 0 }, 200);
  120. var urldest = getUrldest();
  121. template = Handlebars.compile(document.getElementById(urldest).innerHTML);
  122. //try {
  123. // getLocation();
  124. //}
  125. //catch (e) {
  126. // console.log("error loc");
  127. //}
  128. if (urldest != 'activite') {
  129. $(".main").empty();
  130. try {
  131. var db = open.result;
  132. var txs = db.transaction(urldest, "readonly");
  133. var stores = txs.objectStore(urldest);
  134. console.log("Got all " + urldest + ": ");
  135. stores.getAll().onsuccess = function (event) {
  136. var data = { data: event.target.result };
  137. main.innerHTML = template(data);
  138. };
  139. }
  140. catch (e) {
  141. main.innerHTML = template({});
  142. }
  143. }
  144. });
  145. var imgdata;
  146. $("body").on("click", ".data-del", function (event) {
  147. // console.log($(this).data("id") + " " + $(this).data("type"));
  148. var id = $(this).data("id");
  149. var datatype = $(this).data("type");
  150. //console.log(id + " " + datatype);
  151. var r = confirm("Supprimer cet élément!");
  152. if (r == true) {
  153. var db = open.result;
  154. var tx = db.transaction(datatype, "readwrite");
  155. var store = tx.objectStore(datatype);
  156. store.delete(id).onsuccess = function (evt) {
  157. // console.log(id + " " + datatype);
  158. location.reload();
  159. };
  160. }
  161. });
  162. $("body").on("click", ".send-message", function (event) {
  163. event.preventDefault();
  164. var form = $(this).closest("form");
  165. function getLocation() {
  166. if (navigator.geolocation) {
  167. navigator.geolocation.getCurrentPosition(showPosition);
  168. } else {
  169. return "Geolocation is not supported by this browser.";
  170. }
  171. }
  172. function showPosition(position) {
  173. $("input[name='lat']:hidden").val(position.coords.latitude);
  174. $("input[name='lng']:hidden").val(position.coords.longitude);
  175. }
  176. var pp = getLocation();
  177. var data = form.serializeArray().reduce(function (a, x) { a[x.name] = x.value; return a; }, { tstamp: Date.now()});
  178. var request = indexedDB.open("Contenu", 3);
  179. request.onerror = function () {
  180. form.find(".send-result").html("Une erreur c'est produite.");
  181. };
  182. request.onsuccess = function () {
  183. var db = request.result;
  184. var tx = db.transaction("emails", "readwrite");
  185. var store = tx.objectStore("emails");
  186. store.put(data);
  187. form.find(".send-result").html("Votre message est pris en compte.");
  188. }
  189. });
  190. $(".modal-open, .modal-background, .modal-close").click(function () {
  191. console.log("modal");
  192. $(".modal-content,.modal-background").toggleClass("active");
  193. if ($(this).hasClass("modal-close")) location.reload();
  194. });
  195. /* retour haut de page*/
  196. window.onscroll = function (ev) {
  197. document.getElementById("cRetour").className = (window.pageYOffset > 100) ? "cVisible" : "cInvisible";
  198. };
  199. $('#cRetour').on('click', function () {
  200. $('html, body').animate({ scrollTop: 0 }, 200);
  201. });
  202. $(".main").empty();
  203. var urldest = getUrldest();
  204. try{
  205. var db = open.result;
  206. var txs = db.transaction(urldest, "readonly");
  207. var stores = txs.objectStore(urldest);
  208. console.log("Got all " + urldest + ": ");
  209. stores.getAll().onsuccess = function (event) {
  210. var data = { data: event.target.result };
  211. main.innerHTML = template(data);
  212. };}
  213. catch (e) {
  214. main.innerHTML = template({});
  215. }
  216. $("body").on("click", ".del", function (event) {
  217. var del = $(this);
  218. var r = confirm("Supprimer la selection!");
  219. if (r == true) {
  220. $(del).prop("disabled",true);
  221. $(".ui-selected").each(function () {
  222. var elt = $(this);
  223. var id = $(elt).data("id");
  224. var datatype = $(elt).data("type");
  225. //console.log(id + " " + datatype);
  226. var db = open.result;
  227. var tx = db.transaction(datatype, "readwrite");
  228. var store = tx.objectStore(datatype);
  229. store.delete(id).onsuccess = function (evt) {
  230. // console.log(id + " " + datatype);
  231. $(elt).remove();
  232. };
  233. });
  234. }
  235. });
  236. /**
  237. * Checks that an element has a non-empty `name` and `value` property.
  238. * @param {Element} element the element to check
  239. * @return {Bool} true if the element is an input, false if not
  240. */
  241. var isValidElement = function isValidElement(element) {
  242. return element.name && element.value;
  243. };
  244. /**
  245. * Checks if an element’s value can be saved (e.g. not an unselected checkbox).
  246. * @param {Element} element the element to check
  247. * @return {Boolean} true if the value should be added, false if not
  248. */
  249. var isValidValue = function isValidValue(element) {
  250. return !['checkbox', 'radio'].includes(element.type) || element.checked;
  251. };
  252. /**
  253. * Checks if an input is a checkbox, because checkboxes allow multiple values.
  254. * @param {Element} element the element to check
  255. * @return {Boolean} true if the element is a checkbox, false if not
  256. */
  257. var isCheckbox = function isCheckbox(element) {
  258. return element.type === 'checkbox';
  259. };
  260. //var isHidden = function isHidden(element) {
  261. // return element.type === 'hidden';
  262. //};
  263. /**
  264. * Checks if an input is a `select` with the `multiple` attribute.
  265. * @param {Element} element the element to check
  266. * @return {Boolean} true if the element is a multiselect, false if not
  267. */
  268. var isMultiSelect = function isMultiSelect(element) {
  269. return element.options && element.multiple;
  270. };
  271. /**
  272. * Retrieves the selected options from a multi-select as an array.
  273. * @param {HTMLOptionsCollection} options the options for the select
  274. * @return {Array} an array of selected option values
  275. */
  276. var getSelectValues = function getSelectValues(options) {
  277. return [].reduce.call(options, function (values, option) {
  278. return option.selected ? values.concat(option.value) : values;
  279. }, []);
  280. };
  281. /**
  282. * A more verbose implementation of `formToJSON()` to explain how it works.
  283. *
  284. * NOTE: This function is unused, and is only here for the purpose of explaining how
  285. * reducing form elements works.
  286. *
  287. * @param {HTMLFormControlsCollection} elements the form elements
  288. * @return {Object} form data as an object literal
  289. */
  290. var formToJSON_deconstructed = function formToJSON_deconstructed(elements) {
  291. // This is the function that is called on each element of the array.
  292. var reducerFunction = function reducerFunction(data, element) {
  293. // Add the current field to the object.
  294. data[element.name] = element.value;
  295. // For the demo only: show each step in the reducer’s progress.
  296. console.log(JSON.stringify(data));
  297. return data;
  298. };
  299. // This is used as the initial value of `data` in `reducerFunction()`.
  300. var reducerInitialValue = {};
  301. // To help visualize what happens, log the inital value, which we know is `{}`.
  302. console.log('Initial `data` value:', JSON.stringify(reducerInitialValue));
  303. // Now we reduce by `call`-ing `Array.prototype.reduce()` on `elements`.
  304. var formData = [].reduce.call(elements, reducerFunction, reducerInitialValue);
  305. // The result is then returned for use elsewhere.
  306. return formData;
  307. };
  308. /**
  309. * Retrieves input data from a form and returns it as a JSON object.
  310. * @param {HTMLFormControlsCollection} elements the form elements
  311. * @return {Object} form data as an object literal
  312. */
  313. var formToJSON = function formToJSON(elements) {
  314. return [].reduce.call(elements, function (data, element) {
  315. // Make sure the element has the required properties and should be added.
  316. if (isValidElement(element) && isValidValue(element)) {
  317. /*
  318. * Some fields allow for more than one value, so we need to check if this
  319. * is one of those fields and, if so, store the values as an array.
  320. */
  321. if (isCheckbox(element)) {
  322. data[element.name] = (data[element.name] || []).concat(element.value);
  323. } else if (isMultiSelect(element)) {
  324. data[element.name] = getSelectValues(element);
  325. } else {
  326. data[element.name] = element.value;
  327. }
  328. }
  329. return data;
  330. }, {});
  331. };
  332. var indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB || window.shimIndexedDB;
  333. // Open (or create) the database
  334. var open = indexedDB.open("MobiParc", 3);
  335. // Create the schema
  336. open.onupgradeneeded = function () {
  337. var db = open.result;
  338. //creation anomalies
  339. var store = db.createObjectStore("activite", { keyPath: "tstamp" });
  340. };
  341. /**
  342. * A handler function to prevent default submission and run our custom script.
  343. * @param {Event} event the submit event triggered by the user
  344. * @return {void}
  345. */
  346. var form;
  347. var handleFormSubmit = function handleFormSubmit(event) {
  348. // Stop the form from submitting since we’re handling that with AJAX.
  349. event.preventDefault();
  350. // Call our function to get the form data.
  351. var data = formToJSON(form.elements);
  352. // Demo only: print the form data onscreen as a formatted JSON object.
  353. var dataContainer = document.getElementsByClassName('results-display')[0];
  354. // Use `JSON.stringify()` to make the output valid, human-readable JSON.
  355. dataContainer.textContent = JSON.stringify(data, null, " ");
  356. // ...this is where we’d actually do something with the form data...
  357. if ($(form).hasClass("param")) {
  358. localStorage.setItem("params", JSON.stringify(data));
  359. }
  360. if ($(form).hasClass("activite")) {
  361. data.tstamp = Date.now();
  362. data.user = localStorage.hasOwnProperty("params") ? JSON.parse(localStorage.getItem("params")).user : "";
  363. var db = open.result;
  364. var txs = db.transaction("activite", "readwrite");
  365. var stores = txs.objectStore("activite");
  366. stores.put(data);
  367. $(".main").empty();
  368. console.log("Got all activite: ");
  369. stores.getAll().onsuccess = function (event) {
  370. var data = { data: event.target.result };
  371. var template = Handlebars.compile(document.getElementById("activite").innerHTML);
  372. $(".main").html(template(data));
  373. };
  374. }
  375. console.log(data);
  376. };
  377. /*
  378. * This is where things actually get started. We find the form element using
  379. * its class name, then attach the `handleFormSubmit()` function to the
  380. * `submit` event.
  381. */
  382. function handleFileSelect(evt) {
  383. console.log(evt.target.name);
  384. console.log(evt.target.id);
  385. var preview = $(this).closest('div').find('.img-preview');
  386. var hidden = $(this).closest('div').find('.hidden-file-img');
  387. console.log(evt.target.files);
  388. var files = evt.target.files; // FileList object
  389. // use the 1st file from the list
  390. var f = files[0];
  391. var reader = new FileReader();
  392. // Closure to capture the file information.
  393. reader.onload = (function (theFile) {
  394. return function (e) {
  395. $(hidden).val( e.target.result); //{ data: e.target.result, name: f.name };
  396. $(preview).attr('src', e.target.result);
  397. };
  398. })(f);
  399. // Read in the image file as a data URL.
  400. reader.readAsDataURL(f);
  401. //console.log(reader.readAsDataURL(f))
  402. }
  403. function getLocation() {
  404. if (navigator.geolocation) {
  405. navigator.geolocation.getCurrentPosition(showPosition);
  406. } else {
  407. return "Geolocation is not supported by this browser.";
  408. }
  409. }
  410. function showPosition(position) {
  411. $("input[name='coordinates']").val(position.coords.latitude + "," + position.coords.longitude);
  412. console.log(position.coords);
  413. }
  414. function getUrldest() {
  415. return (window.location.href.replace("index.html", "") == "http://localhost:62188/" ? "index" : window.location.hash.slice(1));
  416. }
  417. new MutationObserver(function (mutations, observer) {
  418. //gestion des mise element selectable
  419. $(".selectable > tbody").selectable({
  420. filter: "tr",
  421. stop: function () {
  422. $(".del").removeAttr("disabled");
  423. }
  424. });
  425. $(".select-contact").change(function () {
  426. console.log("contact");
  427. var contact = $(this).find("option:selected").val();
  428. localStorage.setItem("contact", contact);
  429. var result = contacts;
  430. result.intervention = contact;
  431. console.log(result);
  432. var template = Handlebars.compile(document.getElementById("interventions").innerHTML);
  433. $(".main").html(template(result));
  434. });
  435. document.getElementsByClassName('results-display')[0].innerHTML = null;
  436. if ($(".main").find(".data-form").length){
  437. form = $(".main").find(".data-form")[0];
  438. form.addEventListener('submit', handleFormSubmit);
  439. var today = new Date();
  440. if ($(".main").find("#year_week").length) document.getElementById('year_week').value = today.getFullYear() + "_" + today.getWeekNumber();
  441. var imginputs = document.querySelectorAll('.input-file-img');
  442. Array.from(imginputs).forEach(img => {
  443. img.addEventListener('change', handleFileSelect, false); });
  444. if (localStorage.hasOwnProperty('params')) { }
  445. else {
  446. // console.log("no local");
  447. if (!$(form).hasClass("param") && !$(form).hasClass("anomalie")) {
  448. $(".main .data-form").toggle();
  449. alert("Vous devez d'abord définir les paramètres de la campagne");
  450. //console.log("pas param");
  451. }
  452. }
  453. }
  454. }).observe(document.querySelector('section.main'), { childList: true });