1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710 |
- var isProcessing;
- //Permet aux composant de mutualiser leurs appels
- var componentQueue = {};
- const is_mobile = (function(a){
- var check = false;
- if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4)))
- check = true;
- return check;
- })(navigator.userAgent||navigator.vendor||window.opera);
- $(document).ready(function(){
- if($.urlParam('title')!=null){
- window.parent.document.title = decodeURI($.urlParam('title'));
- }
- var page = $.page();
- page = page == '' ? 'index' : page;
- var init = 'init_'+page;
- init = init.replace(/[^a-z_0-9]/g,'_');
- init_components();
- if($.urlParam('module')==null){
- if(window[init]!=null) window[init]($.urlParam());
- } else {
- var mod = $.urlParam('module').replace(/[^a-z_0-9]/g,'_');
- var init = 'init_plugin_'+mod;
- if(window[init]!=null) window[init]($.urlParam());
- }
- //SHOW HTTP ERROR/NOTICE
- if ($.urlParam('error') != null) {
- $.message('error', decodeURIComponent($.urlParam('error')), 0);
- $.urlParam('error', false);
- }
- if ($.urlParam('info') != null) {
- $.message('info', decodeURIComponent($.urlParam('info')));
- $.urlParam('info', false);
- }
- if ($.urlParam('success') != null) {
- $.message('success', decodeURIComponent($.urlParam('success')));
- $.urlParam('success', false);
- }
- //Icône menu mobile
- $('#mainMenu > button').on('click', function(e){
- $('.menu').toggleClass('open');
- });
- $('.navbar-toggler').on('click', function(e){
- if($(e.target).closest('#mainMenu').length) return;
- $('#navbarCollapse').collapse('hide');
- $('.menu').removeClass('open');
- });
- //Positionnement nom de l'utilisateur
- if($(document).width() <= 767){
- var userFullname = $('#loginHeader > .user-dropdown-menu .user-fullname').detach();
- $('#loginHeader > .user-dropdown-menu > button.dropdown-toggle').append(userFullname);
- }
- });
- //Changement positionnement nom de l'utilisateur
- //connecté au redimensionnement de la fenêtre
- $(window).resize(function(event) {
- if($(document).width() > 767){
- var userFullname = $('#loginHeader > .user-dropdown-menu > button.dropdown-toggle > .user-fullname').detach();
- $('#loginHeader > .user-dropdown-menu > .dropdown-menu').prepend(userFullname);
- }
- if($(document).width() <= 767){
- var userFullname = $('#loginHeader > .user-dropdown-menu .user-fullname').detach();
- $('#loginHeader > .user-dropdown-menu > button.dropdown-toggle').append(userFullname);
- }
- });
- /* COMPOSANT */
- function init_components(selector){
- var selected = selector ? $('[data-type]',selector) : '[data-type]';
- $(selected).each(function(i,input){
- var input = $(input);
- switch($(input).attr('data-type')){
- /**
- * data-format : Supporte les formats dd/mm/yyyy ou yyyy/mm/dd avec séparateur "/" ou "-"
- * data-begin : date de début de sélection par rapport à aujourd'hui(peut être en nb de jour, en objet Date ou en string de type dateFormat ou en date relative [+1m +7d]==>Début à 1 mois et 7 jours)
- * data-end : date de début de sélection par rapport à aujourd'hui(peut être en nb de jour, en objet Date ou en string de type dateFormat ou en date relative [+1m +7d]==>Début à 1 mois et 7 jours)
- */
- case 'date':
- //Les séparateurs doivent être similaires entre les éléments de la chaîne
- var dateFormatRegex = /^(dd|yy)([\/|-])(mm)\2(dd|yy)$/;
- var dateFormat = input.attr('data-format') != undefined && input.attr('data-format').match(dateFormatRegex) ? input.attr('data-format').match(dateFormatRegex)[0] : "dd/mm/yy";
- var begin = input.attr('data-begin');
- begin = (begin != undefined && (begin.match(/-?\d+/) || begin.match(/^(\d{2}(?:\d{2})?)\/(\d{2})\/(\d{2}(?:\d{2})?)$/))) ? begin : null ;
- var end = input.attr('data-end');
- end = (end != undefined && (end.match(/-?\d+/) || end.match(/^(\d{2}(?:\d{2})?)[-|\/](\d{2})[-|\/](\d{2}(?:\d{2})?)$/))) ? end : null ;
- input.date({
- placeholder: input.attr('placeholder') != undefined ? input.attr('placeholder') : "jj/mm/aaaa",
- dateFormat: dateFormat,
- beginDate: begin,
- endDate: end
- });
- break;
- /**
- * data-format : Supporte les formats dd/mm/yyyy ou yyyy/mm/dd avec séparateur "/" ou "-"
- * data-step : L'intervalle entre 2 valeurs en minutes
- */
- case 'hour':
- var timeFormatRegex = /^(H):(i)$/;
- var timeFormat = input.attr('data-format') != undefined && input.attr('data-format').match(timeFormatRegex) ? input.attr('data-format').match(timeFormatRegex)[0] : "H:i";
- var step = input.attr('data-step');
- input.hour({
- placeholder: input.attr('placeholder') != undefined ? input.attr('placeholder') : "hh:mm",
- timeFormat: timeFormat,
- step: is_numeric(step) && step>0 ? step : 1
- });
- break;
- case 'image':
- if(input.closest('.type-image-bloc').length!=0) break;
- input.wrap( "<div class='type-image-bloc'></div>");
- var src = ($(input).attr('value')!='') ? $(input).attr('value') : 'img/default-image.png';
-
- src += src.indexOf('?')!=-1 ? '&' : '?';
- src += 't='+(Math.random()*1000);
- var thumbnail = $('<img src="'+src+'" >');
- var deleteBtn = !input.attr('data-delete') ? '' : '<div class="btn btn-delete-img noPrint" onclick="'+input.attr('data-delete')+'"><i class="fas fa-times"></i></div>';
- input.before(thumbnail);
- if(thumbnail.attr('src').indexOf('default-') === -1) thumbnail.before(deleteBtn);
- input.addClass('noPrint');
- input.change(function(){
- var reader = new FileReader();
- reader.onload = function (e) {
- thumbnail.attr('src', e.target.result);
- thumbnail.before(deleteBtn);
- }
- reader.readAsDataURL(input.get(0).files[0]);
- });
- break;
- //Selection de tag liés a un dictionnary
- case 'tag-list':
- var container;
- var picker;
- var pickerLi;
-
- if(!input.data("data-component")){
- container = $('<div class="'+input.attr('class')+' data-type-tag-list"><ul><li class="tag-picker-li"><input type="text"></li></ul></div>');
- input.before(container);
- input.data("data-component", container);
- if(input.attr("required")) container.attr("required","");
- } else {
- container = input.data("data-component");
- }
- picker = container.find('input:eq(0)');
- pickerLi = container.find('ul li.tag-picker-li');
- container.find('.tag-picker-tag').remove();
- pickerLi.removeClass('hidden');
-
- var pickerFunctions = {
- //Récuperation des valeurs sélectionnées (objet et id) en fonction des tags visuels présents
- getValues : function( container){
- var tags = container.find('ul .tag-picker-tag');
- var values = {object:[],id:[]};
- tags.each(function(i,element){
- if($(element).attr('data-id') == '') return;
- var object = $(element).data();
- values['object'].push(object);
- values['id'].push(object.id);
- });
- return values;
- },
- //Ajout d'un tag visuel et mise à jour de l'input brut en fonction de l'objet fournis
- addTag : function( container,tag){
- pickerLi = container.find('ul li.tag-picker-li');
- if( container.find('li[data-id="'+tag.id+'"]').length>0) return;
- var tag = $('<li class="tag-picker-tag" data-slug="'+tag.slug+'" data-id="'+tag.id+'"><div>'+tag.name+'<i class="fa fa-times"></i></div></li>');
- pickerLi.before(tag);
- var values = pickerFunctions.getValues( container);
- input.val(values['id'].join(','));
- input.data('values',values['object']);
- if((values['id'].length) == 1 && input.attr('data-multiple') == null){
- pickerLi.addClass('hidden');
- }else{
- pickerLi.removeClass('hidden');
- }
- tag.find('i').click(function(){
- $(this).closest('.tag-picker-tag').remove();
- var values = pickerFunctions.getValues( container);
- input.val(values['id'].join(','));
- input.data('values',values['object']);
- if((values['id'].length-1) ==1 && input.attr('data-multiple') == null){
- pickerLi.addClass('hidden');
- }else{
- pickerLi.removeClass('hidden');
- }
- });
- }
- }
- //Gestion des champs déja remplis au chargement de la page
- if(input.val() !=''){
- var id = input.val();
- container.find('ul').append('<li class="tag-picker-loader"><i class="fas fa-spinner fa-pulse"></i> Chargement</li>');
- picker.addClass('hidden');
- $.action({
- action : 'tag_list_by_id',
- id : id
- },function(r){
- container.find('.tag-picker-loader').remove();
- picker.removeClass('hidden');
- for(var key in r.tags)
- pickerFunctions.addTag( container,r.tags[key]);
- });
- }
- //Sélectionne l'input d'auto-completion ou que l'on clique dans le composant
- container.find('ul').click(function(e){
- picker.focus();
- e.stopPropagation();
- });
- //Selectionne l'item dropdown actif lors de l'appuis sur entré
- picker.keyup(function(e){
- if(e.keyCode!=13 || input.is('[readonly]')) return;
- var active = $('.tag-picker-li .dropdown-menu .active');
- if(active.length==0) return;
- active.trigger('click');
- });
-
- //aucompletion sur le nom des tags
- picker.autocomplete({
- action : 'tag_list_autocomplete',
- suggest : true,
- items : input.attr('data-items'),
- data : {
- parent : input.attr('data-slug')
- },
- skin : function(item){
- var html = '';
- var re = new RegExp(picker.val(),"gi");
- name = item.name.replace(re, function (x) {
- return '<strong>'+x+'</strong>';
- });
- html += '<div class="tag-infos"><span>'+name+'</span>';
- html += '<div class="clear"></div>';
-
- return html;
- },
- highlight : function(item){
- return item;
- },
- onClick : function(selected,element){
- picker.val('');
- selected.label = selected.name;
- pickerFunctions.addTag(container,selected);
- input.trigger('click').trigger('change');
- },
- onBlur : function(selected){
- if(input.attr('data-force')!='false' && input.val() == '') picker.val('');
- }
- });
- break;
-
- //composant permettant les listes sous
- //form de dropdown avec icones et couleurs
- case 'dropdown-select':
- if(!input.is(':visible')) return;
-
- var container;
- if(!input.data("data-component")){
- container = $('<div class="'+input.attr('class')+' btn-group data-type-dropdown-select"> \
- <button title="'+input.attr('title')+'" type="button" class="btn btn-small btn-secondary border-0 dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"></button> \
- <div class="dropdown-menu w-100 text-center"></div> \
- </div>');
- input.before(container);
- input.data("data-component", container);
- if(input.attr("required")) container.attr("required","");
- var html = '';
- input.find('option').each(function(i,element){
- var option = $(element);
- icon = option.attr("data-icon") ? '<i class="'+option.attr("data-icon")+'"></i> ': '';
- html+='<a class="dropdown-item pointer" data-value="'+option.val()+'" style="'+option.attr("style")+'" >'+icon+option.html()+'</a>';
- });
- container.find('.dropdown-menu').append(html);
- $('.dropdown-menu a',container).click(function(){
- if(input.attr("readonly") == 'readonly') return;
- var item = $(this);
- $('.dropdown-menu a',container).removeClass('active');
- //Utilisation background-color pour fonctionner sous FF
- container.find('.dropdown-toggle').html(item.html()).css('background-color',item.css('background-color'));
- item.addClass('active');
- input.val(item.attr('data-value')).trigger('change');
- });
- } else {
- container = input.data("data-component");
- }
- input.addClass('hidden');
-
- var state = input.attr('data-value') != null ? input.attr('data-value') : input.val();
- if(state == '') return;
- var item = $('.dropdown-menu a[data-value="'+state+'"]', container);
- //Utilisation background-color pour fonctionner sous FF
- container.find('.dropdown-toggle').html(item.html()).css('background-color',item.css('background-color'));
- item.addClass('active');
- input.val(item.attr('data-value')).trigger('change');
- break;
- case 'user':
- var userContainer;
- var userPicker;
- var pickerLi;
- if(!input.data("data-component")){
- userContainer = $('<div class="'+input.attr('class')+' data-type-user"><ul><li class="user-picker-li"><input type="text" '+(input.attr('placeholder')!==undefined?'placeholder="'+input.attr('placeholder'):'')+'"></li></ul></div>');
- input.before(userContainer);
- input.data("data-component", userContainer);
- if(input.attr("required")) userContainer.attr("required","");
- if(input.attr("disabled")) userContainer.attr("disabled","");
- } else {
- userContainer = input.data("data-component");
- }
- userPicker = userContainer.find('input:eq(0)');
- pickerLi = userContainer.find('ul li.user-picker-li');
- userContainer.find('.user-picker-tag').remove();
- pickerLi.removeClass('hidden');
- var pickerFunctions = {
- //Récuperation des valeurs sélectionnées (objet et uid) en fonction des tags visuels présents
- getValues : function(userContainer){
- var tags = userContainer.find('ul .user-picker-tag');
- var values = {object:[],uid:[]};
- tags.each(function(i,element){
- if($(element).attr('data-uid') == '') return;
- var object = $(element).data();
- values['object'].push(object);
- values['uid'].push(object.uid);
- });
- return values;
- },
- //Ajout d'un tag visuel et mise à jour de l'input brut en fonction de l'objet user fournis
- addTag : function(userContainer,user){
- pickerLi = userContainer.find('ul li.user-picker-li');
- if(userContainer.find('li[data-uid="'+user.uid+'"]').length>0) return;
- var closeBtn = userContainer.attr('disabled') || userContainer.attr('readonly') ? '' : '<i class="fa fa-times"></i>';
- var tag = $('<li class="user-picker-tag" data-entity="'+user.type+'" data-fullname="'+user.fullname+'" data-uid="'+user.uid+'"><div title="'+(user.type=='rank'?'Rang':'Utilisateur')+'">'+user.fullname+closeBtn+'</div></li>');
- pickerLi.before(tag);
- var values = pickerFunctions.getValues(userContainer);
- input.val(values['uid'].join(','));
- input.data('values',values['object']);
- if((values['uid'].length) == 1 && input.attr('data-multiple') == null){
- pickerLi.addClass('hidden');
- }else{
- pickerLi.removeClass('hidden');
- }
- tag.find('i').click(function(){
- if(userContainer.attr('disabled') || userContainer.attr('readonly')) return;
- $(this).closest('.user-picker-tag').remove();
- var values = pickerFunctions.getValues(userContainer);
- input.val(values['uid'].join(','));
- input.data('values',values['object']);
- if((values['uid'].length-1) ==1 && input.attr('data-multiple') == null){
- pickerLi.addClass('hidden');
- }else{
- pickerLi.removeClass('hidden');
- }
- });
- if(userContainer.find('ul li.user-picker-tag'))
- userContainer.find('ul li.user-picker-li input').removeAttr('placeholder');
- }
- }
- //Gestion des champs déja remplis au chargement de la page
- if(input.val() !=''){
- var uid = input.val();
- if(!window.componentQueue.user) window.componentQueue.user = {timeout : null,components : [],uids :{} };
- clearTimeout(window.componentQueue.user.timeout);
- var uids = uid.split(',');
- for(var k in uids){
- window.componentQueue.user.uids[uids[k]] = 1;
- }
- window.componentQueue.user.components.push({
- input : input,
- picker : userPicker,
- container : userContainer,
- values : uids
- });
- userContainer.find('ul').append('<li class="user-picker-loader"><i class="fas fa-spinner fa-pulse"></i> Chargement</li>');
- userPicker.addClass('hidden');
- window.componentQueue.user.timeout = setTimeout(function(){
- $.action({
- action : 'user_by_uid',
- uids : Object.keys(window.componentQueue.user.uids)
- },function(r){
- for(var key in window.componentQueue.user.components){
- var component = window.componentQueue.user.components[key];
- component.container.find('.user-picker-loader').remove();
- component.picker.removeClass('hidden');
-
- for(var i in component.values){
- var value = component.values[i];
- if(!r.users[value]) continue;
- pickerFunctions.addTag(component.container,r.users[value]);
- }
- }
- delete window.componentQueue.user;
- });
- },50);
- // var login = input.val();
- // userContainer.find('ul').append('<li class="user-picker-loader"><i class="fas fa-spinner fa-pulse"></i> Chargement</li>');
- // userPicker.addClass('hidden');
- // $.action({
- // action : 'user_by_uid',
- // login : login
- // },function(r){
- // userContainer.find('.user-picker-loader').remove();
- // userPicker.removeClass('hidden');
- // for(var key in r.users)
- // pickerFunctions.addTag(userContainer,r.users[key]);
- // });
- }
- //Sélectionne l'input d'auto-completion ou que l'on clique dans le composant
- userContainer.find('ul').click(function(e){
- if(input.attr("readonly") == "readonly") return;
- userPicker.focus();
- e.stopPropagation();
- });
- //Selectionne l'item dropdown actif lors de l'appui sur entrée
- userPicker.keyup(function(e){
- if(e.keyCode!=13 || input.is('[readonly]')) return;
- if(input.attr("readonly") == "readonly") return;
- var active = $('.user-picker-li .dropdown-menu .active');
- if(active.length==0) return;
- active.trigger('click').trigger('change');
- });
- var types = ['user'];
- if(input.data('types') && input.data('types')!='')
- types = input.data('types').split(',');
- //aucompletion sur le nom des users / rangs
- userPicker.autocomplete({
- action : 'user_autocomplete',
- data : {
- types : types
- },
- skin : function(item){
- var html = '';
- var re = new RegExp(userPicker.val(),"gi");
- name = item.name.replace(re, function (x) {
- return '<strong>'+x+'</strong>';
- });
- if(item.type=='user'){
- if(item.avatar) html += '<div class="user-logo"><img src="'+item.avatar+'" class="avatar-mini avatar-rounded"></div>';
- html += '<div class="user-infos"><span>'+name+'</span> <small class="text-muted">- Utilisateur (@'+item.id+')</small>';
- html += item.function ? '<br/><small>'+item.function+'</small></div>' : '</div>';
- html += '<div class="clear"></div>';
- }else{
- html += '<div class="rank-logo"><i class="far fa-address-card"></i></div>';
- html += '<div class="rank-infos"><span>'+name+'</span> <small class="text-muted">- Rang</small>';
- html += item.description ? '<br/><small>'+item.description+'</small></div>' : '</div>';
- html += '<div class="clear"></div>';
- }
-
- return html;
- },
- highlight : function(item){
- return item;
- },
- onClick : function(selected,element){
- userPicker.val('');
- selected.fullname = selected.name;
- selected.uid = selected.id;
-
- pickerFunctions.addTag(userContainer,selected);
- input.trigger('click').trigger('change');
- },
- onBlur : function(selected){
- if(input.attr('data-force')!='false' && input.val() == '') userPicker.val('');
- }
- });
- break;
- /**
- * data-labels : tableau des libellés entre double quotes eg : ["Libellé 1","Libellé 2"]
- * data-values : taleau des valeurs eg : [12,13]
- * data-colors : taleau des couleurs entre double quotes eg : ["#cecece","#222222"]
- */
- case 'doughnut':
- var data = input.data();
- var myChart = new Chart(input.get(0).getContext('2d'), {
- type: 'doughnut',
- data: {
- labels: data.labels,
- datasets: [{
- data: data.values,
- backgroundColor: data.colors
- }]
- },
- options: {
- cutoutPercentage:80
- }
- });
- break;
- /**
- * data-labels : tableau des libellés entre double quotes eg : ["Libellé1","Libellé 2"]
- * data-values : taleau des valeurs eg : [12,13]
- * data-colors : taleau des couleurs entre double quotes eg : ["#cecece","#222222"]
- */
- case 'bar':
- var data = input.data();
- var myChart = new Chart(input.get(0).getContext('2d'), {
- type: 'bar',
- data: {
- labels: data.labels,
- datasets: [{
- label : input.html(),
- data: data.values,
- backgroundColor: data.colors
- }]
- },
- options: {
- scales: {
- yAxes: [{
- ticks: {
- beginAtZero:true
- }
- }]
- },
- legend: {
- display: false
- }
- }
- });
- break;
- /**
- * data-labels : tableau des libellés entre double quotes eg : ["Libellé1","Libellé 2"]
- * data-values : taleau des valeurs eg : [12,13]
- * data-color : couleurs eg : #cecece
- */
- case 'line':
- var data = input.data();
- var myChart = new Chart(input.get(0).getContext('2d'), {
- type: 'line',
-
- data: {
- labels: data.labels,
- datasets: [{
- label : input.html(),
- data: data.values,
- borderColor: [data.color]
- }]
- },
- options: {
- scales: {
- yAxes: [{
- ticks: {
- beginAtZero:true
- }
- }]
- }
- }
- });
- break;
- /**
- * data-input-city : le champ d'id "#votre-id" à remplir avec la ville
- * data-input-latitude : le champ d'id "#votre-id" à remplir avec la latitude
- * data-input-longitude : le champ d'id "#votre-id" à remplir avec la longitude
- * data-input-country : le champ d'id "#votre-id" à remplir avec le pays
- * data-input-code : le champ d'id "#votre-id" à remplir avec le code postal
- * data-input-street : le champ d'id "#votre-id" à remplir avec la rue
- * data-input-number : le champ d'id "#votre-id" à remplir avec le n°
- */
- case 'location':
- input.location({
- select :function(location){
- var attributes = {};
- for(var key in location){
- attributes['data-'+key] = location[key];
- if(input.attr('data-input-'+key)!='') $(input.attr('data-input-'+key)).val(location[key]).text(location[key]);
- }
- input.attr(attributes);
- }
- });
- break;
- /**
- * data-depth : nb de profondeur de liste (ex: 2, affichera 2 select au maximum), 1 par défaut
- * data-slug : le slug de la liste mère à afficher, listes primaires par défaut
- * data-value : la valeur de l'entité à récup en base
- * data-disable-label : cache le label de sous-liste si mentionné
- * data-hierarchy : si mentionné à false, ne récupère pas
- * data-parent-id : l'id de la liste parente associée
- */
- case 'dictionnary':
- var slug = input.attr('data-slug') ? input.attr('data-slug') : "";
- var parentId = input.attr('data-parent-id') && input.attr('data-parent-id').length ? input.attr('data-parent-id') : "";
- if (!slug.match(/^[a-z\d\-_]+$/i) && parentId == '') return;
- $.action({
- action : 'load_dictionnary_component',
- slug: slug,
- parentId : parentId,
- hierarchy : input.attr('data-hierarchy') == 'false' ? 0 : 1,
- value: input.attr('data-value')
- },function(r){
- var children = r.content.childs ? r.content.childs : r.content;
- input.attr('onchange', 'get_sub_dictionnary(this, "'+input.attr('name')+'",'+1+');');
- input.append('<option value=""> - </option>');
- $.each(children, function (index, value){
- if (value.selected) {
- input.append('<option value="'+value.id+'" data-parent="'+value.parent+'" data-sublabel="'+value.sublistlabel+'" selected>'+value.label+'</option>');
- get_selected_values(input, value);
- }
- else
- input.append('<option value="'+value.id+'" data-parent="'+value.parent+'" data-sublabel="'+value.sublistlabel+'">'+value.label+'</option>');
- });
- });
- break;
- /**
- * data-label : le label affiché dans la zone
- * data-delete : méthode de suppression de doc de l'entité
- * data-save : méthode de sauvegarde de doc de l'entité (si mentionné, save automatique)
- * data-readonly: Empeche l'ajout/suppression de documents
- * data-allowed : les extensions de fichier acceptées
- */
- case 'dropzone':
- if(input.find('form').length != 0 || input.find('ul>li').length) break;
- if(!input.attr('data-action')) input.attr('data-action','action.php?action=upload_temporary_file');
- var readonly = input.attr('data-readonly') == "true" ? true : false;
- if(!input.get(0).hasAttribute('id')) input.attr('id',generate_uuid(10));
- var customTpl = input.find('> *:not(:visible)');
- var customActions = '';
- if(customTpl && customTpl.length){
- $.each(customTpl, function(i, action){
- if(i>2) return;
- var valCalc = readonly ? i*28+3 : i*28+25;
- customActions += $(action).removeClass('hidden').css('right', valCalc).get(0).outerHTML;
- });
- }
- var preview = '<li data-path="{{path}}">';
- preview += input.get(0).hasAttribute('data-preview') ? '<img style="margin: 0 5px;float: left;max-height:100px;max-width:80px;" src="{{url}}"/>' : '<i class="fa {{icon}}"></i>';
- preview += ' <a {{#url}}href="{{url}}"{{/url}} target="_blank" title="{{name}}">{{name}}{{lastModification}}</a> '+customActions+' <i class="fas fa-times pointer '+(input.attr('data-delete')?'':'hidden')+'" onclick="{{#temporary}}dropzone_delete_file(this);{{/temporary}}{{^temporary}}'+input.attr('data-delete')+'(this){{/temporary}}"></i><div class="clear"></div></li>';
- var valueFiles = input.html()!='' && is_json_string(input.text()) ? JSON.parse(input.text()) : [];
- input.html('');
- var allowed = input.attr('data-allowed');
- if(allowed) allowed = allowed.split(',');
- var save = input.attr('data-save');
- var size = input.attr('data-max-size');
- input.upload({
- allowed : allowed,
- size : size == '' ? 0 : size,
- readonly: readonly,
- start: function(){
- preload.removeClass('hidden');
- },
- success: function(response){
- if(response.previews.length && response.previews[0].name) {
- var inputTemp = $('#'+input.attr('id')+'_temporary');
- var currVal = inputTemp.val().length ? JSON.parse(inputTemp.val()) : [];
- for(var i in response.previews){
- files.append(Mustache.render(preview,response.previews[i]));
- currVal.push(response.previews[i]);
- }
- inputTemp.val(JSON.stringify(currVal));
- if(save)
- window[save](response.previews);
- }
- preload.addClass('hidden');
- },
- complete: function(){
- preload.addClass('hidden');
- }
- });
- var preload = $('<div class="preload progress-bar progress-bar-striped progress-bar-animated"></div>');
- input.append(preload);
- var files = $('<ul></ul>');
- input.append(files);
- var filesValues = $('<input type="hidden" name="'+input.attr('id')+'_temporary" id="'+input.attr('id')+'_temporary">');
- input.append(filesValues);
- for(var i in valueFiles) {
- files.append(Mustache.render(preview,valueFiles[i]));
- if(readonly) files.find('li > i.fa-times').remove();
- }
- if(!valueFiles.length && readonly)
- input.append('<div>Aucun document</div>');
- break;
- /**
- * data-simple : Si "true" alors interface avec moins de boutons
- */
- case 'wysiwyg':
- var buttons = [
- ['strong', 'em', 'underline','del'],
- ['foreColor', 'backColor'],
- ['undo', 'redo'], // Only supported in Blink browsers
- ['formatting'],
- ['superscript', 'subscript'],
- ['link'],
- ['insertImage'],
- ['table'],
- ['justifyLeft', 'justifyCenter', 'justifyRight', 'justifyFull'],
- ['unorderedList', 'orderedList'],
- ['horizontalRule'],
- ['removeformat'],
- ['fullscreen'],
- ['viewHTML']
- ]
- if(input.attr('data-simple') == 'true'){
- buttons = [
- ['strong', 'em', 'underline','del'],
- ['foreColor', 'backColor'],
- ['undo', 'redo'], // Only supported in Blink browsers
- ['formatting'],
- ['link'],
- ['unorderedList', 'orderedList'],
- ['insertImage']
- ]
- }
- var defaultOptions = {
- btns: buttons,
- lang: 'fr',
- autogrow: true,
- semantic: false
- };
- var data = input.data();
- var options = $.extend(defaultOptions,data);
- input.trumbowyg(options);
- if(input.attr('required')) $(input).closest('div.trumbowyg-box').attr('required', true);
- break;
- /**
- * data-join : Spécifie la liaison par défaut des filtres (and | or) si rien n'est spéficié ou que l'attrbute n'existe pas,
- * un select apparait pour que l'utilisateur puisse choisir,
- * data-slug : Si spécifié, la recherche devient enregistrable pour une réutilisation ultérieure,
- * data-only-advanced : Si l'attribut est présent, cache la recherche simple et ouvre par defaut la recherche avancée
- * data-autosearch (default: true) : si définit a false, ne lancera pas la fonction data-function automatiquement en fin de chargement du composant
- */
- case 'filter':
- if(input.next('.filter-box:visible').length!=0) break;
- input.addClass('hidden');
- var data = input.data();
- var box = $('.filter-box:not(:visible)').clone();
- input.after(box);
- box.removeClass('hidden');
- if($('option',input).length == 0)
- box.find('.advanced-button-search').addClass('hidden');
- box.attr('data-join',data.join);
- if(data.join!='' && data.join!=null)
- box.find('.filter-join').addClass('hidden');
- var options = '<option value=""> - Choix filtre - </option>';
- $('option',input).each(function(i,element){
- options += element.outerHTML;
- });
- $('.filter-column').append(options);
- box.on('keyup', '.filter-value, .filter-keyword', function(event){
- if(event.keyCode == 13) filter_search();
- });
-
- if(data.onlyAdvanced!=null){
- $('.simple-search').addClass('hidden');
- box.find('.advanced-search').removeClass('hidden');
- }
- if(data.onlyAdvanced==null && $('option',input).length != 0)
- $('.simple-search div.btn.filter-button-search:visible').html('<i class="fas fa-search"></i>');
- var filters = $.urlParam('filters');
- if(data.slug && data.slug!=''){
- box.find('.advanced-search-save').removeClass('hidden');
- box.find('.advanced-search-action-separator').removeClass('hidden');
-
- //On ne charge les filtres enregistrés que si pas de filtres dans la barre d'adresse (la barre d'adresse prévaut)
- if(!filters|| filters==''){
- $.action({
- action : 'filter_load',
- slug : data.slug,
- },function(response){
- if(response.filters.advanced && response.filters.advanced.length > 0) {
- box.find('.advanced-search').removeClass('hidden');
- for(var i=response.filters.advanced.length-1; i!=-1; i--){
- var filter = response.filters.advanced[i];
- filter_add(box.find('.filterRow:visible:eq(0)'),filter);
- }
- }
- if(response.filters.custom && !is_empty_obj(response.filters.custom)) {
- box.find('.advanced-search').removeClass('hidden');
- for(var key in response.filters.custom){
- var filter = response.filters.custom[key];
- filter_add(box.find('.filterRow:visible:eq(0)'),filter);
- }
- }
- box.find('.filterRow:visible:eq(0)').remove();
- //Problème:
- //Quand on load une recherche enregistrée avec un
- //composant de type dictionnary, le autosearch qui lance
- //la fonction de recherche n'attend pas que l'intégralité
- //des filtres soient settés et chargés et donc il manque
- //une info lors de la recherche
- //--> besoin d'un timeout ?
- if(data.function && (!data.hasOwnProperty('autosearch') || data.autosearch==true))
- // setTimeout(function(){window[data.function]();}, 500);
- window[data.function]();
- });
- }
- }
- if(filters && filters!=''){
- filters = JSON.parse(atob(filters));
- input.filters(filters);
-
- if(filters.advanced && filters.advanced.length>0){
- box.find('.advanced-search').removeClass('hidden');
- box.find('.filterRow:visible:eq(0)').remove();
- }
- }
- break;
- /**
- * data-toggle-event : Pour le moment, que "hover", de base au click
- * data-show-strength: Si indiqué, affiche la barre de force du mot de passe renseigné dans l'input
- * data-generator : Si indiqué, affiche une icône pour géénrer un mdp sécurisé
- */
- case 'password':
- if(input.closest('.password-field').length) return;
- input.attr('type', 'password');
- input.wrap(function() {return '<div class="password-field"></div>';});
- var container = input.parent('.password-field');
- container.append('<i class="fas fa-eye-slash noPrint password-toggler"></i>');
- container.find('i.password-toggler').attr((input.attr('data-toggle-event') == 'hover')?{
- 'onmouseover': 'toggle_password(this);',
- 'onmouseleave': 'toggle_password(this);'
- }:{'onclick': 'toggle_password(this);'});
- if(input.attr('data-generator') !== undefined) {
- container.append('<i class="fas fa-shield-alt noPrint password-generator"></i>')
- container.find('i.password-generator').on('click', function(){
- if(input.val()!='' && !confirm('Attention, un mot de passe est déjà défini.\nVoulez-vous quand même en générer un nouveau ?')) return;
- //regex norme ANSSI
- var strong = new RegExp('^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[=/\()%ยง!@#$%^&*])(?=.{12,})');
- do {
- password = generate_password();
- } while(!strong.test(password))
-
- input.val(password);
- if(input.attr('data-show-strength') !== undefined)
- check_password_strength(input);
- });
- function generate_password(){
- var password = "";
- var charset = get_characters_set();
- var length = Math.ceil(parseFloat(78) * Math.log(2) / Math.log(charset.length));
- for (var i=0; i<length; ++i)
- password += charset[get_random_int(charset.length)];
- return password;
- }
- }
- if(input.attr('data-show-strength') !== undefined) {
- input.parent('.password-field').append('<div class="strength-lines"><div class="line"></div><div class="line"></div><div class="line"></div></div>');
- // check_password_strength($('input[data-type="password"][data-show-strength]'));
-
- // Strength validation on keyup-event
- input.on("keyup mouseup", function(e) {
- check_password_strength($(this));
- });
- //Check password strength
- function check_password_strength(input) {
- var value = $(input).val();
- var container = $(input).closest('.password-field');
- $(".line", container).removeClass("strength-low strength-medium strength-hard").addClass("strength-transparent");
- if(!value.length) return;
- var strongRegex = new RegExp('^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[=/\()%ยง!@#$%^&*])(?=.{12,})'),
- mediumRegex = new RegExp('^(((?=.*[a-z])(?=.*[A-Z]))|((?=.*[a-z])(?=.*[0-9]))|((?=.*[A-Z])(?=.*[0-9])))(?=.{6,})');
- if(strongRegex.test(value)) {
- $(".line", container).removeClass("strength-transparent").addClass("strength-hard");
- } else if (mediumRegex.test(value)) {
- $(".line:not(:last-of-type)", container).removeClass("strength-transparent").addClass("strength-medium");
- } else {
- $(".line:nth-child(1)", container).removeClass("strength-transparent").addClass("strength-low");
- }
- }
- }
- break;
- case 'icon':
- input.addClass('hidden');
- input.next('.component-icon').remove();
-
- var data = {
- value : input.val(),
- choices : []
- };
-
- var icons = $.fontAwesome();
- var line = [];
- for(var key in icons){
- if(line.length==15){
- data.choices.push(line);
- line = [];
- }
- line.push(icons[key].icon);
- }
- var selector = $(Mustache.render($('.component-icon.hidden').get(0).outerHTML,data));
- selector.removeClass('hidden');
- input.after(selector);
- selector.on('show.bs.dropdown', function () {
- setTimeout(function(){selector.find('input.form-control').focus();},0);
- })
- selector.find('.dropdown-icon-item').click(function(){
- selector.find('.dropdown-icon-item').removeClass('hidden');
- selector.find('input.form-control').val('');
- var icon = $(this).attr('data-icon');
- input.val(icon);
- selector.find('.dropdown-toggle i').attr('class',icon);
- input.trigger('change');
- });
- selector.find('input.form-control').keyup(function(){
- var value = $(this).val();
- $('.dropdown-icon-item i',selector).each(function(i,iconElement){
- iconElement = $(iconElement);
- parent = iconElement.parent();
- iconElement.attr('class').indexOf(value)!=-1 ? parent.removeClass('hidden') : parent.addClass('hidden');
- });
- /*var icon = $(this).attr('data-icon');
- input.val(icon);
- selector.find('.dropdown-toggle i').attr('class',icon);*/
- });
- break;
- break;
- /**
- * data-title (*) : Le titre du modal
- * data-warning : Message affiché dans le tooltip au survol
- * data-loaded (*): fonction callback appelée auprès le chargement du modal (bien pour setter des actions custom sur les boutons dans le modal par exemple)
- * data-params : Les paramètres utilisés pour l'appel du callback
- * data-url (*) : L'URL vers le contenu du modal qui sera ajouté au modal préexistant dans le footer
- * data-precall : fonction appelée avant le chargement du modal (méthode de check sur l'UI par exemple)
- * Pour customiser l'icône du quickform, il suffit de placer le contenu que l'on veut dans la div de data-type="quickform"
- */
- case 'quickform':
- if(input.find('span').length) return;
- if(input.attr('disabled')) return;
- var qfUrl = input.attr('data-url');
- var cbLoaded = input.attr('data-loaded');
- var preCb = input.attr('data-precall') ? input.attr('data-precall') : '';
- var warningMsg = input.attr('data-warning') ? input.attr('data-warning') : '';
- var icon = !input.find('i').length ? $('<i class="fas fa-plus-square"></i>') : input.find('i').detach();
- var checker = '<span class="tooltip-warning" title="'+warningMsg+'">'+icon.get(0).outerHTML+input.html()+'</span>';
- input.html(checker);
- var title = input.attr('data-title');
- var params = input.attr('data-params') ? input.attr('data-params').split(',') : [];
- $(document).ready(function(e){
- if(warningMsg.length)
- $('span.tooltip-warning').tooltip({
- track: true,
- tooltipClass: 'quickform-tooltip',
- });
- input.on('click', function(e){
- if(preCb.length && !window[preCb]()) return;
- $.ajax({
- type: 'GET',
- url: qfUrl,
- async: true,
- success : function(modal){
- $('#quickform-modal-label').text(title);
- $('.quickform-modal .modal-footer > div:first-of-type').nextAll().remove();
- }
- }).done(function(modalBody){
- var modal = $('.quickform-modal');
- var qfBody = $('.modal-body', modal)
- qfBody.html('').append(modalBody);
- reset_quickform_modal();
- if(cbLoaded) window[cbLoaded].apply(null,params);
- modal.modal('show');
- init_components($('#quickform-modal'));
- });
- });
- });
- break;
- /**
- * data-class : Classe custom à ajouter au conteneur du l'input
- */
- case 'checkbox':
- //3 cas possibles :
- // - input sans rien, data-type="checkbox" --> on fait tout
- // - input avec coquille sans data-uuid, --> on génère simplement un data-uuid et maj valeur
- // - input avec coquille et data-uuid --> on maj simplement sa valeur
-
- if(input.get(0).hasAttribute('data-uuid')) return;
- if(input.attr('type') != 'checkbox') input.attr('type', 'checkbox');
- if(!input.closest('label.check-component').length) {
- var labelBox = $('<label class="check-component"></label>');
- var checkbox = $('<div class="box"></div>');
- var id = input.attr('id');
- var title = input.attr('title');
- var customClass = input.attr('data-class');
- if(id) labelBox.attr('for', id);
- if(title) labelBox.attr('title', title);
- if(customClass) labelBox.addClass(customClass);
- if(input.prop('disabled') == true) labelBox.attr('disabled', true);
- input.removeAttr('title data-class').wrap(labelBox);
- input.after(checkbox);
- }
- var uuid = generate_uuid(15);
- input.attr('data-uuid', uuid);
- if(input.get(0).hasAttribute('id')) return;
- input.closest('label.check-component').off('click','div.box').on('click','div.box',function(e){
- var checkboxInput = $('input[data-uuid="'+uuid+'"]');
- checkboxInput.prop('checked', checkboxInput.prop('checked'));
- });
- break;
- /**
- * data-label : Libellé affiché à côté de l'input radio
- * name (*) : Le nom du groupe dont fait partie l'input radio
- */
- case 'radio':
- if(input.get(0).hasAttribute('data-uuid')) return;
- if(input.attr('type') != 'radio') input.attr('type', 'radio');
- var uuid = generate_uuid(15);
- var id = input.get(0).hasAttribute('id')? input.attr('id') : '';
- var title = input.get(0).hasAttribute('title') ? input.attr('title') : '';
- var label = input.attr('data-label');
- var labelBox = $('<label data-uid="'+uuid+'"></label>');
- labelBox.attr({
- 'for': id,
- 'title': title
- });
- if(input.prop('disabled') == true) labelBox.attr('disabled', true);
- input.addClass('radio-component').removeAttr('title data-label').attr('data-uuid', uuid);
- input.after(labelBox);
- if(label) labelBox.after('<label for="'+id+'">'+label+'</label>');
- if(input.attr('id') && input.attr('id').length) return;
- labelBox.click(function(e){
- var radioInput = $('input[data-uuid="'+uuid+'"]');
- if(radioInput.prop('disabled') != true) radioInput.prop('checked', true);
- });
- break;
- /**
- * data-action : l'action php pour récupérer l'UI de la card
- * data-parameters : paramètres à passer avec l'action json encodés
- */
- case 'card':
- if(!input.is(':visible')) return;
- var action = input.attr('data-action');
- if(!action) {
- console.log('CARD COMPONENT: Need "data-action" to get card content');
- return;
- }
- var showDelay = input.attr('data-show-delay') ? input.attr('data-show-delay') : 0;
- var hideDelay = input.attr('data-hide-delay') ? input.attr('data-hide-delay') : 600;
- var parameters = input.attr('data-parameters');
- var data = parameters ? JSON.parse(parameters) : {};
- data.action = action;
- input.addClass('card-component-container');
- $(document).ready(function(){
- var timeout;
- input.mouseenter(function(event){
- var e = event.target || event.relatedTarget;
- if (e.parentNode != this && e != this) return;
- event.stopImmediatePropagation();
- event.stopPropagation();
- $('*[data-type="card"]').find('.card-component')
- .addClass('card-component-hide')
- .removeClass('card-component-hover')
- .one('webkitAnimationEnd oanimationend msAnimationEnd animationend',
- function(e) {
- $(this).closest('.wrapper').remove();
- });
- timeout = setTimeout(function(){
- var currInput = input;
- if(!currInput.find('.card-component').length) {
- $.action(data, function(r){
- if(!r.content) return;
- //On utilise un wrapper pour gérer les overflows "out of the box"
- var wrapper = $('<div class="wrapper"></div>');
- var card = $(r.content);
- var leftOffset = currInput.offset().left;
- var topOffset = currInput.offset().top;
- currInput.append(card);
- var cardWidth = card.outerWidth();
- var position = {};
- card.wrap(wrapper);
- card.addClass('card-component card-component-hover');
- var wrapper = card.closest('div.wrapper');
- if($('body').width() < (leftOffset + cardWidth))
- position['right'] = cardWidth;
- else
- position['left'] = -currInput.outerWidth();
- var cardHeight = card.outerHeight();
- if($('body').height() < (topOffset + cardHeight))
- position['top'] = -cardHeight;
- currInput.find('.wrapper').css(position);
- });
- } else {
- var card = $(currInput.find('.card-component'));
- card.addClass('card-component-hover').removeClass('card-component-hide');
- }
- clearTimeout(currInput.data('tOutbox'));
- }, showDelay);
- });
- input.add(input.find('.card-component')).mouseleave(function(e){
- e.stopImmediatePropagation();
- e.stopPropagation();
- var input = $(this),
- card = input.find('.card-component'),
- tOutbox = setTimeout(function(){
- if(!$('.card-component:hover').length) {
- card.addClass('card-component-hide').removeClass('card-component-hover');
- card.one('webkitAnimationEnd oanimationend msAnimationEnd animationend', function(e) {
- $(this).closest('.wrapper').remove();
- });
- }
- }, hideDelay);
- //Clear du timeout d'apparition
- clearTimeout(timeout);
- //Set du l'id de timeout, permet de clear ce trigger si la souris revient sur l'input
- input.data('tOutbox', tOutbox);
- });
- });
- break;
- /**
- * data-dictionnary : Le slug du dictionnary à utiliser
- */
- case 'dictionnary-table':
- if(input.hasClass('component-dictionnary-table')) return;
- if(!input.attr('data-dictionnary') || !input.attr('data-dictionnary').length) return;
- var tpl = $('.component-dictionnary-table').get(0).outerHTML;
- $.action({
- action: 'load_dictionnary_component',
- slug : input.attr('data-dictionnary')
- },function(r){
- var list = $(Mustache.render(tpl,{label:'{{label}}', slug:'{{slug}}', id:'{{id}}',parent:r.content}));
- input.append(list);
- list.removeClass('hidden');
- dictionnary_table_refresh(list);
-
- //Save
- $(input).on('click','thead .btn-success',function(){
- var line = $(this).closest('tr');
- var data = {
- action: 'dictionnary_table_save',
- label: line.find('input.list-label').val(),
- id: list.attr('data-id'),
- list: list.attr('data-dictionnary')
- };
- if(list.find('input.list-slug')) data.slug = $('input.list-slug', list).val();
- $.action(data, function(r){
- list.attr('data-id', '');
- line.find('input').val('');
- $.message('success','Enregistré');
- dictionnary_table_refresh(list);
- });
- });
- //Suppression
- $(input).on('click','tbody tr .btn-danger',function(){
- if(!confirm('Êtes-vous sûr de vouloir supprimer cet élément de liste ?')) return;
- var line = $(this).closest('tr');
- $.action({
- action: 'delete_dictionnary',
- id: line.attr('data-id')
- },function(r){
- line.remove();
- line.closest('.edit-field').val('');
- $.message('info', 'Élément de liste supprimé');
- });
- });
- //Édition
- $(input).on('click','tbody tr .btn-edit',function(){
- var line = $(this).closest('tr');
- $.action({
- action: 'edit_dictionnary',
- id: line.attr('data-id')
- },function(r){
- list.find('input.list-label').val(r.label);
- if(list.find('input.list-slug')) $('input.list-slug', list).val(r.slug);
- list.attr('data-id',r.id);
- });
- });
- });
- break;
- //Permet aux plugins d'ajouter leurs composants
- //via la fonction init_components_nomcomposant(input);
- default:
- var type = input.attr('data-type').replace(/[^a-z0-9]/i,'_');
- if(window['init_components_'+type] !=null) window['init_components_'+type](input);
- break;
- }
- });
- }
- /** PRELOADER **/
- var detached;
- function preloader(parent, mode){
- var mode = typeof mode !== "undefined" ? mode : 'add';
- if(['toggle', 'add', 'delete'].indexOf(mode) === -1) return;
- var parent = $(parent);
- var loader = $('<div class="loader-container text-center"><div class="loader"><div class="inner one"></div><div class="inner two"></div><div class="inner three"></div></div></div>');
- switch (mode) {
- case 'add':
- parent.html(loader);
- break;
- case 'delete':
- parent.find('div.loader-container').remove();
- break;
- case 'toggle':
- if(parent.find('div.loader-container').length) {
- parent.find('div.loader-container').remove();
- parent.append(detached);
- } else {
- detached = parent.find('>*').detach();
- parent.html(loader);
- }
- break;
- default:
- break;
- }
- }
- /** BACK TO TOP **/
- $('#toTheTop').click(function() {
- scroll_top(150);
- });
- // Affichage du bouton dès lors où l'on a scrollé
- $(window).on('ready scroll', function(){
- scrollPos = $(document).scrollTop();
- if (scrollPos >= 100) {
- $('#toTheTop').css('display','flex').animate({opacity:1}, 100);
- } else {
- $('#toTheTop').stop().animate({opacity:0}, 100);
- $('#toTheTop').removeAttr('style');
- }
- });
- //Permet de scroller en haut de page
- function scroll_top(time){
- $('html,body').animate({scrollTop:0},time);
- }
- /** CONTRÔLES DATE ET HEURE **/
- function is_valid_date(string){
- var format = /^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]|(?:Jan|Mar|May|Jul|Aug|Oct|Dec)))\1|(?:(?:29|30)(\/|-|\.)(?:0?[1,3-9]|1[0-2]|(?:Jan|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec))\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)(?:0?2|(?:Feb))\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9]|(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep))|(?:1[0-2]|(?:Oct|Nov|Dec)))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$/;
- return format.test(string);
- }
- function is_valid_hour(string){
- var format = /^(?:\d|[01]\d|2[0-3]):[0-5]\d$/;
- return format.test(string);
- }
- //SHOW/HIDE PASSWORD
- function toggle_password(element){
- if ($(element).hasClass('fa-eye-slash')) {
- $(element).removeClass('fa-eye-slash').addClass('fa-eye');
- $(element).prev('input').attr('type', 'text');
- } else {
- $(element).removeClass('fa-eye').addClass('fa-eye-slash');
- $(element).prev('input').attr('type', 'password');
- }
- }
- /** QUICKFORM **/
- function reset_quickform_modal(){
- $('.modal form').attr('data-id','');
- $('input, textarea', '.modal').each(function(i, v){
- if($(v).attr('type') == 'checkbox')
- $(v).prop('checked', false);
- else
- $(v).val('');
- });
- }
- /** CORE **/
- //LOGIN
- $(document).ready(function(){
- $('#loginForm').on('keyup', 'input', function(e){
- if(e.keyCode == 13) core_login();
- });
- });
- function core_login(parent){
- if(isProcessing) return;
- var parent = parent!=undefined ? parent : '#loginRequest';
- var data = $('#loginForm').toJson();
- var loginBtn = $('#login-button');
- isProcessing = true;
- preloader(parent, 'toggle');
- $('.loader-container').append('<small>Connexion en cours</small>');
- loginBtn.html('<i class="fas fa-spinner fa-pulse"></i> Connexion');
- $.action(data, function(r){
- isProcessing = false;
- if(r.redirect) window.location = r.redirect;
- }, function(r){
- isProcessing = false;
- $('#password').val('');
- $('.user-dropdown-menu').trigger('click');
- loginBtn.html("Se connecter");
- preloader(parent, 'toggle');
- });
- }
- /** FILTER **/
- $(document).ready(function(){
- // RESET KEYWORD
- $("input.filter-keyword").on('keyup',function(){
- var posx = (this.offsetWidth + this.offsetLeft - 20);
- var props = $(this).val()!='' ? {'left':posx,'opacity':'1'} : {'left':posx+30,'opacity':'0'}
- $('#search-clear').css(props);
- });
-
- $("#search-clear").click(function(){
- $(".filter-keyword").val('');
- $(this).attr('style', '');
- $(".filter-keyword").focus();
- var searchCallback = $('#filters').attr('data-function');
- if(searchCallback) window[searchCallback]();
- });
- });
- //TOGGLE FILTERS SEARCH
- function switch_advanced_filter(element){
- $(element).closest('.filter-box').find('.advanced-search').toggleClass('hidden');
- }
- // SEARCH
- function filter_search(box){
- box = !box ? $('.filter-box:eq(0)'): box;
- var component = box.prev('[data-type="filter"]');
- var data = component.data();
- var filters = component.filters();
-
- if(filters.advanced.length>0 || filters.keyword!=''){
- filters = JSON.stringify(filters);
- $.urlParam('filters',btoa(filters));
- }else{
- $.urlParam('filters','');
- }
- window[data.function]();
- if(data.callback) window[data.callback]();
- }
- function filter_clean(element){
- var box = $(element).closest('.filter-box');
- $.urlParam('filters','');
- $('.filterRow:visible:not(:eq(0))',box).remove();
- $('.filterRow:visible .filter-column',box).prop('selectedIndex',0).trigger('change');
- }
- function filter_save(element){
- var input = $(element).closest('.filter-box').prev();
- var data = input.filters();
- $.action({
- action : 'filter_save',
- slug : input.attr('data-slug'),
- filters : data
- },function(response){
- $.message('info',response.message);
- });
- }
- // ADD
- function filter_add(element,data){
- var box = $(element).closest('.filter-box');
- var line = $(element).closest('.filterRow');
- var newline = line.clone();
- newline.find('input').val('');
- newline.find('input:eq(3)').replaceWith('<div readonly="readonly" class="form-control">Sélectionnez la colonne de tri</div>');
- newline.find('.filter-values').removeClass('hidden');
- newline.find('.filter-value-block').remove();
- line.after(newline);
- if(box.attr('data-join') == null || box.attr('data-join') == ''){
- box.find('.filter-join:not(:eq(0))').removeClass('invisible');
- } else {
- box.find('.filter-join:not(:eq(0))').val(box.attr('data-join'));
- }
- init_components(newline);
- if(!data) return;
- $('.filter-column',newline).val(data.column).trigger('change');
- $('.filter-operator',newline).val(data.operator).trigger('change');
- if(!Array.isArray(data.value)) data.value = [data.value];
- //Exception pour les composant dictionnary multi niveau
- $('.filter-value[data-type="dictionnary"]',newline).attr('data-value',data.value.slice(-1)[0] );
- for(var i in data.value){
- $('.filter-value:eq('+i+')',newline).val(data.value[i]).trigger('change');
- }
- init_components(newline);
- }
- // DELETE
- function filter_delete(element){
- var line = $(element).closest('.filterRow');
- if($('.filterRow:visible').length>1){
- line.remove();
- }else{
- line.find('input').val('');
- line.find('select').prop('selectedIndex',0);
- line.find('.filter-value-block').remove();
- line.find('.filter-join').addClass('invisible');
- line.find('div.filter-values').removeClass('hidden');
- }
- }
- //SET COMPARATOR
- function filter_set_comparator(element){
- var selected = $('option:selected',element);
- var line = $(element).closest('.filterRow');
- filter_refresh_values(line);
- if(selected.attr('data-values')){
- if(selected.attr('data-values')==0){
- $('.filter-value:eq(0)',line).remove();
- }else if(selected.attr('data-values')>1){
- for(var i=0;i<selected.attr('data-values')-1;i++){
- var cloneValue = $('.filter-value:eq(0)',line).clone();
- cloneValue.addClass('ml-1').removeClass('hasDatepicker').removeAttr('id');
- $('.filter-value-block',line).append(cloneValue);
- init_components(line);
- }
- }
- }
- init_components(line);
- }
- // SET
- function filter_set_column(element){
- var line = $(element).closest('.filterRow');
- $('.filter-operator,.filter-value',line).remove();
- filter_refresh_operator(line);
- filter_refresh_values(line);
- init_components(line);
- }
- function filter_refresh_operator(line){
- var valueZone = line.find('.filter-values');
- var filterColumn = line.find('.filter-column');
- var operatorColumn = line.find('.filter-operator');
- var option = $('option:selected',filterColumn);
- var data = option.data();
- // Si aucun filtre n'est selctionné, on remove les champs suivants
- if(!option.val().length) {
- line.find('input').val('');
- line.find('select').prop('selectedIndex',0);
- line.find('.filter-value-block').remove();
- line.find('.filter-join').addClass('invisible');
- valueZone.removeClass('hidden');
- return;
- }
- data.value = filterColumn.val();
- //supression de lancien block operateur + valeur
- line.find('.filter-value-block').remove();
- //ajout du bloc operateur / valeur
- var templateOperator = '<div class="filter-value-block">'+$('.filter-value-block[data-value-type="'+data.filterType+'"]:hidden .filter-operator').get(0).outerHTML.replace('data-template','data-type')+"</div>";
-
- filterOperator = $(templateOperator);
- valueZone.addClass('hidden').after(filterOperator);
- line.find('.filter-value-block').css('display','inline-block');
- }
- function filter_refresh_values(line){
- var filterColumn = line.find('.filter-column');
- var currOption = $('option:selected',filterColumn);
- var data = currOption.data();
- if(is_empty_obj(data)) return;
- //data.value = filterColumn.val();
- //supression de l'ancien block operateur + valeur
- line.find('.filter-value-block .filter-value').remove();
- //ajout du bloc operateur / valeur
- var templateValue = $('.filter-value-block[data-value-type="'+data.filterType+'"]:hidden .filter-value').get(0).outerHTML.replace('data-template','data-type');
- filterValue = $(Mustache.render(templateValue,data));
- //Si le type de champ est une liste on la remplit avec le datasource
- if(data.filterSource){
- var source = JSON.parse(currOption.attr('data-filter-source'));
- var options = '<option value=""> - </option>';
- for (var k in source)
- options += '<option value="'+k+'">'+source[k]+'</option>';
- filterValue.append(options);
- }
- filterValue.removeClass('hasDatepicker').removeAttr('id');
- $('.filter-operator',line).after(filterValue);
- }
- // INIT - INDEX
- function init_index(){
- }
- function init_setting(parameter){
- switch(parameter.section){
- case 'plugin':
- search_plugin();
-
- $('.section-plugin').on('change', 'input.toggle', function(){
- var input = $(this);
- var button = input.closest('.activator');
- var label = $('> label', button).detach();
- var value = input.prop('checked');
- if(!value) {
- if(!confirm("Êtes-vous sûr de vouloir désactiver ce plugin ?\nCela entraînera la suppression de toutes les données associées.")) {
- input.prop('checked',!value);
- button.prepend(label);
- return;
- }
- button.removeClass('btn-danger').addClass('btn-info').text('Activer').prepend(label);
- } else {
- button.addClass('btn-danger').removeClass('btn-info').text('Désactiver').prepend(label);
- }
- $.action({
- action : 'change_plugin_state',
- plugin : input.closest('li').attr('data-id'),
- state: value ? 1 : 0
- }, function(r){
-
- }, function(r){
- if(button.hasClass('btn-danger'))
- button.removeClass('btn-danger').addClass('btn-info').text('Activer').prepend(label);
- else if(button.hasClass('btn-info'))
- button.removeClass('btn-info').addClass('btn-danger').text('Désactiver').prepend(label);
- input.prop('checked',!value);
- });
- });
- break;
- case 'user':
- search_user();
- break;
- case 'firm':
- search_firm();
- break;
- case 'firmPlugin':
- search_firm_plugin('update_checkboxes');
- break;
- case 'userfirmrank':
- search_userfirmrank();
- break;
- case 'log':
- $('#logs').sortable_table({
- onSort : search_log
- });
- break;
-
- case 'rank':
- search_rank();
- break;
- case 'dictionnary':
- search_dictionnary();
- break;
- case 'right':
- search_right('update_checkboxes');
- break;
- default:
- if(parameter.section!= null){
- var section = parameter.section.replace(/[^a-z_0-9]/g,'_');
- var init = 'init_setting_'+section;
- if(window[init]!=null) window[init]($.urlParam());
- }
- break;
- }
- }
- /** RIGHT **/
- function right_switch(element){
- $(element).closest('tr').find('input').trigger('click');
- }
- /** FORM **/
- function send_form(element){
- var form = $(element).closest('[data-form]');
- var data = $.getForm(form);
- var data = {};
-
- for(var key in form.data()){
- if(key!="action" && key != "id") continue;
- data[key] = form.attr('data-'+key);
- }
-
- $('input,select,textarea',form).each(function(i,element){
- element = $(element);
- if(element.attr('data-id')!=null && element.attr('data-id')!=""){
- if(element.attr("type")=='checkbox' || element.attr("type")=='radio'){
- data[element.attr('data-id')] = (element.is(':checked')?1:0);
- }else{
- data[element.attr('data-id')] = element.val();
- }
- }
- });
- data.action = 'send_form';
- $.action(data,function(r){
- });
- }
- /** LOG **/
- // SEARCH
- function search_log(callback){
- $('#logs').fill({
- action:'search_log',
- filters : $('#filters').filters(),
- sort : $('#logs').sortable_table('get')
- },function(){
- if(callback!=null) callback();
- });
- }
- /** USER FIRM RANK**/
- // SEARCH
- function search_userfirmrank(callback){
- $('#userfirmranks').fill({firm : $('#firm').val(),action:'search_userfirmrank'},function(){
- if(callback!=null) callback();
- });
- }
- // SAVE
- function save_userfirmrank(){
- var data = $.getForm('#userfirmrankForm');
- data.id = $('#userfirmrankForm').attr('data-id');
- $.action(data,function(r){
- if(typeof r.success !== 'undefined'){
- var messageSuccess = 'Utilisateur ajouté pour '+(r.success.length > 1 ? 'les ' : 'l\'')+'établissement'+(r.success.length > 1 ? 's : ' : ' : ')+r.success
- $.message('success',messageSuccess,0);
- }
-
- $('#userfirmrankForm').attr('data-id','');
- $('#userfirmrankForm input').val('');
- $('#firm').val($("#firm option:first").val());
- $('#rank').val($("#rank option:first").val());
- search_userfirmrank();
- });
- }
- // EDIT
- function edit_userfirmrank(element){
- var line = $(element).closest('tr');
- $.action({
- action:'edit_userfirmrank',
- id:line.attr('data-id')
- },function(r){
- $.setForm('#userfirmrankForm',r);
- $('#firm').change();
- init_components($('#userfirmrankForm'));
- $('#userfirmrankForm').attr('data-id',r.id);
- });
- }
- // DELETE
- function delete_userfirmrank(element){
- if(!confirm('Êtes vous sûr de vouloir supprimer ce lien Établissement / Utilisateur / Rang ?')) return;
- var line = $(element).closest('tr');
- $.action({
- action : 'delete_userfirmrank',
- id : line.attr('data-id')
- },function(r){
- $.message('info', 'Lien Établissement / Utilisateur / Rang supprimé.')
- line.remove();
- });
- }
- /** FIRM **/
- // SEARCH
- function search_firm(callback){
- $('#firms').fill({action:'search_firm'},function(){
- if(callback!=null) callback();
- });
- }
- // EDIT
- function edit_firm(element){
- var line = $(element).closest('tr');
- window.location = 'firm.php?id='+line.attr('data-id');
- }
- // DELETE
- function delete_firm(element){
- if(!confirm('Êtes vous sûr de vouloir supprimer cet établissement ?')) return;
- var line = $(element).closest('tr');
- $.action({
- action : 'delete_firm',
- id : line.attr('data-id')
- },function(r){
- $.message('info','Établissement supprimé');
- line.remove();
- });
- }
- /** FIRM PLUGINS **/
- // SEARCH
- function search_right(callback){
- $('#ranks').fill({
- action: 'search_right',
- rank: $('#rank').attr('data-rank'),
- firm: $('#firm').val()
- },function(r){
- if(callback!=null) update_checkboxes(r);
- });
- }
- // TOGGLE RIGHT
- function toggle_right(element){
- var line = $(element).closest('tr');
- $.action({
- action:'toggle_right',
- rank:$('#rank').attr('data-rank'),
- firm:$('#firm').val(),
- section:line.attr('data-section'),
- right:$(element).attr('data-right'),
- state:$(element).prop('checked')?1:0
- });
- }
- // SEARCH
- function search_firm_plugin(callback){
- $('#firmplugins').fill({
- action:'search_firm_plugin',
- firm:$('#firm').val()
- },function(r){
- if(callback!=null) update_checkboxes(r);
- });
- }
- // ENABLE/DISABLE
- function toggle_firm_plugin(element){
- var line = $(element).closest('tr');
- $.action({
- action:'toggle_firm_plugin',
- firm :$('#firm').val(),
- state : $(element).prop('checked')?1:0,
- plugin: line.attr('data-id')
- });
- }
- function update_checkboxes(response){
- $('input[data-result="0"]').prop('checked',false);
- $('input[data-result="1"]').prop('checked',true);
- $('input[data-result="2"]').prop('indeterminate',true);
- }
- // SUPPRESSION LOGO ÉTABLISSEMENT
- function firm_logo_delete(element){
- if(!confirm('Êtes vous sûr de vouloir supprimer l\'image ?')) return;
- var imageComposer = $(element).parent().find("input[data-type='image']");
-
- $.action({
- action: 'firm_logo_delete',
- id: $('#firm').val()
- }, function(r){
- imageComposer.wrap('<form>').closest('form').get(0).reset();
- imageComposer.unwrap();
- $(element).next('img').attr('src', $(imageComposer).attr('data-default-src'));
- $(element).remove();
- });
- }
- /** USER **/
- // SEARCH
- function search_user(callback){
- $('#users').fill({action:'search_user'},function(){
- if(callback!=null) callback();
- });
- }
- // SAVE
- function save_user(){
- var data = $.getForm('#userFormAdmin');
- data.id = $('#userFormAdmin').attr('data-id');
- $.action(data,function(r){
- $.message('success','Utilisateur enregistré');
- $('#login').removeAttr('readonly');
- $('#userFormAdmin input').val('');
- $('#userFormAdmin').attr('data-id','');
- search_user();
- });
- }
- // EDIT
- function edit_user(element){
- var line = $(element).closest('tr');
- $.action({
- action:'edit_user',
- login:line.attr('data-user')
- },function(r){
- $.setForm('#userFormAdmin',r);
- $('#userFormAdmin').attr('data-id',r.id);
- $('#login').attr('readonly', true);
- init_components('#userFormAdmin');
- });
- }
- // DELETE
- function delete_user(element){
- if(!confirm('Êtes vous sûr de vouloir supprimer cet utilisateur ?')) return;
- var line = $(element).closest('tr');
- $.action({
- action : 'delete_user',
- login : line.attr('data-user')
- },function(r){
- $.message('info','Utilisateur supprimé');
- $('#userFormAdmin').attr('data-id','');
- reset_inputs($('#userFormAdmin'));
- $('#login').removeAttr('readonly');
- line.remove();
- });
- }
- /* ACCOUNT **/
- function account_lost_password (){
-
- $.action({
- action: 'account_lost_password',
- mail : $('#mail').val()
- }, function(r){
- $.message('success','Confirmation envoyée par e-mail');
- });
- }
- function account_save(element){
- var data = $('#user-form').toJson();
- data.login= $('#login').val();
- data.avatar = $('#avatar')[0].files[0];
- data.action = 'account_save';
- $.action(data, function(r){
- $.message('success','Enregistré');
- if(r.warning) $.message('warning',r.warning);
- });
- }
- // SUPPRIME AVATAR USER
- function account_avatar_delete(element){
- if(!confirm('Êtes vous sûr de vouloir supprimer l\'image ?')) return;
- var imageComposer = $(element).parent().find("input[data-type='image']");
-
- $.action({
- action: 'account_avatar_delete',
- login: $('#login').val()
- }, function(r){
- imageComposer.wrap('<form>').closest('form').get(0).reset();
- imageComposer.unwrap();
- $(element).next('img').attr('src', $(imageComposer).attr('data-default-src'));
- $(element).remove();
- });
- }
- /** RANKS **/
- // SEARCH
- function search_rank(callback){
- $('#ranks').fill({action:'search_rank'},function(){
- if(callback!=null) callback();
- });
- }
- // SAVE
- function save_rank(){
- var data = $.getForm('#rankForm');
- data.id = $('#rankForm').attr('data-id');
- $.action(data,function(r){
- $.message('success','Rang enregistré');
- $('#rankForm input').val('');
- $('#rankForm').attr('data-id','');
- search_rank();
- });
- }
- // EDIT
- function edit_rank(element){
- var line = $(element).closest('tr');
- $.action({action:'edit_rank',id:line.attr('data-id')},function(r){
- $.setForm('#rankForm',r);
- $('#rankForm').attr('data-id',r.id);
- });
- }
- // DELETE
- function delete_rank(element){
- if(!confirm('Êtes vous sûr de vouloir supprimer ce rang ?')) return;
- var line = $(element).closest('tr');
- $.action({
- action : 'delete_rank',
- id : line.attr('data-id')
- },function(r){
- $.message('info','Rang supprimé');
- line.remove();
- });
- }
- /** DICTIONNARY **/
- // SEARCH
- function search_dictionnary(callback){
- var parentValue = $('#parent').val();
- parentValue != "" ? $('#prev-button').removeClass('hidden') : $('#prev-button').addClass('hidden');
- $('#dictionnaries').fill({
- action:'search_dictionnary',
- parent : parentValue
- },function(r){
- reset_inputs($('#dictionnaryForm'), false, true);
- if(callback!=null) callback();
- var tpl = $('#parent').find('option[value="{{id}}"]');
- if(!tpl.parent('span').length) tpl.wrap('<span>').addClass('hidden');
- });
- }
- // SAVE
- function save_dictionnary(){
- var data = $.getForm('#dictionnaryForm');
- data.id = $('#dictionnaryForm').attr('data-id');
- data.parent = $('#parent').val();
- $.action(data,function(r){
- $.message('success','Liste enregistrée');
- $('#dictionnaryForm input').val('');
- $('#dictionnaryForm').attr('data-id','');
- search_dictionnary();
- });
- }
- // EDIT
- function edit_dictionnary(element){
- var line = $(element).closest('tr');
- $.action({
- action: 'edit_dictionnary',
- id: line.attr('data-id')
- },function(r){
- $.setForm('#dictionnaryForm',r);
- $('#dictionnaryForm').attr('data-id',r.id);
- });
- }
- // DELETE
- function delete_dictionnary(element){
- if(!confirm('Êtes-vous sûr de vouloir supprimer cette liste ?')) return;
- var line = $(element).closest('tr');
- $.action({
- action: 'delete_dictionnary',
- id: line.attr('data-id')
- },function(r){
- line.remove();
- $.message('info','Liste supprimée');
- });
- }
- // Remplissage de la liste (select) --> Dans les settings
- function get_dictionnary_items(elem, elemToFill){
- var parent = $(elem).closest('tr');
- var id = $(parent).attr('data-id');
- var parentId = $(parent).attr('data-parent');
- $(elemToFill).fill({
- action:'search_dictionnary',
- parent : parentId.toString()
- },function(){
- $(elemToFill).val(id).change();
- });
- }
- // Ajout de sous-liste --> Dans les settings
- function add_sub_dictionnary(elem){
- reset_inputs($('#dictionnaryForm'), false, true);
- var parent = $(elem).closest('tr');
- var id = $(parent).attr('data-id');
- var value = parent.find(".itemLabel").text();
- if ($("#parent option[value='"+id+"']").length > 0)
- $('#parent').val(id).change();
- else {
- get_dictionnary_items(elem, "#parent");
- $('code').addClass('hidden');
- }
- $('#prev-button').removeClass('hidden');
- }
- // Récupération éléments de la liste précédente --> Dans les settings
- function previous_list_dictionnary(elem){
- var selected = $('#parent > option:selected').val();
- reset_inputs($('#dictionnaryForm'), false, true);
- $.action({
- action: 'get_parent_dictionnary',
- selected: selected
- }, function(r){
- var data = r.rows[0];
- $('#parent option[value!="{{id}}"]').remove();
- if (data.parentId == "") $('#prev-button').addClass('hidden');
- if (data.parents[0].parent == "0") {
- $('#parent').append("<option value='' selected>-</option>");
- $('code').removeClass('hidden');
- }
- $.each(data.parents, function (index, value){
- if (value.id == data.parentId)
- $('#parent').append("<option selected value='"+value.id+"'>"+value.label+"</option>");
- else
- $('#parent').append("<option value='"+value.id+"'>"+value.label+"</option>");
- });
- search_dictionnary();
- });
- }
- // Récupération des sous-listes pour les champ de type "dictionnary" --> Où le module est appelé
- function get_sub_dictionnary(elem, name, currentDepth){
- var input = $(elem);
- var selectValue = input.val();
- var optSubLabel = $('option:selected', elem).attr('data-sublabel');
- var depth = (input.attr('data-depth') && input.attr('data-depth') != "") ? input.attr('data-depth') : "1";
- var fieldName = name == '' ? input.attr('name') : name;
- currentDepth -= currentDepth != 1 ? input.nextAll('select').length : 0;
- if(input.closest('span.dictionnary-container').length != 0){
- var id = input.nextAll().last().attr('id');
- input.attr('id', id).nextAll().remove();
- }
- if (selectValue.length && currentDepth < depth) {
- input.removeAttr('name');
- currentDepth += 1;
- $.action({
- action: 'search_dictionnary',
- parent: selectValue
- }, function(r){
- var option = '';
- if(input.closest('span.dictionnary-container').length == 0) input.wrap('<span class="dictionnary-container"></span>');
- var newSelect = clone_input_dictionnary(input, selectValue, fieldName);
- var currentDepth = input.closest('span.dictionnary-container').children('select').length;
- if (input.attr('data-disable-label') != "" && optSubLabel != "" && optSubLabel != "null") input.after('<label class="label-select">'+optSubLabel+'</label>');
- newSelect.attr('onchange', 'get_sub_dictionnary(this, "'+fieldName+'", '+currentDepth+');');
- newSelect.append('<option value=""> - </option>');
-
- $.each(r.rows, function(index, value){
- option += '<option value="'+value.id+'" data-parent="'+value.parent+'" data-sublabel="'+value.sublistlabel+'">'+value.label+'</option>';
- });
- newSelect.append(option);
- });
- } else if (!selectValue.length) {
- input.attr('name', fieldName);
- } else if (currentDepth == depth && input.attr('data-filter-type-value') && input.attr('data-filter-type-value').length) {
- data = input.data();
- input.closest('.filter-value-block').next('.filter-value-block[data-value-type="'+data.filterTypeValue+'"]').remove();
- var template = $('.filter-value-block[data-value-type="'+data.filterTypeValue+'"]:hidden').get(0).outerHTML;
- filterValue = $(Mustache.render(template,data));
- filterValue.css('display','inline-block');
- filterValue.find('input').removeClass('hasDatepicker').removeAttr('id');
-
- input.closest('.filter-value-block').after(filterValue);
- }
- }
- // Récupération des sous-listes depuis l'id du plus petit enfant --> Où le module est appelé
- function get_selected_values(elem, select){
- var input = $(elem);
- if(input.closest('span.dictionnary-container').length == 0) input.wrap('<span class="dictionnary-container"></span>');
- var fieldName = input.attr('name');
- var currentDepth = 1+input.closest('span.dictionnary-container').children('select').length;
- var optSubLabel = select.sublistlabel;
- var option = '';
- if (typeof select.childs !== 'undefined' && select.childs.length > 0) {
- var newSelect = clone_input_dictionnary(input, select.id, fieldName);
- if (newSelect.attr('data-disable-label') != "" && optSubLabel != "" && optSubLabel != "null" && optSubLabel != undefined) input.after('<label class="label-select">'+optSubLabel+'</label>');
- newSelect.append('<option value=""> - </option>');
- }
- $.each(select.childs, function(index, value){
- var selected = '';
-
- if (value.hasOwnProperty("selected")) {
- input.removeAttr('name');
- get_selected_values(newSelect, value);
- selected = "selected";
- }
- newSelect.attr('onchange', 'get_sub_dictionnary(this,"'+fieldName+'", '+currentDepth+');');
- option += '<option value="'+value.id+'" data-parent="'+value.parent+'" data-sublabel="'+value.sublistlabel+'" '+selected+'>'+value.label+'</option>';
- });
- if(newSelect) newSelect.append(option);
- }
- // Clone du select de type "dictionnary"
- function clone_input_dictionnary(input, id, name){
- var newSelect = input.clone();
- input.removeAttr('id').after(newSelect).after(' ');
- newSelect.removeAttr("data-type").removeAttr('name').removeAttr('data-value');
- // newSelect.attr('id', 'children-select-'+id).attr('name', name);
- newSelect.find('option').remove();
- return newSelect;
- }
- //Rafraîchit la table de la liste donnée
- //En lien avec le composant dictionnary_table
- function dictionnary_table_refresh(elem){
- var id = $(elem).attr('data-dictionnary');
- var table = $(elem).find('table:eq(0)');
- $.action({
- action: 'dictionnary_table_search',
- id: id
- },function(r){
- table.find('tbody tr:visible').remove();
- var tpl = table.find('tbody tr:hidden').get(0).outerHTML;
- for(var key in r.rows){
- var row = r.rows[key];
- var line = $(Mustache.render(tpl,row));
- line.removeClass('hidden');
- table.find('tbody').append(line);
- }
- });
- }
- /** PLUGINS **/
- // SEARCH
- function search_plugin(callback){
- $('#plugins').fill({action:'search_plugin'},function(){
- if(callback!=null) callback();
- });
- }
- // RÉCUPÉRATION PARAMÈTRE URL
- var get_url_parameter = function get_url_parameter(sParam, string) {
- var sPageURL = !string ? decodeURIComponent(window.location.search.substring(1)) : string;
- var sURLVariables = sPageURL.split('&'),
- sParameterName,
- i;
- for (i = 0; i < sURLVariables.length; i++) {
- sParameterName = sURLVariables[i].split('=');
- if (sParameterName[0] === sParam) {
- return sParameterName[1] === undefined ? true : sParameterName[1];
- }
- }
- };
- // DROPZONE
- function dropzone_delete_file(element){
- if(!confirm('Êtes-vous sûr de vouloir supprimer cet item ?')) return;
- var elem = $(element);
- var line = elem.closest('li');
- var container = elem.closest('div[data-type="dropzone"]');
- var inputTemp = container.find('#'+container.attr('id')+'_temporary');
- var values = inputTemp.val().length ? JSON.parse(inputTemp.val()) : [];
- for (var i in values) {
- if(values[i]['path'] == line.attr('data-path'))
- values.splice(i, 1);
- }
- line.remove();
- inputTemp.val(JSON.stringify(values));
- }
- /* GENERAL SETTINGS */
- //Sauvegarde de la configuration générale
- function general_settings_save(){
- var data = $('#general-settings').getForm();
- data.logo = $('#logo')[0].files[0];
- data.logo_dark = $('#logo_dark')[0].files[0];
- data.favicon = $('#favicon')[0].files[0];
- data.password_format = $('#password-format-form').attr('data-format');
- $.action(data, function(r){
- $.message('success', 'Configuration enregistrée');
- });
- }
- function general_reset_password_delay(){
- if(!confirm('Êtes-vous sûr de vouloir forcer tous les utilisateurs à réinitialiser leurs mot de passe ?')) return;
- $.action({
- action: 'general_reset_password_delay'
- }, function(r){
- $.message('success', 'Validé');
- });
- }
- function password_settings_format(){
- var patterns = [];
- $('#password-format-form input[data-pattern]:checked').each(function(){
- patterns.push($(this).attr('data-pattern'));
- });
- $('#password-format-form').attr('data-format',JSON.stringify(patterns));
- }
- //Suppression image générale application
- function general_logo_delete(element){
- if(!confirm('Êtes-vous sûr de vouloir supprimer l\'image ?')) return;
- var imageComposer = $(element).parent().find("input[data-type='image']");
-
- $.action({
- action: 'general_logo_delete'
- }, function(r){
- imageComposer.wrap('<form>').closest('form').get(0).reset();
- imageComposer.unwrap();
- $(element).next('img').attr('src', $(imageComposer).attr('data-default-src'));
- $(element).remove();
- $.message('info', 'Image supprimée');
- });
- }
- //Suppression favicon générale application
- function general_favicon_delete(element){
- if(!confirm('Êtes-vous sûr de vouloir supprimer l\'image ?')) return;
- var imageComposer = $(element).parent().find("input[data-type='image']");
-
- $.action({
- action: 'general_favicon_delete'
- }, function(r){
- imageComposer.wrap('<form>').closest('form').get(0).reset();
- imageComposer.unwrap();
- $(element).next('img').attr('src', $(imageComposer).attr('data-default-src'));
- $(element).remove();
- $.message('info', 'Favicon supprimée');
- });
- }
- //Active/Désactive la page de maintenance du site
- function toggle_maintenance(){
- var checkbox = $('#maintenance');
- var state = checkbox.is(':checked') ? 'd\'activer' : 'de désactiver';
- if(!confirm("Vous êtes sur le point "+state+" la page de maintenance du site.\nVoulez-vous continuer ?")){
- checkbox.is(':checked') ? checkbox.removeAttr('checked').prop('checked', false) : checkbox.attr('checked', true).prop('checked', true);
- return;
- }
- general_settings_save();
- }
- /* FUNCTIONS */
- //Récupère la plus petite valeur d'un tableau
- function getMinValue(arr) {
- return arr.reduce(function (p, v) {
- return ( p < v ? p : v );
- });
- };
- //Récupère la plus grande valeur d'un tableau
- function getMaxValue(arr) {
- return arr.reduce(function (p, v) {
- return ( p > v ? p : v );
- });
- };
- //Check si la valeur saisie dans l'input
- //est une adresse e-mail bien formatée
- function is_email(email) {
- var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
- return re.test(String(email).toLowerCase());
- }
- //Check si la valeur saisie dans
- //l'input est une url bien formatée
- function is_url(str) {
- regexp = /^(?:(?:https?|ftp):\/\/)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:\/\S*)?$/;
- if (regexp.test(str))
- return true;
- return false;
- }
- //Check format n° de téléphone
- function is_phone_number(number, required, label){
- if (required && number == ''){
- $.message('error',label+' obligatoire');
- return false;
- }
- if (number != ''){
- number = number.replace(/\s/g, '');
- number = number.replace(/\./g, '');
- number = number.replace(/-/g, '');
- if(is_numeric(number)) {
- if(/^(?:(?:\+|00)\d{2}|0)\s*[1-9](?:[\s.-]*\d{2}){4}$/.test(number) == false){
- $.message('error',' Le format du n° de '+label.toLowerCase()+' est invalide');
- return false;
- }
- } else {
- $.message('error',' Le n° de '+label.toLowerCase()+' contient des caractères interdits');
- return false;
- }
- }
- return true;
- }
- //Check si la valeur de
- //l'input est numérique
- function is_numeric(n) {
- return !isNaN(parseFloat(n)) && isFinite(n);
- }
- function str_price_to_decimal(str){
- return str.replace(/,/g,'.').replace(/ /g,'');
- }
- //Comme la fonction ucfirst de PHP
- function ucfirst(string) {
- return string.charAt(0).toUpperCase() + string.slice(1);
- }
- //Permet de revenir/rester sur l'onglet courant
- //au reload de page, ou au clic sur un lien particulier
- if (location.hash) {
- $('a[href="' + location.hash + '"]').tab('show');
- }
- var activeTab = localStorage.getItem('activeTab');
- if (activeTab) {
- $('a[href="' + activeTab + '"]').tab('show');
- }
- $('body').on('click', 'a[data-toggle="tab"]', function(e){
- e.preventDefault();
- var tab_name = this.getAttribute('href');
- history.pushState ? history.pushState(null, null, tab_name) : location.hash = tab_name;
- localStorage.setItem('activeTab', tab_name);
- $(this).tab('show');
- return false;
- });
- $(window).on('popstate', function () {
- var anchor = location.hash || $('a[data-toggle="tab"]').first().attr('href');
- $('a[data-toggle="tab"][href="' + anchor + '"]').tab('show');
- });
- //Check si la chaîne de caractères
- //fournies est une chaîne JSON
- function is_json_string(str) {
- try {
- JSON.parse(str);
- } catch (e) {
- return false;
- }
- return true;
- }
- //Sélectionne le texte de l'élément passé en paramètre
- function select_text(element, event){
- event.stopImmediatePropagation();
- var sel, range;
- var el = $(element).get(0); //get element id
- if (window.getSelection && document.createRange) { //Browser compatibility
- sel = window.getSelection();
- if(sel.toString() == ''){ //no text selection
- window.setTimeout(function(){
- range = document.createRange(); //range object
- range.selectNodeContents(el); //sets Range
- sel.removeAllRanges(); //remove all ranges from selection
- sel.addRange(range);//add Range to a Selection.
- },1);
- }
- }else if (document.selection) { //older ie
- sel = document.selection.createRange();
- if(sel.text == ''){ //no text selection
- range = document.body.createTextRange();//Creates TextRange object
- range.moveToElementText(el);//sets Range
- range.select(); //make selection.
- }
- }
- }
- //Permet de copier le contenu de l'element dans le presse-papier
- function copy_to_clipboard(element) {
- var element = $(element);
- var temp = $('<input>');
- $('body').append(temp);
- temp.val(element.text()).select();
- setTimeout(function(){document.execCommand('copy');},0);
- temp.remove();
-
- if(element.data('ui-tooltip')) return;
- element.tooltip({
- items: '*',
- tooltipClass: 'quickform-tooltip',
- content: 'Copié dans le presse papier',
- open: {effect:'fade',duration:750},
- close: {effect:'fade',duration:750}
- });
- element.tooltip('open');
- setTimeout(function(){element.tooltip('close');element.tooltip('destroy');}, 2000);
- }
- //Reset des inputs d'un conteneur
- function reset_inputs(container, onlyVisible, domData){
- var container = container ? container : $('body');
- var visibility = onlyVisible ? onlyVisible : false;
- var dom = domData ? domData : false;
- if(dom) container.removeAttr('data-id');
- var classicInputs = visibility==true ? $('input:visible, textarea:visible', container) : $('input, textarea', container);
- classicInputs.each(function(i, v){
- if($(v).attr('type') == 'checkbox')
- $(v).prop('checked', false);
- else
- $(v).val('');
- });
- var customInputs = visibility==true ? $('*[contenteditable="true"]:visible', container) : $('*[contenteditable="true"]', container);
- customInputs.each(function(j,val){
- $(val).text('');
- });
- }
- //Check si le contenu d'un input est
- //selectionné (en surbrillance avec le curseur)
- function is_text_selected(input) {
- if (typeof input.selectionStart == "number") {
- return input.selectionStart == 0 && input.selectionEnd == input.value.length;
- } else if (typeof document.selection != "undefined") {
- input.focus();
- return document.selection.createRange().text == input.value;
- }
- }
- //Renvoie un tableau en ayant supprimé
- //toutes les valuers dupliquées
- function only_uniq_values(a) {
- var seen = {};
- var out = [];
- var len = a.length;
- var j = 0;
- for(var i = 0; i < len; i++) {
- var item = a[i];
- if(seen[item] !== 1) {
- seen[item] = 1;
- out[j++] = item;
- }
- }
- return out;
- }
- //Contrôle éléments saisis dans input de type number.
- //Autorise ou non les décimales et les nb négatifs
- function input_number_control(e, decimal, relative){
- var authorizedKeys = [8,9,37,39,46,54,109,110,188,190];
- switch (e.keyCode) {
- case 110:
- case 188:
- case 190:
- return decimal?decimal:false;
- break;
- case 109:
- return relative?relative:false;
- break;
- case 54:
- return (is_caps()) ? true : (relative?relative:false);
- break;
- default:
- return (
- ((e.keyCode >= 48 && e.keyCode <= 57) && (is_caps())) ||
- (e.keyCode >= 96 && e.keyCode <= 105) ||
- ((e.keyCode == 65 || e.keyCode == 86 || e.keyCode == 67) && (e.ctrlKey === true || e.metaKey === true)) ||
- (authorizedKeys.indexOf(e.keyCode) !== -1)
- );
- break;
- }
- }
- //Permet de checker si la
- //saisie est en majuscule ou non
- function is_caps(){
- e = window.event;
- return is_mobile ? true : (e.shiftKey !== true && e.metaKey !== true) ? (e.getModifierState("CapsLock") ? true : false) : (e.getModifierState("CapsLock") ? false : true);
- }
- //Check si l'objet est vide ou non
- //Retourne true si vide, false sinon
- function is_empty_obj(obj) {
- for(var key in obj)
- if(obj.hasOwnProperty(key)) return false;
- return true;
- }
- //Permet de retourner une propriété d'un
- //objet de manière totalement aléatoire
- function random_property(obj) {
- var keys = Object.keys(obj)
- return obj[keys[ keys.length * Math.random() << 0]];
- }
- function get_characters_set() {
- var CHARACTER_SETS = [
- ["0123456789"],
- ["abcdefghijklmnopqrstuvwxyz"],
- ["ABCDEFGHIJKLMNOPQRSTUVWXYZ"],
- ["!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"],
- ];
- // Concatène les jeux de caractères
- var rawCharset = "";
- CHARACTER_SETS.forEach(function(entry, i) {
- rawCharset += entry[0];
- });
-
- // Parse en UTF-16, supprime les doublons, convertit en tableau de string
- var charset = [];
- for (var i = 0; i < rawCharset.length; ++i) {
- var c = rawCharset.charCodeAt(i);
- if (c<0xD800 || c>=0xE000) {//Check si character UTF-16 valide
- var s = rawCharset.charAt(i);
- if (charset.indexOf(s) == -1) charset.push(s);
- continue;
- }
- if (0xD800<=c && c<0xDC00 && i+1<rawCharset.length) {
- var d = rawCharset.charCodeAt(i + 1);
- if (0xDC00<=d && d<0xE000) {
- var s = rawCharset.substring(i, i+2);
- i++;
- if (charset.indexOf(s) == -1) charset.push(s);
- continue;
- }
- }
- throw "Invalid UTF-16";
- }
- return charset;
- }
- //Retourne un entier aléatoire dans la plage [0, n)
- //(2 méthodes utilisées)
- function get_random_int(maxRange) {
- //Récup d'un entier aléatoire via le module Math
- //(fallback si pas de module crypto)
- var x = random_int_math(maxRange);
- //Récupération d'un entier aléatoire via le moule crypto
- x = (x + random_int_crypto(maxRange)) % maxRange;
- return x;
- }
- //Retourne un entier aléatoire
- //Peu sécurisé (car calculable) mais
- //présent sur tous les navigateurs
- function random_int_math(maxRange) {
- var x = Math.floor(Math.random() * maxRange);
- if (x < 0 || x >= maxRange) throw "Arithmetic exception";
- return x;
- }
- //Retourne un entier aléatoire
- //Extrêmement sécurisé, mais pas
- //disponible sur tous les navigateurs
- //+ d'infos ici: https://developer.mozilla.org/fr/docs/Web/API/RandomSource/getRandomValues
- function random_int_crypto(maxRange) {
- var cryptoObject = null
- if ("crypto" in window) {
- //Check si le module crypto est disponible (Chrome, Firefox, Safari)
- cryptoObject = crypto;
- } else if ("msCrypto" in window) {
- //Check si le module crypto est disponible (Edge, IE)
- cryptoObject = msCrypto;
- }
-
- //Check + récupération propriétés/fonctions nécessaires du module crypto
- if ("getRandomValues" in cryptoObject && "Uint32Array" in window && typeof Uint32Array == "function") {
- //Génère un échantillon impartial/aléatoire
- var x = new Uint32Array(1);
- //Modification des élements du
- //tableau par des nb aléatoires
- do cryptoObject.getRandomValues(x);
- while (x[0] - x[0] % maxRange > 4294967296 - maxRange);
-
- return x[0] % maxRange;
- } else {
- return 0;
- }
- }
- //Permet de générer un UUID de
- //longueur souhaitée (ou 10 si pas de paramètre)
- function generate_uuid(length){
- var length = length !== undefined ? length : 10;
- //Fallback repeat sur string
- //pour les anciens navigateurs
- if(!String.prototype.repeat){
- String.prototype.repeat = function(length){
- var length = parseInt(length);
- if (length < 1) return '';
- var result = '',
- pattern = this.valueOf();
- while (length > 1) {
- if(length & 1) result += pattern;
- length >>= 1, pattern += pattern;
- }
- return result + pattern;
- };
- }
- var mem = "0x1"+("0".repeat(length));
- return Math.floor((1 + Math.random()) * mem).toString(16).substring(1);
- }
- function readable_size(bytes) {
- var thresh = 1000;
- if(Math.abs(bytes) < thresh) {
- return bytes + ' B';
- }
- var units = ['ko','Mo','Go','To','Po','Eo','Zo','Yo'];
- var u = -1;
- do {
- bytes /= thresh;
- ++u;
- } while(Math.abs(bytes) >= thresh && u < units.length - 1);
- return bytes.toFixed(1)+' '+units[u];
- }
- /**
- * Permet e faire cligner l'onglet
- * navigateur avec un message custom
- * @param {string} message => le message à afficher
- * @param {int} interval => l'intervalle entre 2 clignotement en ms
- * @param {int} repetitions => le nombre de clignotements
- */
- function blink_tab(message, interval, repetitions) {
- interval = interval != undefined && !isNaN(interval) ? interval : 750;
- repetitions = parseInt(repetitions)*2;
- if(isNaN(repetitions)) repetitions = 10;
- if(repetitions%2!==0) repetitions += 1
- var original = document.title,
- timeoutId,
- blink = function() {
- document.title = document.title == message ? original : message;
- if(--repetitions > 0) timeoutId = setTimeout(blink, interval);
- },
- clear = function() {
- clearTimeout(timeoutId);
- document.title = original;
- window.onmousemove = null;
- timeoutId = null;
- };
-
- if(!timeoutId) {
- timeoutId = setTimeout(blink, interval);
- window.onmousemove = clear;
- }
- }
|