plugins.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836
  1. // Avoid `console` errors in browsers that lack a console.
  2. (function() {
  3. var method;
  4. var noop = function () {};
  5. var methods = [
  6. 'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
  7. 'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
  8. 'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
  9. 'timeline', 'timelineEnd', 'timeStamp', 'trace', 'warn'
  10. ];
  11. var length = methods.length;
  12. var console = (window.console = window.console || {});
  13. while (length--) {
  14. method = methods[length];
  15. // Only stub undefined methods.
  16. if (!console[method]) {
  17. console[method] = noop;
  18. }
  19. }
  20. }());
  21. //Affiche un message 'message' de type 'type' pendant 'timeout' secondes
  22. $.message = function (type,message,timeout){
  23. $.toast({ type: type, content: message, timeout: timeout });
  24. }
  25. //Permet les notifications types toast sans dépendance de librairie/css/html
  26. $.toast = function (options) {
  27. var defaults = {
  28. title: null,
  29. content: '',
  30. type: 'info',
  31. timeout: 3000
  32. };
  33. var o = $.extend(defaults, options);
  34. var css = "word-wrap:break-word;color:#ffffff;display:none;border-radius:1px;margin-bottom:10px;text-align:center;width:100%;box-shadow: 1px 1px 3px rgba(0, 0, 0, 0.3);position:relative;";
  35. var types = {
  36. error: { css: "background:#dc2626;", icon: 'fas fa-exclamation-triangle' },
  37. warning: { css: "background:#ffc107;color:#212529;", icon: 'fas fa-exclamation-circle' },
  38. info: { css: "background:#2AA7EA;", icon: 'fas fa-info-circle' },
  39. success: { css: "background:#28a745;", icon: 'fas fa-check' },
  40. }
  41. css += types[o.type].css;
  42. o.icon = types[o.type].icon;
  43. if ($('.toastContainer').length == 0)
  44. $('body').append('<div class="toastContainer" style="z-index:1100;position:fixed;right:15px;top:65px;width:350px;"></div>');
  45. var popupContainer = $('.toastContainer');
  46. var popup = $('<div style="' + css + '" class="noPrint toast-'+o.type+'"><i class="toastRemove fas fa-times" style="position:absolute;top:5px;right:5px;display:none;cursor:pointer;" onclick="$(this).parent().remove();"; style="position:absolute;top:5px;right:5px;cursor:pointer;"></i><h1 class="toastTitle" style="margin:0;padding:10px;"></h1><i class="toastIcon" style="display:inline-block;vertical-align:top;width:30px;font-size:20px;margin:15px 0;"></i><p style="display: inline-block;margin-top: 10px;padding:0 10px 0 10px;width:300px;" class="toastContent"></p><div style="clear:both;"></div></div>');
  47. $(popupContainer).append(popup);
  48. if (o.title) $('.toastTitle', popup).html(o.title);
  49. $('.toastIcon', popup).attr('class', o.icon);
  50. if (!o.title) $('.toastTitle', popup).remove();
  51. $('.toastContent', popup).html(o.content);
  52. popup.fadeIn();
  53. if (o.timeout != 0) {
  54. setTimeout(function () { popup.fadeOut(); }, o.timeout);
  55. } else {
  56. popup.find('.toastRemove').show();
  57. }
  58. }
  59. $.page = function(element){
  60. var path = window.location.pathname.split('/') ;
  61. path = path[path.length-1];
  62. path = path.replace('.php','');
  63. return path;
  64. }
  65. $.getForm= function(element){
  66. return $(element).getForm();
  67. }
  68. $.setForm= function(element,data){
  69. var o = {};
  70. var obj = $(element);
  71. $('input,select,textarea',obj).each(function(i,element){
  72. if(element.id!=null && element.id!=""){
  73. if(data[element.id]!=null){
  74. if($(element).attr("type")=='checkbox' || $(element).attr("type")=='radio'){
  75. $(element).prop("checked",data[element.id]==1 || data[element.id]=='true' ?true:false);
  76. } else {
  77. $(element).val(data[element.id]);
  78. }
  79. }
  80. }
  81. });
  82. return o;
  83. }
  84. //Gestion des tableaux pour le formData
  85. $.form_data = function(formData, key,values){
  86. var hasFile = false;
  87. if(values instanceof File ) hasFile = true;
  88. if( typeof values == 'object' && !(values instanceof File) ){
  89. for(subkey in values)
  90. if($.form_data(formData,key + '[' + subkey + ']',values[subkey])) hasFile = true;
  91. }else{
  92. formData.append(key, values);
  93. }
  94. return hasFile;
  95. }
  96. $.action = function(data,success,error,progress) {
  97. var formData = new FormData();
  98. var defaultSuccess = data.defaultSuccess !== undefined ? data.defaultSuccess : true;
  99. // if(data.defaultSuccess !== undefined) delete data.defaultSuccess;
  100. //hasFile determine si un fichier uploadé se trouve dans le tableau des data
  101. // Si c'est le cas, il envois les données en multipart, sinon il les envoie en json classique.
  102. var hasFile = false;
  103. $.each(data, function(key, value){
  104. if($.form_data(formData,key, value) == true) hasFile = true;
  105. });
  106. var request = {
  107. url : 'action.php',
  108. method : 'POST',
  109. success: function(response){
  110. if(response && !response.error){
  111. if(success!=null)success(response);
  112. } else {
  113. var errorMessage = 'ERREUR : '+"\n"+response.error;
  114. if(response.trace) errorMessage += "\n<div style='font-size:10px;max-height:200px;overflow:auto;text-align:left;'>"+response.trace+"</div>";
  115. if(defaultSuccess) $.message('error',errorMessage,0);
  116. if(error!=null) error(response);
  117. }
  118. },
  119. error : function(response){
  120. if(response.status == 200 && $.localhost() ){
  121. $('body').append('<div class="debugFrame" style="box-shadow: 0px 0px 10px rgba(0,0,0,0.5);z-index: 10001;padding: 5px;position: fixed;left: 0;top: 0;width: 40%;min-height: 100%;border-right: 2px solid #ff3b00;background: rgba(210, 222, 255, 0.9);overflow-y: auto;height: 100%;"><h3>Action debug</h3> <i style="position:absolute; right:10px; top:10px;font-size:1.5em;" onclick="$(this).parent().remove()" class="fas fa-times pointer"></i>'+response.responseText+'</div>');
  122. } else {
  123. if(response.readyState == 0 && error==null) return;
  124. if(error!=null)
  125. error(response);
  126. else
  127. $.message('error','Erreur indefinie, merci de contacter un administrateur',0);
  128. }
  129. },
  130. xhr: function()
  131. {
  132. var xhr = new window.XMLHttpRequest();
  133. xhr.upload.addEventListener("progress", function(evt){
  134. if (evt.lengthComputable) {
  135. var percentComplete = (evt.loaded / evt.total) * 100;
  136. percentComplete = Math.round(percentComplete * 100) / 100;
  137. if(progress) progress(percentComplete,'upload');
  138. }
  139. }, false);
  140. xhr.addEventListener("progress", function(evt){
  141. if (evt.lengthComputable) {
  142. var percentComplete = evt.loaded / evt.total;
  143. if(progress) progress(percentComplete,'download');
  144. }
  145. }, false);
  146. return xhr;
  147. }
  148. };
  149. if(!hasFile){
  150. request.data = data;
  151. }else{
  152. request.data = formData;
  153. request.processData = false;
  154. request.contentType = false;
  155. }
  156. $.ajax(request);
  157. }
  158. $.localhost = function(){
  159. return (document.location.hostname=='127.0.0.1' || document.location.hostname=='localhost');
  160. }
  161. $.hashData = function(name){
  162. var page = window.location.hash.substring(1);
  163. page += "&"+window.location.search.substring(1);
  164. data = {};
  165. if(page!='' && page!= null){
  166. options = page.split('&');
  167. var data = {};
  168. for(var key in options){
  169. infos = options[key].split('=');
  170. data[infos[0]] = infos[1];
  171. }
  172. }
  173. if(name == null) return data;
  174. if(typeof name === "object"){
  175. data = name;
  176. hashstring = '';
  177. for(var key in data)
  178. hashstring+= "&"+key+"="+data[key];
  179. hashstring = hashstring.substring(1);
  180. window.location.hash = hashstring;
  181. return;
  182. }
  183. return typeof data[name] == "undefined" ? '':data[name];
  184. }
  185. $.urlParam = function (name,value) {
  186. var parameters = window.location.href.match(/[\\?&]([^&#]*)=([^&#]*)/g);
  187. var data = {};
  188. for (var key in parameters) {
  189. var couple = parameters[key].substring(1, parameters[key].length).split('=');
  190. data[couple[0]] = couple[1];
  191. }
  192. if(name == null) return data;
  193. if (value == null)
  194. return data[name] ? data[name] : null;
  195. if (value != false) data[name] = value;
  196. var url = '?';
  197. for (var key in data) {
  198. if (value == false && key == name) continue;
  199. url += key + '=' + data[key]+'&';
  200. }
  201. window.history.pushState('', document.title, url.substring(0, url.length-1));
  202. }
  203. $.fn.extend({
  204. toJson : function(){
  205. return $.getForm(this);
  206. },
  207. getForm : function(){
  208. var o = {};
  209. var obj = $(this);
  210. for(var key in obj.data()){
  211. if(key!="action" && key != "id") continue;
  212. o[key] = obj.attr('data-'+key);
  213. }
  214. $('input,select,textarea',obj).each(function(i,element){
  215. if(element.id!=null && element.id!=""){
  216. if($(element).attr("type")=='checkbox' || $(element).attr("type")=='radio'){
  217. o[element.id] = ($(element).is(':checked')?1:0);
  218. }else{
  219. o[element.id] = $(element).val();
  220. }
  221. }
  222. });
  223. return o;
  224. },
  225. upload: function (options) {
  226. //var options = $.extend(defaults, options);
  227. return this.each(function () {
  228. var o = options;
  229. var droppedFiles = false;
  230. var div = $(this);
  231. var data = div.data();
  232. data.html =!div.attr('data-label') ? '': div.attr('data-label');
  233. data.label = data.html;
  234. div.html('');
  235. var o = $.extend(o, data);
  236. if(o.readonly == false){
  237. var form = $('<form class="box" method="post" action="' + o.action + '" enctype="multipart/form-data"><input type="file" name="'+(o.fileName?o.fileName:div.attr('id'))+'[]" multiple /></form>');
  238. div.append(form);
  239. var input = form.find('input[type="file"]');
  240. var zone = $('<div>' + o.label + '</div>');
  241. div.append(zone);
  242. //test if dnd is enabled n browser
  243. var div = document.createElement('div');
  244. var dragAndDropEnabled = (('draggable' in div) || ('ondragstart' in div && 'ondrop' in div)) && 'FormData' in window && 'FileReader' in window;
  245. //set elements styles
  246. input.attr('style', "width: 0.1px;height: 0.1px;opacity: 0;overflow: hidden; position: absolute;z-index: -1");
  247. zone.css('cursor', "pointer");
  248. //set events
  249. zone
  250. .on('click', function (e) {
  251. form.find('input[type="file"]').trigger('click');
  252. e.preventDefault();
  253. e.stopPropagation();
  254. })
  255. .on('drag dragstart dragend dragover dragenter dragleave drop', function (e) {
  256. e.preventDefault();
  257. e.stopPropagation();
  258. })
  259. .on('dragover dragenter', function () {
  260. if (o.hover) form.addClass(o.hover);
  261. })
  262. .on('dragleave dragend drop', function () {
  263. if (o.hover) form.removeClass(o.hover);
  264. })
  265. .on('drop', function (e) {
  266. droppedFiles = e.originalEvent.dataTransfer.files;
  267. form.trigger('submit');
  268. });
  269. input.on('change', function (e) {
  270. form.trigger('submit');
  271. });
  272. form.on('submit', function (e) {
  273. if (o.start) o.start();
  274. if (dragAndDropEnabled) {
  275. e.preventDefault();
  276. var ajaxData = new FormData();
  277. if (droppedFiles) {
  278. $.each(droppedFiles, function (i, file) {
  279. var ext = file.name.split('.');
  280. ext = ext.pop();
  281. if(o.allowed && $.inArray(ext.toLowerCase(),o.allowed.split(','))===-1){
  282. $.message('error','Extension fichier '+ext+' non permise (autorisé:'+o.allowed+')',0);
  283. return;
  284. }
  285. if(o.size && file.size > o.size){
  286. $.message('error','Taille fichier '+file.size+' octets trop grande (autorisé:'+o.size+' octets)',0);
  287. return;
  288. }
  289. ajaxData.append(input.attr('name'), file);
  290. });
  291. }else{
  292. ajaxData = new FormData(form.get(0));
  293. for(var key in $('input',form).get(0).files){
  294. var file = $('input',form).get(0).files[key];
  295. if(file.name==null || typeof file !='object') continue;
  296. var ext = file.name.split('.');
  297. ext = ext.pop();
  298. if(o.allowed && $.inArray(ext.toLowerCase(),o.allowed.split(','))===-1){
  299. $.message('error','Extension fichier '+ext+' non permise (autorisé:'+o.allowed+')',0);
  300. $('input',form).val();
  301. return;
  302. }
  303. if(o.size && file.size > o.size){
  304. $.message('error','Taille fichier '+file.size+' octets trop grande (autorisé:'+o.size+' octets)',0);
  305. $('input',form).val();
  306. return;
  307. }
  308. }
  309. }
  310. if (o.addData){
  311. var addionalData = o.addData();
  312. for(var k in addionalData){
  313. ajaxData.append(k, addionalData[k]);
  314. }
  315. }
  316. droppedFiles = null;
  317. $.ajax({
  318. url: form.attr('action'),
  319. type: form.attr('method'),
  320. data: ajaxData,
  321. dataType: 'json',
  322. cache: false,
  323. contentType: false,
  324. processData: false,
  325. complete: function (data) {
  326. if (o.complete) o.complete(data.responseJSON);
  327. },
  328. success: function (data) {
  329. if (o.success) o.success(data);
  330. },
  331. error: function (data) {
  332. if (o.error) o.error(data);
  333. }
  334. });
  335. } else {
  336. var iframeName = 'uploadiframe' + new Date().getTime();
  337. iframe = $('<iframe name="' + iframeName + '" style="display: none;"></iframe>');
  338. $('body').append(iframe);
  339. form.attr('target', iframeName);
  340. iframe.one('load', function () {
  341. var data = JSON.parse(iframe.contents().find('body').text());
  342. if (!data.success) alert(data.error);
  343. form.removeAttr('target');
  344. iframe.remove();
  345. if (o.complete) o.complete();
  346. });
  347. }
  348. });
  349. }
  350. });
  351. },
  352. clear: function (){
  353. return this.each(function() {
  354. var obj = $(this);
  355. obj.find('input,select,textarea').val('');
  356. });
  357. },
  358. addLine: function (rows){
  359. return this.each(function() {
  360. var obj = $(this);
  361. var model = null;
  362. var container = null;
  363. if(obj.prop("tagName") == 'UL'){
  364. container = obj;
  365. model = container.find('li:first-child');
  366. container.find('li:visible').remove();
  367. }else if(obj.prop("tagName") == 'TABLE'){
  368. container = obj.find('tbody');
  369. model = container.find('tr:first-child');
  370. container.find('tr:visible').remove();
  371. }else{
  372. container = obj;
  373. childName = container.children().get(0).nodeName;
  374. model = container.find(childName+':first-child');
  375. container.find(childName+':visible:not(.nofill)').remove();
  376. }
  377. var tpl = model.get(0).outerHTML;
  378. //fix jquery backslahes break
  379. tpl = tpl.replace(/{{##/g,'{{/').replace(/{{\/(.*)}}=""/g,'{{/$1}}');
  380. //fix images url not found on template
  381. tpl = tpl.replace(/(<img\s[^>]*\s)(data-src)/g,'$1src');
  382. for(var key in rows){
  383. var line = $(Mustache.render(tpl,rows[key]));
  384. container.append(line);
  385. line.show();
  386. }
  387. });
  388. },
  389. fill: function (option,callback,progress){
  390. return this.each(function() {
  391. var obj = $(this);
  392. var model = null;
  393. var container = null;
  394. option = $.extend({showItems:true},option);
  395. var preloader = null;
  396. if(option.preloader){
  397. var preloader = $(option.preloader);
  398. preloader.css('position','absolute');
  399. preloader.css('left',(obj.offset().left+obj.width()/2)+'px');
  400. preloader.css('top',(obj.offset().top+30)+'px');
  401. $('body').append(preloader);
  402. }
  403. if(obj.prop("tagName") == 'UL'){
  404. container = obj;
  405. model = container.find('li:first-child');
  406. container.children('li:not(.hidden)').remove();
  407. } else if(obj.prop("tagName") == 'TABLE'){
  408. container = obj.find('tbody');
  409. model = container.find('tr:first-child');
  410. container.children('tr:visible').remove();
  411. } else if(obj.prop("tagName") == "SELECT"){
  412. container = obj;
  413. model = container.find('option[value*="{{"]');
  414. if(model.length==0) model = $('<option class="hidden" value="{{value}}">{{label}}</option>');
  415. container.find('option:not([value*="{{"])').remove();
  416. } else{
  417. container = obj;
  418. childName = container.children().get(0).nodeName;
  419. model = container.find(childName+':first-child');
  420. container.find(childName+':visible:not(.nofill)').remove();
  421. }
  422. var tpl = model.get(0).outerHTML;
  423. //fix jquery backslashes break
  424. tpl = tpl.replace(/{{##/g,'{{/').replace(/{{\/(.*)}}=""/g,'{{/$1}}');
  425. //fix images url not found on template
  426. tpl = tpl.replace(/(<img\s[^>]*\s?)(data-src)/g,'$1src');
  427. var pagination = obj.nextAll('.pagination').length ? obj.nextAll('.pagination') : obj.parent().nextAll('.pagination');
  428. if(pagination.length!=0) option.page = $('li.active',pagination).attr('data-value');
  429. tpl = tpl.replace(/(data-style)/g, 'style');
  430. $.action(option,function(r){
  431. for(var key in r.rows){
  432. var line = $(Mustache.render(tpl,r.rows[key]));
  433. container.append(line);
  434. if(option.showItems){
  435. line.show().removeClass('hidden');
  436. }
  437. }
  438. if(r.pagination){
  439. var template = pagination.find('li:not(:visible)').get(0).outerHTML;
  440. $('li:not(.hidden)',pagination).remove();
  441. for(i=0;i<r.pagination.pages;i++){
  442. var li = $(Mustache.render(template,{value:i,label:i+1}));
  443. li.removeClass('hidden');
  444. pagination.append(li);
  445. }
  446. pagination.find('li:not(.hidden)').eq(r.pagination.current).addClass('active');
  447. if(r.pagination.pages>1)
  448. pagination.find('.page-item:not(.hidden):first .page-link').css('border-radius','0.25rem 0 0 0.25rem');
  449. else
  450. pagination.find('.page-item:not(.hidden):first .page-link').css('border-radius','0.25rem 0.25rem 0.25rem 0.25rem');
  451. }
  452. if(preloader) preloader.remove();
  453. if(callback!=null)callback(r);
  454. },null,function(percent,type){
  455. if(progress) progress(percent,type);
  456. });
  457. });
  458. },
  459. filters: function (option){
  460. var obj = $(this);
  461. var box = obj.next('.filter-box');
  462. var formData = {
  463. keyword : $('.filter-keyword',box).val()
  464. };
  465. formData.advanced = [], formData.multiple = [], formData.custom = {};
  466. $('.filterRow:visible',box).each(function(i,row){
  467. var row = $(row);
  468. if(row.find('.filter-column').val()=='') return;
  469. var filter = {
  470. join : row.find('.filter-join').val(),
  471. column : row.find('.filter-column').val(),
  472. type : row.find('.filter-column option:selected').attr('data-filter-type'),
  473. operator : {},
  474. value : {}
  475. }
  476. if ($('.filter-value-block',row).length > 1) {
  477. $('.filter-value-block',row).each(function(j,block){
  478. var block = $(block);
  479. filter.operator[j] = block.find('.filter-operator').val();
  480. filter.value[j] = block.find('.filter-value').last().val();
  481. });
  482. formData.multiple.push(filter);
  483. } else {
  484. filter.operator = row.find('.filter-operator').val();
  485. values = row.find('.filter-value');
  486. if(values.length > 1){
  487. filter.value = [];
  488. for(var j=0; j<values.length; ++j){
  489. filter.value.push(values.eq(j).val());
  490. }
  491. values.eq(j).attr('data-custom') == 'true' ? formData.custom[filter.column] = filter : formData.advanced.push(filter);
  492. } else {
  493. filter.value = values.val();
  494. values.last().attr('data-custom') == 'true' ? formData.custom[filter.column] = filter : formData.advanced.push(filter);
  495. }
  496. }
  497. });
  498. return formData;
  499. },
  500. enter: function (option){
  501. return this.each(function() {
  502. var obj = $(this);
  503. obj.keydown(function(event){
  504. if(event.keyCode == 13){
  505. option();
  506. return false;
  507. }
  508. });
  509. });
  510. },
  511. sortable_table: function (option){
  512. if(option=='get'){
  513. var obj = $(this);
  514. var response = {};
  515. obj.find('thead th[data-sortable]').each(function(i,th){
  516. var th = $(th);
  517. if(th.attr('data-sort') && th.attr('data-sort')!=""){
  518. response = {
  519. sort : th.attr('data-sort'),
  520. sortable : th.attr('data-sortable')
  521. };
  522. }
  523. });
  524. return response;
  525. }
  526. return this.each(function() {
  527. var obj = $(this);
  528. obj.find('thead th[data-sortable]').click(function(){
  529. var th = $(this);
  530. var data = th.data();
  531. if(!data.sort || data.sort==''){
  532. data.sort = 'asc'
  533. }else if(data.sort == 'asc'){
  534. data.sort ='desc'
  535. }else{
  536. data.sort = '';
  537. }
  538. obj.find('thead th').removeClass('sort-asc').removeClass('sort-desc').removeAttr('data-sort');
  539. if(data.sort!='') th.addClass('sort-'+data.sort);
  540. th.attr('data-sort',data.sort);
  541. if(option.onSort) option.onSort();
  542. });
  543. });
  544. },
  545. autocomplete: function(o){
  546. return this.each(function() {
  547. var obj = $(this);
  548. obj.attr('autocomplete','off');
  549. var option = obj.data();
  550. option = $.extend(option,o);
  551. obj.typeahead({
  552. items: 5,
  553. minLength: 2,
  554. fitToElement: false,
  555. autoSelect : false,
  556. selectOnBlur : false,
  557. displayText : function(item){
  558. return (o.skin) ? o.skin(item) : item.name || item;
  559. },
  560. source: function(keyword, response){
  561. $.action({
  562. action: option.action,
  563. keyword: obj.val(),
  564. data: o.data
  565. },function(r){
  566. if(r.rows != null)
  567. response(r.rows);
  568. });
  569. },
  570. highlighter: function(item){
  571. if(o.highlight) {
  572. return o.highlight(item)
  573. }
  574. else {
  575. var query = this.query.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&')
  576. return item.replace(new RegExp('('+query+')', 'ig'), function($1, match){
  577. return '<strong>'+match+'</strong>';
  578. });
  579. }
  580. },
  581. matcher: function(r){
  582. if(obj.val() == r.name)
  583. if(o.onClick)
  584. o.onClick(r,obj);
  585. return '<div>'+r.name+'</div>';
  586. },
  587. afterSelect: function(item) {
  588. obj.data('selected',true);
  589. if(o.onClick) o.onClick(item,obj);
  590. obj.trigger("change");
  591. }
  592. }).blur(function(){
  593. if(o.onBlur) o.onBlur(obj);
  594. });
  595. obj.data('typeahead').next = function (event) {
  596. var active = this.$menu.find('.active').removeClass('active');
  597. var next = active.next();
  598. if (!next.length) {
  599. next = $(this.$menu.find($(this.options.item || this.theme.item).prop('tagName'))[0]);
  600. }
  601. while (next.hasClass('divider') || next.hasClass('dropdown-header')) {
  602. next = next.next();
  603. }
  604. next.addClass('active');
  605. var newVal = this.updater(next.data('value'));
  606. this.$element.val(newVal.name || newVal);
  607. };
  608. obj.data('typeahead').prev = function (event) {
  609. var active = this.$menu.find('.active').removeClass('active');
  610. var prev = active.prev();
  611. if (!prev.length){
  612. prev = this.$menu.find($(this.options.item || this.theme.item).prop('tagName')).last();
  613. }
  614. while (prev.hasClass('divider') || prev.hasClass('dropdown-header')) {
  615. prev = prev.prev();
  616. }
  617. prev.addClass('active');
  618. var newVal = this.updater(prev.data('value'));
  619. if (this.changeInputOnMove) this.$element.val(newVal.name || newVal);
  620. };
  621. });
  622. },
  623. location: function (options){
  624. return this.each(function() {
  625. try{
  626. //var options = $.extend({},options);
  627. var obj = $(this);
  628. obj.attr('autocomplete','off');
  629. var data = $('#algolia').data();
  630. var placesAutocomplete = places({
  631. appId: data.api,
  632. apiKey: data.key,
  633. container: obj.get(0)
  634. });
  635. placesAutocomplete.on('change', function(e) {
  636. var m = /[0-9]*/m.exec(e.suggestion.name)
  637. var infos = {
  638. latitude: e.suggestion.latlng.lat,
  639. longitude : e.suggestion.lng,
  640. types : e.suggestion.type,
  641. number : '',
  642. street : e.suggestion.name,
  643. city : e.suggestion.city,
  644. country : e.suggestion.country,
  645. code : e.suggestion.postcode,
  646. picture : '',
  647. map : ''
  648. };
  649. if(m && m.length > 0 ) infos.number = m[0] ;
  650. infos.address = (infos.street && infos.street.length && infos.number && infos.number.length) ? infos.number+' '+infos.street : (infos.street ? infos.street : '');
  651. if(options.select) options.select(infos);
  652. });
  653. }catch(e){
  654. console.warn('Composant Location en erreur, désactivé :'+e);
  655. }
  656. });
  657. },
  658. date: function (){
  659. return this.each(function() {
  660. var obj = $(this);
  661. obj.on('paste', function(e){
  662. is_valid_date(e.originalEvent.clipboardData.getData('Text')) ? obj.val("") : e.preventDefault();
  663. });
  664. obj.datepicker({
  665. dateFormat: "dd/mm/yy",
  666. dayNames: ["Dimanche", "Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi"],
  667. dayNamesMin: ["Di", "Lu", "Ma", "Me", "Je", "Ve", "Sa"],
  668. dayNamesShort: ["Dim", "Lun", "Mar", "Mer", "Jeu", "Ven", "Sam"],
  669. monthNames: ["Janvier","Février","Mars","Avril","Mai","Juin","Juillet","Aout","Septembre","Octobre","Novembre","Décembre"],
  670. monthNamesShort: ["Jan","Fév","Mars","Avr","Mai","Juin","Juil","Aout","Sept","Oct","Nov","Déc"],
  671. firstDay: 1,
  672. changeMonth: true,
  673. yearRange: "-100:+0",
  674. changeYear: true,
  675. onSelect: function(dateText, inst) {
  676. $(this).trigger("blur");
  677. }
  678. }).keypress(function(event){
  679. var length = $(this).val().length;
  680. if(length == 2 || length == 5) $(this).val($(this).val()+'/');
  681. }).blur(function(event){
  682. $(this).removeClass('border border-danger')
  683. if($(this).val()=='') return;
  684. var segments = $(this).val().split('/');
  685. if(segments.length!=3) return;
  686. if(segments[0] > 31 || segments[1] > 12) $(this).addClass('border border-danger');
  687. }).attr('maxlength','10');
  688. obj.attr("placeholder","jj/mm/aaaa");
  689. obj.attr('pattern',"[0-9/]{10}");
  690. obj.attr("title","Format jj/mm/aaaa");
  691. });
  692. },
  693. hour: function (){
  694. return this.each(function() {
  695. var obj = $(this);
  696. var step = obj.attr('data-step');
  697. obj.on('paste', function(e){
  698. is_valid_hour(e.originalEvent.clipboardData.getData('Text')) ? obj.val("") : e.preventDefault();
  699. });
  700. obj.timepicker({
  701. disableAlphaInput: true,
  702. timeFormat: 'H:i',
  703. scrollDefault: 'now',
  704. 'step': is_numeric(step) && step>0 ? obj.attr('data-step') : 1
  705. });
  706. obj.attr("placeholder","hh:mm");
  707. obj.attr('pattern',"[0-9:]{5}");
  708. obj.attr('title',"Format hh:mm");
  709. });
  710. },
  711. raiseNumber: function(from,to) {
  712. return this.each(function(){
  713. var obj = $(this);
  714. obj.text(from);
  715. var interval = 800 / (to - from);
  716. var interval = setInterval(function(){
  717. var number = parseFloat(obj.text());
  718. if(number>=to) {
  719. clearInterval(interval);
  720. return;
  721. }
  722. obj.text(number+1);
  723. },interval);
  724. });
  725. }
  726. });